Coverage Report

Created: 2022-01-11 12:24

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/InitHeaderSearch.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- InitHeaderSearch.cpp - Initialize header search paths ------------===//
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 InitHeaderSearch class.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Basic/FileManager.h"
14
#include "clang/Basic/LangOptions.h"
15
#include "clang/Config/config.h" // C_INCLUDE_DIRS
16
#include "clang/Frontend/FrontendDiagnostic.h"
17
#include "clang/Frontend/Utils.h"
18
#include "clang/Lex/HeaderMap.h"
19
#include "clang/Lex/HeaderSearch.h"
20
#include "clang/Lex/HeaderSearchOptions.h"
21
#include "llvm/ADT/SmallPtrSet.h"
22
#include "llvm/ADT/SmallString.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "llvm/ADT/StringExtras.h"
25
#include "llvm/ADT/Triple.h"
26
#include "llvm/ADT/Twine.h"
27
#include "llvm/Support/ErrorHandling.h"
28
#include "llvm/Support/Path.h"
29
#include "llvm/Support/raw_ostream.h"
30
31
using namespace clang;
32
using namespace clang::frontend;
33
34
namespace {
35
/// Holds information about a single DirectoryLookup object.
36
struct DirectoryLookupInfo {
37
  IncludeDirGroup Group;
38
  DirectoryLookup Lookup;
39
  Optional<unsigned> UserEntryIdx;
40
41
  DirectoryLookupInfo(IncludeDirGroup Group, DirectoryLookup Lookup,
42
                      Optional<unsigned> UserEntryIdx)
43
154k
      : Group(Group), Lookup(Lookup), UserEntryIdx(UserEntryIdx) {}
44
};
45
46
/// InitHeaderSearch - This class makes it easier to set the search paths of
47
///  a HeaderSearch object. InitHeaderSearch stores several search path lists
48
///  internally, which can be sent to a HeaderSearch object in one swoop.
49
class InitHeaderSearch {
50
  std::vector<DirectoryLookupInfo> IncludePath;
51
  std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
52
  HeaderSearch &Headers;
53
  bool Verbose;
54
  std::string IncludeSysroot;
55
  bool HasSysroot;
56
57
public:
58
  InitHeaderSearch(HeaderSearch &HS, bool verbose, StringRef sysroot)
59
      : Headers(HS), Verbose(verbose), IncludeSysroot(std::string(sysroot)),
60
87.5k
        HasSysroot(!(sysroot.empty() || sysroot == "/")) {}
61
62
  /// AddPath - Add the specified path to the specified group list, prefixing
63
  /// the sysroot if used.
64
  /// Returns true if the path exists, false if it was ignored.
65
  bool AddPath(const Twine &Path, IncludeDirGroup Group, bool isFramework,
66
               Optional<unsigned> UserEntryIdx = None);
67
68
  /// AddUnmappedPath - Add the specified path to the specified group list,
69
  /// without performing any sysroot remapping.
70
  /// Returns true if the path exists, false if it was ignored.
71
  bool AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
72
                       bool isFramework,
73
                       Optional<unsigned> UserEntryIdx = None);
74
75
  /// AddSystemHeaderPrefix - Add the specified prefix to the system header
76
  /// prefix list.
77
4
  void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader) {
78
4
    SystemHeaderPrefixes.emplace_back(std::string(Prefix), IsSystemHeader);
79
4
  }
80
81
  /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to support a gnu
82
  ///  libstdc++.
83
  /// Returns true if the \p Base path was found, false if it does not exist.
84
  bool AddGnuCPlusPlusIncludePaths(StringRef Base, StringRef ArchDir,
85
                                   StringRef Dir32, StringRef Dir64,
86
                                   const llvm::Triple &triple);
87
88
  /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to support a MinGW
89
  ///  libstdc++.
90
  void AddMinGWCPlusPlusIncludePaths(StringRef Base,
91
                                     StringRef Arch,
92
                                     StringRef Version);
93
94
  // AddDefaultCIncludePaths - Add paths that should always be searched.
95
  void AddDefaultCIncludePaths(const llvm::Triple &triple,
96
                               const HeaderSearchOptions &HSOpts);
