clang  7.0.0svn
HeaderSearch.cpp
Go to the documentation of this file.
1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
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 implements the DirectoryLookup and HeaderSearch interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/HeaderSearch.h"
15 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/Module.h"
23 #include "clang/Lex/HeaderMap.h"
26 #include "clang/Lex/ModuleMap.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/Hashing.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/Capacity.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Path.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <cstddef>
41 #include <cstdio>
42 #include <cstring>
43 #include <string>
44 #include <system_error>
45 #include <utility>
46 
47 using namespace clang;
48 
49 const IdentifierInfo *
51  if (ControllingMacro) {
53  assert(External && "We must have an external source if we have a "
54  "controlling macro that is out of date.");
55  External->updateOutOfDateIdentifier(
56  *const_cast<IdentifierInfo *>(ControllingMacro));
57  }
58  return ControllingMacro;
59  }
60 
61  if (!ControllingMacroID || !External)
62  return nullptr;
63 
65  return ControllingMacro;
66 }
67 
69 
70 HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
71  SourceManager &SourceMgr, DiagnosticsEngine &Diags,
72  const LangOptions &LangOpts,
73  const TargetInfo *Target)
74  : HSOpts(std::move(HSOpts)), Diags(Diags),
75  FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
76  ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
77 
79  // Delete headermaps.
80  for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
81  delete HeaderMaps[i].second;
82 }
83 
85  fprintf(stderr, "\n*** HeaderSearch Stats:\n");
86  fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
87  unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
88  for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
89  NumOnceOnlyFiles += FileInfo[i].isImport;
90  if (MaxNumIncludes < FileInfo[i].NumIncludes)
91  MaxNumIncludes = FileInfo[i].NumIncludes;
92  NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
93  }
94  fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
95  fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
96  fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
97 
98  fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
99  fprintf(stderr, " %d #includes skipped due to"
100  " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
101 
102  fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
103  fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
104 }
105 
106 /// CreateHeaderMap - This method returns a HeaderMap for the specified
107 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
109  // We expect the number of headermaps to be small, and almost always empty.
110  // If it ever grows, use of a linear search should be re-evaluated.
111  if (!HeaderMaps.empty()) {
112  for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
113  // Pointer equality comparison of FileEntries works because they are
114  // already uniqued by inode.
115  if (HeaderMaps[i].first == FE)
116  return HeaderMaps[i].second;
117  }
118 
119  if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
120  HeaderMaps.push_back(std::make_pair(FE, HM));
121  return HM;
122  }
123 
124  return nullptr;
125 }
126 
127 /// \brief Get filenames for all registered header maps.
129  SmallVectorImpl<std::string> &Names) const {
130  for (auto &HM : HeaderMaps)
131  Names.push_back(HM.first->getName());
132 }
133 
135  const FileEntry *ModuleMap =
137  return getCachedModuleFileName(Module->Name, ModuleMap->getName());
138 }
139 
140 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
141  bool FileMapOnly) {
142  // First check the module name to pcm file map.
143  auto i (HSOpts->PrebuiltModuleFiles.find(ModuleName));
144  if (i != HSOpts->PrebuiltModuleFiles.end())
145  return i->second;
146 
147  if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
148  return {};
149 
150  // Then go through each prebuilt module directory and try to find the pcm
151  // file.
152  for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
154  llvm::sys::fs::make_absolute(Result);
155  llvm::sys::path::append(Result, ModuleName + ".pcm");
156  if (getFileMgr().getFile(Result.str()))
157  return Result.str().str();
158  }
159  return {};
160 }
161 
162 std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
163  StringRef ModuleMapPath) {
164  // If we don't have a module cache path or aren't supposed to use one, we
165  // can't do anything.
166  if (getModuleCachePath().empty())
167  return {};
168 
170  llvm::sys::fs::make_absolute(Result);
171 
172  if (HSOpts->DisableModuleHash) {
173  llvm::sys::path::append(Result, ModuleName + ".pcm");
174  } else {
175  // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
176  // ideally be globally unique to this particular module. Name collisions
177  // in the hash are safe (because any translation unit can only import one
178  // module with each name), but result in a loss of caching.
179  //
180  // To avoid false-negatives, we form as canonical a path as we can, and map
181  // to lower-case in case we're on a case-insensitive file system.
182  std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
183  if (Parent.empty())
184  Parent = ".";
185  auto *Dir = FileMgr.getDirectory(Parent);
186  if (!Dir)
187  return {};
188  auto DirName = FileMgr.getCanonicalName(Dir);
189  auto FileName = llvm::sys::path::filename(ModuleMapPath);
190 
191  llvm::hash_code Hash =
192  llvm::hash_combine(DirName.lower(), FileName.lower());
193 
194  SmallString<128> HashStr;
195  llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
196  llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
197  }
198  return Result.str().str();
199 }
200 
201 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
202  // Look in the module map to determine if there is a module by this name.
203  Module *Module = ModMap.findModule(ModuleName);
204  if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
205  return Module;
206 
207  StringRef SearchName = ModuleName;
208  Module = lookupModule(ModuleName, SearchName);
209 
210  // The facility for "private modules" -- adjacent, optional module maps named
211  // module.private.modulemap that are supposed to define private submodules --
212  // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
213  //
214  // Foo.Private is now depracated in favor of Foo_Private. Users of FooPrivate
215  // should also rename to Foo_Private. Representing private as submodules
216  // could force building unwanted dependencies into the parent module and cause
217  // dependency cycles.
218  if (!Module && SearchName.consume_back("_Private"))
219  Module = lookupModule(ModuleName, SearchName);
220  if (!Module && SearchName.consume_back("Private"))
221  Module = lookupModule(ModuleName, SearchName);
222  return Module;
223 }
224 
225 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName) {
226  Module *Module = nullptr;
227 
228  // Look through the various header search paths to load any available module
229  // maps, searching for a module map that describes this module.
230  for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
231  if (SearchDirs[Idx].isFramework()) {
232  // Search for or infer a module map for a framework. Here we use
233  // SearchName rather than ModuleName, to permit finding private modules
234  // named FooPrivate in buggy frameworks named Foo.
235  SmallString<128> FrameworkDirName;
236  FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
237  llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
238  if (const DirectoryEntry *FrameworkDir
239  = FileMgr.getDirectory(FrameworkDirName)) {
240  bool IsSystem
241  = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
242  Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
243  if (Module)
244  break;
245  }
246  }
247 
248  // FIXME: Figure out how header maps and module maps will work together.
249 
250  // Only deal with normal search directories.
251  if (!SearchDirs[Idx].isNormalDir())
252  continue;
253 
254  bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
255  // Search for a module map file in this directory.
256  if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
257  /*IsFramework*/false) == LMM_NewlyLoaded) {
258  // We just loaded a module map file; check whether the module is
259  // available now.
260  Module = ModMap.findModule(ModuleName);
261  if (Module)
262  break;
263  }
264 
265  // Search for a module map in a subdirectory with the same name as the
266  // module.
267  SmallString<128> NestedModuleMapDirName;
268  NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
269  llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
270  if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
271  /*IsFramework*/false) == LMM_NewlyLoaded){
272  // If we just loaded a module map file, look for the module again.
273  Module = ModMap.findModule(ModuleName);
274  if (Module)
275  break;
276  }
277 
278  // If we've already performed the exhaustive search for module maps in this
279  // search directory, don't do it again.
280  if (SearchDirs[Idx].haveSearchedAllModuleMaps())
281  continue;
282 
283  // Load all module maps in the immediate subdirectories of this search
284  // directory.
285  loadSubdirectoryModuleMaps(SearchDirs[Idx]);
286 
287  // Look again for the module.
288  Module = ModMap.findModule(ModuleName);
289  if (Module)
290  break;
291  }
292 
293  return Module;
294 }
295 
296 //===----------------------------------------------------------------------===//
297 // File lookup within a DirectoryLookup scope
298 //===----------------------------------------------------------------------===//
299 
300 /// getName - Return the directory or filename corresponding to this lookup
301 /// object.
302 StringRef DirectoryLookup::getName() const {
303  if (isNormalDir())
304  return getDir()->getName();
305  if (isFramework())
306  return getFrameworkDir()->getName();
307  assert(isHeaderMap() && "Unknown DirectoryLookup");
308  return getHeaderMap()->getFileName();
309 }
310 
311 const FileEntry *HeaderSearch::getFileAndSuggestModule(
312  StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
313  bool IsSystemHeaderDir, Module *RequestingModule,
314  ModuleMap::KnownHeader *SuggestedModule) {
315  // If we have a module map that might map this header, load it and
316  // check whether we'll have a suggestion for a module.
317  const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
318  if (!File)
319  return nullptr;
320 
321  // If there is a module that corresponds to this header, suggest it.
322  if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
323  RequestingModule, SuggestedModule,
324  IsSystemHeaderDir))
325  return nullptr;
326 
327  return File;
328 }
329 
330 /// LookupFile - Lookup the specified file in this search path, returning it
331 /// if it exists or returning null if not.
333  StringRef &Filename,
334  HeaderSearch &HS,
335  SourceLocation IncludeLoc,
336  SmallVectorImpl<char> *SearchPath,
337  SmallVectorImpl<char> *RelativePath,
338  Module *RequestingModule,
339  ModuleMap::KnownHeader *SuggestedModule,
340  bool &InUserSpecifiedSystemFramework,
341  bool &HasBeenMapped,
342  SmallVectorImpl<char> &MappedName) const {
343  InUserSpecifiedSystemFramework = false;
344  HasBeenMapped = false;
345 
346  SmallString<1024> TmpDir;
347  if (isNormalDir()) {
348  // Concatenate the requested file onto the directory.
349  TmpDir = getDir()->getName();
350  llvm::sys::path::append(TmpDir, Filename);
351  if (SearchPath) {
352  StringRef SearchPathRef(getDir()->getName());
353  SearchPath->clear();
354  SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
355  }
356  if (RelativePath) {
357  RelativePath->clear();
358  RelativePath->append(Filename.begin(), Filename.end());
359  }
360 
361  return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
362  isSystemHeaderDirectory(),
363  RequestingModule, SuggestedModule);
364  }
365 
366  if (isFramework())
367  return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
368  RequestingModule, SuggestedModule,
369  InUserSpecifiedSystemFramework);
370 
371  assert(isHeaderMap() && "Unknown directory lookup");
372  const HeaderMap *HM = getHeaderMap();
373  SmallString<1024> Path;
374  StringRef Dest = HM->lookupFilename(Filename, Path);
375  if (Dest.empty())
376  return nullptr;
377 
378  const FileEntry *Result;
379 
380  // Check if the headermap maps the filename to a framework include
381  // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
382  // framework include.
383  if (llvm::sys::path::is_relative(Dest)) {
384  MappedName.clear();
385  MappedName.append(Dest.begin(), Dest.end());
386  Filename = StringRef(MappedName.begin(), MappedName.size());
387  HasBeenMapped = true;
388  Result = HM->LookupFile(Filename, HS.getFileMgr());
389  } else {
390  Result = HS.getFileMgr().getFile(Dest);
391  }
392 
393  if (Result) {
394  if (SearchPath) {
395  StringRef SearchPathRef(getName());
396  SearchPath->clear();
397  SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
398  }
399  if (RelativePath) {
400  RelativePath->clear();
401  RelativePath->append(Filename.begin(), Filename.end());
402  }
403  }
404  return Result;
405 }
406 
407 /// \brief Given a framework directory, find the top-most framework directory.
408 ///
409 /// \param FileMgr The file manager to use for directory lookups.
410 /// \param DirName The name of the framework directory.
411 /// \param SubmodulePath Will be populated with the submodule path from the
412 /// returned top-level module to the originally named framework.
413 static const DirectoryEntry *
414 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
415  SmallVectorImpl<std::string> &SubmodulePath) {
416  assert(llvm::sys::path::extension(DirName) == ".framework" &&
417  "Not a framework directory");
418 
419  // Note: as an egregious but useful hack we use the real path here, because
420  // frameworks moving between top-level frameworks to embedded frameworks tend
421  // to be symlinked, and we base the logical structure of modules on the
422  // physical layout. In particular, we need to deal with crazy includes like
423  //
424  // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
425  //
426  // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
427  // which one should access with, e.g.,
428  //
429  // #include <Bar/Wibble.h>
430  //
431  // Similar issues occur when a top-level framework has moved into an
432  // embedded framework.
433  const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
434  DirName = FileMgr.getCanonicalName(TopFrameworkDir);
435  do {
436  // Get the parent directory name.
437  DirName = llvm::sys::path::parent_path(DirName);
438  if (DirName.empty())
439  break;
440 
441  // Determine whether this directory exists.
442  const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
443  if (!Dir)
444  break;
445 
446  // If this is a framework directory, then we're a subframework of this
447  // framework.
448  if (llvm::sys::path::extension(DirName) == ".framework") {
449  SubmodulePath.push_back(llvm::sys::path::stem(DirName));
450  TopFrameworkDir = Dir;
451  }
452  } while (true);
453 
454  return TopFrameworkDir;
455 }
456 
457 static bool needModuleLookup(Module *RequestingModule,
458  bool HasSuggestedModule) {
459  return HasSuggestedModule ||
460  (RequestingModule && RequestingModule->NoUndeclaredIncludes);
461 }
462 
463 /// DoFrameworkLookup - Do a lookup of the specified file in the current
464 /// DirectoryLookup, which is a framework directory.
465 const FileEntry *DirectoryLookup::DoFrameworkLookup(
466  StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
467  SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
468  ModuleMap::KnownHeader *SuggestedModule,
469  bool &InUserSpecifiedSystemFramework) const {
470  FileManager &FileMgr = HS.getFileMgr();
471 
472  // Framework names must have a '/' in the filename.
473  size_t SlashPos = Filename.find('/');
474  if (SlashPos == StringRef::npos) return nullptr;
475 
476  // Find out if this is the home for the specified framework, by checking
477  // HeaderSearch. Possible answers are yes/no and unknown.
478  HeaderSearch::FrameworkCacheEntry &CacheEntry =
479  HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
480 
481  // If it is known and in some other directory, fail.
482  if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
483  return nullptr;
484 
485  // Otherwise, construct the path to this framework dir.
486 
487  // FrameworkName = "/System/Library/Frameworks/"
488  SmallString<1024> FrameworkName;
489  FrameworkName += getFrameworkDir()->getName();
490  if (FrameworkName.empty() || FrameworkName.back() != '/')
491  FrameworkName.push_back('/');
492 
493  // FrameworkName = "/System/Library/Frameworks/Cocoa"
494  StringRef ModuleName(Filename.begin(), SlashPos);
495  FrameworkName += ModuleName;
496 
497  // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
498  FrameworkName += ".framework/";
499 
500  // If the cache entry was unresolved, populate it now.
501  if (!CacheEntry.Directory) {
503 
504  // If the framework dir doesn't exist, we fail.
505  const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
506  if (!Dir) return nullptr;
507 
508  // Otherwise, if it does, remember that this is the right direntry for this
509  // framework.
510  CacheEntry.Directory = getFrameworkDir();
511 
512  // If this is a user search directory, check if the framework has been
513  // user-specified as a system framework.
514  if (getDirCharacteristic() == SrcMgr::C_User) {
515  SmallString<1024> SystemFrameworkMarker(FrameworkName);
516  SystemFrameworkMarker += ".system_framework";
517  if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
518  CacheEntry.IsUserSpecifiedSystemFramework = true;
519  }
520  }
521  }
522 
523  // Set the 'user-specified system framework' flag.
524  InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
525 
526  if (RelativePath) {
527  RelativePath->clear();
528  RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
529  }
530 
531  // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
532  unsigned OrigSize = FrameworkName.size();
533 
534  FrameworkName += "Headers/";
535 
536  if (SearchPath) {
537  SearchPath->clear();
538  // Without trailing '/'.
539  SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
540  }
541 
542  FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
543  const FileEntry *FE = FileMgr.getFile(FrameworkName,
544  /*openFile=*/!SuggestedModule);
545  if (!FE) {
546  // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
547  const char *Private = "Private";
548  FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
549  Private+strlen(Private));
550  if (SearchPath)
551  SearchPath->insert(SearchPath->begin()+OrigSize, Private,
552  Private+strlen(Private));
553 
554  FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
555  }
556 
557  // If we found the header and are allowed to suggest a module, do so now.
558  if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
559  // Find the framework in which this header occurs.
560  StringRef FrameworkPath = FE->getDir()->getName();
561  bool FoundFramework = false;
562  do {
563  // Determine whether this directory exists.
564  const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
565  if (!Dir)
566  break;
567 
568  // If this is a framework directory, then we're a subframework of this
569  // framework.
570  if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
571  FoundFramework = true;
572  break;
573  }
574 
575  // Get the parent directory name.
576  FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
577  if (FrameworkPath.empty())
578  break;
579  } while (true);
580 
581  bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
582  if (FoundFramework) {
583  if (!HS.findUsableModuleForFrameworkHeader(
584  FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
585  return nullptr;
586  } else {
587  if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
588  SuggestedModule, IsSystem))
589  return nullptr;
590  }
591  }
592  return FE;
593 }
594 
595 void HeaderSearch::setTarget(const TargetInfo &Target) {
596  ModMap.setTarget(Target);
597 }
598 
599 //===----------------------------------------------------------------------===//
600 // Header File Location.
601 //===----------------------------------------------------------------------===//
602 
603 /// \brief Return true with a diagnostic if the file that MSVC would have found
604 /// fails to match the one that Clang would have found with MSVC header search
605 /// disabled.
607  const FileEntry *MSFE, const FileEntry *FE,
608  SourceLocation IncludeLoc) {
609  if (MSFE && FE != MSFE) {
610  Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
611  return true;
612  }
613  return false;
614 }
615 
616 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
617  assert(!Str.empty());
618  char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
619  std::copy(Str.begin(), Str.end(), CopyStr);
620  CopyStr[Str.size()] = '\0';
621  return CopyStr;
622 }
623 
624 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
625 /// return null on failure. isAngled indicates whether the file reference is
626 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
627 /// non-empty, indicates where the \#including file(s) are, in case a relative
628 /// search is needed. Microsoft mode will pass all \#including files.
630  StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
631  const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
632  ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
633  SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
634  Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
635  bool *IsMapped, bool SkipCache, bool BuildSystemModule) {
636  if (IsMapped)
637  *IsMapped = false;
638 
639  if (SuggestedModule)
640  *SuggestedModule = ModuleMap::KnownHeader();
641 
642  // If 'Filename' is absolute, check to see if it exists and no searching.
643  if (llvm::sys::path::is_absolute(Filename)) {
644  CurDir = nullptr;
645 
646  // If this was an #include_next "/absolute/file", fail.
647  if (FromDir) return nullptr;
648 
649  if (SearchPath)
650  SearchPath->clear();
651  if (RelativePath) {
652  RelativePath->clear();
653  RelativePath->append(Filename.begin(), Filename.end());
654  }
655  // Otherwise, just return the file.
656  return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
657  /*IsSystemHeaderDir*/false,
658  RequestingModule, SuggestedModule);
659  }
660 
661  // This is the header that MSVC's header search would have found.
662  const FileEntry *MSFE = nullptr;
663  ModuleMap::KnownHeader MSSuggestedModule;
664 
665  // Unless disabled, check to see if the file is in the #includer's
666  // directory. This cannot be based on CurDir, because each includer could be
667  // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
668  // include of "baz.h" should resolve to "whatever/foo/baz.h".
669  // This search is not done for <> headers.
670  if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
671  SmallString<1024> TmpDir;
672  bool First = true;
673  for (const auto &IncluderAndDir : Includers) {
674  const FileEntry *Includer = IncluderAndDir.first;
675 
676  // Concatenate the requested file onto the directory.
677  // FIXME: Portability. Filename concatenation should be in sys::Path.
678  TmpDir = IncluderAndDir.second->getName();
679  TmpDir.push_back('/');
680  TmpDir.append(Filename.begin(), Filename.end());
681 
682  // FIXME: We don't cache the result of getFileInfo across the call to
683  // getFileAndSuggestModule, because it's a reference to an element of
684  // a container that could be reallocated across this call.
685  //
686  // If we have no includer, that means we're processing a #include
687  // from a module build. We should treat this as a system header if we're
688  // building a [system] module.
689  bool IncluderIsSystemHeader =
690  Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
691  BuildSystemModule;
692  if (const FileEntry *FE = getFileAndSuggestModule(
693  TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
694  RequestingModule, SuggestedModule)) {
695  if (!Includer) {
696  assert(First && "only first includer can have no file");
697  return FE;
698  }
699 
700  // Leave CurDir unset.
701  // This file is a system header or C++ unfriendly if the old file is.
702  //
703  // Note that we only use one of FromHFI/ToHFI at once, due to potential
704  // reallocation of the underlying vector potentially making the first
705  // reference binding dangling.
706  HeaderFileInfo &FromHFI = getFileInfo(Includer);
707  unsigned DirInfo = FromHFI.DirInfo;
708  bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
709  StringRef Framework = FromHFI.Framework;
710 
711  HeaderFileInfo &ToHFI = getFileInfo(FE);
712  ToHFI.DirInfo = DirInfo;
713  ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
714  ToHFI.Framework = Framework;
715 
716  if (SearchPath) {
717  StringRef SearchPathRef(IncluderAndDir.second->getName());
718  SearchPath->clear();
719  SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
720  }
721  if (RelativePath) {
722  RelativePath->clear();
723  RelativePath->append(Filename.begin(), Filename.end());
724  }
725  if (First)
726  return FE;
727 
728  // Otherwise, we found the path via MSVC header search rules. If
729  // -Wmsvc-include is enabled, we have to keep searching to see if we
730  // would've found this header in -I or -isystem directories.
731  if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
732  return FE;
733  } else {
734  MSFE = FE;
735  if (SuggestedModule) {
736  MSSuggestedModule = *SuggestedModule;
737  *SuggestedModule = ModuleMap::KnownHeader();
738  }
739  break;
740  }
741  }
742  First = false;
743  }
744  }
745 
746  CurDir = nullptr;
747 
748  // If this is a system #include, ignore the user #include locs.
749  unsigned i = isAngled ? AngledDirIdx : 0;
750 
751  // If this is a #include_next request, start searching after the directory the
752  // file was found in.
753  if (FromDir)
754  i = FromDir-&SearchDirs[0];
755 
756  // Cache all of the lookups performed by this method. Many headers are
757  // multiply included, and the "pragma once" optimization prevents them from
758  // being relex/pp'd, but they would still have to search through a
759  // (potentially huge) series of SearchDirs to find it.
760  LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
761 
762  // If the entry has been previously looked up, the first value will be
763  // non-zero. If the value is equal to i (the start point of our search), then
764  // this is a matching hit.
765  if (!SkipCache && CacheLookup.StartIdx == i+1) {
766  // Skip querying potentially lots of directories for this lookup.
767  i = CacheLookup.HitIdx;
768  if (CacheLookup.MappedName) {
769  Filename = CacheLookup.MappedName;
770  if (IsMapped)
771  *IsMapped = true;
772  }
773  } else {
774  // Otherwise, this is the first query, or the previous query didn't match
775  // our search start. We will fill in our found location below, so prime the
776  // start point value.
777  CacheLookup.reset(/*StartIdx=*/i+1);
778  }
779 
780  SmallString<64> MappedName;
781 
782  // Check each directory in sequence to see if it contains this file.
783  for (; i != SearchDirs.size(); ++i) {
784  bool InUserSpecifiedSystemFramework = false;
785  bool HasBeenMapped = false;
786  const FileEntry *FE = SearchDirs[i].LookupFile(
787  Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
788  SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
789  MappedName);
790  if (HasBeenMapped) {
791  CacheLookup.MappedName =
792  copyString(Filename, LookupFileCache.getAllocator());
793  if (IsMapped)
794  *IsMapped = true;
795  }
796  if (!FE) continue;
797 
798  CurDir = &SearchDirs[i];
799 
800  // This file is a system header or C++ unfriendly if the dir is.
801  HeaderFileInfo &HFI = getFileInfo(FE);
802  HFI.DirInfo = CurDir->getDirCharacteristic();
803 
804  // If the directory characteristic is User but this framework was
805  // user-specified to be treated as a system framework, promote the
806  // characteristic.
807  if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
809 
810  // If the filename matches a known system header prefix, override
811  // whether the file is a system header.
812  for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
813  if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
814  HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
815  : SrcMgr::C_User;
816  break;
817  }
818  }
819 
820  // If this file is found in a header map and uses the framework style of
821  // includes, then this header is part of a framework we're building.
822  if (CurDir->isIndexHeaderMap()) {
823  size_t SlashPos = Filename.find('/');
824  if (SlashPos != StringRef::npos) {
825  HFI.IndexHeaderMapHeader = 1;
826  HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
827  SlashPos));
828  }
829  }
830 
831  if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
832  if (SuggestedModule)
833  *SuggestedModule = MSSuggestedModule;
834  return MSFE;
835  }
836 
837  // Remember this location for the next lookup we do.
838  CacheLookup.HitIdx = i;
839  return FE;
840  }
841 
842  // If we are including a file with a quoted include "foo.h" from inside
843  // a header in a framework that is currently being built, and we couldn't
844  // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
845  // "Foo" is the name of the framework in which the including header was found.
846  if (!Includers.empty() && Includers.front().first && !isAngled &&
847  Filename.find('/') == StringRef::npos) {
848  HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
849  if (IncludingHFI.IndexHeaderMapHeader) {
850  SmallString<128> ScratchFilename;
851  ScratchFilename += IncludingHFI.Framework;
852  ScratchFilename += '/';
853  ScratchFilename += Filename;
854 
855  const FileEntry *FE =
856  LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
857  CurDir, Includers.front(), SearchPath, RelativePath,
858  RequestingModule, SuggestedModule, IsMapped);
859 
860  if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
861  if (SuggestedModule)
862  *SuggestedModule = MSSuggestedModule;
863  return MSFE;
864  }
865 
866  LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
867  CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
868  // FIXME: SuggestedModule.
869  return FE;
870  }
871  }
872 
873  if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
874  if (SuggestedModule)
875  *SuggestedModule = MSSuggestedModule;
876  return MSFE;
877  }
878 
879  // Otherwise, didn't find it. Remember we didn't find this.
880  CacheLookup.HitIdx = SearchDirs.size();
881  return nullptr;
882 }
883 
884 /// LookupSubframeworkHeader - Look up a subframework for the specified
885 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
886 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
887 /// is a subframework within Carbon.framework. If so, return the FileEntry
888 /// for the designated file, otherwise return null.
891  const FileEntry *ContextFileEnt,
892  SmallVectorImpl<char> *SearchPath,
893  SmallVectorImpl<char> *RelativePath,
894  Module *RequestingModule,
895  ModuleMap::KnownHeader *SuggestedModule) {
896  assert(ContextFileEnt && "No context file?");
897 
898  // Framework names must have a '/' in the filename. Find it.
899  // FIXME: Should we permit '\' on Windows?
900  size_t SlashPos = Filename.find('/');
901  if (SlashPos == StringRef::npos) return nullptr;
902 
903  // Look up the base framework name of the ContextFileEnt.
904  StringRef ContextName = ContextFileEnt->getName();
905 
906  // If the context info wasn't a framework, couldn't be a subframework.
907  const unsigned DotFrameworkLen = 10;
908  auto FrameworkPos = ContextName.find(".framework");
909  if (FrameworkPos == StringRef::npos ||
910  (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
911  ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
912  return nullptr;
913 
914  SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
915  FrameworkPos +
916  DotFrameworkLen + 1);
917 
918  // Append Frameworks/HIToolbox.framework/
919  FrameworkName += "Frameworks/";
920  FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
921  FrameworkName += ".framework/";
922 
923  auto &CacheLookup =
924  *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
925  FrameworkCacheEntry())).first;
926 
927  // Some other location?
928  if (CacheLookup.second.Directory &&
929  CacheLookup.first().size() == FrameworkName.size() &&
930  memcmp(CacheLookup.first().data(), &FrameworkName[0],
931  CacheLookup.first().size()) != 0)
932  return nullptr;
933 
934  // Cache subframework.
935  if (!CacheLookup.second.Directory) {
936  ++NumSubFrameworkLookups;
937 
938  // If the framework dir doesn't exist, we fail.
939  const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
940  if (!Dir) return nullptr;
941 
942  // Otherwise, if it does, remember that this is the right direntry for this
943  // framework.
944  CacheLookup.second.Directory = Dir;
945  }
946 
947  const FileEntry *FE = nullptr;
948 
949  if (RelativePath) {
950  RelativePath->clear();
951  RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
952  }
953 
954  // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
955  SmallString<1024> HeadersFilename(FrameworkName);
956  HeadersFilename += "Headers/";
957  if (SearchPath) {
958  SearchPath->clear();
959  // Without trailing '/'.
960  SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
961  }
962 
963  HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
964  if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
965  // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
966  HeadersFilename = FrameworkName;
967  HeadersFilename += "PrivateHeaders/";
968  if (SearchPath) {
969  SearchPath->clear();
970  // Without trailing '/'.
971  SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
972  }
973 
974  HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
975  if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
976  return nullptr;
977  }
978 
979  // This file is a system header or C++ unfriendly if the old file is.
980  //
981  // Note that the temporary 'DirInfo' is required here, as either call to
982  // getFileInfo could resize the vector and we don't want to rely on order
983  // of evaluation.
984  unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
985  getFileInfo(FE).DirInfo = DirInfo;
986 
987  FrameworkName.pop_back(); // remove the trailing '/'
988  if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
989  SuggestedModule, /*IsSystem*/ false))
990  return nullptr;
991 
992  return FE;
993 }
994 
995 //===----------------------------------------------------------------------===//
996 // File Info Management.
997 //===----------------------------------------------------------------------===//
998 
999 /// \brief Merge the header file info provided by \p OtherHFI into the current
1000 /// header file info (\p HFI)
1002  const HeaderFileInfo &OtherHFI) {
1003  assert(OtherHFI.External && "expected to merge external HFI");
1004 
1005  HFI.isImport |= OtherHFI.isImport;
1006  HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1007  HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1008  HFI.NumIncludes += OtherHFI.NumIncludes;
1009 
1010  if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1011  HFI.ControllingMacro = OtherHFI.ControllingMacro;
1012  HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1013  }
1014 
1015  HFI.DirInfo = OtherHFI.DirInfo;
1016  HFI.External = (!HFI.IsValid || HFI.External);
1017  HFI.IsValid = true;
1019 
1020  if (HFI.Framework.empty())
1021  HFI.Framework = OtherHFI.Framework;
1022 }
1023 
1024 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1025 /// FileEntry.
1027  if (FE->getUID() >= FileInfo.size())
1028  FileInfo.resize(FE->getUID() + 1);
1029 
1030  HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1031  // FIXME: Use a generation count to check whether this is really up to date.
1032  if (ExternalSource && !HFI->Resolved) {
1033  HFI->Resolved = true;
1034  auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1035 
1036  HFI = &FileInfo[FE->getUID()];
1037  if (ExternalHFI.External)
1038  mergeHeaderFileInfo(*HFI, ExternalHFI);
1039  }
1040 
1041  HFI->IsValid = true;
1042  // We have local information about this header file, so it's no longer
1043  // strictly external.
1044  HFI->External = false;
1045  return *HFI;
1046 }
1047 
1048 const HeaderFileInfo *
1050  bool WantExternal) const {
1051  // If we have an external source, ensure we have the latest information.
1052  // FIXME: Use a generation count to check whether this is really up to date.
1053  HeaderFileInfo *HFI;
1054  if (ExternalSource) {
1055  if (FE->getUID() >= FileInfo.size()) {
1056  if (!WantExternal)
1057  return nullptr;
1058  FileInfo.resize(FE->getUID() + 1);
1059  }
1060 
1061  HFI = &FileInfo[FE->getUID()];
1062  if (!WantExternal && (!HFI->IsValid || HFI->External))
1063  return nullptr;
1064  if (!HFI->Resolved) {
1065  HFI->Resolved = true;
1066  auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1067 
1068  HFI = &FileInfo[FE->getUID()];
1069  if (ExternalHFI.External)
1070  mergeHeaderFileInfo(*HFI, ExternalHFI);
1071  }
1072  } else if (FE->getUID() >= FileInfo.size()) {
1073  return nullptr;
1074  } else {
1075  HFI = &FileInfo[FE->getUID()];
1076  }
1077 
1078  if (!HFI->IsValid || (HFI->External && !WantExternal))
1079  return nullptr;
1080 
1081  return HFI;
1082 }
1083 
1085  // Check if we've ever seen this file as a header.
1086  if (auto *HFI = getExistingFileInfo(File))
1087  return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1088  HFI->ControllingMacroID;
1089  return false;
1090 }
1091 
1094  bool isCompilingModuleHeader) {
1095  bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1096 
1097  // Don't mark the file info as non-external if there's nothing to change.
1098  if (!isCompilingModuleHeader) {
1099  if (!isModularHeader)
1100  return;
1101  auto *HFI = getExistingFileInfo(FE);
1102  if (HFI && HFI->isModuleHeader)
1103  return;
1104  }
1105 
1106  auto &HFI = getFileInfo(FE);
1107  HFI.isModuleHeader |= isModularHeader;
1108  HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1109 }
1110 
1112  const FileEntry *File, bool isImport,
1113  bool ModulesEnabled, Module *M) {
1114  ++NumIncluded; // Count # of attempted #includes.
1115 
1116  // Get information about this file.
1117  HeaderFileInfo &FileInfo = getFileInfo(File);
1118 
1119  // FIXME: this is a workaround for the lack of proper modules-aware support
1120  // for #import / #pragma once
1121  auto TryEnterImported = [&]() -> bool {
1122  if (!ModulesEnabled)
1123  return false;
1124  // Ensure FileInfo bits are up to date.
1125  ModMap.resolveHeaderDirectives(File);
1126  // Modules with builtins are special; multiple modules use builtins as
1127  // modular headers, example:
1128  //
1129  // module stddef { header "stddef.h" export * }
1130  //
1131  // After module map parsing, this expands to:
1132  //
1133  // module stddef {
1134  // header "/path_to_builtin_dirs/stddef.h"
1135  // textual "stddef.h"
1136  // }
1137  //
1138  // It's common that libc++ and system modules will both define such
1139  // submodules. Make sure cached results for a builtin header won't
1140  // prevent other builtin modules to potentially enter the builtin header.
1141  // Note that builtins are header guarded and the decision to actually
1142  // enter them is postponed to the controlling macros logic below.
1143  bool TryEnterHdr = false;
1144  if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1145  TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1147  llvm::sys::path::filename(File->getName()));
1148 
1149  // Textual headers can be #imported from different modules. Since ObjC
1150  // headers find in the wild might rely only on #import and do not contain
1151  // controlling macros, be conservative and only try to enter textual headers
1152  // if such macro is present.
1153  if (!FileInfo.isModuleHeader &&
1154  FileInfo.getControllingMacro(ExternalLookup))
1155  TryEnterHdr = true;
1156  return TryEnterHdr;
1157  };
1158 
1159  // If this is a #import directive, check that we have not already imported
1160  // this header.
1161  if (isImport) {
1162  // If this has already been imported, don't import it again.
1163  FileInfo.isImport = true;
1164 
1165  // Has this already been #import'ed or #include'd?
1166  if (FileInfo.NumIncludes && !TryEnterImported())
1167  return false;
1168  } else {
1169  // Otherwise, if this is a #include of a file that was previously #import'd
1170  // or if this is the second #include of a #pragma once file, ignore it.
1171  if (FileInfo.isImport && !TryEnterImported())
1172  return false;
1173  }
1174 
1175  // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1176  // if the macro that guards it is defined, we know the #include has no effect.
1177  if (const IdentifierInfo *ControllingMacro
1178  = FileInfo.getControllingMacro(ExternalLookup)) {
1179  // If the header corresponds to a module, check whether the macro is already
1180  // defined in that module rather than checking in the current set of visible
1181  // modules.
1182  if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1183  : PP.isMacroDefined(ControllingMacro)) {
1184  ++NumMultiIncludeFileOptzn;
1185  return false;
1186  }
1187  }
1188 
1189  // Increment the number of times this file has been included.
1190  ++FileInfo.NumIncludes;
1191 
1192  return true;
1193 }
1194 
1196  return SearchDirs.capacity()
1197  + llvm::capacity_in_bytes(FileInfo)
1198  + llvm::capacity_in_bytes(HeaderMaps)
1199  + LookupFileCache.getAllocator().getTotalMemory()
1200  + FrameworkMap.getAllocator().getTotalMemory();
1201 }
1202 
1203 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1204  return FrameworkNames.insert(Framework).first->first();
1205 }
1206 
1207 bool HeaderSearch::hasModuleMap(StringRef FileName,
1208  const DirectoryEntry *Root,
1209  bool IsSystem) {
1210  if (!HSOpts->ImplicitModuleMaps)
1211  return false;
1212 
1213  SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1214 
1215  StringRef DirName = FileName;
1216  do {
1217  // Get the parent directory name.
1218  DirName = llvm::sys::path::parent_path(DirName);
1219  if (DirName.empty())
1220  return false;
1221 
1222  // Determine whether this directory exists.
1223  const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1224  if (!Dir)
1225  return false;
1226 
1227  // Try to load the module map file in this directory.
1228  switch (loadModuleMapFile(Dir, IsSystem,
1229  llvm::sys::path::extension(Dir->getName()) ==
1230  ".framework")) {
1231  case LMM_NewlyLoaded:
1232  case LMM_AlreadyLoaded:
1233  // Success. All of the directories we stepped through inherit this module
1234  // map file.
1235  for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1236  DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1237  return true;
1238 
1239  case LMM_NoDirectory:
1240  case LMM_InvalidModuleMap:
1241  break;
1242  }
1243 
1244  // If we hit the top of our search, we're done.
1245  if (Dir == Root)
1246  return false;
1247 
1248  // Keep track of all of the directories we checked, so we can mark them as
1249  // having module maps if we eventually do find a module map.
1250  FixUpDirectories.push_back(Dir);
1251  } while (true);
1252 }
1253 
1256  bool AllowTextual) const {
1257  if (ExternalSource) {
1258  // Make sure the external source has handled header info about this file,
1259  // which includes whether the file is part of a module.
1260  (void)getExistingFileInfo(File);
1261  }
1262  return ModMap.findModuleForHeader(File, AllowTextual);
1263 }
1264 
1265 static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1266  Module *RequestingModule,
1267  ModuleMap::KnownHeader *SuggestedModule) {
1269  HS.findModuleForHeader(File, /*AllowTextual*/true);
1270  if (SuggestedModule)
1271  *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1273  : Module;
1274 
1275  // If this module specifies [no_undeclared_includes], we cannot find any
1276  // file that's in a non-dependency module.
1277  if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1278  HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1279  if (!RequestingModule->directlyUses(Module.getModule())) {
1280  return false;
1281  }
1282  }
1283 
1284  return true;
1285 }
1286 
1287 bool HeaderSearch::findUsableModuleForHeader(
1288  const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1289  ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1290  if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1291  // If there is a module that corresponds to this header, suggest it.
1292  hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1293  return suggestModule(*this, File, RequestingModule, SuggestedModule);
1294  }
1295  return true;
1296 }
1297 
1298 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1299  const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1300  ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1301  // If we're supposed to suggest a module, look for one now.
1302  if (needModuleLookup(RequestingModule, SuggestedModule)) {
1303  // Find the top-level framework based on this framework.
1304  SmallVector<std::string, 4> SubmodulePath;
1305  const DirectoryEntry *TopFrameworkDir
1306  = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1307 
1308  // Determine the name of the top-level framework.
1309  StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1310 
1311  // Load this framework module. If that succeeds, find the suggested module
1312  // for this header, if any.
1313  loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1314 
1315  // FIXME: This can find a module not part of ModuleName, which is
1316  // important so that we're consistent about whether this header
1317  // corresponds to a module. Possibly we should lock down framework modules
1318  // so that this is not possible.
1319  return suggestModule(*this, File, RequestingModule, SuggestedModule);
1320  }
1321  return true;
1322 }
1323 
1324 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1325  FileManager &FileMgr) {
1326  StringRef Filename = llvm::sys::path::filename(File->getName());
1327  SmallString<128> PrivateFilename(File->getDir()->getName());
1328  if (Filename == "module.map")
1329  llvm::sys::path::append(PrivateFilename, "module_private.map");
1330  else if (Filename == "module.modulemap")
1331  llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1332  else
1333  return nullptr;
1334  return FileMgr.getFile(PrivateFilename);
1335 }
1336 
1337 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
1338  FileID ID, unsigned *Offset,
1339  StringRef OriginalModuleMapFile) {
1340  // Find the directory for the module. For frameworks, that may require going
1341  // up from the 'Modules' directory.
1342  const DirectoryEntry *Dir = nullptr;
1343  if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1344  Dir = FileMgr.getDirectory(".");
1345  else {
1346  if (!OriginalModuleMapFile.empty()) {
1347  // We're building a preprocessed module map. Find or invent the directory
1348  // that it originally occupied.
1349  Dir = FileMgr.getDirectory(
1350  llvm::sys::path::parent_path(OriginalModuleMapFile));
1351  if (!Dir) {
1352  auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1353  Dir = FakeFile->getDir();
1354  }
1355  } else {
1356  Dir = File->getDir();
1357  }
1358 
1359  StringRef DirName(Dir->getName());
1360  if (llvm::sys::path::filename(DirName) == "Modules") {
1361  DirName = llvm::sys::path::parent_path(DirName);
1362  if (DirName.endswith(".framework"))
1363  Dir = FileMgr.getDirectory(DirName);
1364  // FIXME: This assert can fail if there's a race between the above check
1365  // and the removal of the directory.
1366  assert(Dir && "parent must exist");
1367  }
1368  }
1369 
1370  switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
1371  case LMM_AlreadyLoaded:
1372  case LMM_NewlyLoaded:
1373  return false;
1374  case LMM_NoDirectory:
1375  case LMM_InvalidModuleMap:
1376  return true;
1377  }
1378  llvm_unreachable("Unknown load module map result");
1379 }
1380 
1381 HeaderSearch::LoadModuleMapResult
1382 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1383  const DirectoryEntry *Dir, FileID ID,
1384  unsigned *Offset) {
1385  assert(File && "expected FileEntry");
1386 
1387  // Check whether we've already loaded this module map, and mark it as being
1388  // loaded in case we recursively try to load it from itself.
1389  auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1390  if (!AddResult.second)
1391  return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1392 
1393  if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1394  LoadedModuleMaps[File] = false;
1395  return LMM_InvalidModuleMap;
1396  }
1397 
1398  // Try to load a corresponding private module map.
1399  if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1400  if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1401  LoadedModuleMaps[File] = false;
1402  return LMM_InvalidModuleMap;
1403  }
1404  }
1405 
1406  // This directory has a module map.
1407  return LMM_NewlyLoaded;
1408 }
1409 
1410 const FileEntry *
1411 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1412  if (!HSOpts->ImplicitModuleMaps)
1413  return nullptr;
1414  // For frameworks, the preferred spelling is Modules/module.modulemap, but
1415  // module.map at the framework root is also accepted.
1416  SmallString<128> ModuleMapFileName(Dir->getName());
1417  if (IsFramework)
1418  llvm::sys::path::append(ModuleMapFileName, "Modules");
1419  llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1420  if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1421  return F;
1422 
1423  // Continue to allow module.map
1424  ModuleMapFileName = Dir->getName();
1425  llvm::sys::path::append(ModuleMapFileName, "module.map");
1426  return FileMgr.getFile(ModuleMapFileName);
1427 }
1428 
1429 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1430  const DirectoryEntry *Dir,
1431  bool IsSystem) {
1432  if (Module *Module = ModMap.findModule(Name))
1433  return Module;
1434 
1435  // Try to load a module map file.
1436  switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1437  case LMM_InvalidModuleMap:
1438  // Try to infer a module map from the framework directory.
1439  if (HSOpts->ImplicitModuleMaps)
1440  ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1441  break;
1442 
1443  case LMM_AlreadyLoaded:
1444  case LMM_NoDirectory:
1445  return nullptr;
1446 
1447  case LMM_NewlyLoaded:
1448  break;
1449  }
1450 
1451  return ModMap.findModule(Name);
1452 }
1453 
1454 HeaderSearch::LoadModuleMapResult
1455 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1456  bool IsFramework) {
1457  if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1458  return loadModuleMapFile(Dir, IsSystem, IsFramework);
1459 
1460  return LMM_NoDirectory;
1461 }
1462 
1463 HeaderSearch::LoadModuleMapResult
1464 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1465  bool IsFramework) {
1466  auto KnownDir = DirectoryHasModuleMap.find(Dir);
1467  if (KnownDir != DirectoryHasModuleMap.end())
1468  return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1469 
1470  if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1471  LoadModuleMapResult Result =
1472  loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1473  // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1474  // E.g. Foo.framework/Modules/module.modulemap
1475  // ^Dir ^ModuleMapFile
1476  if (Result == LMM_NewlyLoaded)
1477  DirectoryHasModuleMap[Dir] = true;
1478  else if (Result == LMM_InvalidModuleMap)
1479  DirectoryHasModuleMap[Dir] = false;
1480  return Result;
1481  }
1482  return LMM_InvalidModuleMap;
1483 }
1484 
1486  Modules.clear();
1487 
1488  if (HSOpts->ImplicitModuleMaps) {
1489  // Load module maps for each of the header search directories.
1490  for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1491  bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1492  if (SearchDirs[Idx].isFramework()) {
1493  std::error_code EC;
1494  SmallString<128> DirNative;
1495  llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1496  DirNative);
1497 
1498  // Search each of the ".framework" directories to load them as modules.
1499  vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1500  for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1501  Dir != DirEnd && !EC; Dir.increment(EC)) {
1502  if (llvm::sys::path::extension(Dir->getName()) != ".framework")
1503  continue;
1504 
1505  const DirectoryEntry *FrameworkDir =
1506  FileMgr.getDirectory(Dir->getName());
1507  if (!FrameworkDir)
1508  continue;
1509 
1510  // Load this framework module.
1511  loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1512  FrameworkDir, IsSystem);
1513  }
1514  continue;
1515  }
1516 
1517  // FIXME: Deal with header maps.
1518  if (SearchDirs[Idx].isHeaderMap())
1519  continue;
1520 
1521  // Try to load a module map file for the search directory.
1522  loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1523  /*IsFramework*/ false);
1524 
1525  // Try to load module map files for immediate subdirectories of this
1526  // search directory.
1527  loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1528  }
1529  }
1530 
1531  // Populate the list of modules.
1532  for (ModuleMap::module_iterator M = ModMap.module_begin(),
1533  MEnd = ModMap.module_end();
1534  M != MEnd; ++M) {
1535  Modules.push_back(M->getValue());
1536  }
1537 }
1538 
1540  if (!HSOpts->ImplicitModuleMaps)
1541  return;
1542 
1543  // Load module maps for each of the header search directories.
1544  for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1545  // We only care about normal header directories.
1546  if (!SearchDirs[Idx].isNormalDir()) {
1547  continue;
1548  }
1549 
1550  // Try to load a module map file for the search directory.
1551  loadModuleMapFile(SearchDirs[Idx].getDir(),
1552  SearchDirs[Idx].isSystemHeaderDirectory(),
1553  SearchDirs[Idx].isFramework());
1554  }
1555 }
1556 
1557 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1558  assert(HSOpts->ImplicitModuleMaps &&
1559  "Should not be loading subdirectory module maps");
1560 
1561  if (SearchDir.haveSearchedAllModuleMaps())
1562  return;
1563 
1564  std::error_code EC;
1565  SmallString<128> DirNative;
1566  llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1567  vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1568  for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1569  Dir != DirEnd && !EC; Dir.increment(EC)) {
1570  bool IsFramework =
1571  llvm::sys::path::extension(Dir->getName()) == ".framework";
1572  if (IsFramework == SearchDir.isFramework())
1574  SearchDir.isFramework());
1575  }
1576 
1577  SearchDir.setSearchedAllModuleMaps(true);
1578 }
1579 
1581  bool *IsSystem) {
1582  // FIXME: We assume that the path name currently cached in the FileEntry is
1583  // the most appropriate one for this analysis (and that it's spelled the
1584  // same way as the corresponding header search path).
1585  return suggestPathToFileForDiagnostics(File->getName(), /*BuildDir=*/"",
1586  IsSystem);
1587 }
1588 
1590  llvm::StringRef File, llvm::StringRef WorkingDir, bool *IsSystem) {
1591  using namespace llvm::sys;
1592 
1593  unsigned BestPrefixLength = 0;
1594  unsigned BestSearchDir;
1595 
1596  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1597  // FIXME: Support this search within frameworks and header maps.
1598  if (!SearchDirs[I].isNormalDir())
1599  continue;
1600 
1601  StringRef Dir = SearchDirs[I].getDir()->getName();
1602  llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
1603  if (!WorkingDir.empty() && !path::is_absolute(Dir)) {
1604  auto err = fs::make_absolute(WorkingDir, DirPath);
1605  if (!err)
1606  path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1607  Dir = DirPath;
1608  }
1609  for (auto NI = path::begin(File), NE = path::end(File),
1610  DI = path::begin(Dir), DE = path::end(Dir);
1611  /*termination condition in loop*/; ++NI, ++DI) {
1612  // '.' components in File are ignored.
1613  while (NI != NE && *NI == ".")
1614  ++NI;
1615  if (NI == NE)
1616  break;
1617 
1618  // '.' components in Dir are ignored.
1619  while (DI != DE && *DI == ".")
1620  ++DI;
1621  if (DI == DE) {
1622  // Dir is a prefix of File, up to '.' components and choice of path
1623  // separators.
1624  unsigned PrefixLength = NI - path::begin(File);
1625  if (PrefixLength > BestPrefixLength) {
1626  BestPrefixLength = PrefixLength;
1627  BestSearchDir = I;
1628  }
1629  break;
1630  }
1631 
1632  if (*NI != *DI)
1633  break;
1634  }
1635  }
1636 
1637  if (IsSystem)
1638  *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
1639  return File.drop_front(BestPrefixLength);
1640 }
ModuleHeaderRole getRole() const
The role of this header within the module.
Definition: ModuleMap.h:154
std::string Name
The name of this module.
Definition: Module.h:68
static const DirectoryEntry * getTopFrameworkDir(FileManager &FileMgr, StringRef DirName, SmallVectorImpl< std::string > &SubmodulePath)
Given a framework directory, find the top-most framework directory.
std::string getPrebuiltModuleFileName(StringRef ModuleName, bool FileMapOnly=false)
Retrieve the name of the prebuilt module file that should be used to load a module with the given nam...
unsigned DirInfo
DirInfo - Keep track of whether this is a system header, and if so, whether it is C++ clean or not...
Definition: HeaderSearch.h:62
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
bool isIndexHeaderMap() const
Whether this header map is building a framework or not.
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:116
Defines the clang::FileManager interface and associated types.
This header is part of the module (for layering purposes) but should be textually included...
Definition: ModuleMap.h:118
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:56
Defines the SourceManager interface.
void loadTopLevelSystemModules()
Load all known, top-level system modules.
Defines the clang::Module class, which describes a module in the source code.
void collectAllModules(SmallVectorImpl< Module *> &Modules)
Collect the set of all known, top-level modules.
const FileEntry * getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module...
Definition: ModuleMap.cpp:1147
virtual IdentifierInfo * GetIdentifier(unsigned ID)=0
Return the identifier associated with the given ID number.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1294
StringRef getName() const
getName - Return the directory or filename corresponding to this lookup object.
llvm::StringMap< Module * >::const_iterator module_iterator
Definition: ModuleMap.h:648
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1195
bool isFileMultipleIncludeGuarded(const FileEntry *File)
Determine whether this file is intended to be safe from multiple inclusions, e.g., it has #pragma once or a controlling macro.
void MarkFileModuleHeader(const FileEntry *File, ModuleMap::ModuleHeaderRole Role, bool IsCompiledModuleHeader)
Mark the specified file as part of a module.
FrameworkCacheEntry & LookupFrameworkCache(StringRef FWName)
Look up the specified framework name in our framework cache.
Definition: HeaderSearch.h:415
const FileEntry * lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework)
Try to find a module map file in the given directory, returning nullptr if none is found...
virtual directory_iterator dir_begin(const Twine &Dir, std::error_code &EC)=0
Get a directory_iterator for Dir.
unsigned isCompilingModuleHeader
Whether this header is part of the module that we are building.
Definition: HeaderSearch.h:72
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:647
StringRef lookupFilename(StringRef Filename, SmallVectorImpl< char > &DestPath) const
If the specified relative filename is located in this HeaderMap return the filename it is mapped to...
Definition: HeaderMap.cpp:210
unsigned isImport
True if this is a #import&#39;d or #pragma once file.
Definition: HeaderSearch.h:53
const HeaderFileInfo * getExistingFileInfo(const FileEntry *FE, bool WantExternal=true) const
Return the HeaderFileInfo structure for the specified FileEntry, if it has ever been filled in...
The virtual file system interface.
static const HeaderMap * Create(const FileEntry *FE, FileManager &FM)
This attempts to load the specified file as a header map.
Definition: HeaderMap.cpp:51
One of these records is kept for each identifier that is lexed.
This class represents an Apple concept known as a &#39;header map&#39;.
Definition: HeaderMap.h:67
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1075
const FileEntry * LookupSubframeworkHeader(StringRef Filename, const FileEntry *RelativeFileEnt, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule)
Look up a subframework for the specified #include file.
unsigned getUID() const
Definition: FileManager.h:88
Definition: Format.h:2011
void setTarget(const TargetInfo &Target)
Set the target information for the header search, if not already known.
FileManager & getFileMgr() const
Definition: HeaderSearch.h:273
const IdentifierInfo * getControllingMacro(ExternalPreprocessorSource *External)
Retrieve the controlling macro for this header file, if any.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
Describes a module or submodule.
Definition: Module.h:65
unsigned External
Whether this header file info was supplied by an external source, and has not changed since...
Definition: HeaderSearch.h:66
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:724
static bool isBuiltinHeader(StringRef FileName)
Is this a compiler builtin header?
Definition: ModuleMap.cpp:334
static bool needModuleLookup(Module *RequestingModule, bool HasSuggestedModule)
static void hash_combine(std::size_t &seed, const T &v)
std::string getCachedModuleFileName(Module *Module)
Retrieve the name of the cached module file that should be used to load the given module...
uint32_t Offset
Definition: CacheTokens.cpp:43
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
unsigned short NumIncludes
The number of times the file has been included already.
Definition: HeaderSearch.h:91
bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M)
Determine whether II is defined as a macro within the module M, if that is a module that we&#39;ve alread...
Definition: Preprocessor.h:931
bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File, bool isImport, bool ModulesEnabled, Module *CorrespondingModule)
Mark the specified file as a target of a #include, #include_next, or #import directive.
Defines the Diagnostic-related interfaces.
bool loadModuleMapFile(const FileEntry *File, bool IsSystem, FileID ID=FileID(), unsigned *Offset=nullptr, StringRef OriginalModuleMapFile=StringRef())
Read the contents of the given module map file.
unsigned Resolved
Whether this structure is considered to already have been "resolved", meaning that it was loaded from...
Definition: HeaderSearch.h:76
virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE)=0
Retrieve the header file information for the given file entry.
The preprocessor keeps track of this information for each file that is #included. ...
Definition: HeaderSearch.h:51
void setTarget(const TargetInfo &Target)
Set the target information.
Definition: ModuleMap.cpp:288
unsigned NoUndeclaredIncludes
Whether files in this module can only include non-modular headers and headers from used modules...
Definition: Module.h:259
Encapsulates the information needed to find the file referenced by a #include or #include_next, (sub-)framework lookup, etc.
Definition: HeaderSearch.h:148
NodeId Parent
Definition: ASTDiff.cpp:192
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:335
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
HeaderFileInfo & getFileInfo(const FileEntry *FE)
Return the HeaderFileInfo structure for the specified FileEntry, in preparation for updating it in so...
const DirectoryEntry * getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
bool parseModuleMapFile(const FileEntry *File, bool IsSystem, const DirectoryEntry *HomeDir, FileID ID=FileID(), unsigned *Offset=nullptr, SourceLocation ExternModuleLoc=SourceLocation())
Parse the given module map file, and record any modules we encounter.
Definition: ModuleMap.cpp:2842
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:109
StringRef Filename
Definition: Format.cpp:1522
Exposes information about the current target.
Definition: TargetInfo.h:54
Abstract interface for external sources of preprocessor information.
Defines the clang::Preprocessor interface.
std::string suggestPathToFileForDiagnostics(const FileEntry *File, bool *IsSystem=nullptr)
Suggest a path by which the specified file could be found, for use in diagnostics to suggest a #inclu...
static const FileEntry * getPrivateModuleMap(const FileEntry *File, FileManager &FileMgr)
bool isFramework() const
isFramework - True if this is a framework directory.
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized. ...
Definition: HeaderSearch.h:271
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
KnownHeader findModuleForHeader(const FileEntry *File, bool AllowTextual=false)
Retrieve the module that owns the given header file, if any.
Definition: ModuleMap.cpp:521
module_iterator module_begin() const
Definition: ModuleMap.h:650
const FileEntry * LookupFile(StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, bool &InUserSpecifiedSystemFramework, bool &HasBeenMapped, SmallVectorImpl< char > &MappedName) const
LookupFile - Lookup the specified file in this search path, returning it if it exists or returning nu...
The result type of a method or function.
static const char * copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc)
Module * lookupModule(StringRef ModuleName, bool AllowSearch=true)
Lookup a module Search for a module with the given name.
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
const DirectoryEntry * getDir() const
Return the directory the file lives in.
Definition: FileManager.h:94
const DirectoryEntry * getBuiltinDir() const
Get the directory that contains Clang-supplied include files.
Definition: ModuleMap.h:376
ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File, bool AllowTextual=false) const
Retrieve the module that corresponds to the given file, if any.
const FileEntry * LookupFile(StringRef Filename, FileManager &FM) const
Check to see if the specified relative filename is located in this HeaderMap.
Definition: HeaderMap.cpp:199
unsigned isModuleHeader
Whether this header is part of a module.
Definition: HeaderSearch.h:69
Encodes a location in the source.
bool isSystemHeaderDirectory() const
Whether this describes a system header directory.
StringRef getName() const
Definition: FileManager.h:84
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags, const FileEntry *MSFE, const FileEntry *FE, SourceLocation IncludeLoc)
Return true with a diagnostic if the file that MSVC would have found fails to match the one that Clan...
SrcMgr::CharacteristicKind getDirCharacteristic() const
DirCharacteristic - The type of directory this is, one of the DirType enum values.
const IdentifierInfo * ControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file...
Definition: HeaderSearch.h:108
const FileEntry * getVirtualFile(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
bool haveSearchedAllModuleMaps() const
Determine whether we have already searched this entire directory for module maps. ...
const FileEntry * LookupFile(StringRef Filename, SourceLocation IncludeLoc, bool isAngled, const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, ArrayRef< std::pair< const FileEntry *, const DirectoryEntry *>> Includers, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool SkipCache=false, bool BuildSystemModule=false)
Given a "foo" or <foo> reference, look up the indicated file, return null on failure.
module_iterator module_end() const
Definition: ModuleMap.h:651
bool isMacroDefined(StringRef Id)
Definition: Preprocessor.h:920
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
unsigned ControllingMacroID
The ID number of the controlling macro.
Definition: HeaderSearch.h:98
StringRef getCanonicalName(const DirectoryEntry *Dir)
Retrieve the canonical name for a given directory.
void getHeaderMapFileNames(SmallVectorImpl< std::string > &Names) const
Get filenames for all registered header maps.
Dataflow Directional Tag Classes.
Defines the virtual file system interface vfs::FileSystem.
const DirectoryEntry * getDir() const
getDir - Return the directory that this entry refers to.
void IncrementFrameworkLookupCount()
Definition: HeaderSearch.h:538
static bool suggestModule(HeaderSearch &HS, const FileEntry *File, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule)
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)=0
Update an out-of-date identifier.
static void mergeHeaderFileInfo(HeaderFileInfo &HFI, const HeaderFileInfo &OtherHFI)
Merge the header file info provided by OtherHFI into the current header file info (HFI) ...
Cached information about one directory (either on disk or in the virtual file system).
Definition: FileManager.h:45
StringRef Framework
If this header came from a framework include, this is the name of the framework.
Definition: HeaderSearch.h:112
HeaderSearch(std::shared_ptr< HeaderSearchOptions > HSOpts, SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target)
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
Module * getModule() const
Retrieve the module the header is stored in.
Definition: ModuleMap.h:151
bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root, bool IsSystem)
Determine whether there is a module map that may map the header with the given file name to a (sub)mo...
IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() const
Definition: FileManager.h:225
bool directlyUses(const Module *Requested) const
Determine whether this module has declared its intention to directly use another module.
Definition: Module.cpp:224
const HeaderMap * CreateHeaderMap(const FileEntry *FE)
CreateHeaderMap - This method returns a HeaderMap for the specified FileEntry, uniquing them through ...
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:818
unsigned IndexHeaderMapHeader
Whether this is a header inside a framework that is currently being built.
Definition: HeaderSearch.h:85
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:88
void setSearchedAllModuleMaps(bool SAMM)
Specify whether we have already searched all of the subdirectories for module maps.
A header that is known to reside within a given module, whether it was included or excluded...
Definition: ModuleMap.h:136
This class handles loading and caching of source files into memory.
StringRef getUniqueFrameworkName(StringRef Framework)
Retrieve a uniqued framework name.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127
StringRef getName() const
Definition: FileManager.h:51
size_t getTotalMemory() const