diff --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.h b/clang-tools-extra/clang-tidy/utils/IncludeInserter.h --- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.h +++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.h @@ -71,6 +71,8 @@ void AddInclude(StringRef FileName, bool IsAngled, SourceLocation HashLocation, SourceLocation EndLocation); + IncludeSorter &getOrCreate(FileID File); + llvm::DenseMap> IncludeSorterByFile; llvm::DenseMap> InsertedHeaders; const SourceManager &SourceMgr; diff --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp --- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp +++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp @@ -7,6 +7,7 @@ //===----------------------------------------------------------------------===// #include "IncludeInserter.h" +#include "IncludeSorter.h" #include "clang/Lex/Token.h" namespace clang { @@ -45,6 +46,19 @@ return std::make_unique(this); } +IncludeSorter &IncludeInserter::getOrCreate(FileID FileID) { + // std::unique_ptr is cheap to construct, so force a construction now to save + // the lookup needed if we were to insert into the map. + std::unique_ptr &Entry = IncludeSorterByFile[FileID]; + if (!Entry) { + // If it wasn't found, Entry will be default constructed to nullptr. + Entry = std::make_unique( + &SourceMgr, &LangOpts, FileID, + SourceMgr.getFilename(SourceMgr.getLocForStartOfFile(FileID)), Style); + } + return *Entry; +} + llvm::Optional IncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header, bool IsAngled) { @@ -53,31 +67,14 @@ if (!InsertedHeaders[FileID].insert(std::string(Header)).second) return llvm::None; - if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) { - // This may happen if there have been no preprocessor directives in this - // file. - IncludeSorterByFile.insert(std::make_pair( - FileID, - std::make_unique( - &SourceMgr, &LangOpts, FileID, - SourceMgr.getFilename(SourceMgr.getLocForStartOfFile(FileID)), - Style))); - } - return IncludeSorterByFile[FileID]->CreateIncludeInsertion(Header, IsAngled); + return getOrCreate(FileID).CreateIncludeInsertion(Header, IsAngled); } void IncludeInserter::AddInclude(StringRef FileName, bool IsAngled, SourceLocation HashLocation, SourceLocation EndLocation) { FileID FileID = SourceMgr.getFileID(HashLocation); - if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) { - IncludeSorterByFile.insert(std::make_pair( - FileID, std::make_unique( - &SourceMgr, &LangOpts, FileID, - SourceMgr.getFilename(HashLocation), Style))); - } - IncludeSorterByFile[FileID]->AddInclude(FileName, IsAngled, HashLocation, - EndLocation); + getOrCreate(FileID).AddInclude(FileName, IsAngled, HashLocation, EndLocation); } } // namespace utils