97
98
  // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
99
  //  compiling c++.
100
  void AddDefaultCPlusPlusIncludePaths(const LangOptions &LangOpts,
101
                                       const llvm::Triple &triple,
102
                                       const HeaderSearchOptions &HSOpts);
103
104
  /// AddDefaultSystemIncludePaths - Adds the default system include paths so
105
  ///  that e.g. stdio.h is found.
106
  void AddDefaultIncludePaths(const LangOptions &Lang,
107
                              const llvm::Triple &triple,
108
                              const HeaderSearchOptions &HSOpts);
109
110
  /// Realize - Merges all search path lists into one list and send it to
111
  /// HeaderSearch.
112
  void Realize(const LangOptions &Lang);
113
};
114
115
}  // end anonymous namespace.
116
117
16.9k
static bool CanPrefixSysroot(StringRef Path) {
118
#if defined(_WIN32)
119
  return !Path.empty() && llvm::sys::path::is_separator(Path[0]);
120
#else
121
16.9k
  return llvm::sys::path::is_absolute(Path);
122
16.9k
#endif
123
16.9k
}
124
125
bool InitHeaderSearch::AddPath(const Twine &Path, IncludeDirGroup Group,
126
                               bool isFramework,
127
85.0k
                               Optional<unsigned> UserEntryIdx) {
128
  // Add the path with sysroot prepended, if desired and this is a system header
129
  // group.
130
85.0k
  if (HasSysroot) {
131
16.9k
    SmallString<256> MappedPathStorage;
132
16.9k
    StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
133
16.9k
    if (CanPrefixSysroot(MappedPathStr)) {
134
16.9k
      return AddUnmappedPath(IncludeSysroot + Path, Group, isFramework,
135
16.9k
                             UserEntryIdx);
136
16.9k
    }
137
16.9k
  }
138
139
68.1k
  return AddUnmappedPath(Path, Group, isFramework, UserEntryIdx);
140
85.0k
}
141
142
bool InitHeaderSearch::AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
143
                                       bool isFramework,
144
226k
                                       Optional<unsigned> UserEntryIdx) {
145
226k
  assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
146
147
0
  FileManager &FM = Headers.getFileMgr();
148
226k
  SmallString<256> MappedPathStorage;
149
226k
  StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
150
151
  // If use system headers while cross-compiling, emit the warning.
152
226k
  if (HasSysroot && 
(55.8k
MappedPathStr.startswith("/usr/include")55.8k
||
153
55.8k
                     
MappedPathStr.startswith("/usr/local/include")55.8k
)) {
154
33
    Headers.getDiags().Report(diag::warn_poison_system_directories)
155
33
        << MappedPathStr;
156
33
  }
157
158
  // Compute the DirectoryLookup type.
159
226k
  SrcMgr::CharacteristicKind Type;
160
226k
  if (Group == Quoted || 
Group == Angled226k
||
Group == IndexHeaderMap212k
) {
161
13.9k
    Type = SrcMgr::C_User;
162
212k
  } else if (Group == ExternCSystem) {
163
50.5k
    Type = SrcMgr::C_ExternCSystem;
164
161k
  } else {
165
161k
    Type = SrcMgr::C_System;
166
161k
  }
167
168
  // If the directory exists, add it.
169
226k
  if (auto DE = FM.getOptionalDirectoryRef(MappedPathStr)) {
170
154k
    IncludePath.emplace_back(Group, DirectoryLookup(*DE, Type, isFramework),
171
154k
                             UserEntryIdx);
172
154k
    return true;
173
154k
  }
174
175
  // Check to see if this is an apple-style headermap (which are not allowed to
176
  // be frameworks).
177
71.1k
  if (!isFramework) {
178
62.5k
    if (auto FE = FM.getFile(MappedPathStr)) {
179
37
      if (const HeaderMap *HM = Headers.CreateHeaderMap(*FE)) {
180
        // It is a headermap, add it to the search path.
181
33
        IncludePath.emplace_back(
182
33
            Group, DirectoryLookup(HM, Type, Group == IndexHeaderMap),
183
33
            UserEntryIdx);
184
33
        return true;
185
33
      }
186
37
    }
187
62.5k
  }
188
189
71.1k
  if (Verbose)
190
62
    llvm::errs() << "ignoring nonexistent directory \""
191
62
                 << MappedPathStr << "\"\n";
192
71.1k
  return false;
193
71.1k
}
194
195
bool InitHeaderSearch::AddGnuCPlusPlusIncludePaths(StringRef Base,
196
                                                   StringRef ArchDir,
197
                                                   StringRef Dir32,
198
                                                   StringRef Dir64,
199
0
                                                   const llvm::Triple &triple) {
200
  // Add the base dir
201
0
  bool IsBaseFound = AddPath(Base, CXXSystem, false);
202
203
  // Add the multilib dirs
204
0
  llvm::Triple::ArchType arch = triple.getArch();
205
0
  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
206
0
  if (is64bit)
207
0
    AddPath(Base + "/" + ArchDir + "/" + Dir64, CXXSystem, false);
208
0
  else
209
0
    AddPath(Base + "/" + ArchDir + "/" + Dir32, CXXSystem, false);
210
211
  // Add the backward dir
212
0
  AddPath(Base + "/backward", CXXSystem, false);
213
0
  return IsBaseFound;
214
0
}
215
216
void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(StringRef Base,
217
                                                     StringRef Arch,
218
0
                                                     StringRef Version) {
219
0
  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++",
220
0
          CXXSystem, false);
