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