[Lex] Fix some Clang-tidy modernize and Include What You Use warnings; other minor fixes (NFC).

llvm-svn: 319986
This commit is contained in:
Eugene Zelenko 2017-12-06 23:18:41 +00:00
parent 9c26546d61
commit afd1b1c989
8 changed files with 313 additions and 225 deletions

View File

@ -1,4 +1,4 @@
//===--- HeaderSearch.h - Resolve Header File Locations ---------*- C++ -*-===//
//===- HeaderSearch.h - Resolve Header File Locations -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -14,25 +14,37 @@
#ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
#define LLVM_CLANG_LEX_HEADERSEARCH_H
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/DirectoryLookup.h"
#include "clang/Lex/ModuleMap.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include <cassert>
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace clang {
class DiagnosticsEngine;
class DiagnosticsEngine;
class DirectoryEntry;
class ExternalPreprocessorSource;
class FileEntry;
class FileManager;
class HeaderMap;
class HeaderSearchOptions;
class IdentifierInfo;
class LangOptions;
class Module;
class Preprocessor;
class TargetInfo;
/// \brief The preprocessor keeps track of this information for each
/// file that is \#included.
@ -76,14 +88,14 @@ struct HeaderFileInfo {
unsigned IsValid : 1;
/// \brief The number of times the file has been included already.
unsigned short NumIncludes;
unsigned short NumIncludes = 0;
/// \brief The ID number of the controlling macro.
///
/// This ID number will be non-zero when there is a controlling
/// macro whose IdentifierInfo may not yet have been loaded from
/// external storage.
unsigned ControllingMacroID;
unsigned ControllingMacroID = 0;
/// If this file has a \#ifndef XXX (or equivalent) guard that
/// protects the entire contents of the file, this is the identifier
@ -93,17 +105,16 @@ struct HeaderFileInfo {
/// the controlling macro of this header, since
/// getControllingMacro() is able to load a controlling macro from
/// external storage.
const IdentifierInfo *ControllingMacro;
const IdentifierInfo *ControllingMacro = nullptr;
/// \brief If this header came from a framework include, this is the name
/// of the framework.
StringRef Framework;
HeaderFileInfo()
: isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
External(false), isModuleHeader(false), isCompilingModuleHeader(false),
Resolved(false), IndexHeaderMapHeader(false), IsValid(0),
NumIncludes(0), ControllingMacroID(0), ControllingMacro(nullptr) {}
: isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
External(false), isModuleHeader(false), isCompilingModuleHeader(false),
Resolved(false), IndexHeaderMapHeader(false), IsValid(false) {}
/// \brief Retrieve the controlling macro for this header file, if
/// any.
@ -135,6 +146,8 @@ public:
/// \brief Encapsulates the information needed to find the file referenced
/// by a \#include or \#include_next, (sub-)framework lookup, etc.
class HeaderSearch {
friend class DirectoryLookup;
/// This structure is used to record entries in our framework cache.
struct FrameworkCacheEntry {
/// The directory entry which should be used for the cached framework.
@ -151,6 +164,7 @@ class HeaderSearch {
DiagnosticsEngine &Diags;
FileManager &FileMgr;
/// \#include search path information. Requests for \#include "x" search the
/// directory of the \#including file first, then each directory in SearchDirs
/// consecutively. Requests for <x> search the current dir first, then each
@ -158,9 +172,9 @@ class HeaderSearch {
/// NoCurDirSearch is true, then the check for the file in the current
/// directory is suppressed.
std::vector<DirectoryLookup> SearchDirs;
unsigned AngledDirIdx;
unsigned SystemDirIdx;
bool NoCurDirSearch;
unsigned AngledDirIdx = 0;
unsigned SystemDirIdx = 0;
bool NoCurDirSearch = false;
/// \brief \#include prefixes for which the 'system header' property is
/// overridden.
@ -168,7 +182,7 @@ class HeaderSearch {
/// For a \#include "x" or \#include \<x> directive, the last string in this
/// list which is a prefix of 'x' determines whether the file is treated as
/// a system header.
std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
std::vector<std::pair<std::string, bool>> SystemHeaderPrefixes;
/// \brief The path to the module cache.
std::string ModuleCachePath;
@ -182,15 +196,17 @@ class HeaderSearch {
/// Starting index in SearchDirs that the cached search was performed from.
/// If there is a hit and this value doesn't match the current query, the
/// cache has to be ignored.
unsigned StartIdx;
unsigned StartIdx = 0;
/// The entry in SearchDirs that satisfied the query.
unsigned HitIdx;
unsigned HitIdx = 0;
/// This is non-null if the original filename was mapped to a framework
/// include via a headermap.
const char *MappedName;
const char *MappedName = nullptr;
/// Default constructor -- Initialize all members with zero.
LookupFileCacheInfo(): StartIdx(0), HitIdx(0), MappedName(nullptr) {}
LookupFileCacheInfo() = default;
void reset(unsigned StartIdx) {
this->StartIdx = StartIdx;
@ -206,13 +222,13 @@ class HeaderSearch {
/// IncludeAliases - maps include file names (including the quotes or
/// angle brackets) to other include file names. This is used to support the
/// include_alias pragma for Microsoft compatibility.
typedef llvm::StringMap<std::string, llvm::BumpPtrAllocator>
IncludeAliasMap;
using IncludeAliasMap =
llvm::StringMap<std::string, llvm::BumpPtrAllocator>;
std::unique_ptr<IncludeAliasMap> IncludeAliases;
/// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
/// headermaps. This vector owns the headermap.
std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
std::vector<std::pair<const FileEntry *, const HeaderMap *>> HeaderMaps;
/// \brief The mapping between modules and headers.
mutable ModuleMap ModMap;
@ -231,26 +247,23 @@ class HeaderSearch {
/// \brief Entity used to resolve the identifier IDs of controlling
/// macros into IdentifierInfo pointers, and keep the identifire up to date,
/// as needed.
ExternalPreprocessorSource *ExternalLookup;
ExternalPreprocessorSource *ExternalLookup = nullptr;
/// \brief Entity used to look up stored header file information.
ExternalHeaderFileInfoSource *ExternalSource;
ExternalHeaderFileInfoSource *ExternalSource = nullptr;
// Various statistics we track for performance analysis.
unsigned NumIncluded;
unsigned NumMultiIncludeFileOptzn;
unsigned NumFrameworkLookups, NumSubFrameworkLookups;
unsigned NumIncluded = 0;
unsigned NumMultiIncludeFileOptzn = 0;
unsigned NumFrameworkLookups = 0;
unsigned NumSubFrameworkLookups = 0;
// HeaderSearch doesn't support default or copy construction.
HeaderSearch(const HeaderSearch&) = delete;
void operator=(const HeaderSearch&) = delete;
friend class DirectoryLookup;
public:
HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
SourceManager &SourceMgr, DiagnosticsEngine &Diags,
const LangOptions &LangOpts, const TargetInfo *Target);
HeaderSearch(const HeaderSearch &) = delete;
HeaderSearch &operator=(const HeaderSearch &) = delete;
~HeaderSearch();
/// \brief Retrieve the header-search options with which this header search
@ -282,7 +295,7 @@ public:
}
/// \brief Set the list of system header prefixes.
void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool> > P) {
void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool>> P) {
SystemHeaderPrefixes.assign(P.begin(), P.end());
}
@ -310,7 +323,7 @@ public:
IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
if (Iter != IncludeAliases->end())
return Iter->second;
return StringRef();
return {};
}
/// \brief Set the path to the module cache.
@ -493,7 +506,6 @@ public:
std::string getPrebuiltModuleFileName(StringRef ModuleName,
bool FileMapOnly = false);
/// \brief Retrieve the name of the (to-be-)cached module file that should
/// be used to load a module with the given name.
///
@ -572,7 +584,6 @@ public:
void loadTopLevelSystemModules();
private:
/// \brief Lookup a module with the given module name and search-name.
///
/// \param ModuleName The name of the module we're looking for.
@ -652,7 +663,8 @@ public:
bool WantExternal = true) const;
// Used by external tools
typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator;
using search_dir_iterator = std::vector<DirectoryLookup>::const_iterator;
search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
unsigned search_dir_size() const { return SearchDirs.size(); }
@ -660,6 +672,7 @@ public:
search_dir_iterator quoted_dir_begin() const {
return SearchDirs.begin();
}
search_dir_iterator quoted_dir_end() const {
return SearchDirs.begin() + AngledDirIdx;
}
@ -667,6 +680,7 @@ public:
search_dir_iterator angled_dir_begin() const {
return SearchDirs.begin() + AngledDirIdx;
}
search_dir_iterator angled_dir_end() const {
return SearchDirs.begin() + SystemDirIdx;
}
@ -674,6 +688,7 @@ public:
search_dir_iterator system_dir_begin() const {
return SearchDirs.begin() + SystemDirIdx;
}
search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
/// \brief Retrieve a uniqued framework name.
@ -696,10 +711,13 @@ private:
enum LoadModuleMapResult {
/// \brief The module map file had already been loaded.
LMM_AlreadyLoaded,
/// \brief The module map file was loaded by this invocation.
LMM_NewlyLoaded,
/// \brief There is was directory with the given name.
LMM_NoDirectory,
/// \brief There was either no module map file or the module map file was
/// invalid.
LMM_InvalidModuleMap
@ -735,6 +753,6 @@ private:
bool IsSystem, bool IsFramework);
};
} // end namespace clang
} // namespace clang
#endif
#endif // LLVM_CLANG_LEX_HEADERSEARCH_H

View File

@ -1,4 +1,4 @@
//===--- HeaderSearchOptions.h ----------------------------------*- C++ -*-===//
//===- HeaderSearchOptions.h ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -12,9 +12,9 @@
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/CachedHashString.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringRef.h"
#include <cstdint>
#include <string>
#include <vector>
#include <map>
@ -22,26 +22,45 @@
namespace clang {
namespace frontend {
/// IncludeDirGroup - Identifies the group an include Entry belongs to,
/// representing its relative positive in the search list.
/// \#include directives whose paths are enclosed by string quotes ("")
/// start searching at the Quoted group (specified by '-iquote'),
/// then search the Angled group, then the System group, etc.
enum IncludeDirGroup {
Quoted = 0, ///< '\#include ""' paths, added by 'gcc -iquote'.
Angled, ///< Paths for '\#include <>' added by '-I'.
IndexHeaderMap, ///< Like Angled, but marks header maps used when
/// building frameworks.
System, ///< Like Angled, but marks system directories.
ExternCSystem, ///< Like System, but headers are implicitly wrapped in
/// extern "C".
CSystem, ///< Like System, but only used for C.
CXXSystem, ///< Like System, but only used for C++.
ObjCSystem, ///< Like System, but only used for ObjC.
ObjCXXSystem, ///< Like System, but only used for ObjC++.
After ///< Like System, but searched after the system directories.
};
}
/// IncludeDirGroup - Identifies the group an include Entry belongs to,
/// representing its relative positive in the search list.
/// \#include directives whose paths are enclosed by string quotes ("")
/// start searching at the Quoted group (specified by '-iquote'),
/// then search the Angled group, then the System group, etc.
enum IncludeDirGroup {
/// '\#include ""' paths, added by 'gcc -iquote'.
Quoted = 0,
/// Paths for '\#include <>' added by '-I'.
Angled,
/// Like Angled, but marks header maps used when building frameworks.
IndexHeaderMap,
/// Like Angled, but marks system directories.
System,
/// Like System, but headers are implicitly wrapped in extern "C".
ExternCSystem,
/// Like System, but only used for C.
CSystem,
/// Like System, but only used for C++.
CXXSystem,
/// Like System, but only used for ObjC.
ObjCSystem,
/// Like System, but only used for ObjC++.
ObjCXXSystem,
/// Like System, but searched after the system directories.
After
};
} // namespace frontend
/// HeaderSearchOptions - Helper class for storing options related to the
/// initialization of the HeaderSearch object.
@ -59,8 +78,8 @@ public:
Entry(StringRef path, frontend::IncludeDirGroup group, bool isFramework,
bool ignoreSysRoot)
: Path(path), Group(group), IsFramework(isFramework),
IgnoreSysRoot(ignoreSysRoot) {}
: Path(path), Group(group), IsFramework(isFramework),
IgnoreSysRoot(ignoreSysRoot) {}
};
struct SystemHeaderPrefix {
@ -72,7 +91,7 @@ public:
bool IsSystemHeader;
SystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader)
: Prefix(Prefix), IsSystemHeader(IsSystemHeader) {}
: Prefix(Prefix), IsSystemHeader(IsSystemHeader) {}
};
/// If non-empty, the directory to use as a "virtual system root" for include
@ -130,7 +149,7 @@ public:
/// files.
///
/// The default value is large, e.g., the operation runs once a week.
unsigned ModuleCachePruneInterval;
unsigned ModuleCachePruneInterval = 7 * 24 * 60 * 60;
/// \brief The time (in seconds) after which an unused module file will be
/// considered unused and will, therefore, be pruned.
@ -139,13 +158,13 @@ public:
/// accessed in this many seconds will be removed. The default value is
/// large, e.g., a month, to avoid forcing infrequently-used modules to be
/// regenerated often.
unsigned ModuleCachePruneAfter;
unsigned ModuleCachePruneAfter = 31 * 24 * 60 * 60;
/// \brief The time in seconds when the build session started.
///
/// This time is used by other optimizations in header search and module
/// loading.
uint64_t BuildSessionTimestamp;
uint64_t BuildSessionTimestamp = 0;
/// \brief The set of macro names that should be ignored for the purposes
/// of computing the module hash.
@ -185,10 +204,8 @@ public:
unsigned ModulesHashContent : 1;
HeaderSearchOptions(StringRef _Sysroot = "/")
: Sysroot(_Sysroot), ModuleFormat("raw"), DisableModuleHash(0),
ImplicitModuleMaps(0), ModuleMapFileHomeIsCwd(0),
ModuleCachePruneInterval(7 * 24 * 60 * 60),
ModuleCachePruneAfter(31 * 24 * 60 * 60), BuildSessionTimestamp(0),
: Sysroot(_Sysroot), ModuleFormat("raw"), DisableModuleHash(false),
ImplicitModuleMaps(false), ModuleMapFileHomeIsCwd(false),
UseBuiltinIncludes(true), UseStandardSystemIncludes(true),
UseStandardCXXIncludes(true), UseLibcxx(false), Verbose(false),
ModulesValidateOncePerBuildSession(false),
@ -217,6 +234,6 @@ public:
}
};
} // end namespace clang
} // namespace clang
#endif
#endif // LLVM_CLANG_LEX_HEADERSEARCHOPTIONS_H

