InitHeaderSearch.cpp revision 47adebef0df6dce752fe9a45e9190e8005b5d07c
1//===--- InitHeaderSearch.cpp - Initialize header search paths ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the InitHeaderSearch class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifdef HAVE_CLANG_CONFIG_H
15# include "clang/Config/config.h"
16#endif
17
18#include "clang/Frontend/Utils.h"
19#include "clang/Basic/FileManager.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Frontend/HeaderSearchOptions.h"
22#include "clang/Lex/HeaderSearch.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/Triple.h"
28#include "llvm/ADT/Twine.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/Support/Path.h"
31#include "llvm/Config/config.h"
32#ifdef _MSC_VER
33  #define WIN32_LEAN_AND_MEAN 1
34  #include <windows.h>
35#endif
36using namespace clang;
37using namespace clang::frontend;
38
39namespace {
40
41/// InitHeaderSearch - This class makes it easier to set the search paths of
42///  a HeaderSearch object. InitHeaderSearch stores several search path lists
43///  internally, which can be sent to a HeaderSearch object in one swoop.
44class InitHeaderSearch {
45  std::vector<std::pair<IncludeDirGroup, DirectoryLookup> > IncludePath;
46  typedef std::vector<std::pair<IncludeDirGroup,
47                      DirectoryLookup> >::const_iterator path_iterator;
48  HeaderSearch &Headers;
49  bool Verbose;
50  std::string IncludeSysroot;
51  bool IsNotEmptyOrRoot;
52
53public:
54
55  InitHeaderSearch(HeaderSearch &HS, bool verbose, StringRef sysroot)
56    : Headers(HS), Verbose(verbose), IncludeSysroot(sysroot),
57      IsNotEmptyOrRoot(!(sysroot.empty() || sysroot == "/")) {
58  }
59
60  /// AddPath - Add the specified path to the specified group list.
61  void AddPath(const Twine &Path, IncludeDirGroup Group,
62               bool isCXXAware, bool isUserSupplied,
63               bool isFramework, bool IgnoreSysRoot = false);
64
65  /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to support a gnu
66  ///  libstdc++.
67  void AddGnuCPlusPlusIncludePaths(StringRef Base,
68                                   StringRef ArchDir,
69                                   StringRef Dir32,
70                                   StringRef Dir64,
71                                   const llvm::Triple &triple);
72
73  /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to support a MinGW
74  ///  libstdc++.
75  void AddMinGWCPlusPlusIncludePaths(StringRef Base,
76                                     StringRef Arch,
77                                     StringRef Version);
78
79  /// AddMinGW64CXXPaths - Add the necessary paths to support
80  /// libstdc++ of x86_64-w64-mingw32 aka mingw-w64.
81  void AddMinGW64CXXPaths(StringRef Base,
82                          StringRef Version);
83
84  // AddDefaultCIncludePaths - Add paths that should always be searched.
85  void AddDefaultCIncludePaths(const llvm::Triple &triple,
86                               const HeaderSearchOptions &HSOpts);
87
88  // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
89  //  compiling c++.
90  void AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple,
91                                       const HeaderSearchOptions &HSOpts);
92
93  /// AddDefaultSystemIncludePaths - Adds the default system include paths so
94  ///  that e.g. stdio.h is found.
95  void AddDefaultSystemIncludePaths(const LangOptions &Lang,
96                                    const llvm::Triple &triple,
97                                    const HeaderSearchOptions &HSOpts);
98
99  /// Realize - Merges all search path lists into one list and send it to
100  /// HeaderSearch.
101  void Realize(const LangOptions &Lang);
102};
103
104}  // end anonymous namespace.
105
106void InitHeaderSearch::AddPath(const Twine &Path,
107                               IncludeDirGroup Group, bool isCXXAware,
108                               bool isUserSupplied, bool isFramework,
109                               bool IgnoreSysRoot) {
110  assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
111  FileManager &FM = Headers.getFileMgr();
112
113  // Compute the actual path, taking into consideration -isysroot.
114  llvm::SmallString<256> MappedPathStorage;
115  StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
116
117  // Handle isysroot.
118  if ((Group == System || Group == CXXSystem) && !IgnoreSysRoot &&
119#if defined(_WIN32)
120      !MappedPathStr.empty() &&
121      llvm::sys::path::is_separator(MappedPathStr[0]) &&
122#else
123      llvm::sys::path::is_absolute(MappedPathStr) &&
124#endif
125      IsNotEmptyOrRoot) {
126    MappedPathStorage.clear();
127    MappedPathStr =
128      (IncludeSysroot + Path).toStringRef(MappedPathStorage);
129  }
130
131  // Compute the DirectoryLookup type.
132  SrcMgr::CharacteristicKind Type;
133  if (Group == Quoted || Group == Angled || Group == IndexHeaderMap)
134    Type = SrcMgr::C_User;
135  else if (isCXXAware)
136    Type = SrcMgr::C_System;
137  else
138    Type = SrcMgr::C_ExternCSystem;
139
140
141  // If the directory exists, add it.
142  if (const DirectoryEntry *DE = FM.getDirectory(MappedPathStr)) {
143    IncludePath.push_back(std::make_pair(Group, DirectoryLookup(DE, Type,
144                          isUserSupplied, isFramework)));
145    return;
146  }
147
148  // Check to see if this is an apple-style headermap (which are not allowed to
149  // be frameworks).
150  if (!isFramework) {
151    if (const FileEntry *FE = FM.getFile(MappedPathStr)) {
152      if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
153        // It is a headermap, add it to the search path.
154        IncludePath.push_back(std::make_pair(Group, DirectoryLookup(HM, Type,
155                              isUserSupplied, Group == IndexHeaderMap)));
156        return;
157      }
158    }
159  }
160
161  if (Verbose)
162    llvm::errs() << "ignoring nonexistent directory \""
163                 << MappedPathStr << "\"\n";
164}
165
166void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(StringRef Base,
167                                                   StringRef ArchDir,
168                                                   StringRef Dir32,
169                                                   StringRef Dir64,
170                                                   const llvm::Triple &triple) {
171  // Add the base dir
172  AddPath(Base, CXXSystem, true, false, false);
173
174  // Add the multilib dirs
175  llvm::Triple::ArchType arch = triple.getArch();
176  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
177  if (is64bit)
178    AddPath(Base + "/" + ArchDir + "/" + Dir64, CXXSystem, true, false, false);
179  else
180    AddPath(Base + "/" + ArchDir + "/" + Dir32, CXXSystem, true, false, false);
181
182  // Add the backward dir
183  AddPath(Base + "/backward", CXXSystem, true, false, false);
184}
185
186void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(StringRef Base,
187                                                     StringRef Arch,
188                                                     StringRef Version) {
189  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++",
190          CXXSystem, true, false, false);
191  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/" + Arch,
192          CXXSystem, true, false, false);
193  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/backward",
194          CXXSystem, true, false, false);
195}
196
197void InitHeaderSearch::AddMinGW64CXXPaths(StringRef Base,
198                                          StringRef Version) {
199  // Assumes Base is HeaderSearchOpts' ResourceDir
200  AddPath(Base + "/../../../include/c++/" + Version,
201          CXXSystem, true, false, false);
202  AddPath(Base + "/../../../include/c++/" + Version + "/x86_64-w64-mingw32",
203          CXXSystem, true, false, false);
204  AddPath(Base + "/../../../include/c++/" + Version + "/i686-w64-mingw32",
205          CXXSystem, true, false, false);
206  AddPath(Base + "/../../../include/c++/" + Version + "/backward",
207          CXXSystem, true, false, false);
208}
209
210  // FIXME: This probably should goto to some platform utils place.
211#ifdef _MSC_VER
212
213  // Read registry string.
214  // This also supports a means to look for high-versioned keys by use
215  // of a $VERSION placeholder in the key path.
216  // $VERSION in the key path is a placeholder for the version number,
217  // causing the highest value path to be searched for and used.
218  // I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
219  // There can be additional characters in the component.  Only the numberic
220  // characters are compared.
221static bool getSystemRegistryString(const char *keyPath, const char *valueName,
222                                    char *value, size_t maxLength) {
223  HKEY hRootKey = NULL;
224  HKEY hKey = NULL;
225  const char* subKey = NULL;
226  DWORD valueType;
227  DWORD valueSize = maxLength - 1;
228  long lResult;
229  bool returnValue = false;
230
231  if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) {
232    hRootKey = HKEY_CLASSES_ROOT;
233    subKey = keyPath + 18;
234  } else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) {
235    hRootKey = HKEY_USERS;
236    subKey = keyPath + 11;
237  } else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) {
238    hRootKey = HKEY_LOCAL_MACHINE;
239    subKey = keyPath + 19;
240  } else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) {
241    hRootKey = HKEY_CURRENT_USER;
242    subKey = keyPath + 18;
243  }
244  else
245    return false;
246
247  const char *placeHolder = strstr(subKey, "$VERSION");
248  char bestName[256];
249  bestName[0] = '\0';
250  // If we have a $VERSION placeholder, do the highest-version search.
251  if (placeHolder) {
252    const char *keyEnd = placeHolder - 1;
253    const char *nextKey = placeHolder;
254    // Find end of previous key.
255    while ((keyEnd > subKey) && (*keyEnd != '\\'))
256      keyEnd--;
257    // Find end of key containing $VERSION.
258    while (*nextKey && (*nextKey != '\\'))
259      nextKey++;
260    size_t partialKeyLength = keyEnd - subKey;
261    char partialKey[256];
262    if (partialKeyLength > sizeof(partialKey))
263      partialKeyLength = sizeof(partialKey);
264    strncpy(partialKey, subKey, partialKeyLength);
265    partialKey[partialKeyLength] = '\0';
266    HKEY hTopKey = NULL;
267    lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ, &hTopKey);
268    if (lResult == ERROR_SUCCESS) {
269      char keyName[256];
270      int bestIndex = -1;
271      double bestValue = 0.0;
272      DWORD index, size = sizeof(keyName) - 1;
273      for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
274          NULL, NULL, NULL) == ERROR_SUCCESS; index++) {
275        const char *sp = keyName;
276        while (*sp && !isdigit(*sp))
277          sp++;
278        if (!*sp)
279          continue;
280        const char *ep = sp + 1;
281        while (*ep && (isdigit(*ep) || (*ep == '.')))
282          ep++;
283        char numBuf[32];
284        strncpy(numBuf, sp, sizeof(numBuf) - 1);
285        numBuf[sizeof(numBuf) - 1] = '\0';
286        double value = strtod(numBuf, NULL);
287        if (value > bestValue) {
288          bestIndex = (int)index;
289          bestValue = value;
290          strcpy(bestName, keyName);
291        }
292        size = sizeof(keyName) - 1;
293      }
294      // If we found the highest versioned key, open the key and get the value.
295      if (bestIndex != -1) {
296        // Append rest of key.
297        strncat(bestName, nextKey, sizeof(bestName) - 1);
298        bestName[sizeof(bestName) - 1] = '\0';
299        // Open the chosen key path remainder.
300        lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ, &hKey);
301        if (lResult == ERROR_SUCCESS) {
302          lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
303            (LPBYTE)value, &valueSize);
304          if (lResult == ERROR_SUCCESS)
305            returnValue = true;
306          RegCloseKey(hKey);
307        }
308      }
309      RegCloseKey(hTopKey);
310    }
311  }
312  else {
313    lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey);
314    if (lResult == ERROR_SUCCESS) {
315      lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
316        (LPBYTE)value, &valueSize);
317      if (lResult == ERROR_SUCCESS)
318        returnValue = true;
319      RegCloseKey(hKey);
320    }
321  }
322  return returnValue;
323}
324#else // _MSC_VER
325  // Read registry string.
326static bool getSystemRegistryString(const char*, const char*, char*, size_t) {
327  return(false);
328}
329#endif // _MSC_VER
330
331  // Get Visual Studio installation directory.
332static bool getVisualStudioDir(std::string &path) {
333  // First check the environment variables that vsvars32.bat sets.
334  const char* vcinstalldir = getenv("VCINSTALLDIR");
335  if (vcinstalldir) {
336    char *p = const_cast<char *>(strstr(vcinstalldir, "\\VC"));
337    if (p)
338      *p = '\0';
339    path = vcinstalldir;
340    return true;
341  }
342
343  char vsIDEInstallDir[256];
344  char vsExpressIDEInstallDir[256];
345  // Then try the windows registry.
346  bool hasVCDir = getSystemRegistryString(
347    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
348    "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1);
349  bool hasVCExpressDir = getSystemRegistryString(
350    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
351    "InstallDir", vsExpressIDEInstallDir, sizeof(vsExpressIDEInstallDir) - 1);
352    // If we have both vc80 and vc90, pick version we were compiled with.
353  if (hasVCDir && vsIDEInstallDir[0]) {
354    char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE");
355    if (p)
356      *p = '\0';
357    path = vsIDEInstallDir;
358    return true;
359  }
360
361  if (hasVCExpressDir && vsExpressIDEInstallDir[0]) {
362    char *p = (char*)strstr(vsExpressIDEInstallDir, "\\Common7\\IDE");
363    if (p)
364      *p = '\0';
365    path = vsExpressIDEInstallDir;
366    return true;
367  }
368
369  // Try the environment.
370  const char *vs100comntools = getenv("VS100COMNTOOLS");
371  const char *vs90comntools = getenv("VS90COMNTOOLS");
372  const char *vs80comntools = getenv("VS80COMNTOOLS");
373  const char *vscomntools = NULL;
374
375  // Try to find the version that we were compiled with
376  if(false) {}
377  #if (_MSC_VER >= 1600)  // VC100
378  else if(vs100comntools) {
379    vscomntools = vs100comntools;
380  }
381  #elif (_MSC_VER == 1500) // VC80
382  else if(vs90comntools) {
383    vscomntools = vs90comntools;
384  }
385  #elif (_MSC_VER == 1400) // VC80
386  else if(vs80comntools) {
387    vscomntools = vs80comntools;
388  }
389  #endif
390  // Otherwise find any version we can
391  else if (vs100comntools)
392    vscomntools = vs100comntools;
393  else if (vs90comntools)
394    vscomntools = vs90comntools;
395  else if (vs80comntools)
396    vscomntools = vs80comntools;
397
398  if (vscomntools && *vscomntools) {
399    const char *p = strstr(vscomntools, "\\Common7\\Tools");
400    path = p ? std::string(vscomntools, p) : vscomntools;
401    return true;
402  }
403  return false;
404}
405
406  // Get Windows SDK installation directory.
407static bool getWindowsSDKDir(std::string &path) {
408  char windowsSDKInstallDir[256];
409  // Try the Windows registry.
410  bool hasSDKDir = getSystemRegistryString(
411   "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
412                                           "InstallationFolder",
413                                           windowsSDKInstallDir,
414                                           sizeof(windowsSDKInstallDir) - 1);
415    // If we have both vc80 and vc90, pick version we were compiled with.
416  if (hasSDKDir && windowsSDKInstallDir[0]) {
417    path = windowsSDKInstallDir;
418    return(true);
419  }
420  return(false);
421}
422
423void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
424                                            const HeaderSearchOptions &HSOpts) {
425  llvm::Triple::OSType os = triple.getOS();
426
427  switch (os) {
428  case llvm::Triple::FreeBSD:
429  case llvm::Triple::NetBSD:
430    break;
431  default:
432    // FIXME: temporary hack: hard-coded paths.
433    AddPath("/usr/local/include", System, true, false, false);
434    break;
435  }
436
437  // Builtin includes use #include_next directives and should be positioned
438  // just prior C include dirs.
439  if (HSOpts.UseBuiltinIncludes) {
440    // Ignore the sys root, we *always* look for clang headers relative to
441    // supplied path.
442    llvm::sys::Path P(HSOpts.ResourceDir);
443    P.appendComponent("include");
444    AddPath(P.str(), System, false, false, false, /*IgnoreSysRoot=*/ true);
445  }
446
447  // Add dirs specified via 'configure --with-c-include-dirs'.
448  StringRef CIncludeDirs(C_INCLUDE_DIRS);
449  if (CIncludeDirs != "") {
450    SmallVector<StringRef, 5> dirs;
451    CIncludeDirs.split(dirs, ":");
452    for (SmallVectorImpl<StringRef>::iterator i = dirs.begin();
453         i != dirs.end();
454         ++i)
455      AddPath(*i, System, false, false, false);
456    return;
457  }
458
459  switch (os) {
460  case llvm::Triple::Win32: {
461    std::string VSDir;
462    std::string WindowsSDKDir;
463    if (getVisualStudioDir(VSDir)) {
464      AddPath(VSDir + "\\VC\\include", System, false, false, false);
465      if (getWindowsSDKDir(WindowsSDKDir))
466        AddPath(WindowsSDKDir + "\\include", System, false, false, false);
467      else
468        AddPath(VSDir + "\\VC\\PlatformSDK\\Include",
469                System, false, false, false);
470    } else {
471      // Default install paths.
472      AddPath("C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
473              System, false, false, false);
474      AddPath("C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
475              System, false, false, false);
476      AddPath(
477        "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
478        System, false, false, false);
479      AddPath("C:/Program Files/Microsoft Visual Studio 8/VC/include",
480              System, false, false, false);
481      AddPath(
482        "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include",
483        System, false, false, false);
484    }
485    break;
486  }
487  case llvm::Triple::Haiku:
488    AddPath("/boot/common/include", System, true, false, false);
489    AddPath("/boot/develop/headers/os", System, true, false, false);
490    AddPath("/boot/develop/headers/os/app", System, true, false, false);
491    AddPath("/boot/develop/headers/os/arch", System, true, false, false);
492    AddPath("/boot/develop/headers/os/device", System, true, false, false);
493    AddPath("/boot/develop/headers/os/drivers", System, true, false, false);
494    AddPath("/boot/develop/headers/os/game", System, true, false, false);
495    AddPath("/boot/develop/headers/os/interface", System, true, false, false);
496    AddPath("/boot/develop/headers/os/kernel", System, true, false, false);
497    AddPath("/boot/develop/headers/os/locale", System, true, false, false);
498    AddPath("/boot/develop/headers/os/mail", System, true, false, false);
499    AddPath("/boot/develop/headers/os/media", System, true, false, false);
500    AddPath("/boot/develop/headers/os/midi", System, true, false, false);
501    AddPath("/boot/develop/headers/os/midi2", System, true, false, false);
502    AddPath("/boot/develop/headers/os/net", System, true, false, false);
503    AddPath("/boot/develop/headers/os/storage", System, true, false, false);
504    AddPath("/boot/develop/headers/os/support", System, true, false, false);
505    AddPath("/boot/develop/headers/os/translation",
506      System, true, false, false);
507    AddPath("/boot/develop/headers/os/add-ons/graphics",
508      System, true, false, false);
509    AddPath("/boot/develop/headers/os/add-ons/input_server",
510      System, true, false, false);
511    AddPath("/boot/develop/headers/os/add-ons/screen_saver",
512      System, true, false, false);
513    AddPath("/boot/develop/headers/os/add-ons/tracker",
514      System, true, false, false);
515    AddPath("/boot/develop/headers/os/be_apps/Deskbar",
516      System, true, false, false);
517    AddPath("/boot/develop/headers/os/be_apps/NetPositive",
518      System, true, false, false);
519    AddPath("/boot/develop/headers/os/be_apps/Tracker",
520      System, true, false, false);
521    AddPath("/boot/develop/headers/cpp", System, true, false, false);
522    AddPath("/boot/develop/headers/cpp/i586-pc-haiku",
523      System, true, false, false);
524    AddPath("/boot/develop/headers/3rdparty", System, true, false, false);
525    AddPath("/boot/develop/headers/bsd", System, true, false, false);
526    AddPath("/boot/develop/headers/glibc", System, true, false, false);
527    AddPath("/boot/develop/headers/posix", System, true, false, false);
528    AddPath("/boot/develop/headers",  System, true, false, false);
529    break;
530  case llvm::Triple::RTEMS:
531    break;
532  case llvm::Triple::Cygwin:
533    AddPath("/usr/include/w32api", System, true, false, false);
534    break;
535  case llvm::Triple::MinGW32: {
536      // mingw-w64 crt include paths
537      llvm::sys::Path P(HSOpts.ResourceDir);
538      P.appendComponent("../../../i686-w64-mingw32/include"); // <sysroot>/i686-w64-mingw32/include
539      AddPath(P.str(), System, true, false, false);
540      P = llvm::sys::Path(HSOpts.ResourceDir);
541      P.appendComponent("../../../x86_64-w64-mingw32/include"); // <sysroot>/x86_64-w64-mingw32/include
542      AddPath(P.str(), System, true, false, false);
543      // mingw.org crt include paths
544      P = llvm::sys::Path(HSOpts.ResourceDir);
545      P.appendComponent("../../../include"); // <sysroot>/include
546      AddPath(P.str(), System, true, false, false);
547      AddPath("/mingw/include", System, true, false, false);
548      AddPath("c:/mingw/include", System, true, false, false);
549    }
550    break;
551
552  case llvm::Triple::Linux:
553    // Generic Debian multiarch support:
554    if (triple.getArch() == llvm::Triple::x86_64) {
555      AddPath("/usr/include/x86_64-linux-gnu", System, false, false, false);
556      AddPath("/usr/include/i686-linux-gnu/64", System, false, false, false);
557      AddPath("/usr/include/i486-linux-gnu/64", System, false, false, false);
558    } else if (triple.getArch() == llvm::Triple::x86) {
559      AddPath("/usr/include/x86_64-linux-gnu/32", System, false, false, false);
560      AddPath("/usr/include/i686-linux-gnu", System, false, false, false);
561      AddPath("/usr/include/i486-linux-gnu", System, false, false, false);
562    } else if (triple.getArch() == llvm::Triple::arm) {
563      AddPath("/usr/include/arm-linux-gnueabi", System, false, false, false);
564    }
565  default:
566    break;
567  }
568
569  if ( os != llvm::Triple::RTEMS )
570    AddPath("/usr/include", System, false, false, false);
571}
572
573void InitHeaderSearch::
574AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple, const HeaderSearchOptions &HSOpts) {
575  llvm::Triple::OSType os = triple.getOS();
576  StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
577  if (CxxIncludeRoot != "") {
578    StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
579    if (CxxIncludeArch == "")
580      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
581                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
582                                  triple);
583    else
584      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
585                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
586                                  triple);
587    return;
588  }
589  // FIXME: temporary hack: hard-coded paths.
590
591  if (triple.isOSDarwin()) {
592    switch (triple.getArch()) {
593    default: break;
594
595    case llvm::Triple::ppc:
596    case llvm::Triple::ppc64:
597      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
598                                  "powerpc-apple-darwin10", "", "ppc64",
599                                  triple);
600      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
601                                  "powerpc-apple-darwin10", "", "ppc64",
602                                  triple);
603      break;
604
605    case llvm::Triple::x86:
606    case llvm::Triple::x86_64:
607      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
608                                  "i686-apple-darwin10", "", "x86_64", triple);
609      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
610                                  "i686-apple-darwin8", "", "", triple);
611      break;
612
613    case llvm::Triple::arm:
614    case llvm::Triple::thumb:
615      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
616                                  "arm-apple-darwin10", "v7", "", triple);
617      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
618                                  "arm-apple-darwin10", "v6", "", triple);
619      break;
620    }
621    return;
622  }
623
624  switch (os) {
625  case llvm::Triple::Cygwin:
626    // Cygwin-1.7
627    AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.4");
628    // g++-4 / Cygwin-1.5
629    AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.2");
630    // FIXME: Do we support g++-3.4.4?
631    AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "3.4.4");
632    break;
633  case llvm::Triple::MinGW32:
634    // mingw-w64 C++ include paths (i686-w64-mingw32 and x86_64-w64-mingw32)
635    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.0");
636    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.1");
637    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.2");
638    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.3");
639    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.0");
640    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.1");
641    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.2");
642    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.7.0");
643    // mingw.org C++ include paths
644    AddMinGWCPlusPlusIncludePaths("/mingw/lib/gcc", "mingw32", "4.5.2"); //MSYS
645    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.5.0");
646    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
647    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
648    break;
649  case llvm::Triple::DragonFly:
650    AddPath("/usr/include/c++/4.1", CXXSystem, true, false, false);
651    break;
652  case llvm::Triple::Linux:
653    //===------------------------------------------------------------------===//
654    // Debian based distros.
655    // Note: these distros symlink /usr/include/c++/X.Y.Z -> X.Y
656    //===------------------------------------------------------------------===//
657
658    // Ubuntu 11.11 "Oneiric Ocelot" -- gcc-4.6.0
659    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6",
660                                "x86_64-linux-gnu", "32", "", triple);
661    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6",
662                                "i686-linux-gnu", "", "64", triple);
663    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6",
664                                "i486-linux-gnu", "", "64", triple);
665    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6",
666                                "arm-linux-gnueabi", "", "", triple);
667
668    // Ubuntu 11.04 "Natty Narwhal" -- gcc-4.5.2
669    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5",
670                                "x86_64-linux-gnu", "32", "", triple);
671    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5",
672                                "i686-linux-gnu", "", "64", triple);
673    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5",
674                                "i486-linux-gnu", "", "64", triple);
675    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5",
676                                "arm-linux-gnueabi", "", "", triple);
677
678    // Ubuntu 10.10 "Maverick Meerkat" -- gcc-4.4.5
679    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
680                                "i686-linux-gnu", "", "64", triple);
681    // The rest of 10.10 is the same as previous versions.
682
683    // Ubuntu 10.04 LTS "Lucid Lynx" -- gcc-4.4.3
684    // Ubuntu 9.10 "Karmic Koala"    -- gcc-4.4.1
685    // Debian 6.0 "squeeze"          -- gcc-4.4.2
686    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
687                                "x86_64-linux-gnu", "32", "", triple);
688    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
689                                "i486-linux-gnu", "", "64", triple);
690    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
691                                "arm-linux-gnueabi", "", "", triple);
692    // Ubuntu 9.04 "Jaunty Jackalope" -- gcc-4.3.3
693    // Ubuntu 8.10 "Intrepid Ibex"    -- gcc-4.3.2
694    // Debian 5.0 "lenny"             -- gcc-4.3.2
695    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
696                                "x86_64-linux-gnu", "32", "", triple);
697    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
698                                "i486-linux-gnu", "", "64", triple);
699    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
700                                "arm-linux-gnueabi", "", "", triple);
701    // Ubuntu 8.04.4 LTS "Hardy Heron"     -- gcc-4.2.4
702    // Ubuntu 8.04.[0-3] LTS "Hardy Heron" -- gcc-4.2.3
703    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2",
704                                "x86_64-linux-gnu", "32", "", triple);
705    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2",
706                                "i486-linux-gnu", "", "64", triple);
707    // Ubuntu 7.10 "Gutsy Gibbon" -- gcc-4.1.3
708    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1",
709                                "x86_64-linux-gnu", "32", "", triple);
710    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1",
711                                "i486-linux-gnu", "", "64", triple);
712
713    //===------------------------------------------------------------------===//
714    // Redhat based distros.
715    //===------------------------------------------------------------------===//
716    // Fedora 15
717    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6.0",
718                                "x86_64-redhat-linux", "32", "", triple);
719    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6.0",
720                                "i686-redhat-linux", "", "", triple);
721    // Fedora 14
722    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5.1",
723                                "x86_64-redhat-linux", "32", "", triple);
724    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5.1",
725                                "i686-redhat-linux", "", "", triple);
726    // RHEL5(gcc44)
727    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.4",
728                                "x86_64-redhat-linux6E", "32", "", triple);
729    // Fedora 13
730    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.4",
731                                "x86_64-redhat-linux", "32", "", triple);
732    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.4",
733                                "i686-redhat-linux","", "", triple);
734    // Fedora 12
735    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
736                                "x86_64-redhat-linux", "32", "", triple);
737    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
738                                "i686-redhat-linux","", "", triple);
739    // Fedora 12 (pre-FEB-2010)
740    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
741                                "x86_64-redhat-linux", "32", "", triple);
742    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
743                                "i686-redhat-linux","", "", triple);
744    // Fedora 11
745    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
746                                "x86_64-redhat-linux", "32", "", triple);
747    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
748                                "i586-redhat-linux","", "", triple);
749    // Fedora 10
750    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
751                                "x86_64-redhat-linux", "32", "", triple);
752    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
753                                "i386-redhat-linux","", "", triple);
754    // Fedora 9
755    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
756                                "x86_64-redhat-linux", "32", "", triple);
757    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
758                                "i386-redhat-linux", "", "", triple);
759    // Fedora 8
760    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
761                                "x86_64-redhat-linux", "", "", triple);
762    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
763                                "i386-redhat-linux", "", "", triple);
764
765    // RHEL 5
766    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.1",
767                                "x86_64-redhat-linux", "32", "", triple);
768    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.1",
769                                "i386-redhat-linux", "", "", triple);
770
771
772    //===------------------------------------------------------------------===//
773
774    // Exherbo (2010-01-25)
775    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
776                                "x86_64-pc-linux-gnu", "32", "", triple);
777    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
778                                "i686-pc-linux-gnu", "", "", triple);
779
780    // openSUSE 11.1 32 bit
781    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
782                                "i586-suse-linux", "", "", triple);
783    // openSUSE 11.1 64 bit
784    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
785                                "x86_64-suse-linux", "32", "", triple);
786    // openSUSE 11.2
787    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
788                                "i586-suse-linux", "", "", triple);
789    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
790                                "x86_64-suse-linux", "", "", triple);
791
792    // openSUSE 11.4
793    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5",
794                                "i586-suse-linux", "", "", triple);
795    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5",
796                                "x86_64-suse-linux", "", "", triple);
797
798    // openSUSE 12.1
799    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6",
800                                "i586-suse-linux", "", "", triple);
801    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6",
802                                "x86_64-suse-linux", "", "", triple);
803    // Arch Linux 2008-06-24
804    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
805                                "i686-pc-linux-gnu", "", "", triple);
806    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
807                                "x86_64-unknown-linux-gnu", "", "", triple);
808
809    // Arch Linux gcc 4.6
810    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6.1",
811                                "i686-pc-linux-gnu", "", "", triple);
812    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6.1",
813                                "x86_64-unknown-linux-gnu", "", "", triple);
814    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6.0",
815                                "i686-pc-linux-gnu", "", "", triple);
816    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.6.0",
817                                "x86_64-unknown-linux-gnu", "", "", triple);
818
819    // Slackware gcc 4.5.2 (13.37)
820    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5.2",
821                                "i486-slackware-linux", "", "", triple);
822    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5.2",
823                                "x86_64-slackware-linux", "", "", triple);
824    // Slackware gcc 4.5.3 (-current)
825    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5.3",
826                                "i486-slackware-linux", "", "", triple);
827    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5.3",
828                                "x86_64-slackware-linux", "", "", triple);
829
830    // Gentoo x86 gcc 4.5.2
831    AddGnuCPlusPlusIncludePaths(
832      "/usr/lib/gcc/i686-pc-linux-gnu/4.5.2/include/g++-v4",
833      "i686-pc-linux-gnu", "", "", triple);
834    // Gentoo x86 gcc 4.4.5
835    AddGnuCPlusPlusIncludePaths(
836      "/usr/lib/gcc/i686-pc-linux-gnu/4.4.5/include/g++-v4",
837      "i686-pc-linux-gnu", "", "", triple);
838    // Gentoo x86 gcc 4.4.4
839    AddGnuCPlusPlusIncludePaths(
840      "/usr/lib/gcc/i686-pc-linux-gnu/4.4.4/include/g++-v4",
841      "i686-pc-linux-gnu", "", "", triple);
842   // Gentoo x86 2010.0 stable
843    AddGnuCPlusPlusIncludePaths(
844      "/usr/lib/gcc/i686-pc-linux-gnu/4.4.3/include/g++-v4",
845      "i686-pc-linux-gnu", "", "", triple);
846    // Gentoo x86 2009.1 stable
847    AddGnuCPlusPlusIncludePaths(
848      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4",
849      "i686-pc-linux-gnu", "", "", triple);
850    // Gentoo x86 2009.0 stable
851    AddGnuCPlusPlusIncludePaths(
852      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
853      "i686-pc-linux-gnu", "", "", triple);
854    // Gentoo x86 2008.0 stable
855    AddGnuCPlusPlusIncludePaths(
856      "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
857      "i686-pc-linux-gnu", "", "", triple);
858    // Gentoo x86 llvm-gcc trunk
859    AddGnuCPlusPlusIncludePaths(
860        "/usr/lib/llvm-gcc-4.2-9999/include/c++/4.2.1",
861        "i686-pc-linux-gnu", "", "", triple);
862
863    // Gentoo amd64 gcc 4.5.2
864    AddGnuCPlusPlusIncludePaths(
865        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.2/include/g++-v4",
866        "x86_64-pc-linux-gnu", "32", "", triple);
867    // Gentoo amd64 gcc 4.4.5
868    AddGnuCPlusPlusIncludePaths(
869        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.4.5/include/g++-v4",
870        "x86_64-pc-linux-gnu", "32", "", triple);
871    // Gentoo amd64 gcc 4.4.4
872    AddGnuCPlusPlusIncludePaths(
873        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.4.4/include/g++-v4",
874        "x86_64-pc-linux-gnu", "32", "", triple);
875    // Gentoo amd64 gcc 4.4.3
876    AddGnuCPlusPlusIncludePaths(
877        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.4.3/include/g++-v4",
878        "x86_64-pc-linux-gnu", "32", "", triple);
879    // Gentoo amd64 gcc 4.3.4
880    AddGnuCPlusPlusIncludePaths(
881        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4",
882        "x86_64-pc-linux-gnu", "", "", triple);
883    // Gentoo amd64 gcc 4.3.2
884    AddGnuCPlusPlusIncludePaths(
885        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.2/include/g++-v4",
886        "x86_64-pc-linux-gnu", "", "", triple);
887    // Gentoo amd64 stable
888    AddGnuCPlusPlusIncludePaths(
889        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
890        "x86_64-pc-linux-gnu", "", "", triple);
891
892    // Gentoo amd64 llvm-gcc trunk
893    AddGnuCPlusPlusIncludePaths(
894        "/usr/lib/llvm-gcc-4.2-9999/include/c++/4.2.1",
895        "x86_64-pc-linux-gnu", "", "", triple);
896
897    break;
898  case llvm::Triple::FreeBSD:
899    // FreeBSD 8.0
900    // FreeBSD 7.3
901    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2", "", "", "", triple);
902    break;
903  case llvm::Triple::NetBSD:
904    AddGnuCPlusPlusIncludePaths("/usr/include/g++", "", "", "", triple);
905    break;
906  case llvm::Triple::OpenBSD: {
907    std::string t = triple.getTriple();
908    if (t.substr(0, 6) == "x86_64")
909      t.replace(0, 6, "amd64");
910    AddGnuCPlusPlusIncludePaths("/usr/include/g++",
911                                t, "", "", triple);
912    break;
913  }
914  case llvm::Triple::Minix:
915    AddGnuCPlusPlusIncludePaths("/usr/gnu/include/c++/4.4.3",
916                                "", "", "", triple);
917    break;
918  case llvm::Triple::Solaris:
919    // Solaris - Fall though..
920  case llvm::Triple::AuroraUX:
921    // AuroraUX
922    AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
923                                "i386-pc-solaris2.11", "", "", triple);
924    break;
925  default:
926    break;
927  }
928}
929
930void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang,
931                                                    const llvm::Triple &triple,
932                                            const HeaderSearchOptions &HSOpts) {
933  if (Lang.CPlusPlus && HSOpts.UseStandardCXXIncludes) {
934    if (HSOpts.UseLibcxx) {
935      if (triple.isOSDarwin()) {
936        // On Darwin, libc++ may be installed alongside the compiler in
937        // lib/c++/v1.
938        llvm::sys::Path P(HSOpts.ResourceDir);
939        if (!P.isEmpty()) {
940          P.eraseComponent();  // Remove version from foo/lib/clang/version
941          P.eraseComponent();  // Remove clang from foo/lib/clang
942
943          // Get foo/lib/c++/v1
944          P.appendComponent("c++");
945          P.appendComponent("v1");
946          AddPath(P.str(), CXXSystem, true, false, false, true);
947        }
948      }
949
950      AddPath("/usr/include/c++/v1", CXXSystem, true, false, false);
951    }
952    else
953      AddDefaultCPlusPlusIncludePaths(triple, HSOpts);
954  }
955
956  AddDefaultCIncludePaths(triple, HSOpts);
957
958  // Add the default framework include paths on Darwin.
959  if (triple.isOSDarwin()) {
960    AddPath("/System/Library/Frameworks", System, true, false, true);
961    AddPath("/Library/Frameworks", System, true, false, true);
962  }
963}
964
965/// RemoveDuplicates - If there are duplicate directory entries in the specified
966/// search list, remove the later (dead) ones.
967static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
968                             unsigned First, bool Verbose) {
969  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
970  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
971  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
972  for (unsigned i = First; i != SearchList.size(); ++i) {
973    unsigned DirToRemove = i;
974
975    const DirectoryLookup &CurEntry = SearchList[i];
976
977    if (CurEntry.isNormalDir()) {
978      // If this isn't the first time we've seen this dir, remove it.
979      if (SeenDirs.insert(CurEntry.getDir()))
980        continue;
981    } else if (CurEntry.isFramework()) {
982      // If this isn't the first time we've seen this framework dir, remove it.
983      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
984        continue;
985    } else {
986      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
987      // If this isn't the first time we've seen this headermap, remove it.
988      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
989        continue;
990    }
991
992    // If we have a normal #include dir/framework/headermap that is shadowed
993    // later in the chain by a system include location, we actually want to
994    // ignore the user's request and drop the user dir... keeping the system
995    // dir.  This is weird, but required to emulate GCC's search path correctly.
996    //
997    // Since dupes of system dirs are rare, just rescan to find the original
998    // that we're nuking instead of using a DenseMap.
999    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
1000      // Find the dir that this is the same of.
1001      unsigned FirstDir;
1002      for (FirstDir = 0; ; ++FirstDir) {
1003        assert(FirstDir != i && "Didn't find dupe?");
1004
1005        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
1006
1007        // If these are different lookup types, then they can't be the dupe.
1008        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
1009          continue;
1010
1011        bool isSame;
1012        if (CurEntry.isNormalDir())
1013          isSame = SearchEntry.getDir() == CurEntry.getDir();
1014        else if (CurEntry.isFramework())
1015          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
1016        else {
1017          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
1018          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
1019        }
1020
1021        if (isSame)
1022          break;
1023      }
1024
1025      // If the first dir in the search path is a non-system dir, zap it
1026      // instead of the system one.
1027      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
1028        DirToRemove = FirstDir;
1029    }
1030
1031    if (Verbose) {
1032      llvm::errs() << "ignoring duplicate directory \""
1033                   << CurEntry.getName() << "\"\n";
1034      if (DirToRemove != i)
1035        llvm::errs() << "  as it is a non-system directory that duplicates "
1036                     << "a system directory\n";
1037    }
1038
1039    // This is reached if the current entry is a duplicate.  Remove the
1040    // DirToRemove (usually the current dir).
1041    SearchList.erase(SearchList.begin()+DirToRemove);
1042    --i;
1043  }
1044}
1045
1046
1047void InitHeaderSearch::Realize(const LangOptions &Lang) {
1048  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1049  std::vector<DirectoryLookup> SearchList;
1050  SearchList.reserve(IncludePath.size());
1051
1052  // Quoted arguments go first.
1053  for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
1054       it != ie; ++it) {
1055    if (it->first == Quoted)
1056      SearchList.push_back(it->second);
1057  }
1058  // Deduplicate and remember index.
1059  RemoveDuplicates(SearchList, 0, Verbose);
1060  unsigned NumQuoted = SearchList.size();
1061
1062  for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
1063       it != ie; ++it) {
1064    if (it->first == Angled || it->first == IndexHeaderMap)
1065      SearchList.push_back(it->second);
1066  }
1067
1068  RemoveDuplicates(SearchList, NumQuoted, Verbose);
1069  unsigned NumAngled = SearchList.size();
1070
1071  for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
1072       it != ie; ++it) {
1073    if (it->first == System ||
1074        (!Lang.ObjC1 && !Lang.CPlusPlus && it->first == CSystem)    ||
1075        (!Lang.ObjC1 && Lang.CPlusPlus  && it->first == CXXSystem)  ||
1076        (Lang.ObjC1  && !Lang.CPlusPlus && it->first == ObjCSystem) ||
1077        (Lang.ObjC1  && Lang.CPlusPlus  && it->first == ObjCXXSystem))
1078      SearchList.push_back(it->second);
1079  }
1080
1081  for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
1082       it != ie; ++it) {
1083    if (it->first == After)
1084      SearchList.push_back(it->second);
1085  }
1086
1087  // Remove duplicates across both the Angled and System directories.  GCC does
1088  // this and failing to remove duplicates across these two groups breaks
1089  // #include_next.
1090  RemoveDuplicates(SearchList, NumQuoted, Verbose);
1091
1092  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
1093  Headers.SetSearchPaths(SearchList, NumQuoted, NumAngled, DontSearchCurDir);
1094
1095  // If verbose, print the list of directories that will be searched.
1096  if (Verbose) {
1097    llvm::errs() << "#include \"...\" search starts here:\n";
1098    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1099      if (i == NumQuoted)
1100        llvm::errs() << "#include <...> search starts here:\n";
1101      const char *Name = SearchList[i].getName();
1102      const char *Suffix;
1103      if (SearchList[i].isNormalDir())
1104        Suffix = "";
1105      else if (SearchList[i].isFramework())
1106        Suffix = " (framework directory)";
1107      else {
1108        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
1109        Suffix = " (headermap)";
1110      }
1111      llvm::errs() << " " << Name << Suffix << "\n";
1112    }
1113    llvm::errs() << "End of search list.\n";
1114  }
1115}
1116
1117void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
1118                                     const HeaderSearchOptions &HSOpts,
1119                                     const LangOptions &Lang,
1120                                     const llvm::Triple &Triple) {
1121  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
1122
1123  // Add the user defined entries.
1124  for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
1125    const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
1126    Init.AddPath(E.Path, E.Group, false, E.IsUserSupplied, E.IsFramework,
1127                 E.IgnoreSysRoot);
1128  }
1129
1130  if (HSOpts.UseStandardIncludes)
1131    Init.AddDefaultSystemIncludePaths(Lang, Triple, HSOpts);
1132
1133  Init.Realize(Lang);
1134}
1135