blob: 3bb7f8e042889c0b87bd429dff99fc8dd0264be5 [file] [log] [blame]
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59a9ebd2006-10-18 05:34:33 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner59a9ebd2006-10-18 05:34:33 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattneref6b1362007-10-07 08:58:51 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Richard Smith2aedca32015-07-01 02:29:35 +000017#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/HeaderMap.h"
19#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000020#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000021#include "clang/Lex/Lexer.h"
Richard Smith20e883e2015-04-29 23:20:19 +000022#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000023#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000025#include "llvm/ADT/SmallString.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000026#include "llvm/Support/Capacity.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/Path.h"
Daniel Jasperba7f2f72013-09-24 09:14:14 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000030#include <cstdio>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000031#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoeadae012013-01-26 16:29:36 +000032#include <limits.h>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000033#endif
Chris Lattner59a9ebd2006-10-18 05:34:33 +000034using namespace clang;
35
Douglas Gregor99734e72009-04-25 23:30:02 +000036const IdentifierInfo *
Richard Smith2aedca32015-07-01 02:29:35 +000037HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
38 if (ControllingMacro) {
39 if (ControllingMacro->isOutOfDate())
40 External->updateOutOfDateIdentifier(
41 *const_cast<IdentifierInfo *>(ControllingMacro));
Douglas Gregor99734e72009-04-25 23:30:02 +000042 return ControllingMacro;
Richard Smith2aedca32015-07-01 02:29:35 +000043 }
Douglas Gregor99734e72009-04-25 23:30:02 +000044
45 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000046 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000047
48 ControllingMacro = External->GetIdentifier(ControllingMacroID);
49 return ControllingMacro;
50}
51
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000052ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
Douglas Gregor09b69892011-02-10 17:09:37 +000053
Dmitri Gribenkof8579502013-01-12 19:30:44 +000054HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000055 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000056 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000057 const TargetInfo *Target)
Will Wilsonba2f1462013-12-27 20:02:27 +000058 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
Samuel Antao610954a2016-04-27 22:28:32 +000059 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
Nico Weber3b1d1212011-05-24 04:31:14 +000060 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000061 SystemDirIdx = 0;
62 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000063
Craig Topperd2d442c2014-05-17 23:10:59 +000064 ExternalLookup = nullptr;
65 ExternalSource = nullptr;
Chris Lattner641a0be2006-10-20 06:23:14 +000066 NumIncluded = 0;
67 NumMultiIncludeFileOptzn = 0;
68 NumFrameworkLookups = NumSubFrameworkLookups = 0;
69}
70
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000071HeaderSearch::~HeaderSearch() {
72 // Delete headermaps.
73 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
74 delete HeaderMaps[i].second;
75}
Mike Stump11289f42009-09-09 15:08:12 +000076
Chris Lattner59a9ebd2006-10-18 05:34:33 +000077void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000078 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
79 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000080 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
81 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
82 NumOnceOnlyFiles += FileInfo[i].isImport;
83 if (MaxNumIncludes < FileInfo[i].NumIncludes)
84 MaxNumIncludes = FileInfo[i].NumIncludes;
85 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
86 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000087 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
88 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
89 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000090
Chris Lattner23b7eb62007-06-15 23:05:46 +000091 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
92 fprintf(stderr, " %d #includes skipped due to"
93 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattner23b7eb62007-06-15 23:05:46 +000095 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
96 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +000097}
98
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000099/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000100/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000101const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000102 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000103 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000104 if (!HeaderMaps.empty()) {
105 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000106 // Pointer equality comparison of FileEntries works because they are
107 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000108 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000109 return HeaderMaps[i].second;
110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Chris Lattner5159f612010-11-23 08:35:12 +0000112 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000113 HeaderMaps.push_back(std::make_pair(FE, HM));
114 return HM;
115 }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Craig Topperd2d442c2014-05-17 23:10:59 +0000117 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000118}
119
Douglas Gregor279a6c32012-01-29 17:08:11 +0000120std::string HeaderSearch::getModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000121 const FileEntry *ModuleMap =
122 getModuleMap().getModuleMapFileForUniquing(Module);
Ben Langmuird89dc562015-02-19 20:23:22 +0000123 return getModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000124}
125
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000126std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
Ben Langmuird89dc562015-02-19 20:23:22 +0000127 StringRef ModuleMapPath) {
Richard Smithd520a252015-07-21 18:07:47 +0000128 // If we don't have a module cache path or aren't supposed to use one, we
129 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000130 if (getModuleCachePath().empty())
Douglas Gregor279a6c32012-01-29 17:08:11 +0000131 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000132
Richard Smith3938f0c2015-08-15 00:34:15 +0000133 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000134 llvm::sys::fs::make_absolute(Result);
135
136 if (HSOpts->DisableModuleHash) {
137 llvm::sys::path::append(Result, ModuleName + ".pcm");
138 } else {
139 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000140 // ideally be globally unique to this particular module. Name collisions
141 // in the hash are safe (because any translation unit can only import one
142 // module with each name), but result in a loss of caching.
143 //
144 // To avoid false-negatives, we form as canonical a path as we can, and map
145 // to lower-case in case we're on a case-insensitive file system.
146 auto *Dir =
147 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
148 if (!Dir)
149 return std::string();
150 auto DirName = FileMgr.getCanonicalName(Dir);
151 auto FileName = llvm::sys::path::filename(ModuleMapPath);
152
153 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000154 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000155
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000156 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000157 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000158 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000159 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000160 return Result.str().str();
161}
162
163Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000164 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000165 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000166 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000167 return Module;
168
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000169 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000170 // maps, searching for a module map that describes this module.
171 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
172 if (SearchDirs[Idx].isFramework()) {
173 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000174 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000175 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
176 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
177 if (const DirectoryEntry *FrameworkDir
178 = FileMgr.getDirectory(FrameworkDirName)) {
179 bool IsSystem
180 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
181 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000182 if (Module)
183 break;
184 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000185 }
186
187 // FIXME: Figure out how header maps and module maps will work together.
188
189 // Only deal with normal search directories.
190 if (!SearchDirs[Idx].isNormalDir())
191 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000192
193 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000194 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000195 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
196 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000197 // We just loaded a module map file; check whether the module is
198 // available now.
199 Module = ModMap.findModule(ModuleName);
200 if (Module)
201 break;
202 }
203
204 // Search for a module map in a subdirectory with the same name as the
205 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000206 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000207 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
208 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000209 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
210 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000211 // If we just loaded a module map file, look for the module again.
212 Module = ModMap.findModule(ModuleName);
213 if (Module)
214 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000215 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000216
217 // If we've already performed the exhaustive search for module maps in this
218 // search directory, don't do it again.
219 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
220 continue;
221
222 // Load all module maps in the immediate subdirectories of this search
223 // directory.
224 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
225
226 // Look again for the module.
227 Module = ModMap.findModule(ModuleName);
228 if (Module)
229 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000230 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000231
Douglas Gregor279a6c32012-01-29 17:08:11 +0000232 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000233}
234
Chris Lattnerf62f7582007-12-17 07:52:39 +0000235//===----------------------------------------------------------------------===//
236// File lookup within a DirectoryLookup scope
237//===----------------------------------------------------------------------===//
238
Chris Lattner8d720d02007-12-17 17:57:27 +0000239/// getName - Return the directory or filename corresponding to this lookup
240/// object.
241const char *DirectoryLookup::getName() const {
242 if (isNormalDir())
243 return getDir()->getName();
244 if (isFramework())
245 return getFrameworkDir()->getName();
246 assert(isHeaderMap() && "Unknown DirectoryLookup");
247 return getHeaderMap()->getFileName();
248}
249
Richard Smith3d5b48c2015-10-16 21:42:56 +0000250const FileEntry *HeaderSearch::getFileAndSuggestModule(
251 StringRef FileName, const DirectoryEntry *Dir, bool IsSystemHeaderDir,
252 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000253 // If we have a module map that might map this header, load it and
254 // check whether we'll have a suggestion for a module.
Richard Smith3d5b48c2015-10-16 21:42:56 +0000255 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
Reid Klecknerafb9aae2015-10-20 18:45:57 +0000256 if (!File)
257 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000258
Richard Smith3d5b48c2015-10-16 21:42:56 +0000259 // If there is a module that corresponds to this header, suggest it.
260 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
261 RequestingModule, SuggestedModule,
262 IsSystemHeaderDir))
263 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000264
Richard Smith3d5b48c2015-10-16 21:42:56 +0000265 return File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000266}
Chris Lattner8d720d02007-12-17 17:57:27 +0000267
Chris Lattnerf62f7582007-12-17 07:52:39 +0000268/// LookupFile - Lookup the specified file in this search path, returning it
269/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000270const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000271 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000272 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000273 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000274 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000275 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000276 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000277 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000278 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000279 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000280 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000281 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000282
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000283 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000284 if (isNormalDir()) {
285 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000286 TmpDir = getDir()->getName();
287 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000288 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000289 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000290 SearchPath->clear();
291 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
292 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000293 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000294 RelativePath->clear();
295 RelativePath->append(Filename.begin(), Filename.end());
296 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000297
Richard Smith3d5b48c2015-10-16 21:42:56 +0000298 return HS.getFileAndSuggestModule(TmpDir, getDir(),
299 isSystemHeaderDirectory(),
300 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000301 }
Mike Stump11289f42009-09-09 15:08:12 +0000302
Chris Lattner712e3872007-12-17 08:13:48 +0000303 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000304 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000305 RequestingModule, SuggestedModule,
306 InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000307
Chris Lattner44bd21b2007-12-17 08:17:39 +0000308 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000309 const HeaderMap *HM = getHeaderMap();
310 SmallString<1024> Path;
311 StringRef Dest = HM->lookupFilename(Filename, Path);
312 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000313 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000314
315 const FileEntry *Result;
316
317 // Check if the headermap maps the filename to a framework include
318 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
319 // framework include.
320 if (llvm::sys::path::is_relative(Dest)) {
321 MappedName.clear();
322 MappedName.append(Dest.begin(), Dest.end());
323 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000324 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000325 Result = HM->LookupFile(Filename, HS.getFileMgr());
326
327 } else {
328 Result = HS.getFileMgr().getFile(Dest);
329 }
330
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000331 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000332 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000333 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000334 SearchPath->clear();
335 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
336 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000337 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000338 RelativePath->clear();
339 RelativePath->append(Filename.begin(), Filename.end());
340 }
341 }
342 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000343}
344
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000345/// \brief Given a framework directory, find the top-most framework directory.
346///
347/// \param FileMgr The file manager to use for directory lookups.
348/// \param DirName The name of the framework directory.
349/// \param SubmodulePath Will be populated with the submodule path from the
350/// returned top-level module to the originally named framework.
351static const DirectoryEntry *
352getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
353 SmallVectorImpl<std::string> &SubmodulePath) {
354 assert(llvm::sys::path::extension(DirName) == ".framework" &&
355 "Not a framework directory");
356
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000357 // Note: as an egregious but useful hack we use the real path here, because
358 // frameworks moving between top-level frameworks to embedded frameworks tend
359 // to be symlinked, and we base the logical structure of modules on the
360 // physical layout. In particular, we need to deal with crazy includes like
361 //
362 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
363 //
364 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
365 // which one should access with, e.g.,
366 //
367 // #include <Bar/Wibble.h>
368 //
369 // Similar issues occur when a top-level framework has moved into an
370 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000371 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000372 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000373 do {
374 // Get the parent directory name.
375 DirName = llvm::sys::path::parent_path(DirName);
376 if (DirName.empty())
377 break;
378
379 // Determine whether this directory exists.
380 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
381 if (!Dir)
382 break;
383
384 // If this is a framework directory, then we're a subframework of this
385 // framework.
386 if (llvm::sys::path::extension(DirName) == ".framework") {
387 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
388 TopFrameworkDir = Dir;
389 }
390 } while (true);
391
392 return TopFrameworkDir;
393}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000394
Chris Lattner712e3872007-12-17 08:13:48 +0000395/// DoFrameworkLookup - Do a lookup of the specified file in the current
396/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000397const FileEntry *DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000398 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
399 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000400 ModuleMap::KnownHeader *SuggestedModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000401 bool &InUserSpecifiedSystemFramework) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000402 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000404 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000405 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000406 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattner712e3872007-12-17 08:13:48 +0000408 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000409 // HeaderSearch. Possible answers are yes/no and unknown.
410 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000411 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner712e3872007-12-17 08:13:48 +0000413 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000414 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000415 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattner712e3872007-12-17 08:13:48 +0000417 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000418
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000419 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000420 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000421 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000422 if (FrameworkName.empty() || FrameworkName.back() != '/')
423 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000425 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000426 StringRef ModuleName(Filename.begin(), SlashPos);
427 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000429 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
430 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000431
Daniel Dunbar17138612012-04-05 17:09:40 +0000432 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000433 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000434 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattner5ed76da2006-10-22 07:24:13 +0000436 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000437 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000438 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000439
Chris Lattner5ed76da2006-10-22 07:24:13 +0000440 // Otherwise, if it does, remember that this is the right direntry for this
441 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000442 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000443
444 // If this is a user search directory, check if the framework has been
445 // user-specified as a system framework.
446 if (getDirCharacteristic() == SrcMgr::C_User) {
447 SmallString<1024> SystemFrameworkMarker(FrameworkName);
448 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000449 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000450 CacheEntry.IsUserSpecifiedSystemFramework = true;
451 }
452 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000453 }
Mike Stump11289f42009-09-09 15:08:12 +0000454
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000455 // Set the 'user-specified system framework' flag.
456 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
457
Craig Topperd2d442c2014-05-17 23:10:59 +0000458 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000459 RelativePath->clear();
460 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
461 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000462
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000463 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000464 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000465
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000466 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000467
Craig Topperd2d442c2014-05-17 23:10:59 +0000468 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000469 SearchPath->clear();
470 // Without trailing '/'.
471 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
472 }
473
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000474 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000475 const FileEntry *FE = FileMgr.getFile(FrameworkName,
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000476 /*openFile=*/!SuggestedModule);
477 if (!FE) {
478 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
479 const char *Private = "Private";
480 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
481 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000482 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000483 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
484 Private+strlen(Private));
485
Yaron Keren92e1b622015-03-18 10:17:07 +0000486 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000487 }
Mike Stump11289f42009-09-09 15:08:12 +0000488
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000489 // If we found the header and are allowed to suggest a module, do so now.
490 if (FE && SuggestedModule) {
491 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000492 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000493 bool FoundFramework = false;
494 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000495 // Determine whether this directory exists.
496 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
497 if (!Dir)
498 break;
499
500 // If this is a framework directory, then we're a subframework of this
501 // framework.
502 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
503 FoundFramework = true;
504 break;
505 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000506
507 // Get the parent directory name.
508 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
509 if (FrameworkPath.empty())
510 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000511 } while (true);
512
Richard Smith3d5b48c2015-10-16 21:42:56 +0000513 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000514 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000515 if (!HS.findUsableModuleForFrameworkHeader(
516 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
517 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000518 } else {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000519 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
520 SuggestedModule, IsSystem))
521 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000522 }
523 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000524 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000525}
526
Douglas Gregor89929282012-01-30 06:01:29 +0000527void HeaderSearch::setTarget(const TargetInfo &Target) {
528 ModMap.setTarget(Target);
529}
530
Chris Lattnerf62f7582007-12-17 07:52:39 +0000531
Chris Lattner712e3872007-12-17 08:13:48 +0000532//===----------------------------------------------------------------------===//
533// Header File Location.
534//===----------------------------------------------------------------------===//
535
Reid Klecknera97d4c02014-02-18 23:49:24 +0000536/// \brief Return true with a diagnostic if the file that MSVC would have found
537/// fails to match the one that Clang would have found with MSVC header search
538/// disabled.
539static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
540 const FileEntry *MSFE, const FileEntry *FE,
541 SourceLocation IncludeLoc) {
542 if (MSFE && FE != MSFE) {
543 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
544 return true;
545 }
546 return false;
547}
Chris Lattner712e3872007-12-17 08:13:48 +0000548
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000549static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
550 assert(!Str.empty());
551 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
552 std::copy(Str.begin(), Str.end(), CopyStr);
553 CopyStr[Str.size()] = '\0';
554 return CopyStr;
555}
556
James Dennettc07ab2c2012-06-20 00:56:32 +0000557/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000558/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000559/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
560/// non-empty, indicates where the \#including file(s) are, in case a relative
561/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000562const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000563 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
564 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000565 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
566 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000567 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
568 bool SkipCache) {
Douglas Gregor97eec242011-09-15 22:00:41 +0000569 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000570 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000571
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000572 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000573 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000574 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000575
576 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000577 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000578
Craig Topperd2d442c2014-05-17 23:10:59 +0000579 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000580 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000581 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000582 RelativePath->clear();
583 RelativePath->append(Filename.begin(), Filename.end());
584 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000585 // Otherwise, just return the file.
Richard Smith3d5b48c2015-10-16 21:42:56 +0000586 return getFileAndSuggestModule(Filename, nullptr,
587 /*IsSystemHeaderDir*/false,
588 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000589 }
Mike Stump11289f42009-09-09 15:08:12 +0000590
Reid Klecknera97d4c02014-02-18 23:49:24 +0000591 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000592 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000593 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000594
Douglas Gregor9f93e382011-07-28 04:45:53 +0000595 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000596 // directory. This cannot be based on CurDir, because each includer could be
597 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
598 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000599 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000600 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000601 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000602 bool First = true;
603 for (const auto &IncluderAndDir : Includers) {
604 const FileEntry *Includer = IncluderAndDir.first;
605
Will Wilson0fafd342013-12-27 19:46:16 +0000606 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000607 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000608 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000609 TmpDir.push_back('/');
610 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000611
Richard Smith6f548ec2014-03-06 18:08:08 +0000612 // FIXME: We don't cache the result of getFileInfo across the call to
613 // getFileAndSuggestModule, because it's a reference to an element of
614 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000615 //
616 // FIXME: If we have no includer, that means we're processing a #include
617 // from a module build. We should treat this as a system header if we're
618 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000619 bool IncluderIsSystemHeader =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000620 Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000621 if (const FileEntry *FE = getFileAndSuggestModule(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000622 TmpDir, IncluderAndDir.second, IncluderIsSystemHeader,
623 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000624 if (!Includer) {
625 assert(First && "only first includer can have no file");
626 return FE;
627 }
628
Will Wilson0fafd342013-12-27 19:46:16 +0000629 // Leave CurDir unset.
630 // This file is a system header or C++ unfriendly if the old file is.
631 //
632 // Note that we only use one of FromHFI/ToHFI at once, due to potential
633 // reallocation of the underlying vector potentially making the first
634 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000635 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000636 unsigned DirInfo = FromHFI.DirInfo;
637 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
638 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000639
Will Wilson0fafd342013-12-27 19:46:16 +0000640 HeaderFileInfo &ToHFI = getFileInfo(FE);
641 ToHFI.DirInfo = DirInfo;
642 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
643 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000644
Craig Topperd2d442c2014-05-17 23:10:59 +0000645 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000646 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000647 SearchPath->clear();
648 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
649 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000650 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000651 RelativePath->clear();
652 RelativePath->append(Filename.begin(), Filename.end());
653 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000654 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000655 return FE;
656
657 // Otherwise, we found the path via MSVC header search rules. If
658 // -Wmsvc-include is enabled, we have to keep searching to see if we
659 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000660 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000661 return FE;
662 } else {
663 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000664 if (SuggestedModule) {
665 MSSuggestedModule = *SuggestedModule;
666 *SuggestedModule = ModuleMap::KnownHeader();
667 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000668 break;
669 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000670 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000671 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000672 }
673 }
Mike Stump11289f42009-09-09 15:08:12 +0000674
Craig Topperd2d442c2014-05-17 23:10:59 +0000675 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000676
677 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000678 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000679
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000680 // If this is a #include_next request, start searching after the directory the
681 // file was found in.
682 if (FromDir)
683 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000684
Chris Lattnerd4275422007-07-22 07:28:00 +0000685 // Cache all of the lookups performed by this method. Many headers are
686 // multiply included, and the "pragma once" optimization prevents them from
687 // being relex/pp'd, but they would still have to search through a
688 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000689 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000690
691 // If the entry has been previously looked up, the first value will be
692 // non-zero. If the value is equal to i (the start point of our search), then
693 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000694 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000695 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000696 i = CacheLookup.HitIdx;
697 if (CacheLookup.MappedName)
698 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000699 } else {
700 // Otherwise, this is the first query, or the previous query didn't match
701 // our search start. We will fill in our found location below, so prime the
702 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000703 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000704 }
Mike Stump11289f42009-09-09 15:08:12 +0000705
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000706 SmallString<64> MappedName;
707
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000708 // Check each directory in sequence to see if it contains this file.
709 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000710 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000711 bool HasBeenMapped = false;
Richard Smith3d5b48c2015-10-16 21:42:56 +0000712 const FileEntry *FE = SearchDirs[i].LookupFile(
713 Filename, *this, SearchPath, RelativePath, RequestingModule,
714 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
715 MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000716 if (HasBeenMapped) {
717 CacheLookup.MappedName =
718 copyString(Filename, LookupFileCache.getAllocator());
719 }
Chris Lattner712e3872007-12-17 08:13:48 +0000720 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000721
Chris Lattner712e3872007-12-17 08:13:48 +0000722 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000723
Chris Lattner712e3872007-12-17 08:13:48 +0000724 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000725 HeaderFileInfo &HFI = getFileInfo(FE);
726 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000727
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000728 // If the directory characteristic is User but this framework was
729 // user-specified to be treated as a system framework, promote the
730 // characteristic.
731 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
732 HFI.DirInfo = SrcMgr::C_System;
733
Richard Smith8acadcb2012-06-13 20:27:03 +0000734 // If the filename matches a known system header prefix, override
735 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000736 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
737 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
738 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000739 : SrcMgr::C_User;
740 break;
741 }
742 }
743
Douglas Gregor9f93e382011-07-28 04:45:53 +0000744 // If this file is found in a header map and uses the framework style of
745 // includes, then this header is part of a framework we're building.
746 if (CurDir->isIndexHeaderMap()) {
747 size_t SlashPos = Filename.find('/');
748 if (SlashPos != StringRef::npos) {
749 HFI.IndexHeaderMapHeader = 1;
750 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
751 SlashPos));
752 }
753 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000754
Richard Smith8c71eba2014-03-05 20:51:45 +0000755 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
756 if (SuggestedModule)
757 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000758 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000759 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000760
Chris Lattner712e3872007-12-17 08:13:48 +0000761 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000762 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000763 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000764 }
Mike Stump11289f42009-09-09 15:08:12 +0000765
Douglas Gregord8575e12011-07-30 06:28:34 +0000766 // If we are including a file with a quoted include "foo.h" from inside
767 // a header in a framework that is currently being built, and we couldn't
768 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
769 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000770 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000771 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000772 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000773 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000774 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000775 ScratchFilename += IncludingHFI.Framework;
776 ScratchFilename += '/';
777 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000778
Richard Smith3d5b48c2015-10-16 21:42:56 +0000779 const FileEntry *FE =
780 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
781 CurDir, Includers.front(), SearchPath, RelativePath,
782 RequestingModule, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000783
Richard Smith8c71eba2014-03-05 20:51:45 +0000784 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
785 if (SuggestedModule)
786 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000787 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000788 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000789
David Blaikie3c8c46e2014-11-19 05:48:40 +0000790 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000791 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000792 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000793 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000794 }
795 }
796
Craig Topperd2d442c2014-05-17 23:10:59 +0000797 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000798 if (SuggestedModule)
799 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000800 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000801 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000802
Chris Lattnerd4275422007-07-22 07:28:00 +0000803 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000804 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000805 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000806}
807
Chris Lattner63dd32b2006-10-20 04:42:40 +0000808/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000809/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000810/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
811/// is a subframework within Carbon.framework. If so, return the FileEntry
812/// for the designated file, otherwise return null.
813const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000814LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000815 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000816 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000817 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000818 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000819 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000820 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000821
Chris Lattner63dd32b2006-10-20 04:42:40 +0000822 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000823 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000824 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000825 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000826
Chris Lattner63dd32b2006-10-20 04:42:40 +0000827 // Look up the base framework name of the ContextFileEnt.
Chris Lattner48043482006-10-27 05:12:36 +0000828 const char *ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000829
Chris Lattner63dd32b2006-10-20 04:42:40 +0000830 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000831 const unsigned DotFrameworkLen = 10;
832 const char *FrameworkPos = strstr(ContextName, ".framework");
Craig Topperd2d442c2014-05-17 23:10:59 +0000833 if (FrameworkPos == nullptr ||
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000834 (FrameworkPos[DotFrameworkLen] != '/' &&
835 FrameworkPos[DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000836 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000837
Daniel Dunbar17138612012-04-05 17:09:40 +0000838 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000839
Chris Lattner63dd32b2006-10-20 04:42:40 +0000840 // Append Frameworks/HIToolbox.framework/
841 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000842 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000843 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000844
David Blaikie13156b62014-11-19 03:06:06 +0000845 auto &CacheLookup =
846 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
847 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Chris Lattner5ed76da2006-10-22 07:24:13 +0000849 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000850 if (CacheLookup.second.Directory &&
851 CacheLookup.first().size() == FrameworkName.size() &&
852 memcmp(CacheLookup.first().data(), &FrameworkName[0],
853 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000854 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000855
Chris Lattner5ed76da2006-10-22 07:24:13 +0000856 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000857 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000858 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Chris Lattner5ed76da2006-10-22 07:24:13 +0000860 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000861 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000862 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000863
Chris Lattner5ed76da2006-10-22 07:24:13 +0000864 // Otherwise, if it does, remember that this is the right direntry for this
865 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000866 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000867 }
Mike Stump11289f42009-09-09 15:08:12 +0000868
Craig Topperd2d442c2014-05-17 23:10:59 +0000869 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000870
Craig Topperd2d442c2014-05-17 23:10:59 +0000871 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000872 RelativePath->clear();
873 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
874 }
875
Chris Lattner63dd32b2006-10-20 04:42:40 +0000876 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000877 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000878 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000879 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000880 SearchPath->clear();
881 // Without trailing '/'.
882 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
883 }
884
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000885 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000886 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000887
Chris Lattner63dd32b2006-10-20 04:42:40 +0000888 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000889 HeadersFilename = FrameworkName;
890 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000891 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000892 SearchPath->clear();
893 // Without trailing '/'.
894 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
895 }
896
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000897 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000898 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000899 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000900 }
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattner577377e2006-10-20 04:55:45 +0000902 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000903 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000904 // Note that the temporary 'DirInfo' is required here, as either call to
905 // getFileInfo could resize the vector and we don't want to rely on order
906 // of evaluation.
907 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
908 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000909
Richard Smith3d5b48c2015-10-16 21:42:56 +0000910 FrameworkName.pop_back(); // remove the trailing '/'
911 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
912 SuggestedModule, /*IsSystem*/ false))
913 return nullptr;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000914
Chris Lattner577377e2006-10-20 04:55:45 +0000915 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000916}
917
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000918//===----------------------------------------------------------------------===//
919// File Info Management.
920//===----------------------------------------------------------------------===//
921
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000922/// \brief Merge the header file info provided by \p OtherHFI into the current
923/// header file info (\p HFI)
924static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
925 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +0000926 assert(OtherHFI.External && "expected to merge external HFI");
927
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000928 HFI.isImport |= OtherHFI.isImport;
929 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000930 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000931 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +0000932
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000933 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
934 HFI.ControllingMacro = OtherHFI.ControllingMacro;
935 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
936 }
Richard Smithd8879c82015-08-24 21:59:32 +0000937
938 HFI.DirInfo = OtherHFI.DirInfo;
939 HFI.External = (!HFI.IsValid || HFI.External);
940 HFI.IsValid = true;
941 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000942
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000943 if (HFI.Framework.empty())
944 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000945}
946
Steve Naroff3fa455a2009-04-24 20:03:17 +0000947/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000948/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000949HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000950 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +0000951 FileInfo.resize(FE->getUID() + 1);
952
Richard Smithd8879c82015-08-24 21:59:32 +0000953 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +0000954 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +0000955 if (ExternalSource && !HFI->Resolved) {
956 HFI->Resolved = true;
957 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
958
959 HFI = &FileInfo[FE->getUID()];
960 if (ExternalHFI.External)
961 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +0000962 }
963
Richard Smithd8879c82015-08-24 21:59:32 +0000964 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +0000965 // We have local information about this header file, so it's no longer
966 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +0000967 HFI->External = false;
968 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +0000969}
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000970
Richard Smith386bb072015-08-18 23:42:23 +0000971const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +0000972HeaderSearch::getExistingFileInfo(const FileEntry *FE,
973 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +0000974 // If we have an external source, ensure we have the latest information.
975 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +0000976 HeaderFileInfo *HFI;
977 if (ExternalSource) {
978 if (FE->getUID() >= FileInfo.size()) {
979 if (!WantExternal)
980 return nullptr;
981 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +0000982 }
Richard Smithd8879c82015-08-24 21:59:32 +0000983
984 HFI = &FileInfo[FE->getUID()];
985 if (!WantExternal && (!HFI->IsValid || HFI->External))
986 return nullptr;
987 if (!HFI->Resolved) {
988 HFI->Resolved = true;
989 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
990
991 HFI = &FileInfo[FE->getUID()];
992 if (ExternalHFI.External)
993 mergeHeaderFileInfo(*HFI, ExternalHFI);
994 }
995 } else if (FE->getUID() >= FileInfo.size()) {
996 return nullptr;
997 } else {
998 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +0000999 }
Richard Smith386bb072015-08-18 23:42:23 +00001000
Richard Smithd8879c82015-08-24 21:59:32 +00001001 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001002 return nullptr;
1003
Richard Smithd8879c82015-08-24 21:59:32 +00001004 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001005}
1006
Douglas Gregor37aa4932011-05-04 00:14:37 +00001007bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1008 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001009 if (auto *HFI = getExistingFileInfo(File))
1010 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1011 HFI->ControllingMacroID;
1012 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001013}
1014
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001015void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001016 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001017 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001018 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1019
1020 // Don't mark the file info as non-external if there's nothing to change.
1021 if (!isCompilingModuleHeader) {
1022 if (!isModularHeader)
1023 return;
1024 auto *HFI = getExistingFileInfo(FE);
1025 if (HFI && HFI->isModuleHeader)
1026 return;
1027 }
1028
Richard Smith386bb072015-08-18 23:42:23 +00001029 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001030 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001031 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001032}
1033
Richard Smith20e883e2015-04-29 23:20:19 +00001034bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1035 const FileEntry *File,
Richard Smith035f6dc2015-07-01 01:51:38 +00001036 bool isImport, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001037 ++NumIncluded; // Count # of attempted #includes.
1038
1039 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001040 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001042 // If this is a #import directive, check that we have not already imported
1043 // this header.
1044 if (isImport) {
1045 // If this has already been imported, don't import it again.
1046 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001048 // Has this already been #import'ed or #include'd?
1049 if (FileInfo.NumIncludes) return false;
1050 } else {
1051 // Otherwise, if this is a #include of a file that was previously #import'd
1052 // or if this is the second #include of a #pragma once file, ignore it.
1053 if (FileInfo.isImport)
1054 return false;
1055 }
Mike Stump11289f42009-09-09 15:08:12 +00001056
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001057 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1058 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001059 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001060 = FileInfo.getControllingMacro(ExternalLookup)) {
1061 // If the header corresponds to a module, check whether the macro is already
1062 // defined in that module rather than checking in the current set of visible
1063 // modules.
1064 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1065 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001066 ++NumMultiIncludeFileOptzn;
1067 return false;
1068 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001071 // Increment the number of times this file has been included.
1072 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001074 return true;
1075}
1076
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001077size_t HeaderSearch::getTotalMemory() const {
1078 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001079 + llvm::capacity_in_bytes(FileInfo)
1080 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001081 + LookupFileCache.getAllocator().getTotalMemory()
1082 + FrameworkMap.getAllocator().getTotalMemory();
1083}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001084
1085StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001086 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001087}
Douglas Gregor718292f2011-11-11 19:10:28 +00001088
1089bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001090 const DirectoryEntry *Root,
1091 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001092 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001093 return false;
1094
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001095 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001096
1097 StringRef DirName = FileName;
1098 do {
1099 // Get the parent directory name.
1100 DirName = llvm::sys::path::parent_path(DirName);
1101 if (DirName.empty())
1102 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001103
Douglas Gregor718292f2011-11-11 19:10:28 +00001104 // Determine whether this directory exists.
1105 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1106 if (!Dir)
1107 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001108
Ben Langmuir984e1df2014-03-19 20:23:34 +00001109 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001110 switch (loadModuleMapFile(Dir, IsSystem,
1111 llvm::sys::path::extension(Dir->getName()) ==
1112 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001113 case LMM_NewlyLoaded:
1114 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001115 // Success. All of the directories we stepped through inherit this module
1116 // map file.
1117 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1118 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1119 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001120
1121 case LMM_NoDirectory:
1122 case LMM_InvalidModuleMap:
1123 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001124 }
1125
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001126 // If we hit the top of our search, we're done.
1127 if (Dir == Root)
1128 return false;
1129
Douglas Gregor718292f2011-11-11 19:10:28 +00001130 // Keep track of all of the directories we checked, so we can mark them as
1131 // having module maps if we eventually do find a module map.
1132 FixUpDirectories.push_back(Dir);
1133 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001134}
1135
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001136ModuleMap::KnownHeader
1137HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001138 if (ExternalSource) {
1139 // Make sure the external source has handled header info about this file,
1140 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001141 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001142 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001143 return ModMap.findModuleForHeader(File);
Douglas Gregor718292f2011-11-11 19:10:28 +00001144}
1145
Richard Smith3d5b48c2015-10-16 21:42:56 +00001146bool HeaderSearch::findUsableModuleForHeader(
1147 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1148 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1149 if (File && SuggestedModule) {
1150 // If there is a module that corresponds to this header, suggest it.
1151 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1152 *SuggestedModule = findModuleForHeader(File);
1153 }
1154 return true;
1155}
1156
1157bool HeaderSearch::findUsableModuleForFrameworkHeader(
1158 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1159 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1160 // If we're supposed to suggest a module, look for one now.
1161 if (SuggestedModule) {
1162 // Find the top-level framework based on this framework.
1163 SmallVector<std::string, 4> SubmodulePath;
1164 const DirectoryEntry *TopFrameworkDir
1165 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1166
1167 // Determine the name of the top-level framework.
1168 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1169
1170 // Load this framework module. If that succeeds, find the suggested module
1171 // for this header, if any.
1172 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1173
1174 // FIXME: This can find a module not part of ModuleName, which is
1175 // important so that we're consistent about whether this header
1176 // corresponds to a module. Possibly we should lock down framework modules
1177 // so that this is not possible.
1178 *SuggestedModule = findModuleForHeader(File);
1179 }
1180 return true;
1181}
1182
Richard Smith9acb99e32014-12-10 03:09:48 +00001183static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001184 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001185 StringRef Filename = llvm::sys::path::filename(File->getName());
1186 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001187 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001188 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001189 else if (Filename == "module.modulemap")
1190 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1191 else
1192 return nullptr;
1193 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001194}
1195
Ben Langmuir984e1df2014-03-19 20:23:34 +00001196bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001197 // Find the directory for the module. For frameworks, that may require going
1198 // up from the 'Modules' directory.
1199 const DirectoryEntry *Dir = nullptr;
1200 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1201 Dir = FileMgr.getDirectory(".");
1202 else {
1203 Dir = File->getDir();
1204 StringRef DirName(Dir->getName());
1205 if (llvm::sys::path::filename(DirName) == "Modules") {
1206 DirName = llvm::sys::path::parent_path(DirName);
1207 if (DirName.endswith(".framework"))
1208 Dir = FileMgr.getDirectory(DirName);
1209 // FIXME: This assert can fail if there's a race between the above check
1210 // and the removal of the directory.
1211 assert(Dir && "parent must exist");
1212 }
1213 }
1214
1215 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001216 case LMM_AlreadyLoaded:
1217 case LMM_NewlyLoaded:
1218 return false;
1219 case LMM_NoDirectory:
1220 case LMM_InvalidModuleMap:
1221 return true;
1222 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001223 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001224}
1225
1226HeaderSearch::LoadModuleMapResult
Richard Smith9acb99e32014-12-10 03:09:48 +00001227HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1228 const DirectoryEntry *Dir) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001229 assert(File && "expected FileEntry");
1230
Richard Smith9887d792014-10-17 01:42:53 +00001231 // Check whether we've already loaded this module map, and mark it as being
1232 // loaded in case we recursively try to load it from itself.
1233 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1234 if (!AddResult.second)
1235 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001236
Richard Smith9acb99e32014-12-10 03:09:48 +00001237 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001238 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001239 return LMM_InvalidModuleMap;
1240 }
1241
1242 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001243 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1244 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001245 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001246 return LMM_InvalidModuleMap;
1247 }
1248 }
1249
1250 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001251 return LMM_NewlyLoaded;
1252}
1253
1254const FileEntry *
1255HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001256 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001257 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001258 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1259 // module.map at the framework root is also accepted.
1260 SmallString<128> ModuleMapFileName(Dir->getName());
1261 if (IsFramework)
1262 llvm::sys::path::append(ModuleMapFileName, "Modules");
1263 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1264 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1265 return F;
1266
1267 // Continue to allow module.map
1268 ModuleMapFileName = Dir->getName();
1269 llvm::sys::path::append(ModuleMapFileName, "module.map");
1270 return FileMgr.getFile(ModuleMapFileName);
1271}
1272
1273Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001274 const DirectoryEntry *Dir,
1275 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001276 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001277 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001278
Douglas Gregor56c64012011-11-17 01:41:17 +00001279 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001280 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001281 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001282 // Try to infer a module map from the framework directory.
1283 if (HSOpts->ImplicitModuleMaps)
1284 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001285 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001286
Douglas Gregor56c64012011-11-17 01:41:17 +00001287 case LMM_AlreadyLoaded:
1288 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001289 return nullptr;
1290
Douglas Gregor56c64012011-11-17 01:41:17 +00001291 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001292 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001293 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001294
Ben Langmuira5254002015-07-02 13:19:48 +00001295 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001296}
1297
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001298
Douglas Gregor80b69042011-11-12 00:22:19 +00001299HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001300HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1301 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001302 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001303 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001304
Douglas Gregor80b69042011-11-12 00:22:19 +00001305 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001306}
1307
Douglas Gregor80b69042011-11-12 00:22:19 +00001308HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001309HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1310 bool IsFramework) {
1311 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001312 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001313 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001314
Ben Langmuir984e1df2014-03-19 20:23:34 +00001315 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001316 LoadModuleMapResult Result =
1317 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001318 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1319 // E.g. Foo.framework/Modules/module.modulemap
1320 // ^Dir ^ModuleMapFile
1321 if (Result == LMM_NewlyLoaded)
1322 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001323 else if (Result == LMM_InvalidModuleMap)
1324 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001325 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001326 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001327 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001328}
Douglas Gregor718292f2011-11-11 19:10:28 +00001329
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001330void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001331 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001332
Richard Smith47972af2015-06-16 00:08:24 +00001333 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001334 // Load module maps for each of the header search directories.
1335 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1336 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1337 if (SearchDirs[Idx].isFramework()) {
1338 std::error_code EC;
1339 SmallString<128> DirNative;
1340 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1341 DirNative);
1342
1343 // Search each of the ".framework" directories to load them as modules.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001344 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1345 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001346 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001347 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001348 continue;
1349
1350 const DirectoryEntry *FrameworkDir =
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001351 FileMgr.getDirectory(Dir->getName());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001352 if (!FrameworkDir)
1353 continue;
1354
1355 // Load this framework module.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001356 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1357 FrameworkDir, IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001358 }
1359 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001360 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001361
1362 // FIXME: Deal with header maps.
1363 if (SearchDirs[Idx].isHeaderMap())
1364 continue;
1365
1366 // Try to load a module map file for the search directory.
1367 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1368 /*IsFramework*/ false);
1369
1370 // Try to load module map files for immediate subdirectories of this
1371 // search directory.
1372 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001373 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001374 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001375
Douglas Gregor07f43572012-01-29 18:15:03 +00001376 // Populate the list of modules.
1377 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1378 MEnd = ModMap.module_end();
1379 M != MEnd; ++M) {
1380 Modules.push_back(M->getValue());
1381 }
1382}
Douglas Gregor0339a642013-03-21 01:08:50 +00001383
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001384void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001385 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001386 return;
1387
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001388 // Load module maps for each of the header search directories.
1389 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001390 // We only care about normal header directories.
1391 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001392 continue;
1393 }
1394
1395 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001396 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001397 SearchDirs[Idx].isSystemHeaderDirectory(),
1398 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001399 }
1400}
1401
Douglas Gregor0339a642013-03-21 01:08:50 +00001402void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001403 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001404 "Should not be loading subdirectory module maps");
1405
Douglas Gregor0339a642013-03-21 01:08:50 +00001406 if (SearchDir.haveSearchedAllModuleMaps())
1407 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001408
1409 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001410 SmallString<128> DirNative;
1411 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001412 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1413 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001414 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001415 bool IsFramework =
1416 llvm::sys::path::extension(Dir->getName()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001417 if (IsFramework == SearchDir.isFramework())
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001418 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001419 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001420 }
1421
1422 SearchDir.setSearchedAllModuleMaps(true);
1423}
Richard Smith4eb83932016-04-27 21:57:05 +00001424
1425std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1426 bool *IsSystem) {
1427 // FIXME: We assume that the path name currently cached in the FileEntry is
1428 // the most appropriate one for this analysis (and that it's spelled the same
1429 // way as the corresponding header search path).
1430 const char *Name = File->getName();
1431
1432 unsigned BestPrefixLength = 0;
1433 unsigned BestSearchDir;
1434
1435 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1436 // FIXME: Support this search within frameworks and header maps.
1437 if (!SearchDirs[I].isNormalDir())
1438 continue;
1439
1440 const char *Dir = SearchDirs[I].getDir()->getName();
1441 for (auto NI = llvm::sys::path::begin(Name),
1442 NE = llvm::sys::path::end(Name),
1443 DI = llvm::sys::path::begin(Dir),
1444 DE = llvm::sys::path::end(Dir);
1445 /*termination condition in loop*/; ++NI, ++DI) {
1446 // '.' components in Name are ignored.
1447 while (NI != NE && *NI == ".")
1448 ++NI;
1449 if (NI == NE)
1450 break;
1451
1452 // '.' components in Dir are ignored.
1453 while (DI != DE && *DI == ".")
1454 ++DI;
1455 if (DI == DE) {
1456 // Dir is a prefix of Name, up to '.' components and choice of path
1457 // separators.
1458 unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1459 if (PrefixLength > BestPrefixLength) {
1460 BestPrefixLength = PrefixLength;
1461 BestSearchDir = I;
1462 }
1463 break;
1464 }
1465
1466 if (*NI != *DI)
1467 break;
1468 }
1469 }
1470
1471 if (IsSystem)
1472 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
1473 return Name + BestPrefixLength;
1474}