InitHeaderSearch.cpp revision ea9e56d38485921d596f2366d625c471a6d3c15a
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#include "clang/Frontend/Utils.h"
15#include "clang/Basic/FileManager.h"
16#include "clang/Basic/LangOptions.h"
17#include "clang/Frontend/HeaderSearchOptions.h"
18#include "clang/Lex/HeaderSearch.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/Triple.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/System/Path.h"
27#include "llvm/Config/config.h"
28#ifdef _MSC_VER
29  #define WIN32_LEAN_AND_MEAN 1
30  #include <windows.h>
31#endif
32using namespace clang;
33using namespace clang::frontend;
34
35namespace {
36
37/// InitHeaderSearch - This class makes it easier to set the search paths of
38///  a HeaderSearch object. InitHeaderSearch stores several search path lists
39///  internally, which can be sent to a HeaderSearch object in one swoop.
40class InitHeaderSearch {
41  std::vector<DirectoryLookup> IncludeGroup[4];
42  HeaderSearch& Headers;
43  bool Verbose;
44  std::string isysroot;
45
46public:
47
48  InitHeaderSearch(HeaderSearch &HS,
49      bool verbose = false, const std::string &iSysroot = "")
50    : Headers(HS), Verbose(verbose), isysroot(iSysroot) {}
51
52  /// AddPath - Add the specified path to the specified group list.
53  void AddPath(const llvm::Twine &Path, IncludeDirGroup Group,
54               bool isCXXAware, bool isUserSupplied,
55               bool isFramework, bool IgnoreSysRoot = false);
56
57  /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to support a gnu
58  ///  libstdc++.
59  void AddGnuCPlusPlusIncludePaths(llvm::StringRef Base,
60                                   llvm::StringRef ArchDir,
61                                   llvm::StringRef Dir32,
62                                   llvm::StringRef Dir64,
63                                   const llvm::Triple &triple);
64
65  /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to suport a MinGW
66  ///  libstdc++.
67  void AddMinGWCPlusPlusIncludePaths(llvm::StringRef Base,
68                                     llvm::StringRef Arch,
69                                     llvm::StringRef Version);
70
71  /// AddDelimitedPaths - Add a list of paths delimited by the system PATH
72  /// separator. The processing follows that of the CPATH variable for gcc.
73  void AddDelimitedPaths(llvm::StringRef String);
74
75  // AddDefaultCIncludePaths - Add paths that should always be searched.
76  void AddDefaultCIncludePaths(const llvm::Triple &triple,
77                               const HeaderSearchOptions &HSOpts);
78
79  // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
80  //  compiling c++.
81  void AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple);
82
83  /// AddDefaultSystemIncludePaths - Adds the default system include paths so
84  ///  that e.g. stdio.h is found.
85  void AddDefaultSystemIncludePaths(const LangOptions &Lang,
86                                    const llvm::Triple &triple,
87                                    const HeaderSearchOptions &HSOpts);
88
89  /// Realize - Merges all search path lists into one list and send it to
90  /// HeaderSearch.
91  void Realize();
92};
93
94}
95
96void InitHeaderSearch::AddPath(const llvm::Twine &Path,
97                               IncludeDirGroup Group, bool isCXXAware,
98                               bool isUserSupplied, bool isFramework,
99                               bool IgnoreSysRoot) {
100  assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
101  FileManager &FM = Headers.getFileMgr();
102
103  // Compute the actual path, taking into consideration -isysroot.
104  llvm::SmallString<256> MappedPathStr;
105  llvm::raw_svector_ostream MappedPath(MappedPathStr);
106
107  // Handle isysroot.
108  if (Group == System && !IgnoreSysRoot) {
109    // FIXME: Portability.  This should be a sys::Path interface, this doesn't
110    // handle things like C:\ right, nor win32 \\network\device\blah.
111    if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
112      MappedPath << isysroot;
113  }
114
115  Path.print(MappedPath);
116
117  // Compute the DirectoryLookup type.
118  SrcMgr::CharacteristicKind Type;
119  if (Group == Quoted || Group == Angled)
120    Type = SrcMgr::C_User;
121  else if (isCXXAware)
122    Type = SrcMgr::C_System;
123  else
124    Type = SrcMgr::C_ExternCSystem;
125
126
127  // If the directory exists, add it.
128  if (const DirectoryEntry *DE = FM.getDirectory(MappedPath.str())) {
129    IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
130                                                  isFramework));
131    return;
132  }
133
134  // Check to see if this is an apple-style headermap (which are not allowed to
135  // be frameworks).
136  if (!isFramework) {
137    if (const FileEntry *FE = FM.getFile(MappedPath.str())) {
138      if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
139        // It is a headermap, add it to the search path.
140        IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
141        return;
142      }
143    }
144  }
145
146  if (Verbose)
147    llvm::errs() << "ignoring nonexistent directory \""
148                 << MappedPath.str() << "\"\n";
149}
150
151
152void InitHeaderSearch::AddDelimitedPaths(llvm::StringRef at) {
153  if (at.empty()) // Empty string should not add '.' path.
154    return;
155
156  llvm::StringRef::size_type delim;
157  while ((delim = at.find(llvm::sys::PathSeparator)) != llvm::StringRef::npos) {
158    if (delim == 0)
159      AddPath(".", Angled, false, true, false);
160    else
161      AddPath(at.substr(0, delim), Angled, false, true, false);
162    at = at.substr(delim + 1);
163  }
164
165  if (at.empty())
166    AddPath(".", Angled, false, true, false);
167  else
168    AddPath(at, Angled, false, true, false);
169}
170
171void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(llvm::StringRef Base,
172                                                   llvm::StringRef ArchDir,
173                                                   llvm::StringRef Dir32,
174                                                   llvm::StringRef Dir64,
175                                                   const llvm::Triple &triple) {
176  // Add the base dir
177  AddPath(Base, System, true, false, false);
178
179  // Add the multilib dirs
180  llvm::Triple::ArchType arch = triple.getArch();
181  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
182  if (is64bit)
183    AddPath(Base + "/" + ArchDir + "/" + Dir64, System, true, false, false);
184  else
185    AddPath(Base + "/" + ArchDir + "/" + Dir32, System, true, false, false);
186
187  // Add the backward dir
188  AddPath(Base + "/backward", System, true, false, false);
189}
190
191void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(llvm::StringRef Base,
192                                                     llvm::StringRef Arch,
193                                                     llvm::StringRef Version) {
194  AddPath(Base + "/" + Arch + "/" + Version + "/include",
195          System, true, false, false);
196  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++",
197          System, true, false, false);
198  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/backward",
199          System, true, false, false);
200}
201
202  // FIXME: This probably should goto to some platform utils place.
203#ifdef _MSC_VER
204
205  // Read registry string.
206  // This also supports a means to look for high-versioned keys by use
207  // of a $VERSION placeholder in the key path.
208  // $VERSION in the key path is a placeholder for the version number,
209  // causing the highest value path to be searched for and used.
210  // I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
211  // There can be additional characters in the component.  Only the numberic
212  // characters are compared.
213static bool getSystemRegistryString(const char *keyPath, const char *valueName,
214                                    char *value, size_t maxLength) {
215  HKEY hRootKey = NULL;
216  HKEY hKey = NULL;
217  const char* subKey = NULL;
218  DWORD valueType;
219  DWORD valueSize = maxLength - 1;
220  long lResult;
221  bool returnValue = false;
222  if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) {
223    hRootKey = HKEY_CLASSES_ROOT;
224    subKey = keyPath + 18;
225  }
226  else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) {
227    hRootKey = HKEY_USERS;
228    subKey = keyPath + 11;
229  }
230  else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) {
231    hRootKey = HKEY_LOCAL_MACHINE;
232    subKey = keyPath + 19;
233  }
234  else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) {
235    hRootKey = HKEY_CURRENT_USER;
236    subKey = keyPath + 18;
237  }
238  else
239    return(false);
240  const char *placeHolder = strstr(subKey, "$VERSION");
241  char bestName[256];
242  bestName[0] = '\0';
243  // If we have a $VERSION placeholder, do the highest-version search.
244  if (placeHolder) {
245    const char *keyEnd = placeHolder - 1;
246    const char *nextKey = placeHolder;
247    // Find end of previous key.
248    while ((keyEnd > subKey) && (*keyEnd != '\\'))
249      keyEnd--;
250    // Find end of key containing $VERSION.
251    while (*nextKey && (*nextKey != '\\'))
252      nextKey++;
253    size_t partialKeyLength = keyEnd - subKey;
254    char partialKey[256];
255    if (partialKeyLength > sizeof(partialKey))
256      partialKeyLength = sizeof(partialKey);
257    strncpy(partialKey, subKey, partialKeyLength);
258    partialKey[partialKeyLength] = '\0';
259    HKEY hTopKey = NULL;
260    lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ, &hTopKey);
261    if (lResult == ERROR_SUCCESS) {
262      char keyName[256];
263      int bestIndex = -1;
264      double bestValue = 0.0;
265      DWORD index, size = sizeof(keyName) - 1;
266      for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
267          NULL, NULL, NULL) == ERROR_SUCCESS; index++) {
268        const char *sp = keyName;
269        while (*sp && !isdigit(*sp))
270          sp++;
271        if (!*sp)
272          continue;
273        const char *ep = sp + 1;
274        while (*ep && (isdigit(*ep) || (*ep == '.')))
275          ep++;
276        char numBuf[32];
277        strncpy(numBuf, sp, sizeof(numBuf) - 1);
278        numBuf[sizeof(numBuf) - 1] = '\0';
279        double value = strtod(numBuf, NULL);
280        if (value > bestValue) {
281          bestIndex = (int)index;
282          bestValue = value;
283          strcpy(bestName, keyName);
284        }
285        size = sizeof(keyName) - 1;
286      }
287      // If we found the highest versioned key, open the key and get the value.
288      if (bestIndex != -1) {
289        // Append rest of key.
290        strncat(bestName, nextKey, sizeof(bestName) - 1);
291        bestName[sizeof(bestName) - 1] = '\0';
292        // Open the chosen key path remainder.
293        lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ, &hKey);
294        if (lResult == ERROR_SUCCESS) {
295          lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
296            (LPBYTE)value, &valueSize);
297          if (lResult == ERROR_SUCCESS)
298            returnValue = true;
299          RegCloseKey(hKey);
300        }
301      }
302      RegCloseKey(hTopKey);
303    }
304  }
305  else {
306    lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey);
307    if (lResult == ERROR_SUCCESS) {
308      lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
309        (LPBYTE)value, &valueSize);
310      if (lResult == ERROR_SUCCESS)
311        returnValue = true;
312      RegCloseKey(hKey);
313    }
314  }
315  return(returnValue);
316}
317#else // _MSC_VER
318  // Read registry string.
319static bool getSystemRegistryString(const char*, const char*, char*, size_t) {
320  return(false);
321}
322#endif // _MSC_VER
323
324  // Get Visual Studio installation directory.
325static bool getVisualStudioDir(std::string &path) {
326  char vsIDEInstallDir[256];
327  char vsExpressIDEInstallDir[256];
328  // Try the Windows registry first.
329  bool hasVCDir = getSystemRegistryString(
330    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
331    "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1);
332  bool hasVCExpressDir = getSystemRegistryString(
333    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
334    "InstallDir", vsExpressIDEInstallDir, sizeof(vsExpressIDEInstallDir) - 1);
335    // If we have both vc80 and vc90, pick version we were compiled with.
336  if (hasVCDir && vsIDEInstallDir[0]) {
337    char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE");
338    if (p)
339      *p = '\0';
340    path = vsIDEInstallDir;
341    return(true);
342  }
343  else if (hasVCExpressDir && vsExpressIDEInstallDir[0]) {
344    char *p = (char*)strstr(vsExpressIDEInstallDir, "\\Common7\\IDE");
345    if (p)
346      *p = '\0';
347    path = vsExpressIDEInstallDir;
348    return(true);
349  }
350  else {
351    // Try the environment.
352    const char* vs100comntools = getenv("VS100COMNTOOLS");
353    const char* vs90comntools = getenv("VS90COMNTOOLS");
354    const char* vs80comntools = getenv("VS80COMNTOOLS");
355    const char* vscomntools = NULL;
356
357    // Try to find the version that we were compiled with
358    if(false) {}
359    #if (_MSC_VER >= 1600)  // VC100
360    else if(vs100comntools) {
361      vscomntools = vs100comntools;
362    }
363    #elif (_MSC_VER == 1500) // VC80
364    else if(vs90comntools) {
365      vscomntools = vs90comntools;
366    }
367    #elif (_MSC_VER == 1400) // VC80
368    else if(vs80comntools) {
369      vscomntools = vs80comntools;
370    }
371    #endif
372    // Otherwise find any version we can
373    else if (vs100comntools)
374      vscomntools = vs100comntools;
375    else if (vs90comntools)
376      vscomntools = vs90comntools;
377    else if (vs80comntools)
378      vscomntools = vs80comntools;
379
380    if (vscomntools && *vscomntools) {
381      char *p = const_cast<char *>(strstr(vscomntools, "\\Common7\\Tools"));
382      if (p)
383        *p = '\0';
384      path = vscomntools;
385      return(true);
386    }
387    else
388      return(false);
389  }
390  return(false);
391}
392
393  // Get Windows SDK installation directory.
394static bool getWindowsSDKDir(std::string &path) {
395  char windowsSDKInstallDir[256];
396  // Try the Windows registry.
397  bool hasSDKDir = getSystemRegistryString(
398   "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
399    "InstallationFolder", windowsSDKInstallDir, sizeof(windowsSDKInstallDir) - 1);
400    // If we have both vc80 and vc90, pick version we were compiled with.
401  if (hasSDKDir && windowsSDKInstallDir[0]) {
402    path = windowsSDKInstallDir;
403    return(true);
404  }
405  return(false);
406}
407
408void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
409                                            const HeaderSearchOptions &HSOpts) {
410  // FIXME: temporary hack: hard-coded paths.
411  AddPath("/usr/local/include", System, true, false, false);
412
413  // Builtin includes use #include_next directives and should be positioned
414  // just prior C include dirs.
415  if (HSOpts.UseBuiltinIncludes) {
416    // Ignore the sys root, we *always* look for clang headers relative to
417    // supplied path.
418    llvm::sys::Path P(HSOpts.ResourceDir);
419    P.appendComponent("include");
420    AddPath(P.str(), System, false, false, false, /*IgnoreSysRoot=*/ true);
421  }
422
423  // Add dirs specified via 'configure --with-c-include-dirs'.
424  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
425  if (CIncludeDirs != "") {
426    llvm::SmallVector<llvm::StringRef, 5> dirs;
427    CIncludeDirs.split(dirs, ":");
428    for (llvm::SmallVectorImpl<llvm::StringRef>::iterator i = dirs.begin();
429         i != dirs.end();
430         ++i)
431      AddPath(*i, System, false, false, false);
432    return;
433  }
434  llvm::Triple::OSType os = triple.getOS();
435  switch (os) {
436  case llvm::Triple::Win32:
437    {
438      std::string VSDir;
439      std::string WindowsSDKDir;
440      if (getVisualStudioDir(VSDir)) {
441        AddPath(VSDir + "\\VC\\include", System, false, false, false);
442        if (getWindowsSDKDir(WindowsSDKDir))
443          AddPath(WindowsSDKDir, System, false, false, false);
444        else
445          AddPath(VSDir + "\\VC\\PlatformSDK\\Include",
446            System, false, false, false);
447      }
448      else {
449          // Default install paths.
450        AddPath("C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
451          System, false, false, false);
452        AddPath("C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
453          System, false, false, false);
454        AddPath(
455        "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
456          System, false, false, false);
457        AddPath("C:/Program Files/Microsoft Visual Studio 8/VC/include",
458          System, false, false, false);
459        AddPath(
460        "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include",
461          System, false, false, false);
462          // For some clang developers.
463        AddPath("G:/Program Files/Microsoft Visual Studio 9.0/VC/include",
464          System, false, false, false);
465        AddPath(
466        "G:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
467          System, false, false, false);
468      }
469    }
470    break;
471  case llvm::Triple::Haiku:
472    AddPath("/boot/common/include", System, true, false, false);
473    AddPath("/boot/develop/headers/os", System, true, false, false);
474    AddPath("/boot/develop/headers/os/app", System, true, false, false);
475    AddPath("/boot/develop/headers/os/arch", System, true, false, false);
476    AddPath("/boot/develop/headers/os/device", System, true, false, false);
477    AddPath("/boot/develop/headers/os/drivers", System, true, false, false);
478    AddPath("/boot/develop/headers/os/game", System, true, false, false);
479    AddPath("/boot/develop/headers/os/interface", System, true, false, false);
480    AddPath("/boot/develop/headers/os/kernel", System, true, false, false);
481    AddPath("/boot/develop/headers/os/locale", System, true, false, false);
482    AddPath("/boot/develop/headers/os/mail", System, true, false, false);
483    AddPath("/boot/develop/headers/os/media", System, true, false, false);
484    AddPath("/boot/develop/headers/os/midi", System, true, false, false);
485    AddPath("/boot/develop/headers/os/midi2", System, true, false, false);
486    AddPath("/boot/develop/headers/os/net", System, true, false, false);
487    AddPath("/boot/develop/headers/os/storage", System, true, false, false);
488    AddPath("/boot/develop/headers/os/support", System, true, false, false);
489    AddPath("/boot/develop/headers/os/translation",
490      System, true, false, false);
491    AddPath("/boot/develop/headers/os/add-ons/graphics",
492      System, true, false, false);
493    AddPath("/boot/develop/headers/os/add-ons/input_server",
494      System, true, false, false);
495    AddPath("/boot/develop/headers/os/add-ons/screen_saver",
496      System, true, false, false);
497    AddPath("/boot/develop/headers/os/add-ons/tracker",
498      System, true, false, false);
499    AddPath("/boot/develop/headers/os/be_apps/Deskbar",
500      System, true, false, false);
501    AddPath("/boot/develop/headers/os/be_apps/NetPositive",
502      System, true, false, false);
503    AddPath("/boot/develop/headers/os/be_apps/Tracker",
504      System, true, false, false);
505    AddPath("/boot/develop/headers/cpp", System, true, false, false);
506    AddPath("/boot/develop/headers/cpp/i586-pc-haiku",
507      System, true, false, false);
508    AddPath("/boot/develop/headers/3rdparty", System, true, false, false);
509    AddPath("/boot/develop/headers/bsd", System, true, false, false);
510    AddPath("/boot/develop/headers/glibc", System, true, false, false);
511    AddPath("/boot/develop/headers/posix", System, true, false, false);
512    AddPath("/boot/develop/headers",  System, true, false, false);
513  	break;
514  case llvm::Triple::MinGW64:
515  case llvm::Triple::MinGW32:
516    AddPath("c:/mingw/include", System, true, false, false);
517    break;
518  default:
519    break;
520  }
521
522  AddPath("/usr/include", System, false, false, false);
523}
524
525void InitHeaderSearch::
526AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple) {
527  llvm::Triple::OSType os = triple.getOS();
528  llvm::StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
529  if (CxxIncludeRoot != "") {
530    llvm::StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
531    if (CxxIncludeArch == "")
532      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
533                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
534                                  triple);
535    else
536      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
537                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
538                                  triple);
539    return;
540  }
541  // FIXME: temporary hack: hard-coded paths.
542  switch (os) {
543  case llvm::Triple::Cygwin:
544    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include",
545        System, true, false, false);
546    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include/c++",
547        System, true, false, false);
548    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/i686-pc-cygwin",
549        System, true, false, false);
550    break;
551  case llvm::Triple::MinGW64:
552    // Try gcc 4.4.0
553    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.4.0");
554    // Try gcc 4.3.0
555    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.3.0");
556    // Fall through.
557  case llvm::Triple::MinGW32:
558    // Try gcc 4.4.0
559    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
560    // Try gcc 4.3.0
561    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
562    break;
563  case llvm::Triple::Darwin:
564    switch (triple.getArch()) {
565    default: break;
566
567    case llvm::Triple::ppc:
568    case llvm::Triple::ppc64:
569      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
570                                  "powerpc-apple-darwin10", "", "ppc64",
571                                  triple);
572      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
573                                  "powerpc-apple-darwin10", "", "ppc64",
574                                  triple);
575      break;
576
577    case llvm::Triple::x86:
578    case llvm::Triple::x86_64:
579      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
580                                  "i686-apple-darwin10", "", "x86_64", triple);
581      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
582                                  "i686-apple-darwin8", "", "", triple);
583      break;
584
585    case llvm::Triple::arm:
586    case llvm::Triple::thumb:
587      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
588                                  "arm-apple-darwin10", "v7", "", triple);
589      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
590                                  "arm-apple-darwin10", "v6", "", triple);
591      break;
592    }
593    break;
594  case llvm::Triple::DragonFly:
595    AddPath("/usr/include/c++/4.1", System, true, false, false);
596    break;
597  case llvm::Triple::Linux:
598    //===------------------------------------------------------------------===//
599    // Debian based distros.
600    // Note: these distros symlink /usr/include/c++/X.Y.Z -> X.Y
601    //===------------------------------------------------------------------===//
602    // Ubuntu 10.04 LTS "Lucid Lynx" -- gcc-4.4.3
603    // Ubuntu 9.10 "Karmic Koala"    -- gcc-4.4.1
604    // Debian 6.0 "squeeze"          -- gcc-4.4.2
605    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
606                                "x86_64-linux-gnu", "32", "", triple);
607    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
608                                "i486-linux-gnu", "", "64", triple);
609    // Ubuntu 9.04 "Jaunty Jackalope" -- gcc-4.3.3
610    // Ubuntu 8.10 "Intrepid Ibex"    -- gcc-4.3.2
611    // Debian 5.0 "lenny"             -- gcc-4.3.2
612    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
613                                "x86_64-linux-gnu", "32", "", triple);
614    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
615                                "i486-linux-gnu", "", "64", triple);
616    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
617                                "arm-linux-gnueabi", "", "", triple);
618    // Ubuntu 8.04.4 LTS "Hardy Heron"     -- gcc-4.2.4
619    // Ubuntu 8.04.[0-3] LTS "Hardy Heron" -- gcc-4.2.3
620    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2",
621                                "x86_64-linux-gnu", "32", "", triple);
622    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2",
623                                "i486-linux-gnu", "", "64", triple);
624    // Ubuntu 7.10 "Gutsy Gibbon" -- gcc-4.1.3
625    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1",
626                                "x86_64-linux-gnu", "32", "", triple);
627    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1",
628                                "i486-linux-gnu", "", "64", triple);
629
630    //===------------------------------------------------------------------===//
631    // Redhat based distros.
632    //===------------------------------------------------------------------===//
633    // Fedora 13
634    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.4",
635                                "x86_64-redhat-linux", "32", "", triple);
636    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.4",
637                                "i686-redhat-linux","", "", triple);
638    // Fedora 12
639    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
640                                "x86_64-redhat-linux", "32", "", triple);
641    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
642                                "i686-redhat-linux","", "", triple);
643    // Fedora 12 (pre-FEB-2010)
644    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
645                                "x86_64-redhat-linux", "32", "", triple);
646    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
647                                "i686-redhat-linux","", "", triple);
648    // Fedora 11
649    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
650                                "x86_64-redhat-linux", "32", "", triple);
651    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
652                                "i586-redhat-linux","", "", triple);
653    // Fedora 10
654    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
655                                "x86_64-redhat-linux", "32", "", triple);
656    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
657                                "i386-redhat-linux","", "", triple);
658    // Fedora 9
659    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
660                                "x86_64-redhat-linux", "32", "", triple);
661    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
662                                "i386-redhat-linux", "", "", triple);
663    // Fedora 8
664    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
665                                "x86_64-redhat-linux", "", "", triple);
666    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
667                                "i386-redhat-linux", "", "", triple);
668
669    //===------------------------------------------------------------------===//
670
671    // Exherbo (2010-01-25)
672    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
673                                "x86_64-pc-linux-gnu", "32", "", triple);
674    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
675                                "i686-pc-linux-gnu", "", "", triple);
676
677    // openSUSE 11.1 32 bit
678    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
679                                "i586-suse-linux", "", "", triple);
680    // openSUSE 11.1 64 bit
681    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
682                                "x86_64-suse-linux", "32", "", triple);
683    // openSUSE 11.2
684    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
685                                "i586-suse-linux", "", "", triple);
686    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
687                                "x86_64-suse-linux", "", "", triple);
688    // Arch Linux 2008-06-24
689    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
690                                "i686-pc-linux-gnu", "", "", triple);
691    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
692                                "x86_64-unknown-linux-gnu", "", "", triple);
693    // Gentoo x86 2009.1 stable
694    AddGnuCPlusPlusIncludePaths(
695      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4",
696      "i686-pc-linux-gnu", "", "", triple);
697    // Gentoo x86 2009.0 stable
698    AddGnuCPlusPlusIncludePaths(
699      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
700      "i686-pc-linux-gnu", "", "", triple);
701    // Gentoo x86 2008.0 stable
702    AddGnuCPlusPlusIncludePaths(
703      "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
704      "i686-pc-linux-gnu", "", "", triple);
705    // Gentoo amd64 stable
706    AddGnuCPlusPlusIncludePaths(
707        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
708        "i686-pc-linux-gnu", "", "", triple);
709
710    // Gentoo amd64 gcc 4.3.2
711    AddGnuCPlusPlusIncludePaths(
712        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.2/include/g++-v4",
713        "x86_64-pc-linux-gnu", "", "", triple);
714
715    // Gentoo amd64 gcc 4.4.3
716    AddGnuCPlusPlusIncludePaths(
717        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.4.3/include/g++-v4",
718        "x86_64-pc-linux-gnu", "32", "", triple);
719
720    break;
721  case llvm::Triple::FreeBSD:
722    // FreeBSD 8.0
723    // FreeBSD 7.3
724    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2", "", "", "", triple);
725    break;
726  case llvm::Triple::Solaris:
727    // Solaris - Fall though..
728  case llvm::Triple::AuroraUX:
729    // AuroraUX
730    AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
731                                "i386-pc-solaris2.11", "", "", triple);
732    break;
733  default:
734    break;
735  }
736}
737
738void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang,
739                                                    const llvm::Triple &triple,
740                                            const HeaderSearchOptions &HSOpts) {
741  if (Lang.CPlusPlus && HSOpts.UseStandardCXXIncludes)
742    AddDefaultCPlusPlusIncludePaths(triple);
743
744  AddDefaultCIncludePaths(triple, HSOpts);
745
746  // Add the default framework include paths on Darwin.
747  if (triple.getOS() == llvm::Triple::Darwin) {
748    AddPath("/System/Library/Frameworks", System, true, false, true);
749    AddPath("/Library/Frameworks", System, true, false, true);
750  }
751}
752
753/// RemoveDuplicates - If there are duplicate directory entries in the specified
754/// search list, remove the later (dead) ones.
755static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
756                             bool Verbose) {
757  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
758  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
759  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
760  for (unsigned i = 0; i != SearchList.size(); ++i) {
761    unsigned DirToRemove = i;
762
763    const DirectoryLookup &CurEntry = SearchList[i];
764
765    if (CurEntry.isNormalDir()) {
766      // If this isn't the first time we've seen this dir, remove it.
767      if (SeenDirs.insert(CurEntry.getDir()))
768        continue;
769    } else if (CurEntry.isFramework()) {
770      // If this isn't the first time we've seen this framework dir, remove it.
771      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
772        continue;
773    } else {
774      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
775      // If this isn't the first time we've seen this headermap, remove it.
776      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
777        continue;
778    }
779
780    // If we have a normal #include dir/framework/headermap that is shadowed
781    // later in the chain by a system include location, we actually want to
782    // ignore the user's request and drop the user dir... keeping the system
783    // dir.  This is weird, but required to emulate GCC's search path correctly.
784    //
785    // Since dupes of system dirs are rare, just rescan to find the original
786    // that we're nuking instead of using a DenseMap.
787    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
788      // Find the dir that this is the same of.
789      unsigned FirstDir;
790      for (FirstDir = 0; ; ++FirstDir) {
791        assert(FirstDir != i && "Didn't find dupe?");
792
793        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
794
795        // If these are different lookup types, then they can't be the dupe.
796        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
797          continue;
798
799        bool isSame;
800        if (CurEntry.isNormalDir())
801          isSame = SearchEntry.getDir() == CurEntry.getDir();
802        else if (CurEntry.isFramework())
803          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
804        else {
805          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
806          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
807        }
808
809        if (isSame)
810          break;
811      }
812
813      // If the first dir in the search path is a non-system dir, zap it
814      // instead of the system one.
815      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
816        DirToRemove = FirstDir;
817    }
818
819    if (Verbose) {
820      llvm::errs() << "ignoring duplicate directory \""
821                   << CurEntry.getName() << "\"\n";
822      if (DirToRemove != i)
823        llvm::errs() << "  as it is a non-system directory that duplicates "
824                     << "a system directory\n";
825    }
826
827    // This is reached if the current entry is a duplicate.  Remove the
828    // DirToRemove (usually the current dir).
829    SearchList.erase(SearchList.begin()+DirToRemove);
830    --i;
831  }
832}
833
834
835void InitHeaderSearch::Realize() {
836  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
837  std::vector<DirectoryLookup> SearchList;
838  SearchList = IncludeGroup[Angled];
839  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
840                    IncludeGroup[System].end());
841  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
842                    IncludeGroup[After].end());
843  RemoveDuplicates(SearchList, Verbose);
844  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
845
846  // Prepend QUOTED list on the search list.
847  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
848                    IncludeGroup[Quoted].end());
849
850
851  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
852  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
853                         DontSearchCurDir);
854
855  // If verbose, print the list of directories that will be searched.
856  if (Verbose) {
857    llvm::errs() << "#include \"...\" search starts here:\n";
858    unsigned QuotedIdx = IncludeGroup[Quoted].size();
859    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
860      if (i == QuotedIdx)
861        llvm::errs() << "#include <...> search starts here:\n";
862      const char *Name = SearchList[i].getName();
863      const char *Suffix;
864      if (SearchList[i].isNormalDir())
865        Suffix = "";
866      else if (SearchList[i].isFramework())
867        Suffix = " (framework directory)";
868      else {
869        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
870        Suffix = " (headermap)";
871      }
872      llvm::errs() << " " << Name << Suffix << "\n";
873    }
874    llvm::errs() << "End of search list.\n";
875  }
876}
877
878void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
879                                     const HeaderSearchOptions &HSOpts,
880                                     const LangOptions &Lang,
881                                     const llvm::Triple &Triple) {
882  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
883
884  // Add the user defined entries.
885  for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
886    const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
887    Init.AddPath(E.Path, E.Group, false, E.IsUserSupplied, E.IsFramework,
888                 false);
889  }
890
891  // Add entries from CPATH and friends.
892  Init.AddDelimitedPaths(HSOpts.EnvIncPath);
893  if (Lang.CPlusPlus && Lang.ObjC1)
894    Init.AddDelimitedPaths(HSOpts.ObjCXXEnvIncPath);
895  else if (Lang.CPlusPlus)
896    Init.AddDelimitedPaths(HSOpts.CXXEnvIncPath);
897  else if (Lang.ObjC1)
898    Init.AddDelimitedPaths(HSOpts.ObjCEnvIncPath);
899  else
900    Init.AddDelimitedPaths(HSOpts.CEnvIncPath);
901
902  if (HSOpts.UseStandardIncludes)
903    Init.AddDefaultSystemIncludePaths(Lang, Triple, HSOpts);
904
905  Init.Realize();
906}
907