InitHeaderSearch.cpp revision 199990
175115Sfenner//===--- InitHeaderSearch.cpp - Initialize header search paths ----------*-===//
275115Sfenner//
375115Sfenner//                     The LLVM Compiler Infrastructure
475115Sfenner//
575115Sfenner// This file is distributed under the University of Illinois Open Source
675115Sfenner// License. See LICENSE.TXT for details.
775115Sfenner//
875115Sfenner//===----------------------------------------------------------------------===//
975115Sfenner//
1075115Sfenner// This file implements the InitHeaderSearch class.
1175115Sfenner//
1275115Sfenner//===----------------------------------------------------------------------===//
1375115Sfenner
1475115Sfenner#include "clang/Frontend/Utils.h"
1575115Sfenner#include "clang/Basic/FileManager.h"
1675115Sfenner#include "clang/Basic/LangOptions.h"
1775115Sfenner#include "clang/Frontend/HeaderSearchOptions.h"
1875115Sfenner#include "clang/Lex/HeaderSearch.h"
1975115Sfenner#include "llvm/ADT/SmallString.h"
2075115Sfenner#include "llvm/ADT/SmallPtrSet.h"
2175115Sfenner#include "llvm/ADT/SmallVector.h"
2275115Sfenner#include "llvm/ADT/StringExtras.h"
2375115Sfenner#include "llvm/ADT/Triple.h"
2475115Sfenner#include "llvm/Support/raw_ostream.h"
2575115Sfenner#include "llvm/System/Path.h"
2675115Sfenner#include "llvm/Config/config.h"
27127668Sbms#include <cstdio>
28127668Sbms#ifdef _MSC_VER
2975115Sfenner  #define WIN32_LEAN_AND_MEAN 1
3075115Sfenner  #include <windows.h>
3175115Sfenner#endif
3275115Sfennerusing namespace clang;
3375115Sfennerusing namespace clang::frontend;
3475115Sfenner
35127668Sbmsnamespace {
36127668Sbms
3775115Sfenner/// InitHeaderSearch - This class makes it easier to set the search paths of
3875115Sfenner///  a HeaderSearch object. InitHeaderSearch stores several search path lists
3975115Sfenner///  internally, which can be sent to a HeaderSearch object in one swoop.
4075115Sfennerclass InitHeaderSearch {
4175115Sfenner  std::vector<DirectoryLookup> IncludeGroup[4];
4275115Sfenner  HeaderSearch& Headers;
4375115Sfenner  bool Verbose;
4475115Sfenner  std::string isysroot;
4575115Sfenner
4675115Sfennerpublic:
4775115Sfenner
4875115Sfenner  InitHeaderSearch(HeaderSearch &HS,
4975115Sfenner      bool verbose = false, const std::string &iSysroot = "")
5075115Sfenner    : Headers(HS), Verbose(verbose), isysroot(iSysroot) {}
5175115Sfenner
5275115Sfenner  /// AddPath - Add the specified path to the specified group list.
5375115Sfenner  void AddPath(const llvm::StringRef &Path, IncludeDirGroup Group,
5475115Sfenner               bool isCXXAware, bool isUserSupplied,
5575115Sfenner               bool isFramework, bool IgnoreSysRoot = false);
5675115Sfenner
5775115Sfenner  /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to suport a gnu
5875115Sfenner  ///  libstdc++.
5975115Sfenner  void AddGnuCPlusPlusIncludePaths(const std::string &Base,
6075115Sfenner                                   const char *ArchDir,
6175115Sfenner                                   const char *Dir32,
6275115Sfenner                                   const char *Dir64,
6375115Sfenner                                   const llvm::Triple &triple);
6475115Sfenner
6575115Sfenner  /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to suport a MinGW
6698524Sfenner  ///  libstdc++.
6798524Sfenner  void AddMinGWCPlusPlusIncludePaths(const std::string &Base,
6898524Sfenner                                     const char *Arch,
6998524Sfenner                                     const char *Version);
7098524Sfenner
71127668Sbms  /// AddDelimitedPaths - Add a list of paths delimited by the system PATH
7298524Sfenner  /// separator. The processing follows that of the CPATH variable for gcc.
7398524Sfenner  void AddDelimitedPaths(const char *String);
7498524Sfenner
7598524Sfenner  // AddDefaultCIncludePaths - Add paths that should always be searched.
7698524Sfenner  void AddDefaultCIncludePaths(const llvm::Triple &triple);
7798524Sfenner
7898524Sfenner  // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
7998524Sfenner  //  compiling c++.
8098524Sfenner  void AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple);
8198524Sfenner
8298524Sfenner  /// AddDefaultSystemIncludePaths - Adds the default system include paths so
8398524Sfenner  ///  that e.g. stdio.h is found.
8498524Sfenner  void AddDefaultSystemIncludePaths(const LangOptions &Lang,
8598524Sfenner                                    const llvm::Triple &triple);
8698524Sfenner
8775115Sfenner  /// Realize - Merges all search path lists into one list and send it to
8875115Sfenner  /// HeaderSearch.
8975115Sfenner  void Realize();
9075115Sfenner};
9198524Sfenner
9275115Sfenner}
9375115Sfenner
9475115Sfennervoid InitHeaderSearch::AddPath(const llvm::StringRef &Path,
9575115Sfenner                               IncludeDirGroup Group, bool isCXXAware,
96127668Sbms                               bool isUserSupplied, bool isFramework,
97127668Sbms                               bool IgnoreSysRoot) {
9875115Sfenner  assert(!Path.empty() && "can't handle empty path here");
99127668Sbms  FileManager &FM = Headers.getFileMgr();
10098524Sfenner
10175115Sfenner  // Compute the actual path, taking into consideration -isysroot.
10275115Sfenner  llvm::SmallString<256> MappedPath;
103127668Sbms
10475115Sfenner  // Handle isysroot.
10575115Sfenner  if (Group == System && !IgnoreSysRoot) {
106127668Sbms    // FIXME: Portability.  This should be a sys::Path interface, this doesn't
107127668Sbms    // handle things like C:\ right, nor win32 \\network\device\blah.
10875115Sfenner    if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
10975115Sfenner      MappedPath.append(isysroot.begin(), isysroot.end());
11075115Sfenner  }
11175115Sfenner
11275115Sfenner  MappedPath.append(Path.begin(), Path.end());
11375115Sfenner
114127668Sbms  // Compute the DirectoryLookup type.
11575115Sfenner  SrcMgr::CharacteristicKind Type;
116127668Sbms  if (Group == Quoted || Group == Angled)
11775115Sfenner    Type = SrcMgr::C_User;
11875115Sfenner  else if (isCXXAware)
11975115Sfenner    Type = SrcMgr::C_System;
12075115Sfenner  else
12175115Sfenner    Type = SrcMgr::C_ExternCSystem;
12275115Sfenner
12375115Sfenner
12475115Sfenner  // If the directory exists, add it.
12575115Sfenner  if (const DirectoryEntry *DE = FM.getDirectory(MappedPath.str())) {
12675115Sfenner    IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
12775115Sfenner                                                  isFramework));
12898524Sfenner    return;
12975115Sfenner  }
13098524Sfenner
13198524Sfenner  // Check to see if this is an apple-style headermap (which are not allowed to
13298524Sfenner  // be frameworks).
13375115Sfenner  if (!isFramework) {
13475115Sfenner    if (const FileEntry *FE = FM.getFile(MappedPath.str())) {
13575115Sfenner      if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
13675115Sfenner        // It is a headermap, add it to the search path.
13775115Sfenner        IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
13875115Sfenner        return;
139      }
140    }
141  }
142
143  if (Verbose)
144    llvm::errs() << "ignoring nonexistent directory \""
145                 << MappedPath.str() << "\"\n";
146}
147
148
149void InitHeaderSearch::AddDelimitedPaths(const char *at) {
150  if (*at == 0) // Empty string should not add '.' path.
151    return;
152
153  const char* delim = strchr(at, llvm::sys::PathSeparator);
154  while (delim != 0) {
155    if (delim-at == 0)
156      AddPath(".", Angled, false, true, false);
157    else
158      AddPath(llvm::StringRef(at, delim-at), Angled, false, true, false);
159    at = delim + 1;
160    delim = strchr(at, llvm::sys::PathSeparator);
161  }
162  if (*at == 0)
163    AddPath(".", Angled, false, true, false);
164  else
165    AddPath(at, Angled, false, true, false);
166}
167
168void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(const std::string &Base,
169                                                   const char *ArchDir,
170                                                   const char *Dir32,
171                                                   const char *Dir64,
172                                                   const llvm::Triple &triple) {
173  // Add the base dir
174  AddPath(Base, System, true, false, false);
175
176  // Add the multilib dirs
177  llvm::Triple::ArchType arch = triple.getArch();
178  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
179  if (is64bit)
180    AddPath(Base + "/" + ArchDir + "/" + Dir64, System, true, false, false);
181  else
182    AddPath(Base + "/" + ArchDir + "/" + Dir32, System, true, false, false);
183
184  // Add the backward dir
185  AddPath(Base + "/backward", System, true, false, false);
186}
187
188void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(const std::string &Base,
189                                                     const char *Arch,
190                                                     const char *Version) {
191  std::string localBase = Base + "/" + Arch + "/" + Version + "/include";
192  AddPath(localBase, System, true, false, false);
193  AddPath(localBase + "/c++", System, true, false, false);
194  AddPath(localBase + "/c++/backward", System, true, false, false);
195}
196
197  // FIXME: This probably should goto to some platform utils place.
198#ifdef _MSC_VER
199
200  // Read registry string.
201  // This also supports a means to look for high-versioned keys by use
202  // of a $VERSION placeholder in the key path.
203  // $VERSION in the key path is a placeholder for the version number,
204  // causing the highest value path to be searched for and used.
205  // I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
206  // There can be additional characters in the component.  Only the numberic
207  // characters are compared.
208bool getSystemRegistryString(const char *keyPath, const char *valueName,
209                       char *value, size_t maxLength) {
210  HKEY hRootKey = NULL;
211  HKEY hKey = NULL;
212  const char* subKey = NULL;
213  DWORD valueType;
214  DWORD valueSize = maxLength - 1;
215  long lResult;
216  bool returnValue = false;
217  if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) {
218    hRootKey = HKEY_CLASSES_ROOT;
219    subKey = keyPath + 18;
220  }
221  else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) {
222    hRootKey = HKEY_USERS;
223    subKey = keyPath + 11;
224  }
225  else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) {
226    hRootKey = HKEY_LOCAL_MACHINE;
227    subKey = keyPath + 19;
228  }
229  else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) {
230    hRootKey = HKEY_CURRENT_USER;
231    subKey = keyPath + 18;
232  }
233  else
234    return(false);
235  const char *placeHolder = strstr(subKey, "$VERSION");
236  char bestName[256];
237  bestName[0] = '\0';
238  // If we have a $VERSION placeholder, do the highest-version search.
239  if (placeHolder) {
240    const char *keyEnd = placeHolder - 1;
241    const char *nextKey = placeHolder;
242    // Find end of previous key.
243    while ((keyEnd > subKey) && (*keyEnd != '\\'))
244      keyEnd--;
245    // Find end of key containing $VERSION.
246    while (*nextKey && (*nextKey != '\\'))
247      nextKey++;
248    size_t partialKeyLength = keyEnd - subKey;
249    char partialKey[256];
250    if (partialKeyLength > sizeof(partialKey))
251      partialKeyLength = sizeof(partialKey);
252    strncpy(partialKey, subKey, partialKeyLength);
253    partialKey[partialKeyLength] = '\0';
254    HKEY hTopKey = NULL;
255    lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ, &hTopKey);
256    if (lResult == ERROR_SUCCESS) {
257      char keyName[256];
258      int bestIndex = -1;
259      double bestValue = 0.0;
260      DWORD index, size = sizeof(keyName) - 1;
261      for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
262          NULL, NULL, NULL) == ERROR_SUCCESS; index++) {
263        const char *sp = keyName;
264        while (*sp && !isdigit(*sp))
265          sp++;
266        if (!*sp)
267          continue;
268        const char *ep = sp + 1;
269        while (*ep && (isdigit(*ep) || (*ep == '.')))
270          ep++;
271        char numBuf[32];
272        strncpy(numBuf, sp, sizeof(numBuf) - 1);
273        numBuf[sizeof(numBuf) - 1] = '\0';
274        double value = strtod(numBuf, NULL);
275        if (value > bestValue) {
276          bestIndex = (int)index;
277          bestValue = value;
278          strcpy(bestName, keyName);
279        }
280        size = sizeof(keyName) - 1;
281      }
282      // If we found the highest versioned key, open the key and get the value.
283      if (bestIndex != -1) {
284        // Append rest of key.
285        strncat(bestName, nextKey, sizeof(bestName) - 1);
286        bestName[sizeof(bestName) - 1] = '\0';
287        // Open the chosen key path remainder.
288        lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ, &hKey);
289        if (lResult == ERROR_SUCCESS) {
290          lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
291            (LPBYTE)value, &valueSize);
292          if (lResult == ERROR_SUCCESS)
293            returnValue = true;
294          RegCloseKey(hKey);
295        }
296      }
297      RegCloseKey(hTopKey);
298    }
299  }
300  else {
301    lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey);
302    if (lResult == ERROR_SUCCESS) {
303      lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
304        (LPBYTE)value, &valueSize);
305      if (lResult == ERROR_SUCCESS)
306        returnValue = true;
307      RegCloseKey(hKey);
308    }
309  }
310  return(returnValue);
311}
312#else // _MSC_VER
313  // Read registry string.
314bool getSystemRegistryString(const char *, const char *, char *, size_t) {
315  return(false);
316}
317#endif // _MSC_VER
318
319  // Get Visual Studio installation directory.
320bool getVisualStudioDir(std::string &path) {
321  char vsIDEInstallDir[256];
322  // Try the Windows registry first.
323  bool hasVCDir = getSystemRegistryString(
324    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
325    "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1);
326    // If we have both vc80 and vc90, pick version we were compiled with.
327  if (hasVCDir && vsIDEInstallDir[0]) {
328    char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE");
329    if (p)
330      *p = '\0';
331    path = vsIDEInstallDir;
332    return(true);
333  }
334  else {
335    // Try the environment.
336    const char* vs90comntools = getenv("VS90COMNTOOLS");
337    const char* vs80comntools = getenv("VS80COMNTOOLS");
338    const char* vscomntools = NULL;
339      // If we have both vc80 and vc90, pick version we were compiled with.
340    if (vs90comntools && vs80comntools) {
341      #if (_MSC_VER >= 1500)  // VC90
342          vscomntools = vs90comntools;
343      #elif (_MSC_VER == 1400) // VC80
344          vscomntools = vs80comntools;
345      #else
346          vscomntools = vs90comntools;
347      #endif
348    }
349    else if (vs90comntools)
350      vscomntools = vs90comntools;
351    else if (vs80comntools)
352      vscomntools = vs80comntools;
353    if (vscomntools && *vscomntools) {
354      char *p = (char*)strstr(vscomntools, "\\Common7\\Tools");
355      if (p)
356        *p = '\0';
357      path = vscomntools;
358      return(true);
359    }
360    else
361      return(false);
362  }
363  return(false);
364}
365
366  // Get Windows SDK installation directory.
367bool getWindowsSDKDir(std::string &path) {
368  char windowsSDKInstallDir[256];
369  // Try the Windows registry.
370  bool hasSDKDir = getSystemRegistryString(
371   "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
372    "InstallationFolder", windowsSDKInstallDir, sizeof(windowsSDKInstallDir) - 1);
373    // If we have both vc80 and vc90, pick version we were compiled with.
374  if (hasSDKDir && windowsSDKInstallDir[0]) {
375    path = windowsSDKInstallDir;
376    return(true);
377  }
378  return(false);
379}
380
381void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple) {
382  // FIXME: temporary hack: hard-coded paths.
383  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
384  if (CIncludeDirs != "") {
385    llvm::SmallVector<llvm::StringRef, 5> dirs;
386    CIncludeDirs.split(dirs, ":");
387    for (llvm::SmallVectorImpl<llvm::StringRef>::iterator i = dirs.begin();
388         i != dirs.end();
389         ++i)
390      AddPath(*i, System, false, false, false);
391    return;
392  }
393  llvm::Triple::OSType os = triple.getOS();
394  switch (os) {
395  case llvm::Triple::Win32:
396    {
397      std::string VSDir;
398      std::string WindowsSDKDir;
399      if (getVisualStudioDir(VSDir)) {
400        AddPath(VSDir + "\\VC\\include", System, false, false, false);
401        if (getWindowsSDKDir(WindowsSDKDir))
402          AddPath(WindowsSDKDir, System, false, false, false);
403        else
404          AddPath(VSDir + "\\VC\\PlatformSDK\\Include",
405            System, false, false, false);
406      }
407      else {
408          // Default install paths.
409        AddPath("C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
410          System, false, false, false);
411        AddPath(
412        "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
413          System, false, false, false);
414        AddPath("C:/Program Files/Microsoft Visual Studio 8/VC/include",
415          System, false, false, false);
416        AddPath(
417        "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include",
418          System, false, false, false);
419          // For some clang developers.
420        AddPath("G:/Program Files/Microsoft Visual Studio 9.0/VC/include",
421          System, false, false, false);
422        AddPath(
423        "G:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
424          System, false, false, false);
425      }
426    }
427    break;
428  case llvm::Triple::MinGW64:
429  case llvm::Triple::MinGW32:
430    AddPath("c:/mingw/include", System, true, false, false);
431    break;
432  default:
433    break;
434  }
435
436  AddPath("/usr/local/include", System, false, false, false);
437  AddPath("/usr/include", System, false, false, false);
438}
439
440void InitHeaderSearch::AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple) {
441  llvm::Triple::OSType os = triple.getOS();
442  llvm::StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
443  if (CxxIncludeRoot != "") {
444    llvm::StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
445    if (CxxIncludeArch == "")
446      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
447                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR, triple);
448    else
449      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
450                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR, triple);
451    return;
452  }
453  // FIXME: temporary hack: hard-coded paths.
454  switch (os) {
455  case llvm::Triple::Cygwin:
456    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include",
457        System, true, false, false);
458    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include/c++",
459        System, true, false, false);
460    break;
461  case llvm::Triple::MinGW64:
462    // Try gcc 4.4.0
463    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.4.0");
464    // Try gcc 4.3.0
465    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.3.0");
466    // Fall through.
467  case llvm::Triple::MinGW32:
468    // Try gcc 4.4.0
469    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
470    // Try gcc 4.3.0
471    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
472    break;
473  case llvm::Triple::Darwin:
474    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
475                                "i686-apple-darwin10", "", "x86_64", triple);
476    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
477                                "i686-apple-darwin8", "", "", triple);
478    break;
479  case llvm::Triple::Linux:
480    // Ubuntu 7.10 - Gutsy Gibbon
481    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.3",
482                                "i486-linux-gnu", "", "", triple);
483    // Ubuntu 9.04
484    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.3",
485                                "x86_64-linux-gnu","32", "", triple);
486    // Ubuntu 9.10
487    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
488                                "x86_64-linux-gnu", "32", "", triple);
489    // Fedora 8
490    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
491                                "i386-redhat-linux", "", "", triple);
492    // Fedora 9
493    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
494                                "i386-redhat-linux", "", "", triple);
495    // Fedora 10
496    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
497                                "i386-redhat-linux","", "", triple);
498
499    // Fedora 11
500    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
501                                "i586-redhat-linux","", "", triple);
502
503    // openSUSE 11.1 32 bit
504    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
505                                "i586-suse-linux", "", "", triple);
506    // openSUSE 11.1 64 bit
507    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
508                                "x86_64-suse-linux", "32", "", triple);
509    // openSUSE 11.2
510    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
511                                "i586-suse-linux", "", "", triple);
512    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
513                                "x86_64-suse-linux", "", "", triple);
514    // Arch Linux 2008-06-24
515    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
516                                "i686-pc-linux-gnu", "", "", triple);
517    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
518                                "x86_64-unknown-linux-gnu", "", "", triple);
519    // Gentoo x86 2009.1 stable
520    AddGnuCPlusPlusIncludePaths(
521      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4",
522      "i686-pc-linux-gnu", "", "", triple);
523    // Gentoo x86 2009.0 stable
524    AddGnuCPlusPlusIncludePaths(
525      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
526      "i686-pc-linux-gnu", "", "", triple);
527    // Gentoo x86 2008.0 stable
528    AddGnuCPlusPlusIncludePaths(
529      "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
530      "i686-pc-linux-gnu", "", "", triple);
531    // Ubuntu 8.10
532    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
533                                "i486-pc-linux-gnu", "", "", triple);
534    // Ubuntu 9.04
535    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
536                                "i486-linux-gnu","", "", triple);
537    // Gentoo amd64 stable
538    AddGnuCPlusPlusIncludePaths(
539        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
540        "i686-pc-linux-gnu", "", "", triple);
541    // Exherbo (2009-10-26)
542    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
543                                "x86_64-pc-linux-gnu", "32", "", triple);
544    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
545                                "i686-pc-linux-gnu", "", "", triple);
546    break;
547  case llvm::Triple::FreeBSD:
548    // DragonFly
549    AddPath("/usr/include/c++/4.1", System, true, false, false);
550    // FreeBSD
551    AddPath("/usr/include/c++/4.2", System, true, false, false);
552    break;
553  case llvm::Triple::Solaris:
554    // Solaris - Fall though..
555  case llvm::Triple::AuroraUX:
556    // AuroraUX
557    AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
558                                "i386-pc-solaris2.11", "", "", triple);
559    break;
560  default:
561    break;
562  }
563}
564
565void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang,
566                                                    const llvm::Triple &triple) {
567  if (Lang.CPlusPlus)
568    AddDefaultCPlusPlusIncludePaths(triple);
569
570  AddDefaultCIncludePaths(triple);
571
572  // Add the default framework include paths on Darwin.
573  if (triple.getOS() == llvm::Triple::Darwin) {
574    AddPath("/System/Library/Frameworks", System, true, false, true);
575    AddPath("/Library/Frameworks", System, true, false, true);
576  }
577}
578
579/// RemoveDuplicates - If there are duplicate directory entries in the specified
580/// search list, remove the later (dead) ones.
581static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
582                             bool Verbose) {
583  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
584  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
585  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
586  for (unsigned i = 0; i != SearchList.size(); ++i) {
587    unsigned DirToRemove = i;
588
589    const DirectoryLookup &CurEntry = SearchList[i];
590
591    if (CurEntry.isNormalDir()) {
592      // If this isn't the first time we've seen this dir, remove it.
593      if (SeenDirs.insert(CurEntry.getDir()))
594        continue;
595    } else if (CurEntry.isFramework()) {
596      // If this isn't the first time we've seen this framework dir, remove it.
597      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
598        continue;
599    } else {
600      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
601      // If this isn't the first time we've seen this headermap, remove it.
602      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
603        continue;
604    }
605
606    // If we have a normal #include dir/framework/headermap that is shadowed
607    // later in the chain by a system include location, we actually want to
608    // ignore the user's request and drop the user dir... keeping the system
609    // dir.  This is weird, but required to emulate GCC's search path correctly.
610    //
611    // Since dupes of system dirs are rare, just rescan to find the original
612    // that we're nuking instead of using a DenseMap.
613    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
614      // Find the dir that this is the same of.
615      unsigned FirstDir;
616      for (FirstDir = 0; ; ++FirstDir) {
617        assert(FirstDir != i && "Didn't find dupe?");
618
619        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
620
621        // If these are different lookup types, then they can't be the dupe.
622        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
623          continue;
624
625        bool isSame;
626        if (CurEntry.isNormalDir())
627          isSame = SearchEntry.getDir() == CurEntry.getDir();
628        else if (CurEntry.isFramework())
629          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
630        else {
631          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
632          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
633        }
634
635        if (isSame)
636          break;
637      }
638
639      // If the first dir in the search path is a non-system dir, zap it
640      // instead of the system one.
641      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
642        DirToRemove = FirstDir;
643    }
644
645    if (Verbose) {
646      fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
647              CurEntry.getName());
648      if (DirToRemove != i)
649        fprintf(stderr, "  as it is a non-system directory that duplicates"
650                " a system directory\n");
651    }
652
653    // This is reached if the current entry is a duplicate.  Remove the
654    // DirToRemove (usually the current dir).
655    SearchList.erase(SearchList.begin()+DirToRemove);
656    --i;
657  }
658}
659
660
661void InitHeaderSearch::Realize() {
662  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
663  std::vector<DirectoryLookup> SearchList;
664  SearchList = IncludeGroup[Angled];
665  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
666                    IncludeGroup[System].end());
667  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
668                    IncludeGroup[After].end());
669  RemoveDuplicates(SearchList, Verbose);
670  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
671
672  // Prepend QUOTED list on the search list.
673  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
674                    IncludeGroup[Quoted].end());
675
676
677  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
678  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
679                         DontSearchCurDir);
680
681  // If verbose, print the list of directories that will be searched.
682  if (Verbose) {
683    fprintf(stderr, "#include \"...\" search starts here:\n");
684    unsigned QuotedIdx = IncludeGroup[Quoted].size();
685    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
686      if (i == QuotedIdx)
687        fprintf(stderr, "#include <...> search starts here:\n");
688      const char *Name = SearchList[i].getName();
689      const char *Suffix;
690      if (SearchList[i].isNormalDir())
691        Suffix = "";
692      else if (SearchList[i].isFramework())
693        Suffix = " (framework directory)";
694      else {
695        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
696        Suffix = " (headermap)";
697      }
698      fprintf(stderr, " %s%s\n", Name, Suffix);
699    }
700    fprintf(stderr, "End of search list.\n");
701  }
702}
703
704void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
705                                     const HeaderSearchOptions &HSOpts,
706                                     const LangOptions &Lang,
707                                     const llvm::Triple &Triple) {
708  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
709
710  // Add the user defined entries.
711  for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
712    const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
713    Init.AddPath(E.Path, E.Group, false, E.IsUserSupplied, E.IsFramework,
714                 false);
715  }
716
717  // Add entries from CPATH and friends.
718  Init.AddDelimitedPaths(HSOpts.EnvIncPath.c_str());
719  if (Lang.CPlusPlus && Lang.ObjC1)
720    Init.AddDelimitedPaths(HSOpts.ObjCXXEnvIncPath.c_str());
721  else if (Lang.CPlusPlus)
722    Init.AddDelimitedPaths(HSOpts.CXXEnvIncPath.c_str());
723  else if (Lang.ObjC1)
724    Init.AddDelimitedPaths(HSOpts.ObjCEnvIncPath.c_str());
725  else
726    Init.AddDelimitedPaths(HSOpts.CEnvIncPath.c_str());
727
728  if (!HSOpts.BuiltinIncludePath.empty()) {
729    // Ignore the sys root, we *always* look for clang headers relative to
730    // supplied path.
731    Init.AddPath(HSOpts.BuiltinIncludePath, System,
732                 false, false, false, /*IgnoreSysRoot=*/ true);
733  }
734
735  if (HSOpts.UseStandardIncludes)
736    Init.AddDefaultSystemIncludePaths(Lang, Triple);
737
738  Init.Realize();
739}
740