221
0
  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/" + Arch,
222
0
          CXXSystem, false);
223
0
  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/backward",
224
0
          CXXSystem, false);
225
0
}
226
227
void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
228
20.0k
                                            const HeaderSearchOptions &HSOpts) {
229
20.0k
  llvm::Triple::OSType os = triple.getOS();
230
231
20.0k
  if (triple.isOSDarwin()) {
232
0
    llvm_unreachable("Include management is handled in the driver.");
233
0
  }
234
235
20.0k
  if (HSOpts.UseStandardSystemIncludes) {
236
10.2k
    switch (os) {
237
4
    case llvm::Triple::CloudABI:
238
9
    case llvm::Triple::FreeBSD:
239
17
    case llvm::Triple::NetBSD:
240
17
    case llvm::Triple::OpenBSD:
241
21
    case llvm::Triple::NaCl:
242
36
    case llvm::Triple::PS4:
243
37
    case llvm::Triple::ELFIAMCU:
244
39
    case llvm::Triple::Fuchsia:
245
39
      break;
246
0
    case llvm::Triple::Win32:
247
0
      if (triple.getEnvironment() != llvm::Triple::Cygnus)
248
0
        break;
249
0
      LLVM_FALLTHROUGH;
250
10.1k
    default:
251
      // FIXME: temporary hack: hard-coded paths.
252
10.1k
      AddPath("/usr/local/include", System, false);
253
10.1k
      break;
254
10.2k
    }
255
10.2k
  }
256
257
  // Builtin includes use #include_next directives and should be positioned
258
  // just prior C include dirs.
259
20.0k
  if (HSOpts.UseBuiltinIncludes) {
260
    // Ignore the sys root, we *always* look for clang headers relative to
261
    // supplied path.
262
20.0k
    SmallString<128> P = StringRef(HSOpts.ResourceDir);
263
20.0k
    llvm::sys::path::append(P, "include");
264
20.0k
    AddUnmappedPath(P, ExternCSystem, false);
265
20.0k
  }
266
267
  // All remaining additions are for system include directories, early exit if
268
  // we aren't using them.
269
20.0k
  if (!HSOpts.UseStandardSystemIncludes)
270
9.85k
    return;
271
272
  // Add dirs specified via 'configure --with-c-include-dirs'.
273
10.2k
  StringRef CIncludeDirs(C_INCLUDE_DIRS);
274
10.2k
  if (CIncludeDirs != "") {
275
0
    SmallVector<StringRef, 5> dirs;
276
0
    CIncludeDirs.split(dirs, ":");
277
0
    for (StringRef dir : dirs)
278
0
      AddPath(dir, ExternCSystem, false);
279
0
    return;
280
0
  }
281
282
10.2k
  switch (os) {
283
0
  case llvm::Triple::Linux:
284
0
  case llvm::Triple::Hurd:
285
0
  case llvm::Triple::Solaris:
286
0
  case llvm::Triple::OpenBSD:
287
0
    llvm_unreachable("Include management is handled in the driver.");
288
289
4
  case llvm::Triple::CloudABI: {
290
    // <sysroot>/<triple>/include
291
4
    SmallString<128> P = StringRef(HSOpts.ResourceDir);
292
4
    llvm::sys::path::append(P, "../../..", triple.str(), "include");
293
4
    AddPath(P, System, false);
294
4
    break;
295
0
  }
296
297
0
  case llvm::Triple::Haiku:
298
0
    AddPath("/boot/system/non-packaged/develop/headers", System, false);
299
0
    AddPath("/boot/system/develop/headers/os", System, false);
300
0
    AddPath("/boot/system/develop/headers/os/app", System, false);
301
0
    AddPath("/boot/system/develop/headers/os/arch", System, false);
302
0
    AddPath("/boot/system/develop/headers/os/device", System, false);
303
0
    AddPath("/boot/system/develop/headers/os/drivers", System, false);
304
0
    AddPath("/boot/system/develop/headers/os/game", System, false);
305
0
    AddPath("/boot/system/develop/headers/os/interface", System, false);
306
0
    AddPath("/boot/system/develop/headers/os/kernel", System, false);
307
0
    AddPath("/boot/system/develop/headers/os/locale", System, false);
308
0
    AddPath("/boot/system/develop/headers/os/mail", System, false);
309
0
    AddPath("/boot/system/develop/headers/os/media", System, false);
310
0
    AddPath("/boot/system/develop/headers/os/midi", System, false);
311
0
    AddPath("/boot/system/develop/headers/os/midi2", System, false);
312
0
    AddPath("/boot/system/develop/headers/os/net", System, false);
313
0
    AddPath("/boot/system/develop/headers/os/opengl", System, false);
314
0
    AddPath("/boot/system/develop/headers/os/storage", System, false);
315
0
    AddPath("/boot/system/develop/headers/os/support", System, false);
316
0
    AddPath("/boot/system/develop/headers/os/translation", System, false);
317
0
    AddPath("/boot/system/develop/headers/os/add-ons/graphics", System, false);
318
0
    AddPath("/boot/system/develop/headers/os/add-ons/input_server", System, false);
319
0
    AddPath("/boot/system/develop/headers/os/add-ons/mail_daemon", System, false);
320
0
    AddPath("/boot/system/develop/headers/os/add-ons/registrar", System, false);
321
0
    AddPath("/boot/system/develop/headers/os/add-ons/screen_saver", System, false);
322
0
    AddPath("/boot/system/develop/headers/os/add-ons/tracker", System, false);
323
0
    AddPath("/boot/system/develop/headers/os/be_apps/Deskbar", System, false);
324
0
    AddPath("/boot/system/develop/headers/os/be_apps/NetPositive", System, false);
325
0
    AddPath("/boot/system/develop/headers/os/be_apps/Tracker", System, false);
326
0
    AddPath("/boot/system/develop/headers/3rdparty", System, false);
327
0
    AddPath("/boot/system/develop/headers/bsd", System, false);
328
0
    AddPath("/boot/system/develop/headers/glibc", System, false);
329
0
    AddPath("/boot/system/develop/headers/posix", System, false);
330
0
    AddPath("/boot/system/develop/headers",  System, false);
331
0
    break;
332
4
  case llvm::Triple::RTEMS:
333
4
    break;
334
0
  case llvm::Triple::Win32:
335
0
    switch (triple.getEnvironment()) {
336
0
    default: llvm_unreachable("Include management is handled in the driver.");
337
0
    case llvm::Triple::Cygnus:
338
0
      AddPath("/usr/include/w32api", System, false);
339
0
      break;
340
0
    case llvm::Triple::GNU:
341
0
      break;
342
0
    }
343
0
    break;
344
10.2k
  default:
345
10.2k
    break;
346
10.2k
  }
347
348
10.2k
  switch (os) {
349
4
  case llvm::Triple::CloudABI:
350
8
  case llvm::Triple::RTEMS:
351
12
  case llvm::Triple::NaCl:
352
13
  case llvm::Triple::ELFIAMCU:
353
15
  case llvm::Triple::Fuchsia:
354
15
    break;
355
15
  case llvm::Triple::PS4: {
356
    // <isysroot> gets prepended later in AddPath().
357
15
    std::string BaseSDKPath;
358
15
    if (!HasSysroot) {
359
14
      const char *envValue = getenv("SCE_ORBIS_SDK_DIR");
360
14
      if (envValue)
361
1
        BaseSDKPath = envValue;
362
13
      else {
363
        // HSOpts.ResourceDir variable contains the location of Clang's
364
        // resource files.
365
        // Assuming that Clang is configured for PS4 without
366
        // --with-clang-resource-dir option, the location of Clang's resource
367
        // files is <SDK_DIR>/host_tools/lib/clang
368
13
        SmallString<128> P = StringRef(HSOpts.ResourceDir);
369
13
        llvm::sys::path::append(P, "../../..");
370
13
        BaseSDKPath = std::string(P.str());
371
13
      }
372
14
    }
373
15
    AddPath(BaseSDKPath + "/target/include", System, false);
374
15
    if (triple.isPS4CPU())
375
15
      AddPath(BaseSDKPath + "/target/include_common", System, false);
376
15
    LLVM_FALLTHROUGH;
377
15
  }
378
10.2k
  default:
379
10.2k
    AddPath("/usr/include", ExternCSystem, false);
380
10.2k
    break;
381
10.2k
  }
382
10.2k
}
383
384
void InitHeaderSearch::AddDefaultCPlusPlusIncludePaths(
385
    const LangOptions &LangOpts, const llvm::Triple &triple,
386
8.38k
    const HeaderSearchOptions &HSOpts) {
387
8.38k
  llvm::Triple::OSType os = triple.getOS();
388
  // FIXME: temporary hack: hard-coded paths.
389
390
8.38k
  if (triple.isOSDarwin()) {
391
0
    llvm_unreachable("Include management is handled in the driver.");
392
0
  }
393
394
8.38k
  switch (os) {
395
0
  case llvm::Triple::Linux:
396
0
  case llvm::Triple::Hurd:
397
0
  case llvm::Triple::Solaris:
398
0
  case llvm::Triple::AIX:
399
0
    llvm_unreachable("Include management is handled in the driver.");
400
0
    break;
401
0
  case llvm::Triple::Win32:
402
0
    switch (triple.getEnvironment()) {
403
0
    default: llvm_unreachable("Include management is handled in the driver.");
404
0
    case llvm::Triple::Cygnus:
405
      // Cygwin-1.7
406
0
      AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.7.3");
407
0
      AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.5.3");
408
0
      AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.4");
409
      // g++-4 / Cygwin-1.5
410
0
      AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.2");
411
0
      break;
412
0
    }
413
0
    break;
414
0
  case llvm::Triple::DragonFly:
415
0
    AddPath("/usr/include/c++/5.0", CXXSystem, false);
416
0
    break;
417
0
  case llvm::Triple::Minix:
418
0
    AddGnuCPlusPlusIncludePaths("/usr/gnu/include/c++/4.4.3",
419
0
                                "", "", "", triple);
420
0
    break;
421
8.38k
  default:
422
8.38k
    break;
423
8.38k
  }
424
8.38k
}
425
426
void InitHeaderSearch::AddDefaultIncludePaths(const LangOptions &Lang,
427
                                              const llvm::Triple &triple,
428
87.5k
                                            const HeaderSearchOptions &HSOpts) {
429
  // NB: This code path is going away. All of the logic is moving into the
430
  // driver which has the information necessary to do target-specific
431
  // selections of default include paths. Each target which moves there will be
432
  // exempted from this logic here until we can delete the entire pile of code.
433
87.5k
  switch (triple.getOS()) {
434
51.1k
  default:
435
51.1k
    break; // Everything else continues to use this routine's logic.
436
437
51.1k
  case llvm::Triple::Emscripten:
438
7.42k
  case llvm::Triple::Linux:
439
7.42k
  case llvm::Triple::Hurd:
440
7.47k
  case llvm::Triple::OpenBSD:
441
7.48k
  case llvm::Triple::Solaris:
442
7.48k
  case llvm::Triple::WASI:
443
7.70k
  case llvm::Triple::AIX:
444
7.70k
    return;
445
446
8.96k
  case llvm::Triple::Win32:
447
8.96k
    if (triple.getEnvironment() != llvm::Triple::Cygnus ||
448
8.96k
        
triple.isOSBinFormatMachO()15
)
449
8.94k
      return;
450
15
    break;
451
452
19.7k
  case llvm::Triple::UnknownOS:
453
19.7k
    if (triple.isWasm())
454
93
      return;
455
19.6k
    break;
456
87.5k
  }
457
458
  // All header search logic is handled in the Driver for Darwin.
459
70.8k
  if (triple.isOSDarwin()) {
460
50.7k
    if (HSOpts.UseStandardSystemIncludes) {
461
      // Add the default framework include paths on Darwin.
462
32.3k
      AddPath("/System/Library/Frameworks", System, true);
463
32.3k
      AddPath("/Library/Frameworks", System, true);
464
32.3k
    }
465
50.7k
    return;
466
50.7k
  }
467
468
20.0k
  if (Lang.CPlusPlus && 
!Lang.AsmPreprocessor16.1k
&&
469
20.0k
      
HSOpts.UseStandardCXXIncludes16.1k
&&
HSOpts.UseStandardSystemIncludes16.1k
) {
470
8.38k
    if (HSOpts.UseLibcxx) {
471
7
      AddPath("/usr/include/c++/v1", CXXSystem, false);
472
8.38k
    } else {
473
8.38k
      AddDefaultCPlusPlusIncludePaths(Lang, triple, HSOpts);
474
8.38k
    }
475
8.38k
  }
476
477
20.0k
  AddDefaultCIncludePaths(triple, HSOpts);
478
20.0k
}
479
480
/// RemoveDuplicates - If there are duplicate directory entries in the specified
481
/// search list, remove the later (dead) ones.  Returns the number of non-system
482
/// headers removed, which is used to update NumAngled.
483
static unsigned RemoveDuplicates(std::vector<DirectoryLookupInfo> &SearchList,
484
262k
                                 unsigned First, bool Verbose) {
485
262k
  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
486
262k
  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
487
262k
  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
488
262k
  unsigned NonSystemRemoved = 0;
489
431k
  for (unsigned i = First; i != SearchList.size(); 
++i168k
) {
490
168k
    unsigned DirToRemove = i;
491
492
168k
    const DirectoryLookup &CurEntry = SearchList[i].Lookup;
493
494
168k
    if (CurEntry.isNormalDir()) {
495
      // If this isn't the first time we've seen this dir, remove it.
496
111k
      if (SeenDirs.insert(CurEntry.getDir()).second)
497
101k
        continue;
498
111k
    } else 
if (57.1k
CurEntry.isFramework()57.1k
) {
499
      // If this isn't the first time we've seen this framework dir, remove it.
500
57.1k
      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()).second)
501
57.0k
        continue;
502
57.1k
    } else {
503
45
      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
504
      // If this isn't the first time we've seen this headermap, remove it.
505
45
      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()).second)