View File

@ -1,4 +1,4 @@
//===--- ModuleMap.h - Describe the layout of modules -----------*- C++ -*-===//
//===- ModuleMap.h - Describe the layout of modules -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -18,7 +18,6 @@
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerIntPair.h"
@ -28,20 +27,19 @@
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Twine.h"
#include <algorithm>
#include <ctime>
#include <memory>
#include <string>
#include <utility>
namespace clang {
class DiagnosticsEngine;
class DirectoryEntry;
class FileEntry;
class FileManager;
class DiagnosticConsumer;
class DiagnosticsEngine;
class HeaderSearch;
class ModuleMapParser;
class SourceManager;
/// \brief A mechanism to observe the actions of the module map parser as it
/// reads module map files.
@ -108,11 +106,14 @@ public:
enum ModuleHeaderRole {
/// \brief This header is normally included in the module.
NormalHeader = 0x0,
/// \brief This header is included but private.
PrivateHeader = 0x1,
/// \brief This header is part of the module (for layering purposes) but
/// should be textually included.
TextualHeader = 0x2,
// Caution: Adding an enumerator needs other changes.
// Adjust the number of bits for KnownHeader::Storage.
// Adjust the bitfield HeaderFileInfo::HeaderRole size.
@ -123,6 +124,7 @@ public:
/// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind);
/// Convert a header role to a kind.
static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role);
@ -132,8 +134,8 @@ public:
llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
public:
KnownHeader() : Storage(nullptr, NormalHeader) { }
KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) { }
KnownHeader() : Storage(nullptr, NormalHeader) {}
KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
return A.Storage == B.Storage;
@ -166,11 +168,13 @@ public:
}
};
typedef llvm::SmallPtrSet<const FileEntry *, 1> AdditionalModMapsSet;
using AdditionalModMapsSet = llvm::SmallPtrSet<const FileEntry *, 1>;
private:
typedef llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>
HeadersMap;
friend class ModuleMapParser;
using HeadersMap =
llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>;
/// \brief Mapping from each header to the module that owns the contents of
/// that header.
@ -178,6 +182,7 @@ private:
/// Map from file sizes to modules with lazy header directives of that size.
mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
/// Map from mtimes to modules with lazy header directives with those mtimes.
mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
LazyHeadersByModTime;
@ -192,9 +197,6 @@ private:
/// \brief The set of attributes that can be attached to a module.
struct Attributes {
Attributes()
: IsSystem(), IsExternC(), IsExhaustive(), NoUndeclaredIncludes() {}
/// \brief Whether this is a system module.
unsigned IsSystem : 1;
@ -207,12 +209,14 @@ private:
/// \brief Whether files in this module can only include non-modular headers
/// and headers from used modules.
unsigned NoUndeclaredIncludes : 1;
Attributes()
: IsSystem(false), IsExternC(false), IsExhaustive(false),
NoUndeclaredIncludes(false) {}
};
/// \brief A directory for which framework modules can be inferred.
struct InferredDirectory {
InferredDirectory() : InferModules() {}
/// \brief Whether to infer modules from this directory.
unsigned InferModules : 1;
@ -226,6 +230,8 @@ private:
/// \brief The names of modules that cannot be inferred within this
/// directory.
SmallVector<std::string, 2> ExcludedModules;
InferredDirectory() : InferModules(false) {}
};
/// \brief A mapping from directories to information about inferring
@ -242,8 +248,6 @@ private:
/// map.
llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
friend class ModuleMapParser;
/// \brief Resolve the given export declaration into an actual export
/// declaration.
///
@ -345,7 +349,6 @@ public:
HeaderSearch &HeaderInfo);
/// \brief Destroy the module map.
///
~ModuleMap();
/// \brief Set the target information.
@ -464,7 +467,7 @@ public:
/// \param Name The name of the module to find or create.
///
/// \param Parent The module that will act as the parent of this submodule,
/// or NULL to indicate that this is a top-level module.
/// or nullptr to indicate that this is a top-level module.
///
/// \param IsFramework Whether this is a framework module.
///
@ -505,7 +508,7 @@ public:
/// \param Module The module whose module map file will be returned, if known.
///
/// \returns The file entry for the module map file containing the given
/// module, or NULL if the module definition was inferred.
/// module, or nullptr if the module definition was inferred.
const FileEntry *getContainingModuleMapFile(const Module *Module) const;
/// \brief Get the module map file that (along with the module name) uniquely
@ -612,11 +615,12 @@ public:
/// \brief Dump the contents of the module map, for debugging purposes.
void dump();
typedef llvm::StringMap<Module *>::const_iterator module_iterator;
using module_iterator = llvm::StringMap<Module *>::const_iterator;
module_iterator module_begin() const { return Modules.begin(); }
module_iterator module_end() const { return Modules.end(); }
};
} // end namespace clang
} // namespace clang
#endif // LLVM_CLANG_LEX_MODULEMAP_H

