clang 18.0.0git
HeaderSearch.cpp
Go to the documentation of this file.
1//===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the DirectoryLookup and HeaderSearch interfaces.
10//
11//===----------------------------------------------------------------------===//
12
17#include "clang/Basic/Module.h"
21#include "clang/Lex/HeaderMap.h"
24#include "clang/Lex/ModuleMap.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/Hashing.h"
28#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/Support/Allocator.h"
34#include "llvm/Support/Capacity.h"
35#include "llvm/Support/Errc.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/FileSystem.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/VirtualFileSystem.h"
40#include <algorithm>
41#include <cassert>
42#include <cstddef>
43#include <cstdio>
44#include <cstring>
45#include <string>
46#include <system_error>
47#include <utility>
48
49using namespace clang;
50
51#define DEBUG_TYPE "file-search"
52
53ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.");
55 NumMultiIncludeFileOptzn,
56 "Number of #includes skipped due to the multi-include optimization.");
57ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups.");
58ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups,
59 "Number of subframework lookups.");
60
61const IdentifierInfo *
63 if (ControllingMacro) {
65 assert(External && "We must have an external source if we have a "
66 "controlling macro that is out of date.");
67 External->updateOutOfDateIdentifier(
68 *const_cast<IdentifierInfo *>(ControllingMacro));
69 }
70 return ControllingMacro;
71 }
72
74 return nullptr;
75
77 return ControllingMacro;
78}
79
81
82HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
83 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
84 const LangOptions &LangOpts,
85 const TargetInfo *Target)
86 : HSOpts(std::move(HSOpts)), Diags(Diags),
87 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
88 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
89
91 llvm::errs() << "\n*** HeaderSearch Stats:\n"
92 << FileInfo.size() << " files tracked.\n";
93 unsigned NumOnceOnlyFiles = 0;
94 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i)
95 NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport);
96 llvm::errs() << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
97
98 llvm::errs() << " " << NumIncluded << " #include/#include_next/#import.\n"
99 << " " << NumMultiIncludeFileOptzn
100 << " #includes skipped due to the multi-include optimization.\n";
101
102 llvm::errs() << NumFrameworkLookups << " framework lookups.\n"
103 << NumSubFrameworkLookups << " subframework lookups.\n";
104}
105
107 std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx,
108 unsigned int systemDirIdx, bool noCurDirSearch,
109 llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) {
110 assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
111 "Directory indices are unordered");
112 SearchDirs = std::move(dirs);
113 SearchDirsUsage.assign(SearchDirs.size(), false);
114 AngledDirIdx = angledDirIdx;
115 SystemDirIdx = systemDirIdx;
116 NoCurDirSearch = noCurDirSearch;
117 SearchDirToHSEntry = std::move(searchDirToHSEntry);
118 //LookupFileCache.clear();
119 indexInitialHeaderMaps();
120}
121
122void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
123 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
124 SearchDirs.insert(SearchDirs.begin() + idx, dir);
125 SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false);
126 if (!isAngled)
127 AngledDirIdx++;
128 SystemDirIdx++;
129}
130
131std::vector<bool> HeaderSearch::computeUserEntryUsage() const {
132 std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size());
133 for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) {
134 // Check whether this DirectoryLookup has been successfully used.
135 if (SearchDirsUsage[I]) {
136 auto UserEntryIdxIt = SearchDirToHSEntry.find(I);
137 // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.
138 if (UserEntryIdxIt != SearchDirToHSEntry.end())
139 UserEntryUsage[UserEntryIdxIt->second] = true;
140 }
141 }
142 return UserEntryUsage;
143}
144
145/// CreateHeaderMap - This method returns a HeaderMap for the specified
146/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
148 // We expect the number of headermaps to be small, and almost always empty.
149 // If it ever grows, use of a linear search should be re-evaluated.
150 if (!HeaderMaps.empty()) {
151 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
152 // Pointer equality comparison of FileEntries works because they are
153 // already uniqued by inode.
154 if (HeaderMaps[i].first == FE)
155 return HeaderMaps[i].second.get();
156 }
157
158 if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
159 HeaderMaps.emplace_back(FE, std::move(HM));
160 return HeaderMaps.back().second.get();
161 }
162
163 return nullptr;
164}
165
166/// Get filenames for all registered header maps.
168 SmallVectorImpl<std::string> &Names) const {
169 for (auto &HM : HeaderMaps)
170 Names.push_back(std::string(HM.first.getName()));
171}
172
176 // The ModuleMap maybe a nullptr, when we load a cached C++ module without
177 // *.modulemap file. In this case, just return an empty string.
178 if (!ModuleMap)
179 return {};
180 return getCachedModuleFileName(Module->Name, ModuleMap->getNameAsRequested());
181}
182
183std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
184 bool FileMapOnly) {
185 // First check the module name to pcm file map.
186 auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));
187 if (i != HSOpts->PrebuiltModuleFiles.end())
188 return i->second;
189
190 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
191 return {};
192
193 // Then go through each prebuilt module directory and try to find the pcm
194 // file.
195 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
197 llvm::sys::fs::make_absolute(Result);
198 if (ModuleName.contains(':'))
199 // The separator of C++20 modules partitions (':') is not good for file
200 // systems, here clang and gcc choose '-' by default since it is not a
201 // valid character of C++ indentifiers. So we could avoid conflicts.
202 llvm::sys::path::append(Result, ModuleName.split(':').first + "-" +
203 ModuleName.split(':').second +
204 ".pcm");
205 else
206 llvm::sys::path::append(Result, ModuleName + ".pcm");
207 if (getFileMgr().getFile(Result.str()))
208 return std::string(Result);
209 }
210
211 return {};
212}
213
217 StringRef ModuleName = Module->Name;
218 StringRef ModuleMapPath = ModuleMap->getName();
219 StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash();
220 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
221 SmallString<256> CachePath(Dir);
222 llvm::sys::fs::make_absolute(CachePath);
223 llvm::sys::path::append(CachePath, ModuleCacheHash);
224 std::string FileName =
225 getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath);
226 if (!FileName.empty() && getFileMgr().getFile(FileName))
227 return FileName;
228 }
229 return {};
230}
231
232std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
233 StringRef ModuleMapPath) {
234 return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath,
236}
237
238std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName,
239 StringRef ModuleMapPath,
240 StringRef CachePath) {
241 // If we don't have a module cache path or aren't supposed to use one, we
242 // can't do anything.
243 if (CachePath.empty())
244 return {};
245
246 SmallString<256> Result(CachePath);
247 llvm::sys::fs::make_absolute(Result);
248
249 if (HSOpts->DisableModuleHash) {
250 llvm::sys::path::append(Result, ModuleName + ".pcm");
251 } else {
252 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
253 // ideally be globally unique to this particular module. Name collisions
254 // in the hash are safe (because any translation unit can only import one
255 // module with each name), but result in a loss of caching.
256 //
257 // To avoid false-negatives, we form as canonical a path as we can, and map
258 // to lower-case in case we're on a case-insensitive file system.
259 SmallString<128> CanonicalPath(ModuleMapPath);
260 if (getModuleMap().canonicalizeModuleMapPath(CanonicalPath))
261 return {};
262
263 llvm::hash_code Hash = llvm::hash_combine(CanonicalPath.str().lower());
264
265 SmallString<128> HashStr;
266 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
267 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
268 }
269 return Result.str().str();
270}
271
272Module *HeaderSearch::lookupModule(StringRef ModuleName,
273 SourceLocation ImportLoc, bool AllowSearch,
274 bool AllowExtraModuleMapSearch) {
275 // Look in the module map to determine if there is a module by this name.
276 Module *Module = ModMap.findModule(ModuleName);
277 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
278 return Module;
279
280 StringRef SearchName = ModuleName;
281 Module = lookupModule(ModuleName, SearchName, ImportLoc,
282 AllowExtraModuleMapSearch);
283
284 // The facility for "private modules" -- adjacent, optional module maps named
285 // module.private.modulemap that are supposed to define private submodules --
286 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
287 //
288 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
289 // should also rename to Foo_Private. Representing private as submodules
290 // could force building unwanted dependencies into the parent module and cause
291 // dependency cycles.
292 if (!Module && SearchName.consume_back("_Private"))
293 Module = lookupModule(ModuleName, SearchName, ImportLoc,
294 AllowExtraModuleMapSearch);
295 if (!Module && SearchName.consume_back("Private"))
296 Module = lookupModule(ModuleName, SearchName, ImportLoc,
297 AllowExtraModuleMapSearch);
298 return Module;
299}
300
301Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
302 SourceLocation ImportLoc,
303 bool AllowExtraModuleMapSearch) {
304 Module *Module = nullptr;
305
306 // Look through the various header search paths to load any available module
307 // maps, searching for a module map that describes this module.
308 for (DirectoryLookup &Dir : search_dir_range()) {
309 if (Dir.isFramework()) {
310 // Search for or infer a module map for a framework. Here we use
311 // SearchName rather than ModuleName, to permit finding private modules
312 // named FooPrivate in buggy frameworks named Foo.
313 SmallString<128> FrameworkDirName;
314 FrameworkDirName += Dir.getFrameworkDirRef()->getName();
315 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
316 if (auto FrameworkDir =
317 FileMgr.getOptionalDirectoryRef(FrameworkDirName)) {
318 bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User;
319 Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
320 if (Module)
321 break;
322 }
323 }
324
325 // FIXME: Figure out how header maps and module maps will work together.
326
327 // Only deal with normal search directories.
328 if (!Dir.isNormalDir())
329 continue;
330
331 bool IsSystem = Dir.isSystemHeaderDirectory();
332 // Only returns std::nullopt if not a normal directory, which we just
333 // checked
334 DirectoryEntryRef NormalDir = *Dir.getDirRef();
335 // Search for a module map file in this directory.
336 if (loadModuleMapFile(NormalDir, IsSystem,
337 /*IsFramework*/false) == LMM_NewlyLoaded) {
338 // We just loaded a module map file; check whether the module is
339 // available now.
340 Module = ModMap.findModule(ModuleName);
341 if (Module)
342 break;
343 }
344
345 // Search for a module map in a subdirectory with the same name as the
346 // module.
347 SmallString<128> NestedModuleMapDirName;
348 NestedModuleMapDirName = Dir.getDirRef()->getName();
349 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
350 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
351 /*IsFramework*/false) == LMM_NewlyLoaded){
352 // If we just loaded a module map file, look for the module again.
353 Module = ModMap.findModule(ModuleName);
354 if (Module)
355 break;
356 }
357
358 // If we've already performed the exhaustive search for module maps in this
359 // search directory, don't do it again.
360 if (Dir.haveSearchedAllModuleMaps())
361 continue;
362
363 // Load all module maps in the immediate subdirectories of this search
364 // directory if ModuleName was from @import.
365 if (AllowExtraModuleMapSearch)
366 loadSubdirectoryModuleMaps(Dir);
367
368 // Look again for the module.
369 Module = ModMap.findModule(ModuleName);
370 if (Module)
371 break;
372 }
373
374 return Module;
375}
376
377void HeaderSearch::indexInitialHeaderMaps() {
378 llvm::StringMap<unsigned, llvm::BumpPtrAllocator> Index(SearchDirs.size());
379
380 // Iterate over all filename keys and associate them with the index i.
381 for (unsigned i = 0; i != SearchDirs.size(); ++i) {
382 auto &Dir = SearchDirs[i];
383
384 // We're concerned with only the initial contiguous run of header
385 // maps within SearchDirs, which can be 99% of SearchDirs when
386 // SearchDirs.size() is ~10000.
387 if (!Dir.isHeaderMap()) {
388 SearchDirHeaderMapIndex = std::move(Index);
389 FirstNonHeaderMapSearchDirIdx = i;
390 break;
391 }
392
393 // Give earlier keys precedence over identical later keys.
394 auto Callback = [&](StringRef Filename) {
395 Index.try_emplace(Filename.lower(), i);
396 };
397 Dir.getHeaderMap()->forEachKey(Callback);
398 }
399}
400
401//===----------------------------------------------------------------------===//
402// File lookup within a DirectoryLookup scope
403//===----------------------------------------------------------------------===//
404
405/// getName - Return the directory or filename corresponding to this lookup
406/// object.
407StringRef DirectoryLookup::getName() const {
408 if (isNormalDir())
409 return getDirRef()->getName();
410 if (isFramework())
411 return getFrameworkDirRef()->getName();
412 assert(isHeaderMap() && "Unknown DirectoryLookup");
413 return getHeaderMap()->getFileName();
414}
415
416OptionalFileEntryRef HeaderSearch::getFileAndSuggestModule(
417 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
418 bool IsSystemHeaderDir, Module *RequestingModule,
419 ModuleMap::KnownHeader *SuggestedModule, bool OpenFile /*=true*/,
420 bool CacheFailures /*=true*/) {
421 // If we have a module map that might map this header, load it and
422 // check whether we'll have a suggestion for a module.
423 auto File = getFileMgr().getFileRef(FileName, OpenFile, CacheFailures);
424 if (!File) {
425 // For rare, surprising errors (e.g. "out of file handles"), diag the EC
426 // message.
427 std::error_code EC = llvm::errorToErrorCode(File.takeError());
428 if (EC != llvm::errc::no_such_file_or_directory &&
429 EC != llvm::errc::invalid_argument &&
430 EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
431 Diags.Report(IncludeLoc, diag::err_cannot_open_file)
432 << FileName << EC.message();
433 }
434 return std::nullopt;
435 }
436
437 // If there is a module that corresponds to this header, suggest it.
438 if (!findUsableModuleForHeader(
439 *File, Dir ? Dir : File->getFileEntry().getDir(), RequestingModule,
440 SuggestedModule, IsSystemHeaderDir))
441 return std::nullopt;
442
443 return *File;
444}
445
446/// LookupFile - Lookup the specified file in this search path, returning it
447/// if it exists or returning null if not.
449 StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
450 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
451 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
452 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
453 bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName,
454 bool OpenFile) const {
455 InUserSpecifiedSystemFramework = false;
456 IsInHeaderMap = false;
457 MappedName.clear();
458
459 SmallString<1024> TmpDir;
460 if (isNormalDir()) {
461 // Concatenate the requested file onto the directory.
462 TmpDir = getDirRef()->getName();
463 llvm::sys::path::append(TmpDir, Filename);
464 if (SearchPath) {
465 StringRef SearchPathRef(getDirRef()->getName());
466 SearchPath->clear();
467 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
468 }
469 if (RelativePath) {
470 RelativePath->clear();
471 RelativePath->append(Filename.begin(), Filename.end());
472 }
473
474 return HS.getFileAndSuggestModule(
475 TmpDir, IncludeLoc, getDir(), isSystemHeaderDirectory(),
476 RequestingModule, SuggestedModule, OpenFile);
477 }
478
479 if (isFramework())
480 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
481 RequestingModule, SuggestedModule,
482 InUserSpecifiedSystemFramework, IsFrameworkFound);
483
484 assert(isHeaderMap() && "Unknown directory lookup");
485 const HeaderMap *HM = getHeaderMap();
487 StringRef Dest = HM->lookupFilename(Filename, Path);
488 if (Dest.empty())
489 return std::nullopt;
490
491 IsInHeaderMap = true;
492
493 auto FixupSearchPathAndFindUsableModule =
495 if (SearchPath) {
496 StringRef SearchPathRef(getName());
497 SearchPath->clear();
498 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
499 }
500 if (RelativePath) {
501 RelativePath->clear();
502 RelativePath->append(Filename.begin(), Filename.end());
503 }
504 if (!HS.findUsableModuleForHeader(File, File.getFileEntry().getDir(),
505 RequestingModule, SuggestedModule,
507 return std::nullopt;
508 }
509 return File;
510 };
511
512 // Check if the headermap maps the filename to a framework include
513 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
514 // framework include.
515 if (llvm::sys::path::is_relative(Dest)) {
516 MappedName.append(Dest.begin(), Dest.end());
517 Filename = StringRef(MappedName.begin(), MappedName.size());
518 Dest = HM->lookupFilename(Filename, Path);
519 }
520
521 if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest, OpenFile)) {
522 return FixupSearchPathAndFindUsableModule(*Res);
523 }
524
525 // Header maps need to be marked as used whenever the filename matches.
526 // The case where the target file **exists** is handled by callee of this
527 // function as part of the regular logic that applies to include search paths.
528 // The case where the target file **does not exist** is handled here:
529 HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc);
530 return std::nullopt;
531}
532
533/// Given a framework directory, find the top-most framework directory.
534///
535/// \param FileMgr The file manager to use for directory lookups.
536/// \param DirName The name of the framework directory.
537/// \param SubmodulePath Will be populated with the submodule path from the
538/// returned top-level module to the originally named framework.
540getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
541 SmallVectorImpl<std::string> &SubmodulePath) {
542 assert(llvm::sys::path::extension(DirName) == ".framework" &&
543 "Not a framework directory");
544
545 // Note: as an egregious but useful hack we use the real path here, because
546 // frameworks moving between top-level frameworks to embedded frameworks tend
547 // to be symlinked, and we base the logical structure of modules on the
548 // physical layout. In particular, we need to deal with crazy includes like
549 //
550 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
551 //
552 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
553 // which one should access with, e.g.,
554 //
555 // #include <Bar/Wibble.h>
556 //
557 // Similar issues occur when a top-level framework has moved into an
558 // embedded framework.
559 auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName);
560
561 if (TopFrameworkDir)
562 DirName = FileMgr.getCanonicalName(*TopFrameworkDir);
563 do {
564 // Get the parent directory name.
565 DirName = llvm::sys::path::parent_path(DirName);
566 if (DirName.empty())
567 break;
568
569 // Determine whether this directory exists.
570 auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
571 if (!Dir)
572 break;
573
574 // If this is a framework directory, then we're a subframework of this
575 // framework.
576 if (llvm::sys::path::extension(DirName) == ".framework") {
577 SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));
578 TopFrameworkDir = *Dir;
579 }
580 } while (true);
581
582 return TopFrameworkDir;
583}
584
585static bool needModuleLookup(Module *RequestingModule,
586 bool HasSuggestedModule) {
587 return HasSuggestedModule ||
588 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
589}
590
591/// DoFrameworkLookup - Do a lookup of the specified file in the current
592/// DirectoryLookup, which is a framework directory.
593OptionalFileEntryRef DirectoryLookup::DoFrameworkLookup(
594 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
595 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
596 ModuleMap::KnownHeader *SuggestedModule,
597 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
598 FileManager &FileMgr = HS.getFileMgr();
599
600 // Framework names must have a '/' in the filename.
601 size_t SlashPos = Filename.find('/');
602 if (SlashPos == StringRef::npos)
603 return std::nullopt;
604
605 // Find out if this is the home for the specified framework, by checking
606 // HeaderSearch. Possible answers are yes/no and unknown.
607 FrameworkCacheEntry &CacheEntry =
608 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
609
610 // If it is known and in some other directory, fail.
611 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef())
612 return std::nullopt;
613
614 // Otherwise, construct the path to this framework dir.
615
616 // FrameworkName = "/System/Library/Frameworks/"
617 SmallString<1024> FrameworkName;
618 FrameworkName += getFrameworkDirRef()->getName();
619 if (FrameworkName.empty() || FrameworkName.back() != '/')
620 FrameworkName.push_back('/');
621
622 // FrameworkName = "/System/Library/Frameworks/Cocoa"
623 StringRef ModuleName(Filename.begin(), SlashPos);
624 FrameworkName += ModuleName;
625
626 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
627 FrameworkName += ".framework/";
628
629 // If the cache entry was unresolved, populate it now.
630 if (!CacheEntry.Directory) {
631 ++NumFrameworkLookups;
632
633 // If the framework dir doesn't exist, we fail.
634 auto Dir = FileMgr.getDirectory(FrameworkName);
635 if (!Dir)
636 return std::nullopt;
637
638 // Otherwise, if it does, remember that this is the right direntry for this
639 // framework.
640 CacheEntry.Directory = getFrameworkDirRef();
641
642 // If this is a user search directory, check if the framework has been
643 // user-specified as a system framework.
645 SmallString<1024> SystemFrameworkMarker(FrameworkName);
646 SystemFrameworkMarker += ".system_framework";
647 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
648 CacheEntry.IsUserSpecifiedSystemFramework = true;
649 }
650 }
651 }
652
653 // Set out flags.
654 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
655 IsFrameworkFound = CacheEntry.Directory.has_value();
656
657 if (RelativePath) {
658 RelativePath->clear();
659 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
660 }
661
662 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
663 unsigned OrigSize = FrameworkName.size();
664
665 FrameworkName += "Headers/";
666
667 if (SearchPath) {
668 SearchPath->clear();
669 // Without trailing '/'.
670 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
671 }
672
673 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
674
675 auto File =
676 FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);
677 if (!File) {
678 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
679 const char *Private = "Private";
680 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
681 Private+strlen(Private));
682 if (SearchPath)
683 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
684 Private+strlen(Private));
685
686 File = FileMgr.getOptionalFileRef(FrameworkName,
687 /*OpenFile=*/!SuggestedModule);
688 }
689
690 // If we found the header and are allowed to suggest a module, do so now.
691 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
692 // Find the framework in which this header occurs.
693 StringRef FrameworkPath = File->getDir().getName();
694 bool FoundFramework = false;
695 do {
696 // Determine whether this directory exists.
697 auto Dir = FileMgr.getDirectory(FrameworkPath);
698 if (!Dir)
699 break;
700
701 // If this is a framework directory, then we're a subframework of this
702 // framework.
703 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
704 FoundFramework = true;
705 break;
706 }
707
708 // Get the parent directory name.
709 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
710 if (FrameworkPath.empty())
711 break;
712 } while (true);
713
714 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
715 if (FoundFramework) {
716 if (!HS.findUsableModuleForFrameworkHeader(*File, FrameworkPath,
717 RequestingModule,
718 SuggestedModule, IsSystem))
719 return std::nullopt;
720 } else {
721 if (!HS.findUsableModuleForHeader(*File, getDir(), RequestingModule,
722 SuggestedModule, IsSystem))
723 return std::nullopt;
724 }
725 }
726 if (File)
727 return *File;
728 return std::nullopt;
729}
730
731void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
733 SourceLocation Loc) {
734 CacheLookup.HitIt = HitIt;
735 noteLookupUsage(HitIt.Idx, Loc);
736}
737
738void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) {
739 SearchDirsUsage[HitIdx] = true;
740
741 auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx);
742 if (UserEntryIdxIt != SearchDirToHSEntry.end())
743 Diags.Report(Loc, diag::remark_pp_search_path_usage)
744 << HSOpts->UserEntries[UserEntryIdxIt->second].Path;
745}
746
748 ModMap.setTarget(Target);
749}
750
751//===----------------------------------------------------------------------===//
752// Header File Location.
753//===----------------------------------------------------------------------===//
754
755/// Return true with a diagnostic if the file that MSVC would have found
756/// fails to match the one that Clang would have found with MSVC header search
757/// disabled.
760 const FileEntry *FE,
761 SourceLocation IncludeLoc) {
762 if (MSFE && FE != *MSFE) {
763 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
764 return true;
765 }
766 return false;
767}
768
769static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
770 assert(!Str.empty());
771 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
772 std::copy(Str.begin(), Str.end(), CopyStr);
773 CopyStr[Str.size()] = '\0';
774 return CopyStr;
775}
776
777static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
778 SmallVectorImpl<char> &FrameworkName,
779 SmallVectorImpl<char> &IncludeSpelling) {
780 using namespace llvm::sys;
781 path::const_iterator I = path::begin(Path);
782 path::const_iterator E = path::end(Path);
783 IsPrivateHeader = false;
784
785 // Detect different types of framework style paths:
786 //
787 // ...Foo.framework/{Headers,PrivateHeaders}
788 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
789 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
790 // ...<other variations with 'Versions' like in the above path>
791 //
792 // and some other variations among these lines.
793 int FoundComp = 0;
794 while (I != E) {
795 if (*I == "Headers") {
796 ++FoundComp;
797 } else if (*I == "PrivateHeaders") {
798 ++FoundComp;
799 IsPrivateHeader = true;
800 } else if (I->endswith(".framework")) {
801 StringRef Name = I->drop_back(10); // Drop .framework
802 // Need to reset the strings and counter to support nested frameworks.
803 FrameworkName.clear();
804 FrameworkName.append(Name.begin(), Name.end());
805 IncludeSpelling.clear();
806 IncludeSpelling.append(Name.begin(), Name.end());
807 FoundComp = 1;
808 } else if (FoundComp >= 2) {
809 IncludeSpelling.push_back('/');
810 IncludeSpelling.append(I->begin(), I->end());
811 }
812 ++I;
813 }
814
815 return !FrameworkName.empty() && FoundComp >= 2;
816}
817
818static void
820 StringRef Includer, StringRef IncludeFilename,
821 FileEntryRef IncludeFE, bool isAngled = false,
822 bool FoundByHeaderMap = false) {
823 bool IsIncluderPrivateHeader = false;
824 SmallString<128> FromFramework, ToFramework;
825 SmallString<128> FromIncludeSpelling, ToIncludeSpelling;
826 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework,
827 FromIncludeSpelling))
828 return;
829 bool IsIncludeePrivateHeader = false;
830 bool IsIncludeeInFramework =
831 isFrameworkStylePath(IncludeFE.getName(), IsIncludeePrivateHeader,
832 ToFramework, ToIncludeSpelling);
833
834 if (!isAngled && !FoundByHeaderMap) {
835 SmallString<128> NewInclude("<");
836 if (IsIncludeeInFramework) {
837 NewInclude += ToIncludeSpelling;
838 NewInclude += ">";
839 } else {
840 NewInclude += IncludeFilename;
841 NewInclude += ">";
842 }
843 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
844 << IncludeFilename
845 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
846 }
847
848 // Headers in Foo.framework/Headers should not include headers
849 // from Foo.framework/PrivateHeaders, since this violates public/private
850 // API boundaries and can cause modular dependency cycles.
851 if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
852 IsIncludeePrivateHeader && FromFramework == ToFramework)
853 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
854 << IncludeFilename;
855}
856
857/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
858/// return null on failure. isAngled indicates whether the file reference is
859/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
860/// non-empty, indicates where the \#including file(s) are, in case a relative
861/// search is needed. Microsoft mode will pass all \#including files.
863 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
865 ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>> Includers,
866 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
867 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
868 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
869 bool BuildSystemModule, bool OpenFile, bool CacheFailures) {
870 ConstSearchDirIterator CurDirLocal = nullptr;
871 ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
872
873 if (IsMapped)
874 *IsMapped = false;
875
876 if (IsFrameworkFound)
877 *IsFrameworkFound = false;
878
879 if (SuggestedModule)
880 *SuggestedModule = ModuleMap::KnownHeader();
881
882 // If 'Filename' is absolute, check to see if it exists and no searching.
883 if (llvm::sys::path::is_absolute(Filename)) {
884 CurDir = nullptr;
885
886 // If this was an #include_next "/absolute/file", fail.
887 if (FromDir)
888 return std::nullopt;
889
890 if (SearchPath)
891 SearchPath->clear();
892 if (RelativePath) {
893 RelativePath->clear();
894 RelativePath->append(Filename.begin(), Filename.end());
895 }
896 // Otherwise, just return the file.
897 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
898 /*IsSystemHeaderDir*/ false,
899 RequestingModule, SuggestedModule, OpenFile,
900 CacheFailures);
901 }
902
903 // This is the header that MSVC's header search would have found.
904 ModuleMap::KnownHeader MSSuggestedModule;
906
907 // Unless disabled, check to see if the file is in the #includer's
908 // directory. This cannot be based on CurDir, because each includer could be
909 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
910 // include of "baz.h" should resolve to "whatever/foo/baz.h".
911 // This search is not done for <> headers.
912 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
913 SmallString<1024> TmpDir;
914 bool First = true;
915 for (const auto &IncluderAndDir : Includers) {
916 OptionalFileEntryRef Includer = IncluderAndDir.first;
917
918 // Concatenate the requested file onto the directory.
919 TmpDir = IncluderAndDir.second.getName();
920 llvm::sys::path::append(TmpDir, Filename);
921
922 // FIXME: We don't cache the result of getFileInfo across the call to
923 // getFileAndSuggestModule, because it's a reference to an element of
924 // a container that could be reallocated across this call.
925 //
926 // If we have no includer, that means we're processing a #include
927 // from a module build. We should treat this as a system header if we're
928 // building a [system] module.
929 bool IncluderIsSystemHeader =
930 Includer ? getFileInfo(*Includer).DirInfo != SrcMgr::C_User :
931 BuildSystemModule;
932 if (OptionalFileEntryRef FE = getFileAndSuggestModule(
933 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
934 RequestingModule, SuggestedModule)) {
935 if (!Includer) {
936 assert(First && "only first includer can have no file");
937 return FE;
938 }
939
940 // Leave CurDir unset.
941 // This file is a system header or C++ unfriendly if the old file is.
942 //
943 // Note that we only use one of FromHFI/ToHFI at once, due to potential
944 // reallocation of the underlying vector potentially making the first
945 // reference binding dangling.
946 HeaderFileInfo &FromHFI = getFileInfo(*Includer);
947 unsigned DirInfo = FromHFI.DirInfo;
948 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
949 StringRef Framework = FromHFI.Framework;
950
951 HeaderFileInfo &ToHFI = getFileInfo(*FE);
952 ToHFI.DirInfo = DirInfo;
953 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
954 ToHFI.Framework = Framework;
955
956 if (SearchPath) {
957 StringRef SearchPathRef(IncluderAndDir.second.getName());
958 SearchPath->clear();
959 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
960 }
961 if (RelativePath) {
962 RelativePath->clear();
963 RelativePath->append(Filename.begin(), Filename.end());
964 }
965 if (First) {
966 diagnoseFrameworkInclude(Diags, IncludeLoc,
967 IncluderAndDir.second.getName(), Filename,
968 *FE);
969 return FE;
970 }
971
972 // Otherwise, we found the path via MSVC header search rules. If
973 // -Wmsvc-include is enabled, we have to keep searching to see if we
974 // would've found this header in -I or -isystem directories.
975 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
976 return FE;
977 } else {
978 MSFE = FE;
979 if (SuggestedModule) {
980 MSSuggestedModule = *SuggestedModule;
981 *SuggestedModule = ModuleMap::KnownHeader();
982 }
983 break;
984 }
985 }
986 First = false;
987 }
988 }
989
990 CurDir = nullptr;
991
992 // If this is a system #include, ignore the user #include locs.
994 isAngled ? angled_dir_begin() : search_dir_begin();
995
996 // If this is a #include_next request, start searching after the directory the
997 // file was found in.
998 if (FromDir)
999 It = FromDir;
1000
1001 // Cache all of the lookups performed by this method. Many headers are
1002 // multiply included, and the "pragma once" optimization prevents them from
1003 // being relex/pp'd, but they would still have to search through a
1004 // (potentially huge) series of SearchDirs to find it.
1005 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
1006
1007 ConstSearchDirIterator NextIt = std::next(It);
1008
1009 if (!SkipCache) {
1010 if (CacheLookup.StartIt == NextIt &&
1011 CacheLookup.RequestingModule == RequestingModule) {
1012 // HIT: Skip querying potentially lots of directories for this lookup.
1013 if (CacheLookup.HitIt)
1014 It = CacheLookup.HitIt;
1015 if (CacheLookup.MappedName) {
1016 Filename = CacheLookup.MappedName;
1017 if (IsMapped)
1018 *IsMapped = true;
1019 }
1020 } else {
1021 // MISS: This is the first query, or the previous query didn't match
1022 // our search start. We will fill in our found location below, so prime
1023 // the start point value.
1024 CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt);
1025
1026 if (It == search_dir_begin() && FirstNonHeaderMapSearchDirIdx > 0) {
1027 // Handle cold misses of user includes in the presence of many header
1028 // maps. We avoid searching perhaps thousands of header maps by
1029 // jumping directly to the correct one or jumping beyond all of them.
1030 auto Iter = SearchDirHeaderMapIndex.find(Filename.lower());
1031 if (Iter == SearchDirHeaderMapIndex.end())
1032 // Not in index => Skip to first SearchDir after initial header maps
1033 It = search_dir_nth(FirstNonHeaderMapSearchDirIdx);
1034 else
1035 // In index => Start with a specific header map
1036 It = search_dir_nth(Iter->second);
1037 }
1038 }
1039 } else {
1040 CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt);
1041 }
1042
1043 SmallString<64> MappedName;
1044
1045 // Check each directory in sequence to see if it contains this file.
1046 for (; It != search_dir_end(); ++It) {
1047 bool InUserSpecifiedSystemFramework = false;
1048 bool IsInHeaderMap = false;
1049 bool IsFrameworkFoundInDir = false;
1050 OptionalFileEntryRef File = It->LookupFile(
1051 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
1052 SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
1053 IsInHeaderMap, MappedName, OpenFile);
1054 if (!MappedName.empty()) {
1055 assert(IsInHeaderMap && "MappedName should come from a header map");
1056 CacheLookup.MappedName =
1057 copyString(MappedName, LookupFileCache.getAllocator());
1058 }
1059 if (IsMapped)
1060 // A filename is mapped when a header map remapped it to a relative path
1061 // used in subsequent header search or to an absolute path pointing to an
1062 // existing file.
1063 *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
1064 if (IsFrameworkFound)
1065 // Because we keep a filename remapped for subsequent search directory
1066 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
1067 // just for remapping in a current search directory.
1068 *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
1069 if (!File)
1070 continue;
1071
1072 CurDir = It;
1073
1074 IncludeNames[*File] = Filename;
1075
1076 // This file is a system header or C++ unfriendly if the dir is.
1078 HFI.DirInfo = CurDir->getDirCharacteristic();
1079
1080 // If the directory characteristic is User but this framework was
1081 // user-specified to be treated as a system framework, promote the
1082 // characteristic.
1083 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
1085
1086 // If the filename matches a known system header prefix, override
1087 // whether the file is a system header.
1088 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
1089 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
1090 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
1092 break;
1093 }
1094 }
1095
1096 // Set the `Framework` info if this file is in a header map with framework
1097 // style include spelling or found in a framework dir. The header map case
1098 // is possible when building frameworks which use header maps.
1099 if (CurDir->isHeaderMap() && isAngled) {
1100 size_t SlashPos = Filename.find('/');
1101 if (SlashPos != StringRef::npos)
1102 HFI.Framework =
1103 getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1104 if (CurDir->isIndexHeaderMap())
1105 HFI.IndexHeaderMapHeader = 1;
1106 } else if (CurDir->isFramework()) {
1107 size_t SlashPos = Filename.find('/');
1108 if (SlashPos != StringRef::npos)
1109 HFI.Framework =
1110 getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1111 }
1112
1113 if (checkMSVCHeaderSearch(Diags, MSFE, &File->getFileEntry(), IncludeLoc)) {
1114 if (SuggestedModule)
1115 *SuggestedModule = MSSuggestedModule;
1116 return MSFE;
1117 }
1118
1119 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
1120 if (!Includers.empty())
1121 diagnoseFrameworkInclude(Diags, IncludeLoc,
1122 Includers.front().second.getName(), Filename,
1123 *File, isAngled, FoundByHeaderMap);
1124
1125 // Remember this location for the next lookup we do.
1126 cacheLookupSuccess(CacheLookup, It, IncludeLoc);
1127 return File;
1128 }
1129
1130 // If we are including a file with a quoted include "foo.h" from inside
1131 // a header in a framework that is currently being built, and we couldn't
1132 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
1133 // "Foo" is the name of the framework in which the including header was found.
1134 if (!Includers.empty() && Includers.front().first && !isAngled &&
1135 !Filename.contains('/')) {
1136 HeaderFileInfo &IncludingHFI = getFileInfo(*Includers.front().first);
1137 if (IncludingHFI.IndexHeaderMapHeader) {
1138 SmallString<128> ScratchFilename;
1139 ScratchFilename += IncludingHFI.Framework;
1140 ScratchFilename += '/';
1141 ScratchFilename += Filename;
1142
1144 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir,
1145 Includers.front(), SearchPath, RelativePath, RequestingModule,
1146 SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
1147
1148 if (checkMSVCHeaderSearch(Diags, MSFE,
1149 File ? &File->getFileEntry() : nullptr,
1150 IncludeLoc)) {
1151 if (SuggestedModule)
1152 *SuggestedModule = MSSuggestedModule;
1153 return MSFE;
1154 }
1155
1156 cacheLookupSuccess(LookupFileCache[Filename],
1157 LookupFileCache[ScratchFilename].HitIt, IncludeLoc);
1158 // FIXME: SuggestedModule.
1159 return File;
1160 }
1161 }
1162
1163 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
1164 if (SuggestedModule)
1165 *SuggestedModule = MSSuggestedModule;
1166 return MSFE;
1167 }
1168
1169 // Otherwise, didn't find it. Remember we didn't find this.
1170 CacheLookup.HitIt = search_dir_end();
1171 return std::nullopt;
1172}
1173
1174/// LookupSubframeworkHeader - Look up a subframework for the specified
1175/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
1176/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1177/// is a subframework within Carbon.framework. If so, return the FileEntry
1178/// for the designated file, otherwise return null.
1180 StringRef Filename, FileEntryRef ContextFileEnt,
1181 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1182 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
1183 // Framework names must have a '/' in the filename. Find it.
1184 // FIXME: Should we permit '\' on Windows?
1185 size_t SlashPos = Filename.find('/');
1186 if (SlashPos == StringRef::npos)
1187 return std::nullopt;
1188
1189 // Look up the base framework name of the ContextFileEnt.
1190 StringRef ContextName = ContextFileEnt.getName();
1191
1192 // If the context info wasn't a framework, couldn't be a subframework.
1193 const unsigned DotFrameworkLen = 10;
1194 auto FrameworkPos = ContextName.find(".framework");
1195 if (FrameworkPos == StringRef::npos ||
1196 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1197 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
1198 return std::nullopt;
1199
1200 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1201 FrameworkPos +
1202 DotFrameworkLen + 1);
1203
1204 // Append Frameworks/HIToolbox.framework/
1205 FrameworkName += "Frameworks/";
1206 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1207 FrameworkName += ".framework/";
1208
1209 auto &CacheLookup =
1210 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1211 FrameworkCacheEntry())).first;
1212
1213 // Some other location?
1214 if (CacheLookup.second.Directory &&
1215 CacheLookup.first().size() == FrameworkName.size() &&
1216 memcmp(CacheLookup.first().data(), &FrameworkName[0],
1217 CacheLookup.first().size()) != 0)
1218 return std::nullopt;
1219
1220 // Cache subframework.
1221 if (!CacheLookup.second.Directory) {
1222 ++NumSubFrameworkLookups;
1223
1224 // If the framework dir doesn't exist, we fail.
1225 auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);
1226 if (!Dir)
1227 return std::nullopt;
1228
1229 // Otherwise, if it does, remember that this is the right direntry for this
1230 // framework.
1231 CacheLookup.second.Directory = Dir;
1232 }
1233
1234
1235 if (RelativePath) {
1236 RelativePath->clear();
1237 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1238 }
1239
1240 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1241 SmallString<1024> HeadersFilename(FrameworkName);
1242 HeadersFilename += "Headers/";
1243 if (SearchPath) {
1244 SearchPath->clear();
1245 // Without trailing '/'.
1246 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1247 }
1248
1249 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1250 auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1251 if (!File) {
1252 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1253 HeadersFilename = FrameworkName;
1254 HeadersFilename += "PrivateHeaders/";
1255 if (SearchPath) {
1256 SearchPath->clear();
1257 // Without trailing '/'.
1258 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1259 }
1260
1261 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1262 File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1263
1264 if (!File)
1265 return std::nullopt;
1266 }
1267
1268 // This file is a system header or C++ unfriendly if the old file is.
1269 //
1270 // Note that the temporary 'DirInfo' is required here, as either call to
1271 // getFileInfo could resize the vector and we don't want to rely on order
1272 // of evaluation.
1273 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1274 getFileInfo(*File).DirInfo = DirInfo;
1275
1276 FrameworkName.pop_back(); // remove the trailing '/'
1277 if (!findUsableModuleForFrameworkHeader(*File, FrameworkName,
1278 RequestingModule, SuggestedModule,
1279 /*IsSystem*/ false))
1280 return std::nullopt;
1281
1282 return *File;
1283}
1284
1285//===----------------------------------------------------------------------===//
1286// File Info Management.
1287//===----------------------------------------------------------------------===//
1288
1289/// Merge the header file info provided by \p OtherHFI into the current
1290/// header file info (\p HFI)
1292 const HeaderFileInfo &OtherHFI) {
1293 assert(OtherHFI.External && "expected to merge external HFI");
1294
1295 HFI.isImport |= OtherHFI.isImport;
1296 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1297 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1298
1299 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1300 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1302 }
1303
1304 HFI.DirInfo = OtherHFI.DirInfo;
1305 HFI.External = (!HFI.IsValid || HFI.External);
1306 HFI.IsValid = true;
1308
1309 if (HFI.Framework.empty())
1310 HFI.Framework = OtherHFI.Framework;
1311}
1312
1313/// getFileInfo - Return the HeaderFileInfo structure for the specified
1314/// FileEntry.
1316 if (FE.getUID() >= FileInfo.size())
1317 FileInfo.resize(FE.getUID() + 1);
1318
1319 HeaderFileInfo *HFI = &FileInfo[FE.getUID()];
1320 // FIXME: Use a generation count to check whether this is really up to date.
1321 if (ExternalSource && !HFI->Resolved) {
1322 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1323 if (ExternalHFI.IsValid) {
1324 HFI->Resolved = true;
1325 if (ExternalHFI.External)
1326 mergeHeaderFileInfo(*HFI, ExternalHFI);
1327 }
1328 }
1329
1330 HFI->IsValid = true;
1331 // We have local information about this header file, so it's no longer
1332 // strictly external.
1333 HFI->External = false;
1334 return *HFI;
1335}
1336
1337const HeaderFileInfo *
1339 // If we have an external source, ensure we have the latest information.
1340 // FIXME: Use a generation count to check whether this is really up to date.
1341 HeaderFileInfo *HFI;
1342 if (ExternalSource) {
1343 if (FE.getUID() >= FileInfo.size()) {
1344 if (!WantExternal)
1345 return nullptr;
1346 FileInfo.resize(FE.getUID() + 1);
1347 }
1348
1349 HFI = &FileInfo[FE.getUID()];
1350 if (!WantExternal && (!HFI->IsValid || HFI->External))
1351 return nullptr;
1352 if (!HFI->Resolved) {
1353 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1354 if (ExternalHFI.IsValid) {
1355 HFI->Resolved = true;
1356 if (ExternalHFI.External)
1357 mergeHeaderFileInfo(*HFI, ExternalHFI);
1358 }
1359 }
1360 } else if (FE.getUID() >= FileInfo.size()) {
1361 return nullptr;
1362 } else {
1363 HFI = &FileInfo[FE.getUID()];
1364 }
1365
1366 if (!HFI->IsValid || (HFI->External && !WantExternal))
1367 return nullptr;
1368
1369 return HFI;
1370}
1371
1373 // Check if we've entered this file and found an include guard or #pragma
1374 // once. Note that we dor't check for #import, because that's not a property
1375 // of the file itself.
1376 if (auto *HFI = getExistingFileInfo(File))
1377 return HFI->isPragmaOnce || HFI->ControllingMacro ||
1378 HFI->ControllingMacroID;
1379 return false;
1380}
1381
1384 bool isCompilingModuleHeader) {
1385 bool isModularHeader = ModuleMap::isModular(Role);
1386
1387 // Don't mark the file info as non-external if there's nothing to change.
1388 if (!isCompilingModuleHeader) {
1389 if (!isModularHeader)
1390 return;
1391 auto *HFI = getExistingFileInfo(FE);
1392 if (HFI && HFI->isModuleHeader)
1393 return;
1394 }
1395
1396 auto &HFI = getFileInfo(FE);
1397 HFI.isModuleHeader |= isModularHeader;
1398 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1399}
1400
1402 FileEntryRef File, bool isImport,
1403 bool ModulesEnabled, Module *M,
1404 bool &IsFirstIncludeOfFile) {
1405 ++NumIncluded; // Count # of attempted #includes.
1406
1407 IsFirstIncludeOfFile = false;
1408
1409 // Get information about this file.
1410 HeaderFileInfo &FileInfo = getFileInfo(File);
1411
1412 // FIXME: this is a workaround for the lack of proper modules-aware support
1413 // for #import / #pragma once
1414 auto TryEnterImported = [&]() -> bool {
1415 if (!ModulesEnabled)
1416 return false;
1417 // Ensure FileInfo bits are up to date.
1419 // Modules with builtins are special; multiple modules use builtins as
1420 // modular headers, example:
1421 //
1422 // module stddef { header "stddef.h" export * }
1423 //
1424 // After module map parsing, this expands to:
1425 //
1426 // module stddef {
1427 // header "/path_to_builtin_dirs/stddef.h"
1428 // textual "stddef.h"
1429 // }
1430 //
1431 // It's common that libc++ and system modules will both define such
1432 // submodules. Make sure cached results for a builtin header won't
1433 // prevent other builtin modules from potentially entering the builtin
1434 // header. Note that builtins are header guarded and the decision to
1435 // actually enter them is postponed to the controlling macros logic below.
1436 bool TryEnterHdr = false;
1437 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1438 TryEnterHdr = ModMap.isBuiltinHeader(File);
1439
1440 // Textual headers can be #imported from different modules. Since ObjC
1441 // headers find in the wild might rely only on #import and do not contain
1442 // controlling macros, be conservative and only try to enter textual headers
1443 // if such macro is present.
1444 if (!FileInfo.isModuleHeader &&
1445 FileInfo.getControllingMacro(ExternalLookup))
1446 TryEnterHdr = true;
1447 return TryEnterHdr;
1448 };
1449
1450 // If this is a #import directive, check that we have not already imported
1451 // this header.
1452 if (isImport) {
1453 // If this has already been imported, don't import it again.
1454 FileInfo.isImport = true;
1455
1456 // Has this already been #import'ed or #include'd?
1457 if (PP.alreadyIncluded(File) && !TryEnterImported())
1458 return false;
1459 } else {
1460 // Otherwise, if this is a #include of a file that was previously #import'd
1461 // or if this is the second #include of a #pragma once file, ignore it.
1462 if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported())
1463 return false;
1464 }
1465
1466 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1467 // if the macro that guards it is defined, we know the #include has no effect.
1468 if (const IdentifierInfo *ControllingMacro
1469 = FileInfo.getControllingMacro(ExternalLookup)) {
1470 // If the header corresponds to a module, check whether the macro is already
1471 // defined in that module rather than checking in the current set of visible
1472 // modules.
1473 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1474 : PP.isMacroDefined(ControllingMacro)) {
1475 ++NumMultiIncludeFileOptzn;
1476 return false;
1477 }
1478 }
1479
1480 IsFirstIncludeOfFile = PP.markIncluded(File);
1481
1482 return true;
1483}
1484
1486 return SearchDirs.capacity()
1487 + llvm::capacity_in_bytes(FileInfo)
1488 + llvm::capacity_in_bytes(HeaderMaps)
1489 + LookupFileCache.getAllocator().getTotalMemory()
1490 + FrameworkMap.getAllocator().getTotalMemory();
1491}
1492
1494 return &DL - &*SearchDirs.begin();
1495}
1496
1497StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1498 return FrameworkNames.insert(Framework).first->first();
1499}
1500
1502 auto It = IncludeNames.find(File);
1503 if (It == IncludeNames.end())
1504 return {};
1505 return It->second;
1506}
1507
1509 const DirectoryEntry *Root,
1510 bool IsSystem) {
1511 if (!HSOpts->ImplicitModuleMaps)
1512 return false;
1513
1515
1516 StringRef DirName = FileName;
1517 do {
1518 // Get the parent directory name.
1519 DirName = llvm::sys::path::parent_path(DirName);
1520 if (DirName.empty())
1521 return false;
1522
1523 // Determine whether this directory exists.
1524 auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
1525 if (!Dir)
1526 return false;
1527
1528 // Try to load the module map file in this directory.
1529 switch (loadModuleMapFile(*Dir, IsSystem,
1530 llvm::sys::path::extension(Dir->getName()) ==
1531 ".framework")) {
1532 case LMM_NewlyLoaded:
1533 case LMM_AlreadyLoaded:
1534 // Success. All of the directories we stepped through inherit this module
1535 // map file.
1536 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1537 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1538 return true;
1539
1540 case LMM_NoDirectory:
1541 case LMM_InvalidModuleMap:
1542 break;
1543 }
1544
1545 // If we hit the top of our search, we're done.
1546 if (*Dir == Root)
1547 return false;
1548
1549 // Keep track of all of the directories we checked, so we can mark them as
1550 // having module maps if we eventually do find a module map.
1551 FixUpDirectories.push_back(*Dir);
1552 } while (true);
1553}
1554
1557 bool AllowExcluded) const {
1558 if (ExternalSource) {
1559 // Make sure the external source has handled header info about this file,
1560 // which includes whether the file is part of a module.
1562 }
1563 return ModMap.findModuleForHeader(File, AllowTextual, AllowExcluded);
1564}
1565
1568 if (ExternalSource) {
1569 // Make sure the external source has handled header info about this file,
1570 // which includes whether the file is part of a module.
1572 }
1573 return ModMap.findAllModulesForHeader(File);
1574}
1575
1578 if (ExternalSource) {
1579 // Make sure the external source has handled header info about this file,
1580 // which includes whether the file is part of a module.
1582 }
1583 return ModMap.findResolvedModulesForHeader(File);
1584}
1585
1587 Module *RequestingModule,
1588 ModuleMap::KnownHeader *SuggestedModule) {
1590 HS.findModuleForHeader(File, /*AllowTextual*/true);
1591
1592 // If this module specifies [no_undeclared_includes], we cannot find any
1593 // file that's in a non-dependency module.
1594 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1595 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false);
1596 if (!RequestingModule->directlyUses(Module.getModule())) {
1597 // Builtin headers are a special case. Multiple modules can use the same
1598 // builtin as a modular header (see also comment in
1599 // ShouldEnterIncludeFile()), so the builtin header may have been
1600 // "claimed" by an unrelated module. This shouldn't prevent us from
1601 // including the builtin header textually in this module.
1602 if (HS.getModuleMap().isBuiltinHeader(File)) {
1603 if (SuggestedModule)
1604 *SuggestedModule = ModuleMap::KnownHeader();
1605 return true;
1606 }
1607 // TODO: Add this module (or just its module map file) into something like
1608 // `RequestingModule->AffectingClangModules`.
1609 return false;
1610 }
1611 }
1612
1613 if (SuggestedModule)
1614 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1616 : Module;
1617
1618 return true;
1619}
1620
1621bool HeaderSearch::findUsableModuleForHeader(
1622 FileEntryRef File, const DirectoryEntry *Root, Module *RequestingModule,
1623 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1624 if (needModuleLookup(RequestingModule, SuggestedModule)) {
1625 // If there is a module that corresponds to this header, suggest it.
1626 hasModuleMap(File.getNameAsRequested(), Root, IsSystemHeaderDir);
1627 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1628 }
1629 return true;
1630}
1631
1632bool HeaderSearch::findUsableModuleForFrameworkHeader(
1633 FileEntryRef File, StringRef FrameworkName, Module *RequestingModule,
1634 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1635 // If we're supposed to suggest a module, look for one now.
1636 if (needModuleLookup(RequestingModule, SuggestedModule)) {
1637 // Find the top-level framework based on this framework.
1638 SmallVector<std::string, 4> SubmodulePath;
1639 OptionalDirectoryEntryRef TopFrameworkDir =
1640 ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1641 assert(TopFrameworkDir && "Could not find the top-most framework dir");
1642
1643 // Determine the name of the top-level framework.
1644 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1645
1646 // Load this framework module. If that succeeds, find the suggested module
1647 // for this header, if any.
1648 loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework);
1649
1650 // FIXME: This can find a module not part of ModuleName, which is
1651 // important so that we're consistent about whether this header
1652 // corresponds to a module. Possibly we should lock down framework modules
1653 // so that this is not possible.
1654 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1655 }
1656 return true;
1657}
1658
1660 FileManager &FileMgr) {
1661 StringRef Filename = llvm::sys::path::filename(File.getName());
1662 SmallString<128> PrivateFilename(File.getDir().getName());
1663 if (Filename == "module.map")
1664 llvm::sys::path::append(PrivateFilename, "module_private.map");
1665 else if (Filename == "module.modulemap")
1666 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1667 else
1668 return std::nullopt;
1669 return FileMgr.getOptionalFileRef(PrivateFilename);
1670}
1671
1673 FileID ID, unsigned *Offset,
1674 StringRef OriginalModuleMapFile) {
1675 // Find the directory for the module. For frameworks, that may require going
1676 // up from the 'Modules' directory.
1678 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1679 Dir = FileMgr.getOptionalDirectoryRef(".");
1680 } else {
1681 if (!OriginalModuleMapFile.empty()) {
1682 // We're building a preprocessed module map. Find or invent the directory
1683 // that it originally occupied.
1684 Dir = FileMgr.getOptionalDirectoryRef(
1685 llvm::sys::path::parent_path(OriginalModuleMapFile));
1686 if (!Dir) {
1687 auto FakeFile = FileMgr.getVirtualFileRef(OriginalModuleMapFile, 0, 0);
1688 Dir = FakeFile.getDir();
1689 }
1690 } else {
1691 Dir = File.getDir();
1692 }
1693
1694 assert(Dir && "parent must exist");
1695 StringRef DirName(Dir->getName());
1696 if (llvm::sys::path::filename(DirName) == "Modules") {
1697 DirName = llvm::sys::path::parent_path(DirName);
1698 if (DirName.endswith(".framework"))
1699 if (auto MaybeDir = FileMgr.getOptionalDirectoryRef(DirName))
1700 Dir = *MaybeDir;
1701 // FIXME: This assert can fail if there's a race between the above check
1702 // and the removal of the directory.
1703 assert(Dir && "parent must exist");
1704 }
1705 }
1706
1707 assert(Dir && "module map home directory must exist");
1708 switch (loadModuleMapFileImpl(File, IsSystem, *Dir, ID, Offset)) {
1709 case LMM_AlreadyLoaded:
1710 case LMM_NewlyLoaded:
1711 return false;
1712 case LMM_NoDirectory:
1713 case LMM_InvalidModuleMap:
1714 return true;
1715 }
1716 llvm_unreachable("Unknown load module map result");
1717}
1718
1719HeaderSearch::LoadModuleMapResult
1720HeaderSearch::loadModuleMapFileImpl(FileEntryRef File, bool IsSystem,
1721 DirectoryEntryRef Dir, FileID ID,
1722 unsigned *Offset) {
1723 // Check whether we've already loaded this module map, and mark it as being
1724 // loaded in case we recursively try to load it from itself.
1725 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1726 if (!AddResult.second)
1727 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1728
1729 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1730 LoadedModuleMaps[File] = false;
1731 return LMM_InvalidModuleMap;
1732 }
1733
1734 // Try to load a corresponding private module map.
1735 if (OptionalFileEntryRef PMMFile = getPrivateModuleMap(File, FileMgr)) {
1736 if (ModMap.parseModuleMapFile(*PMMFile, IsSystem, Dir)) {
1737 LoadedModuleMaps[File] = false;
1738 return LMM_InvalidModuleMap;
1739 }
1740 }
1741
1742 // This directory has a module map.
1743 return LMM_NewlyLoaded;
1744}
1745
1748 if (!HSOpts->ImplicitModuleMaps)
1749 return std::nullopt;
1750 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1751 // module.map at the framework root is also accepted.
1752 SmallString<128> ModuleMapFileName(Dir.getName());
1753 if (IsFramework)
1754 llvm::sys::path::append(ModuleMapFileName, "Modules");
1755 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1756 if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))
1757 return *F;
1758
1759 // Continue to allow module.map
1760 ModuleMapFileName = Dir.getName();
1761 llvm::sys::path::append(ModuleMapFileName, "module.map");
1762 if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))
1763 return *F;
1764
1765 // For frameworks, allow to have a private module map with a preferred
1766 // spelling when a public module map is absent.
1767 if (IsFramework) {
1768 ModuleMapFileName = Dir.getName();
1769 llvm::sys::path::append(ModuleMapFileName, "Modules",
1770 "module.private.modulemap");
1771 if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))
1772 return *F;
1773 }
1774 return std::nullopt;
1775}
1776
1777Module *HeaderSearch::loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
1778 bool IsSystem) {
1779 // Try to load a module map file.
1780 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1781 case LMM_InvalidModuleMap:
1782 // Try to infer a module map from the framework directory.
1783 if (HSOpts->ImplicitModuleMaps)
1784 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1785 break;
1786
1787 case LMM_NoDirectory:
1788 return nullptr;
1789
1790 case LMM_AlreadyLoaded:
1791 case LMM_NewlyLoaded:
1792 break;
1793 }
1794
1795 return ModMap.findModule(Name);
1796}
1797
1798HeaderSearch::LoadModuleMapResult
1799HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1800 bool IsFramework) {
1801 if (auto Dir = FileMgr.getOptionalDirectoryRef(DirName))
1802 return loadModuleMapFile(*Dir, IsSystem, IsFramework);
1803
1804 return LMM_NoDirectory;
1805}
1806
1807HeaderSearch::LoadModuleMapResult
1809 bool IsFramework) {
1810 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1811 if (KnownDir != DirectoryHasModuleMap.end())
1812 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1813
1814 if (OptionalFileEntryRef ModuleMapFile =
1815 lookupModuleMapFile(Dir, IsFramework)) {
1816 LoadModuleMapResult Result =
1817 loadModuleMapFileImpl(*ModuleMapFile, IsSystem, Dir);
1818 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1819 // E.g. Foo.framework/Modules/module.modulemap
1820 // ^Dir ^ModuleMapFile
1821 if (Result == LMM_NewlyLoaded)
1822 DirectoryHasModuleMap[Dir] = true;
1823 else if (Result == LMM_InvalidModuleMap)
1824 DirectoryHasModuleMap[Dir] = false;
1825 return Result;
1826 }
1827 return LMM_InvalidModuleMap;
1828}
1829
1831 Modules.clear();
1832
1833 if (HSOpts->ImplicitModuleMaps) {
1834 // Load module maps for each of the header search directories.
1835 for (DirectoryLookup &DL : search_dir_range()) {
1836 bool IsSystem = DL.isSystemHeaderDirectory();
1837 if (DL.isFramework()) {
1838 std::error_code EC;
1839 SmallString<128> DirNative;
1840 llvm::sys::path::native(DL.getFrameworkDirRef()->getName(), DirNative);
1841
1842 // Search each of the ".framework" directories to load them as modules.
1843 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1844 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1845 DirEnd;
1846 Dir != DirEnd && !EC; Dir.increment(EC)) {
1847 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1848 continue;
1849
1850 auto FrameworkDir = FileMgr.getOptionalDirectoryRef(Dir->path());
1851 if (!FrameworkDir)
1852 continue;
1853
1854 // Load this framework module.
1855 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
1856 IsSystem);
1857 }
1858 continue;
1859 }
1860
1861 // FIXME: Deal with header maps.
1862 if (DL.isHeaderMap())
1863 continue;
1864
1865 // Try to load a module map file for the search directory.
1866 loadModuleMapFile(*DL.getDirRef(), IsSystem, /*IsFramework*/ false);
1867
1868 // Try to load module map files for immediate subdirectories of this
1869 // search directory.
1870 loadSubdirectoryModuleMaps(DL);
1871 }
1872 }
1873
1874 // Populate the list of modules.
1875 llvm::transform(ModMap.modules(), std::back_inserter(Modules),
1876 [](const auto &NameAndMod) { return NameAndMod.second; });
1877}
1878
1880 if (!HSOpts->ImplicitModuleMaps)
1881 return;
1882
1883 // Load module maps for each of the header search directories.
1884 for (const DirectoryLookup &DL : search_dir_range()) {
1885 // We only care about normal header directories.
1886 if (!DL.isNormalDir())
1887 continue;
1888
1889 // Try to load a module map file for the search directory.
1890 loadModuleMapFile(*DL.getDirRef(), DL.isSystemHeaderDirectory(),
1891 DL.isFramework());
1892 }
1893}
1894
1895void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1896 assert(HSOpts->ImplicitModuleMaps &&
1897 "Should not be loading subdirectory module maps");
1898
1899 if (SearchDir.haveSearchedAllModuleMaps())
1900 return;
1901
1902 std::error_code EC;
1903 SmallString<128> Dir = SearchDir.getDirRef()->getName();
1904 FileMgr.makeAbsolutePath(Dir);
1905 SmallString<128> DirNative;
1906 llvm::sys::path::native(Dir, DirNative);
1907 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1908 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1909 Dir != DirEnd && !EC; Dir.increment(EC)) {
1910 if (Dir->type() == llvm::sys::fs::file_type::regular_file)
1911 continue;
1912 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1913 if (IsFramework == SearchDir.isFramework())
1914 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1915 SearchDir.isFramework());
1916 }
1917
1918 SearchDir.setSearchedAllModuleMaps(true);
1919}
1920
1922 FileEntryRef File, llvm::StringRef MainFile, bool *IsAngled) const {
1923 return suggestPathToFileForDiagnostics(File.getName(), /*WorkingDir=*/"",
1924 MainFile, IsAngled);
1925}
1926
1928 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1929 bool *IsAngled) const {
1930 using namespace llvm::sys;
1931
1932 llvm::SmallString<32> FilePath = File;
1933 // remove_dots switches to backslashes on windows as a side-effect!
1934 // We always want to suggest forward slashes for includes.
1935 // (not remove_dots(..., posix) as that misparses windows paths).
1936 path::remove_dots(FilePath, /*remove_dot_dot=*/true);
1937 path::native(FilePath, path::Style::posix);
1938 File = FilePath;
1939
1940 unsigned BestPrefixLength = 0;
1941 // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
1942 // the longest prefix we've seen so for it, returns true and updates the
1943 // `BestPrefixLength` accordingly.
1944 auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool {
1945 if (!WorkingDir.empty() && !path::is_absolute(Dir))
1946 fs::make_absolute(WorkingDir, Dir);
1947 path::remove_dots(Dir, /*remove_dot_dot=*/true);
1948 for (auto NI = path::begin(File), NE = path::end(File),
1949 DI = path::begin(Dir), DE = path::end(Dir);
1950 NI != NE; ++NI, ++DI) {
1951 if (DI == DE) {
1952 // Dir is a prefix of File, up to choice of path separators.
1953 unsigned PrefixLength = NI - path::begin(File);
1954 if (PrefixLength > BestPrefixLength) {
1955 BestPrefixLength = PrefixLength;
1956 return true;
1957 }
1958 break;
1959 }
1960
1961 // Consider all path separators equal.
1962 if (NI->size() == 1 && DI->size() == 1 &&
1963 path::is_separator(NI->front()) && path::is_separator(DI->front()))
1964 continue;
1965
1966 // Special case Apple .sdk folders since the search path is typically a
1967 // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
1968 // located in `iPhoneSimulator.sdk` (the real folder).
1969 if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
1970 StringRef NBasename = path::stem(*NI);
1971 StringRef DBasename = path::stem(*DI);
1972 if (DBasename.startswith(NBasename))
1973 continue;
1974 }
1975
1976 if (*NI != *DI)
1977 break;
1978 }
1979 return false;
1980 };
1981
1982 bool BestPrefixIsFramework = false;
1983 for (const DirectoryLookup &DL : search_dir_range()) {
1984 if (DL.isNormalDir()) {
1985 StringRef Dir = DL.getDirRef()->getName();
1986 if (CheckDir(Dir)) {
1987 if (IsAngled)
1988 *IsAngled = BestPrefixLength && isSystem(DL.getDirCharacteristic());
1989 BestPrefixIsFramework = false;
1990 }
1991 } else if (DL.isFramework()) {
1992 StringRef Dir = DL.getFrameworkDirRef()->getName();
1993 if (CheckDir(Dir)) {
1994 // Framework includes by convention use <>.
1995 if (IsAngled)
1996 *IsAngled = BestPrefixLength;
1997 BestPrefixIsFramework = true;
1998 }
1999 }
2000 }
2001
2002 // Try to shorten include path using TUs directory, if we couldn't find any
2003 // suitable prefix in include search paths.
2004 if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) {
2005 if (IsAngled)
2006 *IsAngled = false;
2007 BestPrefixIsFramework = false;
2008 }
2009
2010 // Try resolving resulting filename via reverse search in header maps,
2011 // key from header name is user preferred name for the include file.
2012 StringRef Filename = File.drop_front(BestPrefixLength);
2013 for (const DirectoryLookup &DL : search_dir_range()) {
2014 if (!DL.isHeaderMap())
2015 continue;
2016
2017 StringRef SpelledFilename =
2018 DL.getHeaderMap()->reverseLookupFilename(Filename);
2019 if (!SpelledFilename.empty()) {
2020 Filename = SpelledFilename;
2021 BestPrefixIsFramework = false;
2022 break;
2023 }
2024 }
2025
2026 // If the best prefix is a framework path, we need to compute the proper
2027 // include spelling for the framework header.
2028 bool IsPrivateHeader;
2029 SmallString<128> FrameworkName, IncludeSpelling;
2030 if (BestPrefixIsFramework &&
2031 isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName,
2032 IncludeSpelling)) {
2033 Filename = IncludeSpelling;
2034 }
2035 return path::convert_to_slash(Filename);
2036}
Defines the Diagnostic-related interfaces.
Defines the clang::FileManager interface and associated types.
StringRef Filename
Definition: Format.cpp:2976
unsigned Iter
Definition: HTMLLogger.cpp:154
static OptionalFileEntryRef getPrivateModuleMap(FileEntryRef File, FileManager &FileMgr)
static void mergeHeaderFileInfo(HeaderFileInfo &HFI, const HeaderFileInfo &OtherHFI)
Merge the header file info provided by OtherHFI into the current header file info (HFI)
static bool suggestModule(HeaderSearch &HS, FileEntryRef File, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule)
static void diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc, StringRef Includer, StringRef IncludeFilename, FileEntryRef IncludeFE, bool isAngled=false, bool FoundByHeaderMap=false)
static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags, OptionalFileEntryRef 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...
static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader, SmallVectorImpl< char > &FrameworkName, SmallVectorImpl< char > &IncludeSpelling)
static const char * copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc)
ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.")
static bool needModuleLookup(Module *RequestingModule, bool HasSuggestedModule)
static OptionalDirectoryEntryRef getTopFrameworkDir(FileManager &FileMgr, StringRef DirName, SmallVectorImpl< std::string > &SubmodulePath)
Given a framework directory, find the top-most framework directory.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines the clang::Module class, which describes a module in the source code.
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
constexpr bool has_value() const
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
A reference to a DirectoryEntry that includes the name of the directory as it was accessed by the Fil...
StringRef getName() const
Cached information about one directory (either on disk or in the virtual file system).
StringRef getName() const
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
SrcMgr::CharacteristicKind getDirCharacteristic() const
DirCharacteristic - The type of directory this is, one of the DirType enum values.
OptionalFileEntryRef LookupFile(StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound, bool &IsInHeaderMap, SmallVectorImpl< char > &MappedName, bool OpenFile=true) const
LookupFile - Lookup the specified file in this search path, returning it if it exists or returning nu...
bool isFramework() const
isFramework - True if this is a framework directory.
bool isSystemHeaderDirectory() const
Whether this describes a system header directory.
OptionalDirectoryEntryRef getFrameworkDirRef() const
void setSearchedAllModuleMaps(bool SAMM)
Specify whether we have already searched all of the subdirectories for module maps.
bool isHeaderMap() const
isHeaderMap - Return true if this is a header map, not a normal directory.
StringRef getName() const
getName - Return the directory or filename corresponding to this lookup object.
OptionalDirectoryEntryRef getDirRef() const
bool haveSearchedAllModuleMaps() const
Determine whether we have already searched this entire directory for module maps.
const DirectoryEntry * getDir() const
getDir - Return the directory that this entry refers to.
bool isNormalDir() const
isNormalDir - Return true if this is a normal directory, not a header map.
const HeaderMap * getHeaderMap() const
getHeaderMap - Return the directory that this entry refers to.
Abstract interface for external sources of preprocessor information.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
unsigned getUID() const
Definition: FileEntry.h:418
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:366
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:245
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:234
llvm::ErrorOr< const DirectoryEntry * > getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
StringRef getCanonicalName(DirectoryEntryRef Dir)
Retrieve the canonical name for a given directory.
bool makeAbsolutePath(SmallVectorImpl< char > &Path) const
Makes Path absolute taking into account FileSystemOptions and the working directory option.
FileEntryRef getVirtualFileRef(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...
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:169
llvm::Expected< FileEntryRef > getFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
This class represents an Apple concept known as a 'header map'.
Definition: HeaderMap.h:84
StringRef getFileName() const
Return the filename of the headermap.
Definition: HeaderMap.cpp:108
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:196
static std::unique_ptr< HeaderMap > Create(FileEntryRef FE, FileManager &FM)
This attempts to load the specified file as a header map.
Definition: HeaderMap.cpp:51
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:232
StringRef getUniqueFrameworkName(StringRef Framework)
Retrieve a uniqued framework name.
FileManager & getFileMgr() const
Definition: HeaderSearch.h:370
const HeaderFileInfo * getExistingFileInfo(FileEntryRef FE, bool WantExternal=true) const
Return the HeaderFileInfo structure for the specified FileEntry, if it has ever been filled in.
void AddSearchPath(const DirectoryLookup &dir, bool isAngled)
Add an additional search path.
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
HeaderSearch(std::shared_ptr< HeaderSearchOptions > HSOpts, SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target)
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...
std::string suggestPathToFileForDiagnostics(FileEntryRef File, llvm::StringRef MainFile, bool *IsAngled=nullptr) const
Suggest a path by which the specified file could be found, for use in diagnostics to suggest a #inclu...
OptionalFileEntryRef LookupFile(StringRef Filename, SourceLocation IncludeLoc, bool isAngled, ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDir, ArrayRef< std::pair< OptionalFileEntryRef, DirectoryEntryRef > > Includers, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool BuildSystemModule=false, bool OpenFile=true, bool CacheFailures=true)
Given a "foo" or <foo> reference, look up the indicated file, return null on failure.
void getHeaderMapFileNames(SmallVectorImpl< std::string > &Names) const
Get filenames for all registered header maps.
StringRef getIncludeNameForHeader(const FileEntry *File) const
Retrieve the include name for the header.
std::string getPrebuiltImplicitModuleFileName(Module *Module)
Retrieve the name of the prebuilt module file that should be used to load the given module.
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:432
ConstSearchDirIterator angled_dir_begin() const
Definition: HeaderSearch.h:847
ArrayRef< ModuleMap::KnownHeader > findAllModulesForHeader(FileEntryRef File) const
Retrieve all the modules corresponding to the given file.
unsigned searchDirIdx(const DirectoryLookup &DL) const
Get the index of the given search directory.
bool isFileMultipleIncludeGuarded(FileEntryRef File) const
Determine whether this file is intended to be safe from multiple inclusions, e.g.,...
ConstSearchDirIterator search_dir_nth(size_t n) const
Definition: HeaderSearch.h:833
void loadTopLevelSystemModules()
Load all known, top-level system modules.
SearchDirIterator search_dir_end()
Definition: HeaderSearch.h:827
FrameworkCacheEntry & LookupFrameworkCache(StringRef FWName)
Look up the specified framework name in our framework cache.
Definition: HeaderSearch.h:519
std::vector< bool > computeUserEntryUsage() const
Determine which HeaderSearchOptions::UserEntries have been successfully used so far and mark their in...
ArrayRef< ModuleMap::KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
bool loadModuleMapFile(FileEntryRef File, bool IsSystem, FileID ID=FileID(), unsigned *Offset=nullptr, StringRef OriginalModuleMapFile=StringRef())
Read the contents of the given module map file.
void setTarget(const TargetInfo &Target)
Set the target information for the header search, if not already known.
const HeaderMap * CreateHeaderMap(FileEntryRef FE)
This method returns a HeaderMap for the specified FileEntry, uniquing them through the 'HeaderMaps' d...
ModuleMap::KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual=false, bool AllowExcluded=false) const
Retrieve the module that corresponds to the given file, if any.
SearchDirRange search_dir_range()
Definition: HeaderSearch.h:828
std::string getCachedModuleFileName(Module *Module)
Retrieve the name of the cached module file that should be used to load the given module.
void collectAllModules(SmallVectorImpl< Module * > &Modules)
Collect the set of all known, top-level modules.
void MarkFileModuleHeader(FileEntryRef FE, ModuleMap::ModuleHeaderRole Role, bool isCompilingModuleHeader)
Mark the specified file as part of a module.
OptionalFileEntryRef LookupSubframeworkHeader(StringRef Filename, FileEntryRef ContextFileEnt, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule)
Look up a subframework for the specified #include file.
void SetSearchPaths(std::vector< DirectoryLookup > dirs, unsigned angledDirIdx, unsigned systemDirIdx, bool noCurDirSearch, llvm::DenseMap< unsigned, unsigned > searchDirToHSEntry)
Interface for setting the file search paths.
HeaderFileInfo & getFileInfo(FileEntryRef FE)
Return the HeaderFileInfo structure for the specified FileEntry, in preparation for updating it in so...
OptionalFileEntryRef lookupModuleMapFile(DirectoryEntryRef Dir, bool IsFramework)
Try to find a module map file in the given directory, returning nullopt if none is found.
bool ShouldEnterIncludeFile(Preprocessor &PP, FileEntryRef File, bool isImport, bool ModulesEnabled, Module *M, bool &IsFirstIncludeOfFile)
Mark the specified file as a target of a #include, #include_next, or #import directive.
size_t getTotalMemory() const
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:808
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
Definition: HeaderSearch.h:368
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...
StringRef getModuleHash() const
Retrieve the module hash.
Definition: HeaderSearch.h:429
SearchDirIterator search_dir_begin()
Definition: HeaderSearch.h:826
One of these records is kept for each identifier that is lexed.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:83
A header that is known to reside within a given module, whether it was included or excluded.
Definition: ModuleMap.h:159
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:827
KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual=false, bool AllowExcluded=false)
Retrieve the module that owns the given header file, if any.
Definition: ModuleMap.cpp:606
static bool isModular(ModuleHeaderRole Role)
Check if the header with the given role is a modular one.
Definition: ModuleMap.cpp:109
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1248
ArrayRef< KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
Definition: ModuleMap.cpp:720
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
Definition: ModuleMap.cpp:1320
bool isBuiltinHeader(FileEntryRef File)
Is this a compiler builtin header?
Definition: ModuleMap.cpp:415
bool parseModuleMapFile(FileEntryRef File, bool IsSystem, DirectoryEntryRef 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:3109
void setTarget(const TargetInfo &Target)
Set the target information.
Definition: ModuleMap.cpp:372
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:127
@ TextualHeader
This header is part of the module (for layering purposes) but should be textually included.
Definition: ModuleMap.h:136
ArrayRef< KnownHeader > findAllModulesForHeader(FileEntryRef File)
Retrieve all the modules that contain the given header file.
Definition: ModuleMap.cpp:708
llvm::iterator_range< module_iterator > modules() const
Definition: ModuleMap.h:742
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1407
Describes a module or submodule.
Definition: Module.h:105
bool directlyUses(const Module *Requested)
Determine whether this module has declared its intention to directly use another module.
Definition: Module.cpp:292
std::string Name
The name of this module.
Definition: Module.h:108
unsigned NoUndeclaredIncludes
Whether files in this module can only include non-modular headers and headers from used modules.
Definition: Module.h:372
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
bool markIncluded(FileEntryRef File)
Mark the file as included.
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've alread...
bool isMacroDefined(StringRef Id)
bool alreadyIncluded(FileEntryRef File) const
Return true if this header has already been included.
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Exposes information about the current target.
Definition: TargetInfo.h:212
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: Format.h:5226
#define false
Definition: stdbool.h:22
This structure is used to record entries in our framework cache.
Definition: HeaderSearch.h:155
bool IsUserSpecifiedSystemFramework
Whether this framework has been "user-specified" to be treated as if it were a system framework (even...
Definition: HeaderSearch.h:162
OptionalDirectoryEntryRef Directory
The directory entry which should be used for the cached framework.
Definition: HeaderSearch.h:157
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:58
unsigned IndexHeaderMapHeader
Whether this is a header inside a framework that is currently being built.
Definition: HeaderSearch.h:102
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
Definition: HeaderSearch.h:74
const IdentifierInfo * ControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file,...
Definition: HeaderSearch.h:123
unsigned isModuleHeader
Whether this header is part of a module.
Definition: HeaderSearch.h:83
const IdentifierInfo * getControllingMacro(ExternalPreprocessorSource *External)
Retrieve the controlling macro for this header file, if any.
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:67
unsigned Resolved
Whether this structure is considered to already have been "resolved", meaning that it was loaded from...
Definition: HeaderSearch.h:92
unsigned isCompilingModuleHeader
Whether this header is part of the module that we are building.
Definition: HeaderSearch.h:87
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:106
unsigned isImport
True if this is a #import'd file.
Definition: HeaderSearch.h:63
StringRef Framework
If this header came from a framework include, this is the name of the framework.
Definition: HeaderSearch.h:127
unsigned ControllingMacroID
The ID number of the controlling macro.
Definition: HeaderSearch.h:113
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
Definition: HeaderSearch.h:79