InitHeaderSearch.cpp revision 6638b3a15edea25c4b1fdf8046e71d82683d8efa
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/c++",
195          System, true, false, false);
196  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/" + Arch,
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  // First check the environment variables that vsvars32.bat sets.
327  const char* vcinstalldir = getenv("VCINSTALLDIR");
328  if(vcinstalldir) {
329    char *p = const_cast<char *>(strstr(vcinstalldir, "\\VC"));
330    if (p)
331      *p = '\0';
332    path = vcinstalldir;
333    return(true);
334  }
335
336  char vsIDEInstallDir[256];
337  char vsExpressIDEInstallDir[256];
338  // Then try the windows registry.
339  bool hasVCDir = getSystemRegistryString(
340    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
341    "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1);
342  bool hasVCExpressDir = getSystemRegistryString(
343    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
344    "InstallDir", vsExpressIDEInstallDir, sizeof(vsExpressIDEInstallDir) - 1);
345    // If we have both vc80 and vc90, pick version we were compiled with.
346  if (hasVCDir && vsIDEInstallDir[0]) {
347    char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE");
348    if (p)
349      *p = '\0';
350    path = vsIDEInstallDir;
351    return(true);
352  }
353  else if (hasVCExpressDir && vsExpressIDEInstallDir[0]) {
354    char *p = (char*)strstr(vsExpressIDEInstallDir, "\\Common7\\IDE");
355    if (p)
356      *p = '\0';
357    path = vsExpressIDEInstallDir;
358    return(true);
359  }
360  else {
361    // Try the environment.
362    const char* vs100comntools = getenv("VS100COMNTOOLS");
363    const char* vs90comntools = getenv("VS90COMNTOOLS");
364    const char* vs80comntools = getenv("VS80COMNTOOLS");
365    const char* vscomntools = NULL;
366
367    // Try to find the version that we were compiled with
368    if(false) {}
369    #if (_MSC_VER >= 1600)  // VC100
370    else if(vs100comntools) {
371      vscomntools = vs100comntools;
372    }
373    #elif (_MSC_VER == 1500) // VC80
374    else if(vs90comntools) {
375      vscomntools = vs90comntools;
376    }
377    #elif (_MSC_VER == 1400) // VC80
378    else if(vs80comntools) {
379      vscomntools = vs80comntools;
380    }
381    #endif
382    // Otherwise find any version we can
383    else if (vs100comntools)
384      vscomntools = vs100comntools;
385    else if (vs90comntools)
386      vscomntools = vs90comntools;
387    else if (vs80comntools)
388      vscomntools = vs80comntools;
389
390    if (vscomntools && *vscomntools) {
391      char *p = const_cast<char *>(strstr(vscomntools, "\\Common7\\Tools"));
392      if (p)
393        *p = '\0';
394      path = vscomntools;
395      return(true);
396    }
397    else
398      return(false);
399  }
400  return(false);
401}
402
403  // Get Windows SDK installation directory.
404static bool getWindowsSDKDir(std::string &path) {
405  char windowsSDKInstallDir[256];
406  // Try the Windows registry.
407  bool hasSDKDir = getSystemRegistryString(
408   "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
409    "InstallationFolder", windowsSDKInstallDir, sizeof(windowsSDKInstallDir) - 1);
410    // If we have both vc80 and vc90, pick version we were compiled with.
411  if (hasSDKDir && windowsSDKInstallDir[0]) {
412    path = windowsSDKInstallDir;
413    return(true);
414  }
415  return(false);
416}
417
418void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
419                                            const HeaderSearchOptions &HSOpts) {
420  // FIXME: temporary hack: hard-coded paths.
421  AddPath("/usr/local/include", System, true, false, false);
422
423  // Builtin includes use #include_next directives and should be positioned
424  // just prior C include dirs.
425  if (HSOpts.UseBuiltinIncludes) {
426    // Ignore the sys root, we *always* look for clang headers relative to
427    // supplied path.
428    llvm::sys::Path P(HSOpts.ResourceDir);
429    P.appendComponent("include");
430    AddPath(P.str(), System, false, false, false, /*IgnoreSysRoot=*/ true);
431  }
432
433  // Add dirs specified via 'configure --with-c-include-dirs'.
434  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
435  if (CIncludeDirs != "") {
436    llvm::SmallVector<llvm::StringRef, 5> dirs;
437    CIncludeDirs.split(dirs, ":");
438    for (llvm::SmallVectorImpl<llvm::StringRef>::iterator i = dirs.begin();
439         i != dirs.end();
440         ++i)
441      AddPath(*i, System, false, false, false);
442    return;
443  }
444  llvm::Triple::OSType os = triple.getOS();
445  switch (os) {
446  case llvm::Triple::Win32: {
447    std::string VSDir;
448    std::string WindowsSDKDir;
449    if (getVisualStudioDir(VSDir)) {
450      AddPath(VSDir + "\\VC\\include", System, false, false, false);
451      if (getWindowsSDKDir(WindowsSDKDir))
452        AddPath(WindowsSDKDir + "\\include", System, false, false, false);
453      else
454        AddPath(VSDir + "\\VC\\PlatformSDK\\Include",
455                System, false, false, false);
456    } else {
457      // Default install paths.
458      AddPath("C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
459              System, false, false, false);
460      AddPath("C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
461              System, false, false, false);
462      AddPath(
463        "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
464        System, false, false, false);
465      AddPath("C:/Program Files/Microsoft Visual Studio 8/VC/include",
466              System, false, false, false);
467      AddPath(
468        "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include",
469        System, false, false, false);
470      // For some clang developers.
471      AddPath("G:/Program Files/Microsoft Visual Studio 9.0/VC/include",
472              System, false, false, false);
473      AddPath(
474        "G:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
475        System, false, false, false);
476    }
477    break;
478  }
479  case llvm::Triple::Haiku:
480    AddPath("/boot/common/include", System, true, false, false);
481    AddPath("/boot/develop/headers/os", System, true, false, false);
482    AddPath("/boot/develop/headers/os/app", System, true, false, false);
483    AddPath("/boot/develop/headers/os/arch", System, true, false, false);
484    AddPath("/boot/develop/headers/os/device", System, true, false, false);
485    AddPath("/boot/develop/headers/os/drivers", System, true, false, false);
486    AddPath("/boot/develop/headers/os/game", System, true, false, false);
487    AddPath("/boot/develop/headers/os/interface", System, true, false, false);
488    AddPath("/boot/develop/headers/os/kernel", System, true, false, false);
489    AddPath("/boot/develop/headers/os/locale", System, true, false, false);
490    AddPath("/boot/develop/headers/os/mail", System, true, false, false);
491    AddPath("/boot/develop/headers/os/media", System, true, false, false);
492    AddPath("/boot/develop/headers/os/midi", System, true, false, false);
493    AddPath("/boot/develop/headers/os/midi2", System, true, false, false);
494    AddPath("/boot/develop/headers/os/net", System, true, false, false);
495    AddPath("/boot/develop/headers/os/storage", System, true, false, false);
496    AddPath("/boot/develop/headers/os/support", System, true, false, false);
497    AddPath("/boot/develop/headers/os/translation",
498      System, true, false, false);
499    AddPath("/boot/develop/headers/os/add-ons/graphics",
500      System, true, false, false);
501    AddPath("/boot/develop/headers/os/add-ons/input_server",
502      System, true, false, false);
503    AddPath("/boot/develop/headers/os/add-ons/screen_saver",
504      System, true, false, false);
505    AddPath("/boot/develop/headers/os/add-ons/tracker",
506      System, true, false, false);
507    AddPath("/boot/develop/headers/os/be_apps/Deskbar",
508      System, true, false, false);
509    AddPath("/boot/develop/headers/os/be_apps/NetPositive",
510      System, true, false, false);
511    AddPath("/boot/develop/headers/os/be_apps/Tracker",
512      System, true, false, false);
513    AddPath("/boot/develop/headers/cpp", System, true, false, false);
514    AddPath("/boot/develop/headers/cpp/i586-pc-haiku",
515      System, true, false, false);
516    AddPath("/boot/develop/headers/3rdparty", System, true, false, false);
517    AddPath("/boot/develop/headers/bsd", System, true, false, false);
518    AddPath("/boot/develop/headers/glibc", System, true, false, false);
519    AddPath("/boot/develop/headers/posix", System, true, false, false);
520    AddPath("/boot/develop/headers",  System, true, false, false);
521    break;
522  case llvm::Triple::Cygwin:
523    AddPath("/usr/include/w32api", System, true, false, false);
524    break;
525  case llvm::Triple::MinGW64:
526  case llvm::Triple::MinGW32:
527    AddPath("c:/mingw/include", System, true, false, false);
528    break;
529  default:
530    break;
531  }
532
533  AddPath("/usr/include", System, false, false, false);
534}
535
536void InitHeaderSearch::
537AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple) {
538  llvm::Triple::OSType os = triple.getOS();
539  llvm::StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
540  if (CxxIncludeRoot != "") {
541    llvm::StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
542    if (CxxIncludeArch == "")
543      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
544                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
545                                  triple);
546    else
547      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
548                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
549                                  triple);
550    return;
551  }
552  // FIXME: temporary hack: hard-coded paths.
553  switch (os) {
554  case llvm::Triple::Cygwin:
555    // Cygwin-1.7
556    AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.4");
557    // g++-4 / Cygwin-1.5
558    AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.2");
559    // FIXME: Do we support g++-3.4.4?
560    AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "3.4.4");
561    break;
562  case llvm::Triple::MinGW64:
563    // Try gcc 4.5.0
564    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.5.0");
565    // Try gcc 4.4.0
566    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.4.0");
567    // Try gcc 4.3.0
568    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.3.0");
569    // Fall through.
570  case llvm::Triple::MinGW32:
571   // Try gcc 4.5.0
572    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.5.0");
573    // Try gcc 4.4.0
574    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
575    // Try gcc 4.3.0
576    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
577    break;
578  case llvm::Triple::Darwin:
579    switch (triple.getArch()) {
580    default: break;
581
582    case llvm::Triple::ppc:
583    case llvm::Triple::ppc64:
584      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
585                                  "powerpc-apple-darwin10", "", "ppc64",
586                                  triple);
587      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
588                                  "powerpc-apple-darwin10", "", "ppc64",
589                                  triple);
590      break;
591
592    case llvm::Triple::x86:
593    case llvm::Triple::x86_64:
594      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
595                                  "i686-apple-darwin10", "", "x86_64", triple);
596      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
597                                  "i686-apple-darwin8", "", "", triple);
598      break;
599
600    case llvm::Triple::arm:
601    case llvm::Triple::thumb:
602      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
603                                  "arm-apple-darwin10", "v7", "", triple);
604      AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
605                                  "arm-apple-darwin10", "v6", "", triple);
606      break;
607    }
608    break;
609  case llvm::Triple::DragonFly:
610    AddPath("/usr/include/c++/4.1", System, true, false, false);
611    break;
612  case llvm::Triple::Linux:
613    //===------------------------------------------------------------------===//
614    // Debian based distros.
615    // Note: these distros symlink /usr/include/c++/X.Y.Z -> X.Y
616    //===------------------------------------------------------------------===//
617    // Ubuntu 10.04 LTS "Lucid Lynx" -- gcc-4.4.3
618    // Ubuntu 9.10 "Karmic Koala"    -- gcc-4.4.1
619    // Debian 6.0 "squeeze"          -- gcc-4.4.2
620    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
621                                "x86_64-linux-gnu", "32", "", triple);
622    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
623                                "i486-linux-gnu", "", "64", triple);
624    // Ubuntu 9.04 "Jaunty Jackalope" -- gcc-4.3.3
625    // Ubuntu 8.10 "Intrepid Ibex"    -- gcc-4.3.2
626    // Debian 5.0 "lenny"             -- gcc-4.3.2
627    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
628                                "x86_64-linux-gnu", "32", "", triple);
629    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
630                                "i486-linux-gnu", "", "64", triple);
631    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
632                                "arm-linux-gnueabi", "", "", triple);
633    // Ubuntu 8.04.4 LTS "Hardy Heron"     -- gcc-4.2.4
634    // Ubuntu 8.04.[0-3] LTS "Hardy Heron" -- gcc-4.2.3
635    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2",
636                                "x86_64-linux-gnu", "32", "", triple);
637    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2",
638                                "i486-linux-gnu", "", "64", triple);
639    // Ubuntu 7.10 "Gutsy Gibbon" -- gcc-4.1.3
640    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1",
641                                "x86_64-linux-gnu", "32", "", triple);
642    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1",
643                                "i486-linux-gnu", "", "64", triple);
644
645    //===------------------------------------------------------------------===//
646    // Redhat based distros.
647    //===------------------------------------------------------------------===//
648    // Fedora 14
649    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5.1",
650                                "x86_64-redhat-linux", "32", "", triple);
651    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.5.1",
652                                "i686-redhat-linux", "", "", triple);
653    // Fedora 13
654    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.4",
655                                "x86_64-redhat-linux", "32", "", triple);
656    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.4",
657                                "i686-redhat-linux","", "", triple);
658    // Fedora 12
659    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
660                                "x86_64-redhat-linux", "32", "", triple);
661    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
662                                "i686-redhat-linux","", "", triple);
663    // Fedora 12 (pre-FEB-2010)
664    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
665                                "x86_64-redhat-linux", "32", "", triple);
666    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
667                                "i686-redhat-linux","", "", triple);
668    // Fedora 11
669    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
670                                "x86_64-redhat-linux", "32", "", triple);
671    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
672                                "i586-redhat-linux","", "", triple);
673    // Fedora 10
674    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
675                                "x86_64-redhat-linux", "32", "", triple);
676    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
677                                "i386-redhat-linux","", "", triple);
678    // Fedora 9
679    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
680                                "x86_64-redhat-linux", "32", "", triple);
681    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
682                                "i386-redhat-linux", "", "", triple);
683    // Fedora 8
684    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
685                                "x86_64-redhat-linux", "", "", triple);
686    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
687                                "i386-redhat-linux", "", "", triple);
688
689    //===------------------------------------------------------------------===//
690
691    // Exherbo (2010-01-25)
692    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
693                                "x86_64-pc-linux-gnu", "32", "", triple);
694    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
695                                "i686-pc-linux-gnu", "", "", triple);
696
697    // openSUSE 11.1 32 bit
698    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
699                                "i586-suse-linux", "", "", triple);
700    // openSUSE 11.1 64 bit
701    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
702                                "x86_64-suse-linux", "32", "", triple);
703    // openSUSE 11.2
704    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
705                                "i586-suse-linux", "", "", triple);
706    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
707                                "x86_64-suse-linux", "", "", triple);
708    // Arch Linux 2008-06-24
709    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
710                                "i686-pc-linux-gnu", "", "", triple);
711    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
712                                "x86_64-unknown-linux-gnu", "", "", triple);
713    // Gentoo x86 2010.0 stable
714    AddGnuCPlusPlusIncludePaths(
715      "/usr/lib/gcc/i686-pc-linux-gnu/4.4.3/include/g++-v4",
716      "i686-pc-linux-gnu", "", "", triple);
717    // Gentoo x86 2009.1 stable
718    AddGnuCPlusPlusIncludePaths(
719      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4",
720      "i686-pc-linux-gnu", "", "", triple);
721    // Gentoo x86 2009.0 stable
722    AddGnuCPlusPlusIncludePaths(
723      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
724      "i686-pc-linux-gnu", "", "", triple);
725    // Gentoo x86 2008.0 stable
726    AddGnuCPlusPlusIncludePaths(
727      "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
728      "i686-pc-linux-gnu", "", "", triple);
729    // Gentoo amd64 stable
730    AddGnuCPlusPlusIncludePaths(
731        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
732        "i686-pc-linux-gnu", "", "", triple);
733
734    // Gentoo amd64 gcc 4.3.2
735    AddGnuCPlusPlusIncludePaths(
736        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.2/include/g++-v4",
737        "x86_64-pc-linux-gnu", "", "", triple);
738
739    // Gentoo amd64 gcc 4.4.3
740    AddGnuCPlusPlusIncludePaths(
741        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.4.3/include/g++-v4",
742        "x86_64-pc-linux-gnu", "32", "", triple);
743
744    // Gentoo amd64 llvm-gcc trunk
745    AddGnuCPlusPlusIncludePaths(
746        "/usr/lib/llvm-gcc-4.2-9999/include/c++/4.2.1",
747        "x86_64-pc-linux-gnu", "", "", triple);
748
749    break;
750  case llvm::Triple::FreeBSD:
751    // FreeBSD 8.0
752    // FreeBSD 7.3
753    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2", "", "", "", triple);
754    break;
755  case llvm::Triple::NetBSD:
756    AddGnuCPlusPlusIncludePaths("/usr/include/g++", "", "", "", triple);
757    break;
758  case llvm::Triple::OpenBSD: {
759    std::string t = triple.getTriple();
760    if (t.substr(0, 6) == "x86_64")
761      t.replace(0, 6, "amd64");
762    AddGnuCPlusPlusIncludePaths("/usr/include/g++",
763                                t, "", "", triple);
764    break;
765  }
766  case llvm::Triple::Minix:
767    AddGnuCPlusPlusIncludePaths("/usr/gnu/include/c++/4.4.3",
768                                "", "", "", triple);
769    break;
770  case llvm::Triple::Solaris:
771    // Solaris - Fall though..
772  case llvm::Triple::AuroraUX:
773    // AuroraUX
774    AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
775                                "i386-pc-solaris2.11", "", "", triple);
776    break;
777  default:
778    break;
779  }
780}
781
782void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang,
783                                                    const llvm::Triple &triple,
784                                            const HeaderSearchOptions &HSOpts) {
785  if (Lang.CPlusPlus && HSOpts.UseStandardCXXIncludes) {
786    if (!HSOpts.CXXSystemIncludes.empty()) {
787      for (unsigned i = 0, e = HSOpts.CXXSystemIncludes.size(); i != e; ++i)
788        AddPath(HSOpts.CXXSystemIncludes[i], System, true, false, false);
789    } else
790      AddDefaultCPlusPlusIncludePaths(triple);
791  }
792
793  AddDefaultCIncludePaths(triple, HSOpts);
794
795  // Add the default framework include paths on Darwin.
796  if (triple.getOS() == llvm::Triple::Darwin) {
797    AddPath("/System/Library/Frameworks", System, true, false, true);
798    AddPath("/Library/Frameworks", System, true, false, true);
799  }
800}
801
802/// RemoveDuplicates - If there are duplicate directory entries in the specified
803/// search list, remove the later (dead) ones.
804static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
805                             bool Verbose) {
806  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
807  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
808  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
809  for (unsigned i = 0; i != SearchList.size(); ++i) {
810    unsigned DirToRemove = i;
811
812    const DirectoryLookup &CurEntry = SearchList[i];
813
814    if (CurEntry.isNormalDir()) {
815      // If this isn't the first time we've seen this dir, remove it.
816      if (SeenDirs.insert(CurEntry.getDir()))
817        continue;
818    } else if (CurEntry.isFramework()) {
819      // If this isn't the first time we've seen this framework dir, remove it.
820      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
821        continue;
822    } else {
823      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
824      // If this isn't the first time we've seen this headermap, remove it.
825      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
826        continue;
827    }
828
829    // If we have a normal #include dir/framework/headermap that is shadowed
830    // later in the chain by a system include location, we actually want to
831    // ignore the user's request and drop the user dir... keeping the system
832    // dir.  This is weird, but required to emulate GCC's search path correctly.
833    //
834    // Since dupes of system dirs are rare, just rescan to find the original
835    // that we're nuking instead of using a DenseMap.
836    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
837      // Find the dir that this is the same of.
838      unsigned FirstDir;
839      for (FirstDir = 0; ; ++FirstDir) {
840        assert(FirstDir != i && "Didn't find dupe?");
841
842        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
843
844        // If these are different lookup types, then they can't be the dupe.
845        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
846          continue;
847
848        bool isSame;
849        if (CurEntry.isNormalDir())
850          isSame = SearchEntry.getDir() == CurEntry.getDir();
851        else if (CurEntry.isFramework())
852          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
853        else {
854          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
855          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
856        }
857
858        if (isSame)
859          break;
860      }
861
862      // If the first dir in the search path is a non-system dir, zap it
863      // instead of the system one.
864      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
865        DirToRemove = FirstDir;
866    }
867
868    if (Verbose) {
869      llvm::errs() << "ignoring duplicate directory \""
870                   << CurEntry.getName() << "\"\n";
871      if (DirToRemove != i)
872        llvm::errs() << "  as it is a non-system directory that duplicates "
873                     << "a system directory\n";
874    }
875
876    // This is reached if the current entry is a duplicate.  Remove the
877    // DirToRemove (usually the current dir).
878    SearchList.erase(SearchList.begin()+DirToRemove);
879    --i;
880  }
881}
882
883
884void InitHeaderSearch::Realize() {
885  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
886  std::vector<DirectoryLookup> SearchList;
887  SearchList = IncludeGroup[Angled];
888  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
889                    IncludeGroup[System].end());
890  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
891                    IncludeGroup[After].end());
892  RemoveDuplicates(SearchList, Verbose);
893  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
894
895  // Prepend QUOTED list on the search list.
896  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
897                    IncludeGroup[Quoted].end());
898
899
900  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
901  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
902                         DontSearchCurDir);
903
904  // If verbose, print the list of directories that will be searched.
905  if (Verbose) {
906    llvm::errs() << "#include \"...\" search starts here:\n";
907    unsigned QuotedIdx = IncludeGroup[Quoted].size();
908    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
909      if (i == QuotedIdx)
910        llvm::errs() << "#include <...> search starts here:\n";
911      const char *Name = SearchList[i].getName();
912      const char *Suffix;
913      if (SearchList[i].isNormalDir())
914        Suffix = "";
915      else if (SearchList[i].isFramework())
916        Suffix = " (framework directory)";
917      else {
918        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
919        Suffix = " (headermap)";
920      }
921      llvm::errs() << " " << Name << Suffix << "\n";
922    }
923    llvm::errs() << "End of search list.\n";
924  }
925}
926
927void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
928                                     const HeaderSearchOptions &HSOpts,
929                                     const LangOptions &Lang,
930                                     const llvm::Triple &Triple) {
931  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
932
933  // Add the user defined entries.
934  for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
935    const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
936    Init.AddPath(E.Path, E.Group, false, E.IsUserSupplied, E.IsFramework,
937                 !E.IsSysRootRelative);
938  }
939
940  // Add entries from CPATH and friends.
941  Init.AddDelimitedPaths(HSOpts.EnvIncPath);
942  if (Lang.CPlusPlus && Lang.ObjC1)
943    Init.AddDelimitedPaths(HSOpts.ObjCXXEnvIncPath);
944  else if (Lang.CPlusPlus)
945    Init.AddDelimitedPaths(HSOpts.CXXEnvIncPath);
946  else if (Lang.ObjC1)
947    Init.AddDelimitedPaths(HSOpts.ObjCEnvIncPath);
948  else
949    Init.AddDelimitedPaths(HSOpts.CEnvIncPath);
950
951  if (HSOpts.UseStandardIncludes)
952    Init.AddDefaultSystemIncludePaths(Lang, Triple, HSOpts);
953
954  Init.Realize();
955}
956