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