506
47
        continue;
507
45
    }
508
509
    // If we have a normal #include dir/framework/headermap that is shadowed
510
    // later in the chain by a system include location, we actually want to
511
    // ignore the user's request and drop the user dir... keeping the system
512
    // dir.  This is weird, but required to emulate GCC's search path correctly.
513
    //
514
    // Since dupes of system dirs are rare, just rescan to find the original
515
    // that we're nuking instead of using a DenseMap.
516
10.0k
    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
517
      // Find the dir that this is the same of.
518
9.93k
      unsigned FirstDir;
519
10.0k
      for (FirstDir = First;; 
++FirstDir99
) {
520
10.0k
        assert(FirstDir != i && "Didn't find dupe?");
521
522
0
        const DirectoryLookup &SearchEntry = SearchList[FirstDir].Lookup;
523
524
        // If these are different lookup types, then they can't be the dupe.
525
10.0k
        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
526
40
          continue;
527
528
9.99k
        bool isSame;
529
9.99k
        if (CurEntry.isNormalDir())
530
9.99k
          isSame = SearchEntry.getDir() == CurEntry.getDir();
531
2
        else if (CurEntry.isFramework())
532
2
          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
533
0
        else {
534
0
          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
535
0
          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
536
0
        }
537
538
9.99k
        if (isSame)
539
9.93k
          break;
540
9.99k
      }