View File

@ -1,4 +1,4 @@
//===--- PTHLexer.h - Lexer based on Pre-tokenized input --------*- C++ -*-===//
//===- PTHLexer.h - Lexer based on Pre-tokenized input ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -14,12 +14,15 @@
#ifndef LLVM_CLANG_LEX_PTHLEXER_H
#define LLVM_CLANG_LEX_PTHLEXER_H
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Lex/PreprocessorLexer.h"
#include "clang/Lex/Token.h"
namespace clang {
class Preprocessor;
class PTHManager;
class PTHSpellingSearch;
class PTHLexer : public PreprocessorLexer {
SourceLocation FileStartLoc;
@ -33,7 +36,7 @@ class PTHLexer : public PreprocessorLexer {
/// LastHashTokPtr - Pointer into TokBuf of the last processed '#'
/// token that appears at the start of a line.
const unsigned char* LastHashTokPtr;
const unsigned char* LastHashTokPtr = nullptr;
/// PPCond - Pointer to a side table in the PTH file that provides a
/// a concise summary of the preprocessor conditional block structure.
@ -44,11 +47,8 @@ class PTHLexer : public PreprocessorLexer {
/// to process when doing quick skipping of preprocessor blocks.
const unsigned char* CurPPCondPtr;
PTHLexer(const PTHLexer &) = delete;
void operator=(const PTHLexer &) = delete;
/// ReadToken - Used by PTHLexer to read tokens TokBuf.
void ReadToken(Token& T);
void ReadToken(Token &T);
bool LexEndOfFile(Token &Result);
@ -61,10 +61,13 @@ protected:
friend class PTHManager;
/// Create a PTHLexer for the specified token stream.
PTHLexer(Preprocessor& pp, FileID FID, const unsigned char *D,
PTHLexer(Preprocessor &pp, FileID FID, const unsigned char *D,
const unsigned char* ppcond, PTHManager &PM);
public:
~PTHLexer() override {}
PTHLexer(const PTHLexer &) = delete;
PTHLexer &operator=(const PTHLexer &) = delete;
~PTHLexer() override = default;
/// Lex - Return the next token.
bool Lex(Token &Tok);
@ -99,6 +102,6 @@ public:
bool SkipBlock();
};
} // end namespace clang
} // namespace clang
#endif
#endif // LLVM_CLANG_LEX_PTHLEXER_H

View File

@ -1,4 +1,4 @@
//===--- PTHManager.h - Manager object for PTH processing -------*- C++ -*-===//
//===- PTHManager.h - Manager object for PTH processing ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -17,30 +17,33 @@
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/OnDiskHashTable.h"
#include <memory>
namespace llvm {
class MemoryBuffer;
}
class MemoryBuffer;
} // namespace llvm
namespace clang {
class FileEntry;
class Preprocessor;
class PTHLexer;
class DiagnosticsEngine;
class FileSystemStatCache;
class Preprocessor;
class PTHLexer;
class PTHManager : public IdentifierInfoLookup {
friend class PTHLexer;
friend class PTHStatCache;
class PTHStringLookupTrait;
class PTHFileLookupTrait;
typedef llvm::OnDiskChainedHashTable<PTHStringLookupTrait> PTHStringIdLookup;
typedef llvm::OnDiskChainedHashTable<PTHFileLookupTrait> PTHFileLookup;
class PTHStringLookupTrait;
using PTHStringIdLookup = llvm::OnDiskChainedHashTable<PTHStringLookupTrait>;
using PTHFileLookup = llvm::OnDiskChainedHashTable<PTHFileLookupTrait>;
/// The memory mapped PTH file.
std::unique_ptr<const llvm::MemoryBuffer> Buf;
@ -70,7 +73,7 @@ class PTHManager : public IdentifierInfoLookup {
/// PP - The Preprocessor object that will use this PTHManager to create
/// PTHLexer objects.
Preprocessor* PP;
Preprocessor* PP = nullptr;
/// SpellingBase - The base offset within the PTH memory buffer that
/// contains the cached spellings for literals.
@ -89,16 +92,13 @@ class PTHManager : public IdentifierInfoLookup {
std::unique_ptr<PTHStringIdLookup> stringIdLookup, unsigned numIds,
const unsigned char *spellingBase, const char *originalSourceFile);
PTHManager(const PTHManager &) = delete;
void operator=(const PTHManager &) = delete;
/// getSpellingAtPTHOffset - Used by PTHLexer classes to get the cached
/// spelling for a token.
unsigned getSpellingAtPTHOffset(unsigned PTHOffset, const char*& Buffer);
/// GetIdentifierInfo - Used to reconstruct IdentifierInfo objects from the
/// PTH file.
inline IdentifierInfo* GetIdentifierInfo(unsigned PersistentID) {
IdentifierInfo *GetIdentifierInfo(unsigned PersistentID) {
// Check if the IdentifierInfo has already been resolved.
if (IdentifierInfo* II = PerIDCache[PersistentID])
return II;
@ -110,6 +110,8 @@ public:
// The current PTH version.
enum { Version = 10 };
PTHManager(const PTHManager &) = delete;
PTHManager &operator=(const PTHManager &) = delete;
~PTHManager() override;
/// getOriginalSourceFile - Return the full path to the original header
@ -120,18 +122,18 @@ public:
/// get - Return the identifier token info for the specified named identifier.
/// Unlike the version in IdentifierTable, this returns a pointer instead
/// of a reference. If the pointer is NULL then the IdentifierInfo cannot
/// of a reference. If the pointer is nullptr then the IdentifierInfo cannot
/// be found.
IdentifierInfo *get(StringRef Name) override;
/// Create - This method creates PTHManager objects. The 'file' argument
/// is the name of the PTH file. This method returns NULL upon failure.
/// is the name of the PTH file. This method returns nullptr upon failure.
static PTHManager *Create(StringRef file, DiagnosticsEngine &Diags);
void setPreprocessor(Preprocessor *pp) { PP = pp; }
/// CreateLexer - Return a PTHLexer that "lexes" the cached tokens for the
/// specified file. This method returns NULL if no cached tokens exist.
/// specified file. This method returns nullptr if no cached tokens exist.
/// It is the responsibility of the caller to 'delete' the returned object.
PTHLexer *CreateLexer(FileID FID);
@ -142,6 +144,6 @@ public:
std::unique_ptr<FileSystemStatCache> createStatCache();
};
} // end namespace clang
} // namespace clang
#endif
#endif // LLVM_CLANG_LEX_PTHMANAGER_H

View File

@ -1,4 +1,4 @@
//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
//===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
//
// The LLVM Compiler Infrastructure
//
@ -12,25 +12,38 @@
//===----------------------------------------------------------------------===//
#include "clang/Lex/HeaderSearch.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/VirtualFileSystem.h"
#include "clang/Lex/DirectoryLookup.h"
#include "clang/Lex/ExternalPreprocessorSource.h"
#include "clang/Lex/HeaderMap.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/ModuleMap.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Capacity.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <string>
#include <system_error>
#include <utility>
#if defined(LLVM_ON_UNIX)
#include <limits.h>
#endif
using namespace clang;
const IdentifierInfo *
@ -52,7 +65,7 @@ HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
return ControllingMacro;
}
ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
SourceManager &SourceMgr, DiagnosticsEngine &Diags,
@ -60,17 +73,7 @@ HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
const TargetInfo *Target)
: HSOpts(std::move(HSOpts)), Diags(Diags),
FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
AngledDirIdx = 0;
SystemDirIdx = 0;
NoCurDirSearch = false;
ExternalLookup = nullptr;
ExternalSource = nullptr;
NumIncluded = 0;
NumMultiIncludeFileOptzn = 0;
NumFrameworkLookups = NumSubFrameworkLookups = 0;
}
ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
HeaderSearch::~HeaderSearch() {
// Delete headermaps.
@ -142,27 +145,26 @@ std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
return i->second;
if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
return std::string();
return {};
// Then go through each prebuilt module directory and try to find the pcm
// file.
for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
SmallString<256> Result(Dir);
llvm::sys::fs::make_absolute(Result);
llvm::sys::path::append(Result, ModuleName + ".pcm");
if (getFileMgr().getFile(Result.str()))
return Result.str().str();
}
return std::string();
for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
SmallString<256> Result(Dir);
llvm::sys::fs::make_absolute(Result);
llvm::sys::path::append(Result, ModuleName + ".pcm");
if (getFileMgr().getFile(Result.str()))
return Result.str().str();
}
return {};
}
std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
StringRef ModuleMapPath) {
// If we don't have a module cache path or aren't supposed to use one, we
// can't do anything.
if (getModuleCachePath().empty())
return std::string();
return {};
SmallString<256> Result(getModuleCachePath());
llvm::sys::fs::make_absolute(Result);
@ -182,7 +184,7 @@ std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
Parent = ".";
auto *Dir = FileMgr.getDirectory(Parent);
if (!Dir)
return std::string();
return {};
auto DirName = FileMgr.getCanonicalName(Dir);
auto FileName = llvm::sys::path::filename(ModuleMapPath);
@ -381,7 +383,6 @@ const FileEntry *DirectoryLookup::LookupFile(
Filename = StringRef(MappedName.begin(), MappedName.size());
HasBeenMapped = true;
Result = HM->LookupFile(Filename, HS.getFileMgr());
} else {
Result = HS.getFileMgr().getFile(Dest);
}
@ -592,7 +593,6 @@ void HeaderSearch::setTarget(const TargetInfo &Target) {
ModMap.setTarget(Target);
}
//===----------------------------------------------------------------------===//
// Header File Location.
//===----------------------------------------------------------------------===//
@ -959,7 +959,6 @@ LookupSubframeworkHeader(StringRef Filename,
HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
// Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
HeadersFilename = FrameworkName;
HeadersFilename += "PrivateHeaders/";
@ -1116,7 +1115,7 @@ bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
// FIXME: this is a workaround for the lack of proper modules-aware support
// for #import / #pragma once
auto TryEnterImported = [&](void) -> bool {
auto TryEnterImported = [&]() -> bool {
if (!ModulesEnabled)
return false;
// Ensure FileInfo bits are up to date.
@ -1449,7 +1448,6 @@ Module *HeaderSearch::loadFrameworkModule(StringRef Name,
return ModMap.findModule(Name);
}
HeaderSearch::LoadModuleMapResult
HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
bool IsFramework) {

View File

@ -1,4 +1,4 @@
//===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===//
//===- ModuleMap.cpp - Describe the layout of modules ---------------------===//
//
// The LLVM Compiler Infrastructure
//
@ -11,29 +11,47 @@
// of a module as it relates to headers.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/ModuleMap.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/VirtualFileSystem.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/Token.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <stdlib.h>
#if defined(LLVM_ON_UNIX)
#include <limits.h>
#endif
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <string>
#include <system_error>
#include <utility>
using namespace clang;
Module::HeaderKind ModuleMap::headerRoleToKind(ModuleHeaderRole Role) {
@ -80,7 +98,7 @@ ModuleMap::resolveExport(Module *Mod,
// Resolve the module-id.
Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
if (!Context)
return Module::ExportDecl();
return {};
return Module::ExportDecl(Context, Unresolved.Wildcard);
}
@ -344,7 +362,7 @@ ModuleMap::KnownHeader
ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
if (UmbrellaDirs.empty())
return KnownHeader();
return {};
const DirectoryEntry *Dir = File->getDir();
assert(Dir && "file in no directory");
@ -372,7 +390,7 @@ ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
// Resolve the parent path to a directory entry.
Dir = SourceMgr.getFileManager().getDirectory(DirName);
} while (Dir);
return KnownHeader();
return {};
}
static bool violatesPrivateInclude(Module *RequestingModule,
@ -502,7 +520,7 @@ ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File,
bool AllowTextual) {
auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
return ModuleMap::KnownHeader();
return {};
return R;
};
@ -592,7 +610,7 @@ ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
return Header;
}
return KnownHeader();
return {};
}
ArrayRef<ModuleMap::KnownHeader>
@ -1188,6 +1206,7 @@ bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
//----------------------------------------------------------------------------//
namespace clang {
/// \brief A token in a module map file.
struct MMToken {
enum TokenKind {
@ -1226,6 +1245,7 @@ namespace clang {
union {
// If Kind != IntegerLiteral.
const char *StringData;
// If Kind == IntegerLiteral.
uint64_t IntegerValue;
};
@ -1275,7 +1295,7 @@ namespace clang {
bool IsSystem;
/// \brief Whether an error occurred.
bool HadError;
bool HadError = false;
/// \brief Stores string data for the various string literals referenced
/// during parsing.
@ -1285,7 +1305,7 @@ namespace clang {
MMToken Tok;
/// \brief The active module.
Module *ActiveModule;
Module *ActiveModule = nullptr;
/// \brief Whether a module uses the 'requires excluded' hack to mark its
/// contents as 'textual'.
@ -1304,13 +1324,13 @@ namespace clang {
/// (or the end of the file).
void skipUntil(MMToken::TokenKind K);
typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
bool parseModuleId(ModuleId &Id);
void parseModuleDecl();
void parseExternModuleDecl();
void parseRequiresDecl();
void parseHeaderDecl(clang::MMToken::TokenKind,
SourceLocation LeadingLoc);
void parseHeaderDecl(MMToken::TokenKind, SourceLocation LeadingLoc);
void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
void parseExportDecl();
void parseExportAsDecl();
@ -1320,7 +1340,8 @@ namespace clang {
void parseConflict();
void parseInferredModuleDecl(bool Framework, bool Explicit);
typedef ModuleMap::Attributes Attributes;
using Attributes = ModuleMap::Attributes;
bool parseOptionalAttributes(Attributes &Attrs);
public:
@ -1331,10 +1352,9 @@ namespace clang {
const FileEntry *ModuleMapFile,
const DirectoryEntry *Directory,
bool IsSystem)
: L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
ModuleMapFile(ModuleMapFile), Directory(Directory),
IsSystem(IsSystem), HadError(false), ActiveModule(nullptr)
{
: L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
ModuleMapFile(ModuleMapFile), Directory(Directory),
IsSystem(IsSystem) {
Tok.clear();
consumeToken();
}
@ -1344,7 +1364,8 @@ namespace clang {
bool terminatedByDirective() { return false; }
SourceLocation getLocation() { return Tok.getLocation(); }
};
}
} // namespace clang
SourceLocation ModuleMapParser::consumeToken() {
SourceLocation Result = Tok.getLocation();
@ -1566,20 +1587,26 @@ bool ModuleMapParser::parseModuleId(ModuleId &Id) {
}
namespace {
/// \brief Enumerates the known attributes.
enum AttributeKind {
/// \brief An unknown attribute.
AT_unknown,
/// \brief The 'system' attribute.
AT_system,
/// \brief The 'extern_c' attribute.
AT_extern_c,
/// \brief The 'exhaustive' attribute.
AT_exhaustive,
/// \brief The 'no_undeclared_includes' attribute.
AT_no_undeclared_includes
};
}
} // namespace
/// \brief Parse a module declaration.
///
@ -1702,7 +1729,6 @@ void ModuleMapParser::parseModuleDecl() {
if (parseOptionalAttributes(Attrs))
return;
// Parse the opening brace.
if (!Tok.is(MMToken::LBrace)) {
Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
@ -2574,7 +2600,7 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
Done = true;
break;
case MMToken::ExcludeKeyword: {
case MMToken::ExcludeKeyword:
if (ActiveModule) {
Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
<< (ActiveModule != nullptr);
@ -2593,7 +2619,6 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
.push_back(Tok.getString());
consumeToken();
break;
}
case MMToken::ExportKeyword:
if (!ActiveModule) {

View File

@ -1,4 +1,4 @@
//===--- PTHLexer.cpp - Lex from a token stream ---------------------------===//
//===- PTHLexer.cpp - Lex from a token stream -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
@ -12,19 +12,32 @@
//===----------------------------------------------------------------------===//
#include "clang/Lex/PTHLexer.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemStatCache.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/PTHManager.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/Token.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/OnDiskHashTable.h"
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <memory>
#include <system_error>
#include <utility>
using namespace clang;
static const unsigned StoredTokenSize = 1 + 1 + 2 + 4 + 4;
@ -35,9 +48,8 @@ static const unsigned StoredTokenSize = 1 + 1 + 2 + 4 + 4;
PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
const unsigned char *ppcond, PTHManager &PM)
: PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(nullptr),
PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) {
: PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), PPCond(ppcond),
CurPPCondPtr(ppcond), PTHMgr(PM) {
FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
}
@ -167,7 +179,7 @@ void PTHLexer::DiscardToEndOfLine() {
// We don't need to actually reconstruct full tokens from the token buffer.
// This saves some copies and it also reduces IdentifierInfo* lookup.
const unsigned char* p = CurPtr;
while (1) {
while (true) {
// Read the token kind. Are we at the end of the file?
tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
if (x == tok::eof) break;
@ -186,6 +198,7 @@ void PTHLexer::DiscardToEndOfLine() {
/// SkipBlock - Used by Preprocessor to skip the current conditional block.
bool PTHLexer::SkipBlock() {
using namespace llvm::support;
assert(CurPPCondPtr && "No cached PP conditional information.");
assert(LastHashTokPtr && "No known '#' token.");
@ -303,23 +316,24 @@ SourceLocation PTHLexer::getSourceLocation() {
/// to map from FileEntry objects managed by FileManager to offsets within
/// the PTH file.
namespace {
class PTHFileData {
const uint32_t TokenOff;
const uint32_t PPCondOff;
public:
PTHFileData(uint32_t tokenOff, uint32_t ppCondOff)
: TokenOff(tokenOff), PPCondOff(ppCondOff) {}
: TokenOff(tokenOff), PPCondOff(ppCondOff) {}
uint32_t getTokenOffset() const { return TokenOff; }
uint32_t getPPCondOffset() const { return PPCondOff; }
};
class PTHFileLookupCommonTrait {
public:
typedef std::pair<unsigned char, StringRef> internal_key_type;
typedef unsigned hash_value_type;
typedef unsigned offset_type;
using internal_key_type = std::pair<unsigned char, StringRef>;
using hash_value_type = unsigned;
using offset_type = unsigned;
static hash_value_type ComputeHash(internal_key_type x) {
return llvm::HashString(x.second);
@ -328,6 +342,7 @@ public:
static std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char*& d) {
using namespace llvm::support;
unsigned keyLen =
(unsigned)endian::readNext<uint16_t, little, unaligned>(d);
unsigned dataLen = (unsigned) *(d++);
@ -340,12 +355,12 @@ public:
}
};
} // end anonymous namespace
} // namespace
class PTHManager::PTHFileLookupTrait : public PTHFileLookupCommonTrait {
public:
typedef const FileEntry* external_key_type;
typedef PTHFileData data_type;
using external_key_type = const FileEntry *;
using data_type = PTHFileData;
static internal_key_type GetInternalKey(const FileEntry* FE) {
return std::make_pair((unsigned char) 0x1, FE->getName());
@ -357,8 +372,9 @@ public:
static PTHFileData ReadData(const internal_key_type& k,
const unsigned char* d, unsigned) {
assert(k.first == 0x1 && "Only file lookups can match!");
using namespace llvm::support;
assert(k.first == 0x1 && "Only file lookups can match!");
uint32_t x = endian::readNext<uint32_t, little, unaligned>(d);
uint32_t y = endian::readNext<uint32_t, little, unaligned>(d);
return PTHFileData(x, y);
@ -367,11 +383,11 @@ public:
class PTHManager::PTHStringLookupTrait {
public:
typedef uint32_t data_type;
typedef const std::pair<const char*, unsigned> external_key_type;
typedef external_key_type internal_key_type;
typedef uint32_t hash_value_type;
typedef unsigned offset_type;
using data_type = uint32_t;
using external_key_type = const std::pair<const char *, unsigned>;
using internal_key_type = external_key_type;
using hash_value_type = uint32_t;
using offset_type = unsigned;
static bool EqualKey(const internal_key_type& a,
const internal_key_type& b) {
@ -390,6 +406,7 @@ public:
static std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char*& d) {
using namespace llvm::support;
return std::make_pair(
(unsigned)endian::readNext<uint16_t, little, unaligned>(d),
sizeof(uint32_t));
@ -404,6 +421,7 @@ public:
static uint32_t ReadData(const internal_key_type& k, const unsigned char* d,
unsigned) {
using namespace llvm::support;
return endian::readNext<uint32_t, little, unaligned>(d);
}
};
@ -420,11 +438,10 @@ PTHManager::PTHManager(
const unsigned char *spellingBase, const char *originalSourceFile)
: Buf(std::move(buf)), PerIDCache(std::move(perIDCache)),
FileLookup(std::move(fileLookup)), IdDataTable(idDataTable),
StringIdLookup(std::move(stringIdLookup)), NumIds(numIds), PP(nullptr),
StringIdLookup(std::move(stringIdLookup)), NumIds(numIds),
SpellingBase(spellingBase), OriginalSourceFile(originalSourceFile) {}
PTHManager::~PTHManager() {
}
PTHManager::~PTHManager() = default;
static void InvalidPTH(DiagnosticsEngine &Diags, const char *Msg) {
Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0")) << Msg;
@ -557,6 +574,7 @@ PTHManager *PTHManager::Create(StringRef file, DiagnosticsEngine &Diags) {
IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
using namespace llvm::support;
// Look in the PTH file for the string data for the IdentifierInfo object.
const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
const unsigned char *IDData =
@ -566,7 +584,7 @@ IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
// Allocate the object.
std::pair<IdentifierInfo,const unsigned char*> *Mem =
Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
Alloc.Allocate<std::pair<IdentifierInfo, const unsigned char *>>();
Mem->second = IDData;
assert(IDData[0] != '\0');
@ -626,26 +644,26 @@ PTHLexer *PTHManager::CreateLexer(FileID FID) {
//===----------------------------------------------------------------------===//
namespace {
class PTHStatData {
public:
uint64_t Size;
time_t ModTime;
llvm::sys::fs::UniqueID UniqueID;
const bool HasData;
const bool HasData = false;
bool IsDirectory;
PTHStatData() = default;
PTHStatData(uint64_t Size, time_t ModTime, llvm::sys::fs::UniqueID UniqueID,
bool IsDirectory)
: Size(Size), ModTime(ModTime), UniqueID(UniqueID), HasData(true),
IsDirectory(IsDirectory) {}
PTHStatData() : HasData(false) {}
};
class PTHStatLookupTrait : public PTHFileLookupCommonTrait {
public:
typedef StringRef external_key_type; // const char*
typedef PTHStatData data_type;
using external_key_type = StringRef; // const char*
using data_type = PTHStatData;
static internal_key_type GetInternalKey(StringRef path) {
// The key 'kind' doesn't matter here because it is ignored in EqualKey.
@ -660,7 +678,6 @@ public:
static data_type ReadData(const internal_key_type& k, const unsigned char* d,
unsigned) {
if (k.first /* File or Directory */) {
bool IsDirectory = true;
if (k.first == 0x1 /* File */) {
@ -682,11 +699,14 @@ public:
return data_type();
}
};
} // end anonymous namespace
} // namespace
namespace clang {
class PTHStatCache : public FileSystemStatCache {
typedef llvm::OnDiskChainedHashTable<PTHStatLookupTrait> CacheTy;
using CacheTy = llvm::OnDiskChainedHashTable<PTHStatLookupTrait>;
CacheTy Cache;
public:
@ -720,7 +740,8 @@ public:
return CacheExists;
}
};
}
} // namespace clang
std::unique_ptr<FileSystemStatCache> PTHManager::createStatCache() {
return llvm::make_unique<PTHStatCache>(*FileLookup);