1 //===- HeaderSearch.h - Resolve Header File Locations -----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the HeaderSearch interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CLANG_LEX_HEADERSEARCH_H 15 #define LLVM_CLANG_LEX_HEADERSEARCH_H 16 17 #include "clang/Basic/SourceLocation.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Lex/DirectoryLookup.h" 20 #include "clang/Lex/HeaderMap.h" 21 #include "clang/Lex/ModuleMap.h" 22 #include "llvm/ADT/ArrayRef.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/ADT/StringSet.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/Support/Allocator.h" 28 #include <cassert> 29 #include <cstddef> 30 #include <memory> 31 #include <string> 32 #include <utility> 33 #include <vector> 34 35 namespace clang { 36 37 class DiagnosticsEngine; 38 class DirectoryEntry; 39 class ExternalPreprocessorSource; 40 class FileEntry; 41 class FileManager; 42 class HeaderSearchOptions; 43 class IdentifierInfo; 44 class LangOptions; 45 class Module; 46 class Preprocessor; 47 class TargetInfo; 48 49 /// The preprocessor keeps track of this information for each 50 /// file that is \#included. 51 struct HeaderFileInfo { 52 /// True if this is a \#import'd or \#pragma once file. 53 unsigned isImport : 1; 54 55 /// True if this is a \#pragma once file. 56 unsigned isPragmaOnce : 1; 57 58 /// Keep track of whether this is a system header, and if so, 59 /// whether it is C++ clean or not. This can be set by the include paths or 60 /// by \#pragma gcc system_header. This is an instance of 61 /// SrcMgr::CharacteristicKind. 62 unsigned DirInfo : 3; 63 64 /// Whether this header file info was supplied by an external source, 65 /// and has not changed since. 66 unsigned External : 1; 67 68 /// Whether this header is part of a module. 69 unsigned isModuleHeader : 1; 70 71 /// Whether this header is part of the module that we are building. 72 unsigned isCompilingModuleHeader : 1; 73 74 /// Whether this structure is considered to already have been 75 /// "resolved", meaning that it was loaded from the external source. 76 unsigned Resolved : 1; 77 78 /// Whether this is a header inside a framework that is currently 79 /// being built. 80 /// 81 /// When a framework is being built, the headers have not yet been placed 82 /// into the appropriate framework subdirectories, and therefore are 83 /// provided via a header map. This bit indicates when this is one of 84 /// those framework headers. 85 unsigned IndexHeaderMapHeader : 1; 86 87 /// Whether this file has been looked up as a header. 88 unsigned IsValid : 1; 89 90 /// The number of times the file has been included already. 91 unsigned short NumIncludes = 0; 92 93 /// The ID number of the controlling macro. 94 /// 95 /// This ID number will be non-zero when there is a controlling 96 /// macro whose IdentifierInfo may not yet have been loaded from 97 /// external storage. 98 unsigned ControllingMacroID = 0; 99 100 /// If this file has a \#ifndef XXX (or equivalent) guard that 101 /// protects the entire contents of the file, this is the identifier 102 /// for the macro that controls whether or not it has any effect. 103 /// 104 /// Note: Most clients should use getControllingMacro() to access 105 /// the controlling macro of this header, since 106 /// getControllingMacro() is able to load a controlling macro from 107 /// external storage. 108 const IdentifierInfo *ControllingMacro = nullptr; 109 110 /// If this header came from a framework include, this is the name 111 /// of the framework. 112 StringRef Framework; 113 HeaderFileInfoHeaderFileInfo114 HeaderFileInfo() 115 : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User), 116 External(false), isModuleHeader(false), isCompilingModuleHeader(false), 117 Resolved(false), IndexHeaderMapHeader(false), IsValid(false) {} 118 119 /// Retrieve the controlling macro for this header file, if 120 /// any. 121 const IdentifierInfo * 122 getControllingMacro(ExternalPreprocessorSource *External); 123 124 /// Determine whether this is a non-default header file info, e.g., 125 /// it corresponds to an actual header we've included or tried to include. isNonDefaultHeaderFileInfo126 bool isNonDefault() const { 127 return isImport || isPragmaOnce || NumIncludes || ControllingMacro || 128 ControllingMacroID; 129 } 130 }; 131 132 /// An external source of header file information, which may supply 133 /// information about header files already included. 134 class ExternalHeaderFileInfoSource { 135 public: 136 virtual ~ExternalHeaderFileInfoSource(); 137 138 /// Retrieve the header file information for the given file entry. 139 /// 140 /// \returns Header file information for the given file entry, with the 141 /// \c External bit set. If the file entry is not known, return a 142 /// default-constructed \c HeaderFileInfo. 143 virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0; 144 }; 145 146 /// Encapsulates the information needed to find the file referenced 147 /// by a \#include or \#include_next, (sub-)framework lookup, etc. 148 class HeaderSearch { 149 friend class DirectoryLookup; 150 151 /// This structure is used to record entries in our framework cache. 152 struct FrameworkCacheEntry { 153 /// The directory entry which should be used for the cached framework. 154 const DirectoryEntry *Directory; 155 156 /// Whether this framework has been "user-specified" to be treated as if it 157 /// were a system framework (even if it was found outside a system framework 158 /// directory). 159 bool IsUserSpecifiedSystemFramework; 160 }; 161 162 /// Header-search options used to initialize this header search. 163 std::shared_ptr<HeaderSearchOptions> HSOpts; 164 165 DiagnosticsEngine &Diags; 166 FileManager &FileMgr; 167 168 /// \#include search path information. Requests for \#include "x" search the 169 /// directory of the \#including file first, then each directory in SearchDirs 170 /// consecutively. Requests for <x> search the current dir first, then each 171 /// directory in SearchDirs, starting at AngledDirIdx, consecutively. If 172 /// NoCurDirSearch is true, then the check for the file in the current 173 /// directory is suppressed. 174 std::vector<DirectoryLookup> SearchDirs; 175 unsigned AngledDirIdx = 0; 176 unsigned SystemDirIdx = 0; 177 bool NoCurDirSearch = false; 178 179 /// \#include prefixes for which the 'system header' property is 180 /// overridden. 181 /// 182 /// For a \#include "x" or \#include \<x> directive, the last string in this 183 /// list which is a prefix of 'x' determines whether the file is treated as 184 /// a system header. 185 std::vector<std::pair<std::string, bool>> SystemHeaderPrefixes; 186 187 /// The path to the module cache. 188 std::string ModuleCachePath; 189 190 /// All of the preprocessor-specific data about files that are 191 /// included, indexed by the FileEntry's UID. 192 mutable std::vector<HeaderFileInfo> FileInfo; 193 194 /// Keeps track of each lookup performed by LookupFile. 195 struct LookupFileCacheInfo { 196 /// Starting index in SearchDirs that the cached search was performed from. 197 /// If there is a hit and this value doesn't match the current query, the 198 /// cache has to be ignored. 199 unsigned StartIdx = 0; 200 201 /// The entry in SearchDirs that satisfied the query. 202 unsigned HitIdx = 0; 203 204 /// This is non-null if the original filename was mapped to a framework 205 /// include via a headermap. 206 const char *MappedName = nullptr; 207 208 /// Default constructor -- Initialize all members with zero. 209 LookupFileCacheInfo() = default; 210 resetLookupFileCacheInfo211 void reset(unsigned StartIdx) { 212 this->StartIdx = StartIdx; 213 this->MappedName = nullptr; 214 } 215 }; 216 llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache; 217 218 /// Collection mapping a framework or subframework 219 /// name like "Carbon" to the Carbon.framework directory. 220 llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap; 221 222 /// Maps include file names (including the quotes or 223 /// angle brackets) to other include file names. This is used to support the 224 /// include_alias pragma for Microsoft compatibility. 225 using IncludeAliasMap = 226 llvm::StringMap<std::string, llvm::BumpPtrAllocator>; 227 std::unique_ptr<IncludeAliasMap> IncludeAliases; 228 229 /// This is a mapping from FileEntry -> HeaderMap, uniquing headermaps. 230 std::vector<std::pair<const FileEntry *, std::unique_ptr<HeaderMap>>> HeaderMaps; 231 232 /// The mapping between modules and headers. 233 mutable ModuleMap ModMap; 234 235 /// Describes whether a given directory has a module map in it. 236 llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap; 237 238 /// Set of module map files we've already loaded, and a flag indicating 239 /// whether they were valid or not. 240 llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps; 241 242 /// Uniqued set of framework names, which is used to track which 243 /// headers were included as framework headers. 244 llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames; 245 246 /// Entity used to resolve the identifier IDs of controlling 247 /// macros into IdentifierInfo pointers, and keep the identifire up to date, 248 /// as needed. 249 ExternalPreprocessorSource *ExternalLookup = nullptr; 250 251 /// Entity used to look up stored header file information. 252 ExternalHeaderFileInfoSource *ExternalSource = nullptr; 253 254 // Various statistics we track for performance analysis. 255 unsigned NumIncluded = 0; 256 unsigned NumMultiIncludeFileOptzn = 0; 257 unsigned NumFrameworkLookups = 0; 258 unsigned NumSubFrameworkLookups = 0; 259 260 public: 261 HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts, 262 SourceManager &SourceMgr, DiagnosticsEngine &Diags, 263 const LangOptions &LangOpts, const TargetInfo *Target); 264 HeaderSearch(const HeaderSearch &) = delete; 265 HeaderSearch &operator=(const HeaderSearch &) = delete; 266 267 /// Retrieve the header-search options with which this header search 268 /// was initialized. getHeaderSearchOpts()269 HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; } 270 getFileMgr()271 FileManager &getFileMgr() const { return FileMgr; } 272 getDiags()273 DiagnosticsEngine &getDiags() const { return Diags; } 274 275 /// Interface for setting the file search paths. SetSearchPaths(const std::vector<DirectoryLookup> & dirs,unsigned angledDirIdx,unsigned systemDirIdx,bool noCurDirSearch)276 void SetSearchPaths(const std::vector<DirectoryLookup> &dirs, 277 unsigned angledDirIdx, unsigned systemDirIdx, 278 bool noCurDirSearch) { 279 assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() && 280 "Directory indices are unordered"); 281 SearchDirs = dirs; 282 AngledDirIdx = angledDirIdx; 283 SystemDirIdx = systemDirIdx; 284 NoCurDirSearch = noCurDirSearch; 285 //LookupFileCache.clear(); 286 } 287 288 /// Add an additional search path. AddSearchPath(const DirectoryLookup & dir,bool isAngled)289 void AddSearchPath(const DirectoryLookup &dir, bool isAngled) { 290 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx; 291 SearchDirs.insert(SearchDirs.begin() + idx, dir); 292 if (!isAngled) 293 AngledDirIdx++; 294 SystemDirIdx++; 295 } 296 297 /// Set the list of system header prefixes. SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string,bool>> P)298 void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool>> P) { 299 SystemHeaderPrefixes.assign(P.begin(), P.end()); 300 } 301 302 /// Checks whether the map exists or not. HasIncludeAliasMap()303 bool HasIncludeAliasMap() const { return (bool)IncludeAliases; } 304 305 /// Map the source include name to the dest include name. 306 /// 307 /// The Source should include the angle brackets or quotes, the dest 308 /// should not. This allows for distinction between <> and "" headers. AddIncludeAlias(StringRef Source,StringRef Dest)309 void AddIncludeAlias(StringRef Source, StringRef Dest) { 310 if (!IncludeAliases) 311 IncludeAliases.reset(new IncludeAliasMap); 312 (*IncludeAliases)[Source] = Dest; 313 } 314 315 /// Maps one header file name to a different header 316 /// file name, for use with the include_alias pragma. Note that the source 317 /// file name should include the angle brackets or quotes. Returns StringRef 318 /// as null if the header cannot be mapped. MapHeaderToIncludeAlias(StringRef Source)319 StringRef MapHeaderToIncludeAlias(StringRef Source) { 320 assert(IncludeAliases && "Trying to map headers when there's no map"); 321 322 // Do any filename replacements before anything else 323 IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source); 324 if (Iter != IncludeAliases->end()) 325 return Iter->second; 326 return {}; 327 } 328 329 /// Set the path to the module cache. setModuleCachePath(StringRef CachePath)330 void setModuleCachePath(StringRef CachePath) { 331 ModuleCachePath = CachePath; 332 } 333 334 /// Retrieve the path to the module cache. getModuleCachePath()335 StringRef getModuleCachePath() const { return ModuleCachePath; } 336 337 /// Consider modules when including files from this directory. setDirectoryHasModuleMap(const DirectoryEntry * Dir)338 void setDirectoryHasModuleMap(const DirectoryEntry* Dir) { 339 DirectoryHasModuleMap[Dir] = true; 340 } 341 342 /// Forget everything we know about headers so far. ClearFileInfo()343 void ClearFileInfo() { 344 FileInfo.clear(); 345 } 346 SetExternalLookup(ExternalPreprocessorSource * EPS)347 void SetExternalLookup(ExternalPreprocessorSource *EPS) { 348 ExternalLookup = EPS; 349 } 350 getExternalLookup()351 ExternalPreprocessorSource *getExternalLookup() const { 352 return ExternalLookup; 353 } 354 355 /// Set the external source of header information. SetExternalSource(ExternalHeaderFileInfoSource * ES)356 void SetExternalSource(ExternalHeaderFileInfoSource *ES) { 357 ExternalSource = ES; 358 } 359 360 /// Set the target information for the header search, if not 361 /// already known. 362 void setTarget(const TargetInfo &Target); 363 364 /// Given a "foo" or \<foo> reference, look up the indicated file, 365 /// return null on failure. 366 /// 367 /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member 368 /// the file was found in, or null if not applicable. 369 /// 370 /// \param IncludeLoc Used for diagnostics if valid. 371 /// 372 /// \param isAngled indicates whether the file reference is a <> reference. 373 /// 374 /// \param CurDir If non-null, the file was found in the specified directory 375 /// search location. This is used to implement \#include_next. 376 /// 377 /// \param Includers Indicates where the \#including file(s) are, in case 378 /// relative searches are needed. In reverse order of inclusion. 379 /// 380 /// \param SearchPath If non-null, will be set to the search path relative 381 /// to which the file was found. If the include path is absolute, SearchPath 382 /// will be set to an empty string. 383 /// 384 /// \param RelativePath If non-null, will be set to the path relative to 385 /// SearchPath at which the file was found. This only differs from the 386 /// Filename for framework includes. 387 /// 388 /// \param SuggestedModule If non-null, and the file found is semantically 389 /// part of a known module, this will be set to the module that should 390 /// be imported instead of preprocessing/parsing the file found. 391 /// 392 /// \param IsMapped If non-null, and the search involved header maps, set to 393 /// true. 394 const FileEntry *LookupFile( 395 StringRef Filename, SourceLocation IncludeLoc, bool isAngled, 396 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, 397 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers, 398 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 399 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, 400 bool *IsMapped, bool SkipCache = false, bool BuildSystemModule = false); 401 402 /// Look up a subframework for the specified \#include file. 403 /// 404 /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from 405 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if 406 /// HIToolbox is a subframework within Carbon.framework. If so, return 407 /// the FileEntry for the designated file, otherwise return null. 408 const FileEntry *LookupSubframeworkHeader( 409 StringRef Filename, const FileEntry *ContextFileEnt, 410 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 411 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule); 412 413 /// Look up the specified framework name in our framework cache. 414 /// \returns The DirectoryEntry it is in if we know, null otherwise. LookupFrameworkCache(StringRef FWName)415 FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) { 416 return FrameworkMap[FWName]; 417 } 418 419 /// Mark the specified file as a target of a \#include, 420 /// \#include_next, or \#import directive. 421 /// 422 /// \return false if \#including the file will have no effect or true 423 /// if we should include it. 424 bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File, 425 bool isImport, bool ModulesEnabled, 426 Module *M); 427 428 /// Return whether the specified file is a normal header, 429 /// a system header, or a C++ friendly system header. getFileDirFlavor(const FileEntry * File)430 SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) { 431 return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo; 432 } 433 434 /// Mark the specified file as a "once only" file, e.g. due to 435 /// \#pragma once. MarkFileIncludeOnce(const FileEntry * File)436 void MarkFileIncludeOnce(const FileEntry *File) { 437 HeaderFileInfo &FI = getFileInfo(File); 438 FI.isImport = true; 439 FI.isPragmaOnce = true; 440 } 441 442 /// Mark the specified file as a system header, e.g. due to 443 /// \#pragma GCC system_header. MarkFileSystemHeader(const FileEntry * File)444 void MarkFileSystemHeader(const FileEntry *File) { 445 getFileInfo(File).DirInfo = SrcMgr::C_System; 446 } 447 448 /// Mark the specified file as part of a module. 449 void MarkFileModuleHeader(const FileEntry *FE, 450 ModuleMap::ModuleHeaderRole Role, 451 bool isCompilingModuleHeader); 452 453 /// Increment the count for the number of times the specified 454 /// FileEntry has been entered. IncrementIncludeCount(const FileEntry * File)455 void IncrementIncludeCount(const FileEntry *File) { 456 ++getFileInfo(File).NumIncludes; 457 } 458 459 /// Mark the specified file as having a controlling macro. 460 /// 461 /// This is used by the multiple-include optimization to eliminate 462 /// no-op \#includes. SetFileControllingMacro(const FileEntry * File,const IdentifierInfo * ControllingMacro)463 void SetFileControllingMacro(const FileEntry *File, 464 const IdentifierInfo *ControllingMacro) { 465 getFileInfo(File).ControllingMacro = ControllingMacro; 466 } 467 468 /// Return true if this is the first time encountering this header. FirstTimeLexingFile(const FileEntry * File)469 bool FirstTimeLexingFile(const FileEntry *File) { 470 return getFileInfo(File).NumIncludes == 1; 471 } 472 473 /// Determine whether this file is intended to be safe from 474 /// multiple inclusions, e.g., it has \#pragma once or a controlling 475 /// macro. 476 /// 477 /// This routine does not consider the effect of \#import 478 bool isFileMultipleIncludeGuarded(const FileEntry *File); 479 480 /// This method returns a HeaderMap for the specified 481 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure. 482 const HeaderMap *CreateHeaderMap(const FileEntry *FE); 483 484 /// Get filenames for all registered header maps. 485 void getHeaderMapFileNames(SmallVectorImpl<std::string> &Names) const; 486 487 /// Retrieve the name of the cached module file that should be used 488 /// to load the given module. 489 /// 490 /// \param Module The module whose module file name will be returned. 491 /// 492 /// \returns The name of the module file that corresponds to this module, 493 /// or an empty string if this module does not correspond to any module file. 494 std::string getCachedModuleFileName(Module *Module); 495 496 /// Retrieve the name of the prebuilt module file that should be used 497 /// to load a module with the given name. 498 /// 499 /// \param ModuleName The module whose module file name will be returned. 500 /// 501 /// \param FileMapOnly If true, then only look in the explicit module name 502 // to file name map and skip the directory search. 503 /// 504 /// \returns The name of the module file that corresponds to this module, 505 /// or an empty string if this module does not correspond to any module file. 506 std::string getPrebuiltModuleFileName(StringRef ModuleName, 507 bool FileMapOnly = false); 508 509 /// Retrieve the name of the (to-be-)cached module file that should 510 /// be used to load a module with the given name. 511 /// 512 /// \param ModuleName The module whose module file name will be returned. 513 /// 514 /// \param ModuleMapPath A path that when combined with \c ModuleName 515 /// uniquely identifies this module. See Module::ModuleMap. 516 /// 517 /// \returns The name of the module file that corresponds to this module, 518 /// or an empty string if this module does not correspond to any module file. 519 std::string getCachedModuleFileName(StringRef ModuleName, 520 StringRef ModuleMapPath); 521 522 /// Lookup a module Search for a module with the given name. 523 /// 524 /// \param ModuleName The name of the module we're looking for. 525 /// 526 /// \param AllowSearch Whether we are allowed to search in the various 527 /// search directories to produce a module definition. If not, this lookup 528 /// will only return an already-known module. 529 /// 530 /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps 531 /// in subdirectories. 532 /// 533 /// \returns The module with the given name. 534 Module *lookupModule(StringRef ModuleName, bool AllowSearch = true, 535 bool AllowExtraModuleMapSearch = false); 536 537 /// Try to find a module map file in the given directory, returning 538 /// \c nullptr if none is found. 539 const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir, 540 bool IsFramework); 541 IncrementFrameworkLookupCount()542 void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; } 543 544 /// Determine whether there is a module map that may map the header 545 /// with the given file name to a (sub)module. 546 /// Always returns false if modules are disabled. 547 /// 548 /// \param Filename The name of the file. 549 /// 550 /// \param Root The "root" directory, at which we should stop looking for 551 /// module maps. 552 /// 553 /// \param IsSystem Whether the directories we're looking at are system 554 /// header directories. 555 bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root, 556 bool IsSystem); 557 558 /// Retrieve the module that corresponds to the given file, if any. 559 /// 560 /// \param File The header that we wish to map to a module. 561 /// \param AllowTextual Whether we want to find textual headers too. 562 ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File, 563 bool AllowTextual = false) const; 564 565 /// Read the contents of the given module map file. 566 /// 567 /// \param File The module map file. 568 /// \param IsSystem Whether this file is in a system header directory. 569 /// \param ID If the module map file is already mapped (perhaps as part of 570 /// processing a preprocessed module), the ID of the file. 571 /// \param Offset [inout] An offset within ID to start parsing. On exit, 572 /// filled by the end of the parsed contents (either EOF or the 573 /// location of an end-of-module-map pragma). 574 /// \param OriginalModuleMapFile The original path to the module map file, 575 /// used to resolve paths within the module (this is required when 576 /// building the module from preprocessed source). 577 /// \returns true if an error occurred, false otherwise. 578 bool loadModuleMapFile(const FileEntry *File, bool IsSystem, 579 FileID ID = FileID(), unsigned *Offset = nullptr, 580 StringRef OriginalModuleMapFile = StringRef()); 581 582 /// Collect the set of all known, top-level modules. 583 /// 584 /// \param Modules Will be filled with the set of known, top-level modules. 585 void collectAllModules(SmallVectorImpl<Module *> &Modules); 586 587 /// Load all known, top-level system modules. 588 void loadTopLevelSystemModules(); 589 590 private: 591 /// Lookup a module with the given module name and search-name. 592 /// 593 /// \param ModuleName The name of the module we're looking for. 594 /// 595 /// \param SearchName The "search-name" to derive filesystem paths from 596 /// when looking for the module map; this is usually equal to ModuleName, 597 /// but for compatibility with some buggy frameworks, additional attempts 598 /// may be made to find the module under a related-but-different search-name. 599 /// 600 /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps 601 /// in subdirectories. 602 /// 603 /// \returns The module named ModuleName. 604 Module *lookupModule(StringRef ModuleName, StringRef SearchName, 605 bool AllowExtraModuleMapSearch = false); 606 607 /// Retrieve a module with the given name, which may be part of the 608 /// given framework. 609 /// 610 /// \param Name The name of the module to retrieve. 611 /// 612 /// \param Dir The framework directory (e.g., ModuleName.framework). 613 /// 614 /// \param IsSystem Whether the framework directory is part of the system 615 /// frameworks. 616 /// 617 /// \returns The module, if found; otherwise, null. 618 Module *loadFrameworkModule(StringRef Name, 619 const DirectoryEntry *Dir, 620 bool IsSystem); 621 622 /// Load all of the module maps within the immediate subdirectories 623 /// of the given search directory. 624 void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir); 625 626 /// Find and suggest a usable module for the given file. 627 /// 628 /// \return \c true if the file can be used, \c false if we are not permitted to 629 /// find this file due to requirements from \p RequestingModule. 630 bool findUsableModuleForHeader(const FileEntry *File, 631 const DirectoryEntry *Root, 632 Module *RequestingModule, 633 ModuleMap::KnownHeader *SuggestedModule, 634 bool IsSystemHeaderDir); 635 636 /// Find and suggest a usable module for the given file, which is part of 637 /// the specified framework. 638 /// 639 /// \return \c true if the file can be used, \c false if we are not permitted to 640 /// find this file due to requirements from \p RequestingModule. 641 bool findUsableModuleForFrameworkHeader( 642 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule, 643 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework); 644 645 /// Look up the file with the specified name and determine its owning 646 /// module. 647 const FileEntry * 648 getFileAndSuggestModule(StringRef FileName, SourceLocation IncludeLoc, 649 const DirectoryEntry *Dir, bool IsSystemHeaderDir, 650 Module *RequestingModule, 651 ModuleMap::KnownHeader *SuggestedModule); 652 653 public: 654 /// Retrieve the module map. getModuleMap()655 ModuleMap &getModuleMap() { return ModMap; } 656 657 /// Retrieve the module map. getModuleMap()658 const ModuleMap &getModuleMap() const { return ModMap; } 659 header_file_size()660 unsigned header_file_size() const { return FileInfo.size(); } 661 662 /// Return the HeaderFileInfo structure for the specified FileEntry, 663 /// in preparation for updating it in some way. 664 HeaderFileInfo &getFileInfo(const FileEntry *FE); 665 666 /// Return the HeaderFileInfo structure for the specified FileEntry, 667 /// if it has ever been filled in. 668 /// \param WantExternal Whether the caller wants purely-external header file 669 /// info (where \p External is true). 670 const HeaderFileInfo *getExistingFileInfo(const FileEntry *FE, 671 bool WantExternal = true) const; 672 673 // Used by external tools 674 using search_dir_iterator = std::vector<DirectoryLookup>::const_iterator; 675 search_dir_begin()676 search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); } search_dir_end()677 search_dir_iterator search_dir_end() const { return SearchDirs.end(); } search_dir_size()678 unsigned search_dir_size() const { return SearchDirs.size(); } 679 quoted_dir_begin()680 search_dir_iterator quoted_dir_begin() const { 681 return SearchDirs.begin(); 682 } 683 quoted_dir_end()684 search_dir_iterator quoted_dir_end() const { 685 return SearchDirs.begin() + AngledDirIdx; 686 } 687 angled_dir_begin()688 search_dir_iterator angled_dir_begin() const { 689 return SearchDirs.begin() + AngledDirIdx; 690 } 691 angled_dir_end()692 search_dir_iterator angled_dir_end() const { 693 return SearchDirs.begin() + SystemDirIdx; 694 } 695 system_dir_begin()696 search_dir_iterator system_dir_begin() const { 697 return SearchDirs.begin() + SystemDirIdx; 698 } 699 system_dir_end()700 search_dir_iterator system_dir_end() const { return SearchDirs.end(); } 701 702 /// Retrieve a uniqued framework name. 703 StringRef getUniqueFrameworkName(StringRef Framework); 704 705 /// Suggest a path by which the specified file could be found, for 706 /// use in diagnostics to suggest a #include. 707 /// 708 /// \param IsSystem If non-null, filled in to indicate whether the suggested 709 /// path is relative to a system header directory. 710 std::string suggestPathToFileForDiagnostics(const FileEntry *File, 711 bool *IsSystem = nullptr); 712 713 /// Suggest a path by which the specified file could be found, for 714 /// use in diagnostics to suggest a #include. 715 /// 716 /// \param WorkingDir If non-empty, this will be prepended to search directory 717 /// paths that are relative. 718 std::string suggestPathToFileForDiagnostics(llvm::StringRef File, 719 llvm::StringRef WorkingDir, 720 bool *IsSystem = nullptr); 721 722 void PrintStats(); 723 724 size_t getTotalMemory() const; 725 726 private: 727 /// Describes what happened when we tried to load a module map file. 728 enum LoadModuleMapResult { 729 /// The module map file had already been loaded. 730 LMM_AlreadyLoaded, 731 732 /// The module map file was loaded by this invocation. 733 LMM_NewlyLoaded, 734 735 /// There is was directory with the given name. 736 LMM_NoDirectory, 737 738 /// There was either no module map file or the module map file was 739 /// invalid. 740 LMM_InvalidModuleMap 741 }; 742 743 LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File, 744 bool IsSystem, 745 const DirectoryEntry *Dir, 746 FileID ID = FileID(), 747 unsigned *Offset = nullptr); 748 749 /// Try to load the module map file in the given directory. 750 /// 751 /// \param DirName The name of the directory where we will look for a module 752 /// map file. 753 /// \param IsSystem Whether this is a system header directory. 754 /// \param IsFramework Whether this is a framework directory. 755 /// 756 /// \returns The result of attempting to load the module map file from the 757 /// named directory. 758 LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem, 759 bool IsFramework); 760 761 /// Try to load the module map file in the given directory. 762 /// 763 /// \param Dir The directory where we will look for a module map file. 764 /// \param IsSystem Whether this is a system header directory. 765 /// \param IsFramework Whether this is a framework directory. 766 /// 767 /// \returns The result of attempting to load the module map file from the 768 /// named directory. 769 LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir, 770 bool IsSystem, bool IsFramework); 771 }; 772 773 } // namespace clang 774 775 #endif // LLVM_CLANG_LEX_HEADERSEARCH_H 776