541
542
      // If the first dir in the search path is a non-system dir, zap it
543
      // instead of the system one.
544
9.93k
      if (SearchList[FirstDir].Lookup.getDirCharacteristic() == SrcMgr::C_User)
545
12
        DirToRemove = FirstDir;
546
9.93k
    }
547
548
10.0k
    if (Verbose) {
549
3
      llvm::errs() << "ignoring duplicate directory \""
550
3
                   << CurEntry.getName() << "\"\n";
551
3
      if (DirToRemove != i)
552
0
        llvm::errs() << "  as it is a non-system directory that duplicates "
553
0
                     << "a system directory\n";
554
3
    }
555
10.0k
    if (DirToRemove != i)
556
12
      ++NonSystemRemoved;
557
558
    // This is reached if the current entry is a duplicate.  Remove the
559
    // DirToRemove (usually the current dir).
560
10.0k
    SearchList.erase(SearchList.begin()+DirToRemove);
561
10.0k
    --i;
562
10.0k
  }
563
262k
  return NonSystemRemoved;
564
262k
}
565
566
/// Extract DirectoryLookups from DirectoryLookupInfos.
567
static std::vector<DirectoryLookup>
568
87.5k
extractLookups(const std::vector<DirectoryLookupInfo> &Infos) {
569
87.5k
  std::vector<DirectoryLookup> Lookups;
570
87.5k
  Lookups.reserve(Infos.size());
571
87.5k
  llvm::transform(Infos, std::back_inserter(Lookups),
572
144k
                  [](const DirectoryLookupInfo &Info) { return Info.Lookup; });
573
87.5k
  return Lookups;
574
87.5k
}
575
576
/// Collect the mapping between indices of DirectoryLookups and UserEntries.
577
static llvm::DenseMap<unsigned, unsigned>
578
87.5k
mapToUserEntries(const std::vector<DirectoryLookupInfo> &Infos) {
579
87.5k
  llvm::DenseMap<unsigned, unsigned> LookupsToUserEntries;
580
232k
  for (unsigned I = 0, E = Infos.size(); I < E; 
++I144k
) {
581
    // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.
582
144k
    if (Infos[I].UserEntryIdx)
583
78.2k
      LookupsToUserEntries.insert({I, *Infos[I].UserEntryIdx});
584
144k
  }
585
87.5k
  return LookupsToUserEntries;
586
87.5k
}
587
588
87.5k
void InitHeaderSearch::Realize(const LangOptions &Lang) {
589
  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
590
87.5k
  std::vector<DirectoryLookupInfo> SearchList;
591
87.5k
  SearchList.reserve(IncludePath.size());
592
593
  // Quoted arguments go first.
594
87.5k
  for (auto &Include : IncludePath)
595
154k
    if (Include.Group == Quoted)
596
57
      SearchList.push_back(Include);
597
598
  // Deduplicate and remember index.
599
87.5k
  RemoveDuplicates(SearchList, 0, Verbose);
600
87.5k
  unsigned NumQuoted = SearchList.size();
601
602
87.5k
  for (auto &Include : IncludePath)
603
154k
    if (Include.Group == Angled || 
Include.Group == IndexHeaderMap141k
)
604
13.8k
      SearchList.push_back(Include);
605
606
87.5k
  RemoveDuplicates(SearchList, NumQuoted, Verbose);
607
87.5k
  unsigned NumAngled = SearchList.size();
608
609
87.5k
  for (auto &Include : IncludePath)
610
154k
    if (Include.Group == System || 
Include.Group == ExternCSystem32.5k
||
611
154k
        
(13.9k
!Lang.ObjC13.9k
&&
!Lang.CPlusPlus10.6k
&&
Include.Group == CSystem3.23k
) ||
612
154k
        
(/*FIXME !Lang.ObjC && */ 13.9k
Lang.CPlusPlus13.9k
&&
613
13.9k
         
Include.Group == CXXSystem7.89k
) ||
614
154k
        
(13.9k
Lang.ObjC13.9k
&&
!Lang.CPlusPlus3.25k
&&
Include.Group == ObjCSystem2.77k
) ||
615
154k
        
(13.9k
Lang.ObjC13.9k
&&
Lang.CPlusPlus3.25k
&&
Include.Group == ObjCXXSystem485
))
616
141k
      SearchList.push_back(Include);
617
618
87.5k
  for (auto &Include : IncludePath)
619
154k
    if (Include.Group == After)
620
11
      SearchList.push_back(Include);
621
622
  // Remove duplicates across both the Angled and System directories.  GCC does
623
  // this and failing to remove duplicates across these two groups breaks
624
  // #include_next.
625
87.5k
  unsigned NonSystemRemoved = RemoveDuplicates(SearchList, NumQuoted, Verbose);
626
87.5k
  NumAngled -= NonSystemRemoved;
627
628
87.5k
  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
629
87.5k
  Headers.SetSearchPaths(extractLookups(SearchList), NumQuoted, NumAngled,
630
87.5k
                         DontSearchCurDir, mapToUserEntries(SearchList));
631
632
87.5k
  Headers.SetSystemHeaderPrefixes(SystemHeaderPrefixes);
633
634
  // If verbose, print the list of directories that will be searched.
635
87.5k
  if (Verbose) {
636
63
    llvm::errs() << "#include \"...\" search starts here:\n";
637
296
    for (unsigned i = 0, e = SearchList.size(); i != e; 
++i233
) {
638
233
      if (i == NumQuoted)
639
61
        llvm::errs() << "#include <...> search starts here:\n";
640
233
      StringRef Name = SearchList[i].Lookup.getName();
641
233
      const char *Suffix;
642
233
      if (SearchList[i].Lookup.isNormalDir())
643
157
        Suffix = "";
644
76
      else if (SearchList[i].Lookup.isFramework())
645
76
        Suffix = " (framework directory)";
646
0
      else {
647
0
        assert(SearchList[i].Lookup.isHeaderMap() && "Unknown DirectoryLookup");
648
0
        Suffix = " (headermap)";
649
0
      }
650
0
      llvm::errs() << " " << Name << Suffix << "\n";
651
233
    }
652
63
    llvm::errs() << "End of search list.\n";
653
63
  }
654
87.5k
}
655
656
void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
657
                                     const HeaderSearchOptions &HSOpts,
658
                                     const LangOptions &Lang,
659
87.5k
                                     const llvm::Triple &Triple) {
660
87.5k
  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
661
662
  // Add the user defined entries.
663
208k
  for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; 
++i120k
) {
664
120k
    const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
665
120k
    if (E.IgnoreSysRoot) {
666
120k
      Init.AddUnmappedPath(E.Path, E.Group, E.IsFramework, i);
667
120k
    } else {
668
1
      Init.AddPath(E.Path, E.Group, E.IsFramework, i);
669
1
    }
670
120k
  }
671
672
87.5k
  Init.AddDefaultIncludePaths(Lang, Triple, HSOpts);
673
674
87.5k
  for (unsigned i = 0, e = HSOpts.SystemHeaderPrefixes.size(); i != e; 
++i4
)
675
4
    Init.AddSystemHeaderPrefix(HSOpts.SystemHeaderPrefixes[i].Prefix,
676
4
                               HSOpts.SystemHeaderPrefixes[i].IsSystemHeader);
677
678
87.5k
  if (HSOpts.UseBuiltinIncludes) {
679
    // Set up the builtin include directory in the module map.
680
87.4k
    SmallString<128> P = StringRef(HSOpts.ResourceDir);
681
87.4k
    llvm::sys::path::append(P, "include");
682
87.4k
    if (auto Dir = HS.getFileMgr().getDirectory(P))
683
46.0k
      HS.getModuleMap().setBuiltinIncludeDir(*Dir);
684
87.4k
  }
685
686
87.5k
  Init.Realize(Lang);
687
87.5k
}