ToolChains.cpp revision ca23419b8214654d185d595956e9ddf24984750a
1//===--- ToolChains.cpp - ToolChain Implementations -----------------------===// 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#include "ToolChains.h" 11 12#ifdef HAVE_CLANG_CONFIG_H 13# include "clang/Config/config.h" 14#endif 15 16#include "clang/Driver/Arg.h" 17#include "clang/Driver/ArgList.h" 18#include "clang/Driver/Compilation.h" 19#include "clang/Driver/Driver.h" 20#include "clang/Driver/DriverDiagnostic.h" 21#include "clang/Driver/HostInfo.h" 22#include "clang/Driver/ObjCRuntime.h" 23#include "clang/Driver/OptTable.h" 24#include "clang/Driver/Option.h" 25#include "clang/Driver/Options.h" 26#include "clang/Basic/Version.h" 27 28#include "llvm/ADT/SmallString.h" 29#include "llvm/ADT/StringExtras.h" 30#include "llvm/ADT/StringSwitch.h" 31#include "llvm/ADT/STLExtras.h" 32#include "llvm/Support/ErrorHandling.h" 33#include "llvm/Support/FileSystem.h" 34#include "llvm/Support/MemoryBuffer.h" 35#include "llvm/Support/raw_ostream.h" 36#include "llvm/Support/Path.h" 37#include "llvm/Support/system_error.h" 38 39#include <cstdlib> // ::getenv 40 41#include "llvm/Config/config.h" // for CXX_INCLUDE_ROOT 42 43// Include the necessary headers to interface with the Windows registry and 44// environment. 45#ifdef _MSC_VER 46 #define WIN32_LEAN_AND_MEAN 1 47 #include <windows.h> 48#endif 49 50using namespace clang::driver; 51using namespace clang::driver::toolchains; 52using namespace clang; 53 54/// Darwin - Darwin tool chain for i386 and x86_64. 55 56Darwin::Darwin(const HostInfo &Host, const llvm::Triple& Triple) 57 : ToolChain(Host, Triple), TargetInitialized(false), 58 ARCRuntimeForSimulator(ARCSimulator_None), 59 LibCXXForSimulator(LibCXXSimulator_None) 60{ 61 // Compute the initial Darwin version based on the host. 62 bool HadExtra; 63 std::string OSName = Triple.getOSName(); 64 if (!Driver::GetReleaseVersion(&OSName.c_str()[6], 65 DarwinVersion[0], DarwinVersion[1], 66 DarwinVersion[2], HadExtra)) 67 getDriver().Diag(diag::err_drv_invalid_darwin_version) << OSName; 68 69 llvm::raw_string_ostream(MacosxVersionMin) 70 << "10." << std::max(0, (int)DarwinVersion[0] - 4) << '.' 71 << DarwinVersion[1]; 72} 73 74types::ID Darwin::LookupTypeForExtension(const char *Ext) const { 75 types::ID Ty = types::lookupTypeForExtension(Ext); 76 77 // Darwin always preprocesses assembly files (unless -x is used explicitly). 78 if (Ty == types::TY_PP_Asm) 79 return types::TY_Asm; 80 81 return Ty; 82} 83 84bool Darwin::HasNativeLLVMSupport() const { 85 return true; 86} 87 88bool Darwin::hasARCRuntime() const { 89 // FIXME: Remove this once there is a proper way to detect an ARC runtime 90 // for the simulator. 91 switch (ARCRuntimeForSimulator) { 92 case ARCSimulator_None: 93 break; 94 case ARCSimulator_HasARCRuntime: 95 return true; 96 case ARCSimulator_NoARCRuntime: 97 return false; 98 } 99 100 if (isTargetIPhoneOS()) 101 return !isIPhoneOSVersionLT(5); 102 else 103 return !isMacosxVersionLT(10, 7); 104} 105 106/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0. 107void Darwin::configureObjCRuntime(ObjCRuntime &runtime) const { 108 if (runtime.getKind() != ObjCRuntime::NeXT) 109 return ToolChain::configureObjCRuntime(runtime); 110 111 runtime.HasARC = runtime.HasWeak = hasARCRuntime(); 112 113 // So far, objc_terminate is only available in iOS 5. 114 // FIXME: do the simulator logic properly. 115 if (!ARCRuntimeForSimulator && isTargetIPhoneOS()) 116 runtime.HasTerminate = !isIPhoneOSVersionLT(5); 117 else 118 runtime.HasTerminate = false; 119} 120 121/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2. 122bool Darwin::hasBlocksRuntime() const { 123 if (isTargetIPhoneOS()) 124 return !isIPhoneOSVersionLT(3, 2); 125 else 126 return !isMacosxVersionLT(10, 6); 127} 128 129static const char *GetArmArchForMArch(StringRef Value) { 130 return llvm::StringSwitch<const char*>(Value) 131 .Case("armv6k", "armv6") 132 .Case("armv5tej", "armv5") 133 .Case("xscale", "xscale") 134 .Case("armv4t", "armv4t") 135 .Case("armv7", "armv7") 136 .Cases("armv7a", "armv7-a", "armv7") 137 .Cases("armv7r", "armv7-r", "armv7") 138 .Cases("armv7m", "armv7-m", "armv7") 139 .Default(0); 140} 141 142static const char *GetArmArchForMCpu(StringRef Value) { 143 return llvm::StringSwitch<const char *>(Value) 144 .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5") 145 .Cases("arm10e", "arm10tdmi", "armv5") 146 .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5") 147 .Case("xscale", "xscale") 148 .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", 149 "arm1176jzf-s", "cortex-m0", "armv6") 150 .Cases("cortex-a8", "cortex-r4", "cortex-m3", "cortex-a9", "armv7") 151 .Default(0); 152} 153 154StringRef Darwin::getDarwinArchName(const ArgList &Args) const { 155 switch (getTriple().getArch()) { 156 default: 157 return getArchName(); 158 159 case llvm::Triple::thumb: 160 case llvm::Triple::arm: { 161 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 162 if (const char *Arch = GetArmArchForMArch(A->getValue(Args))) 163 return Arch; 164 165 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 166 if (const char *Arch = GetArmArchForMCpu(A->getValue(Args))) 167 return Arch; 168 169 return "arm"; 170 } 171 } 172} 173 174Darwin::~Darwin() { 175 // Free tool implementations. 176 for (llvm::DenseMap<unsigned, Tool*>::iterator 177 it = Tools.begin(), ie = Tools.end(); it != ie; ++it) 178 delete it->second; 179} 180 181std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args, 182 types::ID InputType) const { 183 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType)); 184 185 // If the target isn't initialized (e.g., an unknown Darwin platform, return 186 // the default triple). 187 if (!isTargetInitialized()) 188 return Triple.getTriple(); 189 190 unsigned Version[3]; 191 getTargetVersion(Version); 192 193 llvm::SmallString<16> Str; 194 llvm::raw_svector_ostream(Str) 195 << (isTargetIPhoneOS() ? "ios" : "macosx") 196 << Version[0] << "." << Version[1] << "." << Version[2]; 197 Triple.setOSName(Str.str()); 198 199 return Triple.getTriple(); 200} 201 202Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA, 203 const ActionList &Inputs) const { 204 Action::ActionClass Key; 205 206 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) { 207 // Fallback to llvm-gcc for i386 kext compiles, we don't support that ABI. 208 if (Inputs.size() == 1 && 209 types::isCXX(Inputs[0]->getType()) && 210 getTriple().isOSDarwin() && 211 getTriple().getArch() == llvm::Triple::x86 && 212 (C.getArgs().getLastArg(options::OPT_fapple_kext) || 213 C.getArgs().getLastArg(options::OPT_mkernel))) 214 Key = JA.getKind(); 215 else 216 Key = Action::AnalyzeJobClass; 217 } else 218 Key = JA.getKind(); 219 220 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, 221 options::OPT_no_integrated_as, 222 IsIntegratedAssemblerDefault()); 223 224 Tool *&T = Tools[Key]; 225 if (!T) { 226 switch (Key) { 227 case Action::InputClass: 228 case Action::BindArchClass: 229 llvm_unreachable("Invalid tool kind."); 230 case Action::PreprocessJobClass: 231 T = new tools::darwin::Preprocess(*this); break; 232 case Action::AnalyzeJobClass: 233 T = new tools::Clang(*this); break; 234 case Action::PrecompileJobClass: 235 case Action::CompileJobClass: 236 T = new tools::darwin::Compile(*this); break; 237 case Action::AssembleJobClass: { 238 if (UseIntegratedAs) 239 T = new tools::ClangAs(*this); 240 else 241 T = new tools::darwin::Assemble(*this); 242 break; 243 } 244 case Action::LinkJobClass: 245 T = new tools::darwin::Link(*this); break; 246 case Action::LipoJobClass: 247 T = new tools::darwin::Lipo(*this); break; 248 case Action::DsymutilJobClass: 249 T = new tools::darwin::Dsymutil(*this); break; 250 case Action::VerifyJobClass: 251 T = new tools::darwin::VerifyDebug(*this); break; 252 } 253 } 254 255 return *T; 256} 257 258 259DarwinClang::DarwinClang(const HostInfo &Host, const llvm::Triple& Triple) 260 : Darwin(Host, Triple) 261{ 262 getProgramPaths().push_back(getDriver().getInstalledDir()); 263 if (getDriver().getInstalledDir() != getDriver().Dir) 264 getProgramPaths().push_back(getDriver().Dir); 265 266 // We expect 'as', 'ld', etc. to be adjacent to our install dir. 267 getProgramPaths().push_back(getDriver().getInstalledDir()); 268 if (getDriver().getInstalledDir() != getDriver().Dir) 269 getProgramPaths().push_back(getDriver().Dir); 270 271 // For fallback, we need to know how to find the GCC cc1 executables, so we 272 // also add the GCC libexec paths. This is legacy code that can be removed 273 // once fallback is no longer useful. 274 AddGCCLibexecPath(DarwinVersion[0]); 275 AddGCCLibexecPath(DarwinVersion[0] - 2); 276 AddGCCLibexecPath(DarwinVersion[0] - 1); 277 AddGCCLibexecPath(DarwinVersion[0] + 1); 278 AddGCCLibexecPath(DarwinVersion[0] + 2); 279} 280 281void DarwinClang::AddGCCLibexecPath(unsigned darwinVersion) { 282 std::string ToolChainDir = "i686-apple-darwin"; 283 ToolChainDir += llvm::utostr(darwinVersion); 284 ToolChainDir += "/4.2.1"; 285 286 std::string Path = getDriver().Dir; 287 Path += "/../llvm-gcc-4.2/libexec/gcc/"; 288 Path += ToolChainDir; 289 getProgramPaths().push_back(Path); 290 291 Path = "/usr/llvm-gcc-4.2/libexec/gcc/"; 292 Path += ToolChainDir; 293 getProgramPaths().push_back(Path); 294} 295 296void DarwinClang::AddLinkSearchPathArgs(const ArgList &Args, 297 ArgStringList &CmdArgs) const { 298 // The Clang toolchain uses explicit paths for internal libraries. 299 300 // Unfortunately, we still might depend on a few of the libraries that are 301 // only available in the gcc library directory (in particular 302 // libstdc++.dylib). For now, hardcode the path to the known install location. 303 llvm::sys::Path P(getDriver().Dir); 304 P.eraseComponent(); // .../usr/bin -> ../usr 305 P.appendComponent("lib"); 306 P.appendComponent("gcc"); 307 switch (getTriple().getArch()) { 308 default: 309 llvm_unreachable("Invalid Darwin arch!"); 310 case llvm::Triple::x86: 311 case llvm::Triple::x86_64: 312 P.appendComponent("i686-apple-darwin10"); 313 break; 314 case llvm::Triple::arm: 315 case llvm::Triple::thumb: 316 P.appendComponent("arm-apple-darwin10"); 317 break; 318 case llvm::Triple::ppc: 319 case llvm::Triple::ppc64: 320 P.appendComponent("powerpc-apple-darwin10"); 321 break; 322 } 323 P.appendComponent("4.2.1"); 324 325 // Determine the arch specific GCC subdirectory. 326 const char *ArchSpecificDir = 0; 327 switch (getTriple().getArch()) { 328 default: 329 break; 330 case llvm::Triple::arm: 331 case llvm::Triple::thumb: { 332 std::string Triple = ComputeLLVMTriple(Args); 333 StringRef TripleStr = Triple; 334 if (TripleStr.startswith("armv5") || TripleStr.startswith("thumbv5")) 335 ArchSpecificDir = "v5"; 336 else if (TripleStr.startswith("armv6") || TripleStr.startswith("thumbv6")) 337 ArchSpecificDir = "v6"; 338 else if (TripleStr.startswith("armv7") || TripleStr.startswith("thumbv7")) 339 ArchSpecificDir = "v7"; 340 break; 341 } 342 case llvm::Triple::ppc64: 343 ArchSpecificDir = "ppc64"; 344 break; 345 case llvm::Triple::x86_64: 346 ArchSpecificDir = "x86_64"; 347 break; 348 } 349 350 if (ArchSpecificDir) { 351 P.appendComponent(ArchSpecificDir); 352 bool Exists; 353 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 354 CmdArgs.push_back(Args.MakeArgString("-L" + P.str())); 355 P.eraseComponent(); 356 } 357 358 bool Exists; 359 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 360 CmdArgs.push_back(Args.MakeArgString("-L" + P.str())); 361} 362 363void DarwinClang::AddLinkARCArgs(const ArgList &Args, 364 ArgStringList &CmdArgs) const { 365 366 CmdArgs.push_back("-force_load"); 367 llvm::sys::Path P(getDriver().ClangExecutable); 368 P.eraseComponent(); // 'clang' 369 P.eraseComponent(); // 'bin' 370 P.appendComponent("lib"); 371 P.appendComponent("arc"); 372 P.appendComponent("libarclite_"); 373 std::string s = P.str(); 374 // Mash in the platform. 375 if (isTargetIOSSimulator()) 376 s += "iphonesimulator"; 377 else if (isTargetIPhoneOS()) 378 s += "iphoneos"; 379 // FIXME: Remove this once we depend fully on -mios-simulator-version-min. 380 else if (ARCRuntimeForSimulator != ARCSimulator_None) 381 s += "iphonesimulator"; 382 else 383 s += "macosx"; 384 s += ".a"; 385 386 CmdArgs.push_back(Args.MakeArgString(s)); 387} 388 389void DarwinClang::AddLinkRuntimeLib(const ArgList &Args, 390 ArgStringList &CmdArgs, 391 const char *DarwinStaticLib) const { 392 llvm::sys::Path P(getDriver().ResourceDir); 393 P.appendComponent("lib"); 394 P.appendComponent("darwin"); 395 P.appendComponent(DarwinStaticLib); 396 397 // For now, allow missing resource libraries to support developers who may 398 // not have compiler-rt checked out or integrated into their build. 399 bool Exists; 400 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 401 CmdArgs.push_back(Args.MakeArgString(P.str())); 402} 403 404void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args, 405 ArgStringList &CmdArgs) const { 406 // Darwin doesn't support real static executables, don't link any runtime 407 // libraries with -static. 408 if (Args.hasArg(options::OPT_static)) 409 return; 410 411 // Reject -static-libgcc for now, we can deal with this when and if someone 412 // cares. This is useful in situations where someone wants to statically link 413 // something like libstdc++, and needs its runtime support routines. 414 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) { 415 getDriver().Diag(diag::err_drv_unsupported_opt) 416 << A->getAsString(Args); 417 return; 418 } 419 420 // Otherwise link libSystem, then the dynamic runtime library, and finally any 421 // target specific static runtime library. 422 CmdArgs.push_back("-lSystem"); 423 424 // Select the dynamic runtime library and the target specific static library. 425 if (isTargetIPhoneOS()) { 426 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1, 427 // it never went into the SDK. 428 // Linking against libgcc_s.1 isn't needed for iOS 5.0+ 429 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator()) 430 CmdArgs.push_back("-lgcc_s.1"); 431 432 // We currently always need a static runtime library for iOS. 433 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a"); 434 } else { 435 // The dynamic runtime library was merged with libSystem for 10.6 and 436 // beyond; only 10.4 and 10.5 need an additional runtime library. 437 if (isMacosxVersionLT(10, 5)) 438 CmdArgs.push_back("-lgcc_s.10.4"); 439 else if (isMacosxVersionLT(10, 6)) 440 CmdArgs.push_back("-lgcc_s.10.5"); 441 442 // For OS X, we thought we would only need a static runtime library when 443 // targeting 10.4, to provide versions of the static functions which were 444 // omitted from 10.4.dylib. 445 // 446 // Unfortunately, that turned out to not be true, because Darwin system 447 // headers can still use eprintf on i386, and it is not exported from 448 // libSystem. Therefore, we still must provide a runtime library just for 449 // the tiny tiny handful of projects that *might* use that symbol. 450 if (isMacosxVersionLT(10, 5)) { 451 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a"); 452 } else { 453 if (getTriple().getArch() == llvm::Triple::x86) 454 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a"); 455 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a"); 456 } 457 } 458} 459 460static inline StringRef SimulatorVersionDefineName() { 461 return "__IPHONE_OS_VERSION_MIN_REQUIRED"; 462} 463 464/// \brief Parse the simulator version define: 465/// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9]) 466// and return the grouped values as integers, e.g: 467// __IPHONE_OS_VERSION_MIN_REQUIRED=40201 468// will return Major=4, Minor=2, Micro=1. 469static bool GetVersionFromSimulatorDefine(StringRef define, 470 unsigned &Major, unsigned &Minor, 471 unsigned &Micro) { 472 assert(define.startswith(SimulatorVersionDefineName())); 473 StringRef name, version; 474 llvm::tie(name, version) = define.split('='); 475 if (version.empty()) 476 return false; 477 std::string verstr = version.str(); 478 char *end; 479 unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10); 480 if (*end != '\0') 481 return false; 482 Major = num / 10000; 483 num = num % 10000; 484 Minor = num / 100; 485 Micro = num % 100; 486 return true; 487} 488 489void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { 490 const OptTable &Opts = getDriver().getOpts(); 491 492 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ); 493 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ); 494 Arg *iOSSimVersion = Args.getLastArg( 495 options::OPT_mios_simulator_version_min_EQ); 496 497 // FIXME: HACK! When compiling for the simulator we don't get a 498 // '-miphoneos-version-min' to help us know whether there is an ARC runtime 499 // or not; try to parse a __IPHONE_OS_VERSION_MIN_REQUIRED 500 // define passed in command-line. 501 if (!iOSVersion && !iOSSimVersion) { 502 for (arg_iterator it = Args.filtered_begin(options::OPT_D), 503 ie = Args.filtered_end(); it != ie; ++it) { 504 StringRef define = (*it)->getValue(Args); 505 if (define.startswith(SimulatorVersionDefineName())) { 506 unsigned Major = 0, Minor = 0, Micro = 0; 507 if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) && 508 Major < 10 && Minor < 100 && Micro < 100) { 509 ARCRuntimeForSimulator = Major < 5 ? ARCSimulator_NoARCRuntime 510 : ARCSimulator_HasARCRuntime; 511 LibCXXForSimulator = Major < 5 ? LibCXXSimulator_NotAvailable 512 : LibCXXSimulator_Available; 513 } 514 break; 515 } 516 } 517 } 518 519 if (OSXVersion && (iOSVersion || iOSSimVersion)) { 520 getDriver().Diag(diag::err_drv_argument_not_allowed_with) 521 << OSXVersion->getAsString(Args) 522 << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args); 523 iOSVersion = iOSSimVersion = 0; 524 } else if (iOSVersion && iOSSimVersion) { 525 getDriver().Diag(diag::err_drv_argument_not_allowed_with) 526 << iOSVersion->getAsString(Args) 527 << iOSSimVersion->getAsString(Args); 528 iOSSimVersion = 0; 529 } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) { 530 // If no deployment target was specified on the command line, check for 531 // environment defines. 532 StringRef OSXTarget; 533 StringRef iOSTarget; 534 StringRef iOSSimTarget; 535 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET")) 536 OSXTarget = env; 537 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET")) 538 iOSTarget = env; 539 if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET")) 540 iOSSimTarget = env; 541 542 // If no '-miphoneos-version-min' specified on the command line and 543 // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default 544 // based on isysroot. 545 if (iOSTarget.empty()) { 546 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { 547 StringRef first, second; 548 StringRef isysroot = A->getValue(Args); 549 llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS")); 550 if (second != "") 551 iOSTarget = second.substr(0,3); 552 } 553 } 554 555 // If no OSX or iOS target has been specified and we're compiling for armv7, 556 // go ahead as assume we're targeting iOS. 557 if (OSXTarget.empty() && iOSTarget.empty()) 558 if (getDarwinArchName(Args) == "armv7") 559 iOSTarget = "0.0"; 560 561 // Handle conflicting deployment targets 562 // 563 // FIXME: Don't hardcode default here. 564 565 // Do not allow conflicts with the iOS simulator target. 566 if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) { 567 getDriver().Diag(diag::err_drv_conflicting_deployment_targets) 568 << "IOS_SIMULATOR_DEPLOYMENT_TARGET" 569 << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" : 570 "IPHONEOS_DEPLOYMENT_TARGET"); 571 } 572 573 // Allow conflicts among OSX and iOS for historical reasons, but choose the 574 // default platform. 575 if (!OSXTarget.empty() && !iOSTarget.empty()) { 576 if (getTriple().getArch() == llvm::Triple::arm || 577 getTriple().getArch() == llvm::Triple::thumb) 578 OSXTarget = ""; 579 else 580 iOSTarget = ""; 581 } 582 583 if (!OSXTarget.empty()) { 584 const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ); 585 OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget); 586 Args.append(OSXVersion); 587 } else if (!iOSTarget.empty()) { 588 const Option *O = Opts.getOption(options::OPT_miphoneos_version_min_EQ); 589 iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget); 590 Args.append(iOSVersion); 591 } else if (!iOSSimTarget.empty()) { 592 const Option *O = Opts.getOption( 593 options::OPT_mios_simulator_version_min_EQ); 594 iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget); 595 Args.append(iOSSimVersion); 596 } else { 597 // Otherwise, assume we are targeting OS X. 598 const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ); 599 OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin); 600 Args.append(OSXVersion); 601 } 602 } 603 604 // Reject invalid architecture combinations. 605 if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 && 606 getTriple().getArch() != llvm::Triple::x86_64)) { 607 getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target) 608 << getTriple().getArchName() << iOSSimVersion->getAsString(Args); 609 } 610 611 // Set the tool chain target information. 612 unsigned Major, Minor, Micro; 613 bool HadExtra; 614 if (OSXVersion) { 615 assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!"); 616 if (!Driver::GetReleaseVersion(OSXVersion->getValue(Args), Major, Minor, 617 Micro, HadExtra) || HadExtra || 618 Major != 10 || Minor >= 100 || Micro >= 100) 619 getDriver().Diag(diag::err_drv_invalid_version_number) 620 << OSXVersion->getAsString(Args); 621 } else { 622 const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion; 623 assert(Version && "Unknown target platform!"); 624 if (!Driver::GetReleaseVersion(Version->getValue(Args), Major, Minor, 625 Micro, HadExtra) || HadExtra || 626 Major >= 10 || Minor >= 100 || Micro >= 100) 627 getDriver().Diag(diag::err_drv_invalid_version_number) 628 << Version->getAsString(Args); 629 } 630 631 bool IsIOSSim = bool(iOSSimVersion); 632 633 // In GCC, the simulator historically was treated as being OS X in some 634 // contexts, like determining the link logic, despite generally being called 635 // with an iOS deployment target. For compatibility, we detect the 636 // simulator as iOS + x86, and treat it differently in a few contexts. 637 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 || 638 getTriple().getArch() == llvm::Triple::x86_64)) 639 IsIOSSim = true; 640 641 setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim); 642} 643 644void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args, 645 ArgStringList &CmdArgs) const { 646 CXXStdlibType Type = GetCXXStdlibType(Args); 647 648 switch (Type) { 649 case ToolChain::CST_Libcxx: 650 CmdArgs.push_back("-lc++"); 651 break; 652 653 case ToolChain::CST_Libstdcxx: { 654 // Unfortunately, -lstdc++ doesn't always exist in the standard search path; 655 // it was previously found in the gcc lib dir. However, for all the Darwin 656 // platforms we care about it was -lstdc++.6, so we search for that 657 // explicitly if we can't see an obvious -lstdc++ candidate. 658 659 // Check in the sysroot first. 660 bool Exists; 661 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { 662 llvm::sys::Path P(A->getValue(Args)); 663 P.appendComponent("usr"); 664 P.appendComponent("lib"); 665 P.appendComponent("libstdc++.dylib"); 666 667 if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) { 668 P.eraseComponent(); 669 P.appendComponent("libstdc++.6.dylib"); 670 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) { 671 CmdArgs.push_back(Args.MakeArgString(P.str())); 672 return; 673 } 674 } 675 } 676 677 // Otherwise, look in the root. 678 if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&& 679 (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){ 680 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib"); 681 return; 682 } 683 684 // Otherwise, let the linker search. 685 CmdArgs.push_back("-lstdc++"); 686 break; 687 } 688 } 689} 690 691void DarwinClang::AddCCKextLibArgs(const ArgList &Args, 692 ArgStringList &CmdArgs) const { 693 694 // For Darwin platforms, use the compiler-rt-based support library 695 // instead of the gcc-provided one (which is also incidentally 696 // only present in the gcc lib dir, which makes it hard to find). 697 698 llvm::sys::Path P(getDriver().ResourceDir); 699 P.appendComponent("lib"); 700 P.appendComponent("darwin"); 701 P.appendComponent("libclang_rt.cc_kext.a"); 702 703 // For now, allow missing resource libraries to support developers who may 704 // not have compiler-rt checked out or integrated into their build. 705 bool Exists; 706 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 707 CmdArgs.push_back(Args.MakeArgString(P.str())); 708} 709 710DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args, 711 const char *BoundArch) const { 712 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 713 const OptTable &Opts = getDriver().getOpts(); 714 715 // FIXME: We really want to get out of the tool chain level argument 716 // translation business, as it makes the driver functionality much 717 // more opaque. For now, we follow gcc closely solely for the 718 // purpose of easily achieving feature parity & testability. Once we 719 // have something that works, we should reevaluate each translation 720 // and try to push it down into tool specific logic. 721 722 for (ArgList::const_iterator it = Args.begin(), 723 ie = Args.end(); it != ie; ++it) { 724 Arg *A = *it; 725 726 if (A->getOption().matches(options::OPT_Xarch__)) { 727 // Skip this argument unless the architecture matches either the toolchain 728 // triple arch, or the arch being bound. 729 // 730 // FIXME: Canonicalize name. 731 StringRef XarchArch = A->getValue(Args, 0); 732 if (!(XarchArch == getArchName() || 733 (BoundArch && XarchArch == BoundArch))) 734 continue; 735 736 Arg *OriginalArg = A; 737 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(Args, 1)); 738 unsigned Prev = Index; 739 Arg *XarchArg = Opts.ParseOneArg(Args, Index); 740 741 // If the argument parsing failed or more than one argument was 742 // consumed, the -Xarch_ argument's parameter tried to consume 743 // extra arguments. Emit an error and ignore. 744 // 745 // We also want to disallow any options which would alter the 746 // driver behavior; that isn't going to work in our model. We 747 // use isDriverOption() as an approximation, although things 748 // like -O4 are going to slip through. 749 if (!XarchArg || Index > Prev + 1) { 750 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args) 751 << A->getAsString(Args); 752 continue; 753 } else if (XarchArg->getOption().isDriverOption()) { 754 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver) 755 << A->getAsString(Args); 756 continue; 757 } 758 759 XarchArg->setBaseArg(A); 760 A = XarchArg; 761 762 DAL->AddSynthesizedArg(A); 763 764 // Linker input arguments require custom handling. The problem is that we 765 // have already constructed the phase actions, so we can not treat them as 766 // "input arguments". 767 if (A->getOption().isLinkerInput()) { 768 // Convert the argument into individual Zlinker_input_args. 769 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) { 770 DAL->AddSeparateArg(OriginalArg, 771 Opts.getOption(options::OPT_Zlinker_input), 772 A->getValue(Args, i)); 773 774 } 775 continue; 776 } 777 } 778 779 // Sob. These is strictly gcc compatible for the time being. Apple 780 // gcc translates options twice, which means that self-expanding 781 // options add duplicates. 782 switch ((options::ID) A->getOption().getID()) { 783 default: 784 DAL->append(A); 785 break; 786 787 case options::OPT_mkernel: 788 case options::OPT_fapple_kext: 789 DAL->append(A); 790 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static)); 791 break; 792 793 case options::OPT_dependency_file: 794 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), 795 A->getValue(Args)); 796 break; 797 798 case options::OPT_gfull: 799 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); 800 DAL->AddFlagArg(A, 801 Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols)); 802 break; 803 804 case options::OPT_gused: 805 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); 806 DAL->AddFlagArg(A, 807 Opts.getOption(options::OPT_feliminate_unused_debug_symbols)); 808 break; 809 810 case options::OPT_shared: 811 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib)); 812 break; 813 814 case options::OPT_fconstant_cfstrings: 815 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings)); 816 break; 817 818 case options::OPT_fno_constant_cfstrings: 819 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings)); 820 break; 821 822 case options::OPT_Wnonportable_cfstrings: 823 DAL->AddFlagArg(A, 824 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings)); 825 break; 826 827 case options::OPT_Wno_nonportable_cfstrings: 828 DAL->AddFlagArg(A, 829 Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings)); 830 break; 831 832 case options::OPT_fpascal_strings: 833 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings)); 834 break; 835 836 case options::OPT_fno_pascal_strings: 837 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings)); 838 break; 839 } 840 } 841 842 if (getTriple().getArch() == llvm::Triple::x86 || 843 getTriple().getArch() == llvm::Triple::x86_64) 844 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ)) 845 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2"); 846 847 // Add the arch options based on the particular spelling of -arch, to match 848 // how the driver driver works. 849 if (BoundArch) { 850 StringRef Name = BoundArch; 851 const Option *MCpu = Opts.getOption(options::OPT_mcpu_EQ); 852 const Option *MArch = Opts.getOption(options::OPT_march_EQ); 853 854 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch, 855 // which defines the list of which architectures we accept. 856 if (Name == "ppc") 857 ; 858 else if (Name == "ppc601") 859 DAL->AddJoinedArg(0, MCpu, "601"); 860 else if (Name == "ppc603") 861 DAL->AddJoinedArg(0, MCpu, "603"); 862 else if (Name == "ppc604") 863 DAL->AddJoinedArg(0, MCpu, "604"); 864 else if (Name == "ppc604e") 865 DAL->AddJoinedArg(0, MCpu, "604e"); 866 else if (Name == "ppc750") 867 DAL->AddJoinedArg(0, MCpu, "750"); 868 else if (Name == "ppc7400") 869 DAL->AddJoinedArg(0, MCpu, "7400"); 870 else if (Name == "ppc7450") 871 DAL->AddJoinedArg(0, MCpu, "7450"); 872 else if (Name == "ppc970") 873 DAL->AddJoinedArg(0, MCpu, "970"); 874 875 else if (Name == "ppc64") 876 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64)); 877 878 else if (Name == "i386") 879 ; 880 else if (Name == "i486") 881 DAL->AddJoinedArg(0, MArch, "i486"); 882 else if (Name == "i586") 883 DAL->AddJoinedArg(0, MArch, "i586"); 884 else if (Name == "i686") 885 DAL->AddJoinedArg(0, MArch, "i686"); 886 else if (Name == "pentium") 887 DAL->AddJoinedArg(0, MArch, "pentium"); 888 else if (Name == "pentium2") 889 DAL->AddJoinedArg(0, MArch, "pentium2"); 890 else if (Name == "pentpro") 891 DAL->AddJoinedArg(0, MArch, "pentiumpro"); 892 else if (Name == "pentIIm3") 893 DAL->AddJoinedArg(0, MArch, "pentium2"); 894 895 else if (Name == "x86_64") 896 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64)); 897 898 else if (Name == "arm") 899 DAL->AddJoinedArg(0, MArch, "armv4t"); 900 else if (Name == "armv4t") 901 DAL->AddJoinedArg(0, MArch, "armv4t"); 902 else if (Name == "armv5") 903 DAL->AddJoinedArg(0, MArch, "armv5tej"); 904 else if (Name == "xscale") 905 DAL->AddJoinedArg(0, MArch, "xscale"); 906 else if (Name == "armv6") 907 DAL->AddJoinedArg(0, MArch, "armv6k"); 908 else if (Name == "armv7") 909 DAL->AddJoinedArg(0, MArch, "armv7a"); 910 911 else 912 llvm_unreachable("invalid Darwin arch"); 913 } 914 915 // Add an explicit version min argument for the deployment target. We do this 916 // after argument translation because -Xarch_ arguments may add a version min 917 // argument. 918 AddDeploymentTarget(*DAL); 919 920 // Validate the C++ standard library choice. 921 CXXStdlibType Type = GetCXXStdlibType(*DAL); 922 if (Type == ToolChain::CST_Libcxx) { 923 switch (LibCXXForSimulator) { 924 case LibCXXSimulator_None: 925 // Handle non-simulator cases. 926 if (isTargetIPhoneOS()) { 927 if (isIPhoneOSVersionLT(5, 0)) { 928 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) 929 << "iOS 5.0"; 930 } 931 } 932 break; 933 case LibCXXSimulator_NotAvailable: 934 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) 935 << "iOS 5.0"; 936 break; 937 case LibCXXSimulator_Available: 938 break; 939 } 940 } 941 942 return DAL; 943} 944 945bool Darwin::IsUnwindTablesDefault() const { 946 // FIXME: Gross; we should probably have some separate target 947 // definition, possibly even reusing the one in clang. 948 return getArchName() == "x86_64"; 949} 950 951bool Darwin::UseDwarfDebugFlags() const { 952 if (const char *S = ::getenv("RC_DEBUG_OPTIONS")) 953 return S[0] != '\0'; 954 return false; 955} 956 957bool Darwin::UseSjLjExceptions() const { 958 // Darwin uses SjLj exceptions on ARM. 959 return (getTriple().getArch() == llvm::Triple::arm || 960 getTriple().getArch() == llvm::Triple::thumb); 961} 962 963const char *Darwin::GetDefaultRelocationModel() const { 964 return "pic"; 965} 966 967const char *Darwin::GetForcedPicModel() const { 968 if (getArchName() == "x86_64") 969 return "pic"; 970 return 0; 971} 972 973bool Darwin::SupportsProfiling() const { 974 // Profiling instrumentation is only supported on x86. 975 return getArchName() == "i386" || getArchName() == "x86_64"; 976} 977 978bool Darwin::SupportsObjCGC() const { 979 // Garbage collection is supported everywhere except on iPhone OS. 980 return !isTargetIPhoneOS(); 981} 982 983std::string 984Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args, 985 types::ID InputType) const { 986 return ComputeLLVMTriple(Args, InputType); 987} 988 989/// Generic_GCC - A tool chain using the 'gcc' command to perform 990/// all subcommands; this relies on gcc translating the majority of 991/// command line options. 992 993Generic_GCC::Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple) 994 : ToolChain(Host, Triple) { 995 getProgramPaths().push_back(getDriver().getInstalledDir()); 996 if (getDriver().getInstalledDir() != getDriver().Dir) 997 getProgramPaths().push_back(getDriver().Dir); 998} 999 1000Generic_GCC::~Generic_GCC() { 1001 // Free tool implementations. 1002 for (llvm::DenseMap<unsigned, Tool*>::iterator 1003 it = Tools.begin(), ie = Tools.end(); it != ie; ++it) 1004 delete it->second; 1005} 1006 1007Tool &Generic_GCC::SelectTool(const Compilation &C, 1008 const JobAction &JA, 1009 const ActionList &Inputs) const { 1010 Action::ActionClass Key; 1011 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1012 Key = Action::AnalyzeJobClass; 1013 else 1014 Key = JA.getKind(); 1015 1016 Tool *&T = Tools[Key]; 1017 if (!T) { 1018 switch (Key) { 1019 case Action::InputClass: 1020 case Action::BindArchClass: 1021 llvm_unreachable("Invalid tool kind."); 1022 case Action::PreprocessJobClass: 1023 T = new tools::gcc::Preprocess(*this); break; 1024 case Action::PrecompileJobClass: 1025 T = new tools::gcc::Precompile(*this); break; 1026 case Action::AnalyzeJobClass: 1027 T = new tools::Clang(*this); break; 1028 case Action::CompileJobClass: 1029 T = new tools::gcc::Compile(*this); break; 1030 case Action::AssembleJobClass: 1031 T = new tools::gcc::Assemble(*this); break; 1032 case Action::LinkJobClass: 1033 T = new tools::gcc::Link(*this); break; 1034 1035 // This is a bit ungeneric, but the only platform using a driver 1036 // driver is Darwin. 1037 case Action::LipoJobClass: 1038 T = new tools::darwin::Lipo(*this); break; 1039 case Action::DsymutilJobClass: 1040 T = new tools::darwin::Dsymutil(*this); break; 1041 case Action::VerifyJobClass: 1042 T = new tools::darwin::VerifyDebug(*this); break; 1043 } 1044 } 1045 1046 return *T; 1047} 1048 1049bool Generic_GCC::IsUnwindTablesDefault() const { 1050 // FIXME: Gross; we should probably have some separate target 1051 // definition, possibly even reusing the one in clang. 1052 return getArchName() == "x86_64"; 1053} 1054 1055const char *Generic_GCC::GetDefaultRelocationModel() const { 1056 return "static"; 1057} 1058 1059const char *Generic_GCC::GetForcedPicModel() const { 1060 return 0; 1061} 1062 1063/// TCEToolChain - A tool chain using the llvm bitcode tools to perform 1064/// all subcommands. See http://tce.cs.tut.fi for our peculiar target. 1065/// Currently does not support anything else but compilation. 1066 1067TCEToolChain::TCEToolChain(const HostInfo &Host, const llvm::Triple& Triple) 1068 : ToolChain(Host, Triple) { 1069 // Path mangling to find libexec 1070 std::string Path(getDriver().Dir); 1071 1072 Path += "/../libexec"; 1073 getProgramPaths().push_back(Path); 1074} 1075 1076TCEToolChain::~TCEToolChain() { 1077 for (llvm::DenseMap<unsigned, Tool*>::iterator 1078 it = Tools.begin(), ie = Tools.end(); it != ie; ++it) 1079 delete it->second; 1080} 1081 1082bool TCEToolChain::IsMathErrnoDefault() const { 1083 return true; 1084} 1085 1086bool TCEToolChain::IsUnwindTablesDefault() const { 1087 return false; 1088} 1089 1090const char *TCEToolChain::GetDefaultRelocationModel() const { 1091 return "static"; 1092} 1093 1094const char *TCEToolChain::GetForcedPicModel() const { 1095 return 0; 1096} 1097 1098Tool &TCEToolChain::SelectTool(const Compilation &C, 1099 const JobAction &JA, 1100 const ActionList &Inputs) const { 1101 Action::ActionClass Key; 1102 Key = Action::AnalyzeJobClass; 1103 1104 Tool *&T = Tools[Key]; 1105 if (!T) { 1106 switch (Key) { 1107 case Action::PreprocessJobClass: 1108 T = new tools::gcc::Preprocess(*this); break; 1109 case Action::AnalyzeJobClass: 1110 T = new tools::Clang(*this); break; 1111 default: 1112 llvm_unreachable("Unsupported action for TCE target."); 1113 } 1114 } 1115 return *T; 1116} 1117 1118/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly. 1119 1120OpenBSD::OpenBSD(const HostInfo &Host, const llvm::Triple& Triple) 1121 : Generic_ELF(Host, Triple) { 1122 getFilePaths().push_back(getDriver().Dir + "/../lib"); 1123 getFilePaths().push_back("/usr/lib"); 1124} 1125 1126Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA, 1127 const ActionList &Inputs) const { 1128 Action::ActionClass Key; 1129 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1130 Key = Action::AnalyzeJobClass; 1131 else 1132 Key = JA.getKind(); 1133 1134 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, 1135 options::OPT_no_integrated_as, 1136 IsIntegratedAssemblerDefault()); 1137 1138 Tool *&T = Tools[Key]; 1139 if (!T) { 1140 switch (Key) { 1141 case Action::AssembleJobClass: { 1142 if (UseIntegratedAs) 1143 T = new tools::ClangAs(*this); 1144 else 1145 T = new tools::openbsd::Assemble(*this); 1146 break; 1147 } 1148 case Action::LinkJobClass: 1149 T = new tools::openbsd::Link(*this); break; 1150 default: 1151 T = &Generic_GCC::SelectTool(C, JA, Inputs); 1152 } 1153 } 1154 1155 return *T; 1156} 1157 1158/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly. 1159 1160FreeBSD::FreeBSD(const HostInfo &Host, const llvm::Triple& Triple) 1161 : Generic_ELF(Host, Triple) { 1162 1163 // Determine if we are compiling 32-bit code on an x86_64 platform. 1164 bool Lib32 = false; 1165 if (Triple.getArch() == llvm::Triple::x86 && 1166 llvm::Triple(getDriver().DefaultHostTriple).getArch() == 1167 llvm::Triple::x86_64) 1168 Lib32 = true; 1169 1170 if (Triple.getArch() == llvm::Triple::ppc && 1171 llvm::Triple(getDriver().DefaultHostTriple).getArch() == 1172 llvm::Triple::ppc64) 1173 Lib32 = true; 1174 1175 if (Lib32) { 1176 getFilePaths().push_back("/usr/lib32"); 1177 } else { 1178 getFilePaths().push_back("/usr/lib"); 1179 } 1180} 1181 1182Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA, 1183 const ActionList &Inputs) const { 1184 Action::ActionClass Key; 1185 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1186 Key = Action::AnalyzeJobClass; 1187 else 1188 Key = JA.getKind(); 1189 1190 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, 1191 options::OPT_no_integrated_as, 1192 IsIntegratedAssemblerDefault()); 1193 1194 Tool *&T = Tools[Key]; 1195 if (!T) { 1196 switch (Key) { 1197 case Action::AssembleJobClass: 1198 if (UseIntegratedAs) 1199 T = new tools::ClangAs(*this); 1200 else 1201 T = new tools::freebsd::Assemble(*this); 1202 break; 1203 case Action::LinkJobClass: 1204 T = new tools::freebsd::Link(*this); break; 1205 default: 1206 T = &Generic_GCC::SelectTool(C, JA, Inputs); 1207 } 1208 } 1209 1210 return *T; 1211} 1212 1213/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly. 1214 1215NetBSD::NetBSD(const HostInfo &Host, const llvm::Triple& Triple, 1216 const llvm::Triple& ToolTriple) 1217 : Generic_ELF(Host, Triple), ToolTriple(ToolTriple) { 1218 1219 // Determine if we are compiling 32-bit code on an x86_64 platform. 1220 bool Lib32 = false; 1221 if (ToolTriple.getArch() == llvm::Triple::x86_64 && 1222 Triple.getArch() == llvm::Triple::x86) 1223 Lib32 = true; 1224 1225 if (getDriver().UseStdLib) { 1226 if (Lib32) 1227 getFilePaths().push_back("=/usr/lib/i386"); 1228 else 1229 getFilePaths().push_back("=/usr/lib"); 1230 } 1231} 1232 1233Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA, 1234 const ActionList &Inputs) const { 1235 Action::ActionClass Key; 1236 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1237 Key = Action::AnalyzeJobClass; 1238 else 1239 Key = JA.getKind(); 1240 1241 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, 1242 options::OPT_no_integrated_as, 1243 IsIntegratedAssemblerDefault()); 1244 1245 Tool *&T = Tools[Key]; 1246 if (!T) { 1247 switch (Key) { 1248 case Action::AssembleJobClass: 1249 if (UseIntegratedAs) 1250 T = new tools::ClangAs(*this); 1251 else 1252 T = new tools::netbsd::Assemble(*this, ToolTriple); 1253 break; 1254 case Action::LinkJobClass: 1255 T = new tools::netbsd::Link(*this, ToolTriple); 1256 break; 1257 default: 1258 T = &Generic_GCC::SelectTool(C, JA, Inputs); 1259 } 1260 } 1261 1262 return *T; 1263} 1264 1265/// Minix - Minix tool chain which can call as(1) and ld(1) directly. 1266 1267Minix::Minix(const HostInfo &Host, const llvm::Triple& Triple) 1268 : Generic_GCC(Host, Triple) { 1269 getFilePaths().push_back(getDriver().Dir + "/../lib"); 1270 getFilePaths().push_back("/usr/lib"); 1271 getFilePaths().push_back("/usr/gnu/lib"); 1272 getFilePaths().push_back("/usr/gnu/lib/gcc/i686-pc-minix/4.4.3"); 1273} 1274 1275Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA, 1276 const ActionList &Inputs) const { 1277 Action::ActionClass Key; 1278 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1279 Key = Action::AnalyzeJobClass; 1280 else 1281 Key = JA.getKind(); 1282 1283 Tool *&T = Tools[Key]; 1284 if (!T) { 1285 switch (Key) { 1286 case Action::AssembleJobClass: 1287 T = new tools::minix::Assemble(*this); break; 1288 case Action::LinkJobClass: 1289 T = new tools::minix::Link(*this); break; 1290 default: 1291 T = &Generic_GCC::SelectTool(C, JA, Inputs); 1292 } 1293 } 1294 1295 return *T; 1296} 1297 1298/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly. 1299 1300AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple) 1301 : Generic_GCC(Host, Triple) { 1302 1303 getProgramPaths().push_back(getDriver().getInstalledDir()); 1304 if (getDriver().getInstalledDir() != getDriver().Dir) 1305 getProgramPaths().push_back(getDriver().Dir); 1306 1307 getFilePaths().push_back(getDriver().Dir + "/../lib"); 1308 getFilePaths().push_back("/usr/lib"); 1309 getFilePaths().push_back("/usr/sfw/lib"); 1310 getFilePaths().push_back("/opt/gcc4/lib"); 1311 getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4"); 1312 1313} 1314 1315Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA, 1316 const ActionList &Inputs) const { 1317 Action::ActionClass Key; 1318 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1319 Key = Action::AnalyzeJobClass; 1320 else 1321 Key = JA.getKind(); 1322 1323 Tool *&T = Tools[Key]; 1324 if (!T) { 1325 switch (Key) { 1326 case Action::AssembleJobClass: 1327 T = new tools::auroraux::Assemble(*this); break; 1328 case Action::LinkJobClass: 1329 T = new tools::auroraux::Link(*this); break; 1330 default: 1331 T = &Generic_GCC::SelectTool(C, JA, Inputs); 1332 } 1333 } 1334 1335 return *T; 1336} 1337 1338 1339/// Linux toolchain (very bare-bones at the moment). 1340 1341enum LinuxDistro { 1342 ArchLinux, 1343 DebianLenny, 1344 DebianSqueeze, 1345 DebianWheezy, 1346 Exherbo, 1347 RHEL4, 1348 RHEL5, 1349 RHEL6, 1350 Fedora13, 1351 Fedora14, 1352 Fedora15, 1353 FedoraRawhide, 1354 OpenSuse11_3, 1355 OpenSuse11_4, 1356 OpenSuse12_1, 1357 UbuntuHardy, 1358 UbuntuIntrepid, 1359 UbuntuJaunty, 1360 UbuntuKarmic, 1361 UbuntuLucid, 1362 UbuntuMaverick, 1363 UbuntuNatty, 1364 UbuntuOneiric, 1365 UnknownDistro 1366}; 1367 1368static bool IsRedhat(enum LinuxDistro Distro) { 1369 return Distro == Fedora13 || Distro == Fedora14 || 1370 Distro == Fedora15 || Distro == FedoraRawhide || 1371 Distro == RHEL4 || Distro == RHEL5 || Distro == RHEL6; 1372} 1373 1374static bool IsOpenSuse(enum LinuxDistro Distro) { 1375 return Distro == OpenSuse11_3 || Distro == OpenSuse11_4 || 1376 Distro == OpenSuse12_1; 1377} 1378 1379static bool IsDebian(enum LinuxDistro Distro) { 1380 return Distro == DebianLenny || Distro == DebianSqueeze || 1381 Distro == DebianWheezy; 1382} 1383 1384static bool IsUbuntu(enum LinuxDistro Distro) { 1385 return Distro == UbuntuHardy || Distro == UbuntuIntrepid || 1386 Distro == UbuntuLucid || Distro == UbuntuMaverick || 1387 Distro == UbuntuJaunty || Distro == UbuntuKarmic || 1388 Distro == UbuntuNatty || Distro == UbuntuOneiric; 1389} 1390 1391// FIXME: This should be deleted. We should assume a multilib environment, and 1392// fallback gracefully if any parts of it are absent. 1393static bool HasMultilib(llvm::Triple::ArchType Arch, enum LinuxDistro Distro) { 1394 if (Arch == llvm::Triple::x86_64) { 1395 bool Exists; 1396 if (Distro == Exherbo && 1397 (llvm::sys::fs::exists("/usr/lib32/libc.so", Exists) || !Exists)) 1398 return false; 1399 } 1400 1401 return true; 1402} 1403 1404static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) { 1405 llvm::OwningPtr<llvm::MemoryBuffer> File; 1406 if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) { 1407 StringRef Data = File.get()->getBuffer(); 1408 SmallVector<StringRef, 8> Lines; 1409 Data.split(Lines, "\n"); 1410 for (unsigned int i = 0, s = Lines.size(); i < s; ++ i) { 1411 if (Lines[i] == "DISTRIB_CODENAME=hardy") 1412 return UbuntuHardy; 1413 else if (Lines[i] == "DISTRIB_CODENAME=intrepid") 1414 return UbuntuIntrepid; 1415 else if (Lines[i] == "DISTRIB_CODENAME=jaunty") 1416 return UbuntuJaunty; 1417 else if (Lines[i] == "DISTRIB_CODENAME=karmic") 1418 return UbuntuKarmic; 1419 else if (Lines[i] == "DISTRIB_CODENAME=lucid") 1420 return UbuntuLucid; 1421 else if (Lines[i] == "DISTRIB_CODENAME=maverick") 1422 return UbuntuMaverick; 1423 else if (Lines[i] == "DISTRIB_CODENAME=natty") 1424 return UbuntuNatty; 1425 else if (Lines[i] == "DISTRIB_CODENAME=oneiric") 1426 return UbuntuOneiric; 1427 } 1428 return UnknownDistro; 1429 } 1430 1431 if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) { 1432 StringRef Data = File.get()->getBuffer(); 1433 if (Data.startswith("Fedora release 15")) 1434 return Fedora15; 1435 else if (Data.startswith("Fedora release 14")) 1436 return Fedora14; 1437 else if (Data.startswith("Fedora release 13")) 1438 return Fedora13; 1439 else if (Data.startswith("Fedora release") && 1440 Data.find("Rawhide") != StringRef::npos) 1441 return FedoraRawhide; 1442 else if (Data.startswith("Red Hat Enterprise Linux") && 1443 Data.find("release 6") != StringRef::npos) 1444 return RHEL6; 1445 else if ((Data.startswith("Red Hat Enterprise Linux") || 1446 Data.startswith("CentOS")) && 1447 Data.find("release 5") != StringRef::npos) 1448 return RHEL5; 1449 else if ((Data.startswith("Red Hat Enterprise Linux") || 1450 Data.startswith("CentOS")) && 1451 Data.find("release 4") != StringRef::npos) 1452 return RHEL4; 1453 return UnknownDistro; 1454 } 1455 1456 if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) { 1457 StringRef Data = File.get()->getBuffer(); 1458 if (Data[0] == '5') 1459 return DebianLenny; 1460 else if (Data.startswith("squeeze/sid")) 1461 return DebianSqueeze; 1462 else if (Data.startswith("wheezy/sid")) 1463 return DebianWheezy; 1464 return UnknownDistro; 1465 } 1466 1467 if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) { 1468 StringRef Data = File.get()->getBuffer(); 1469 if (Data.startswith("openSUSE 11.3")) 1470 return OpenSuse11_3; 1471 else if (Data.startswith("openSUSE 11.4")) 1472 return OpenSuse11_4; 1473 else if (Data.startswith("openSUSE 12.1")) 1474 return OpenSuse12_1; 1475 return UnknownDistro; 1476 } 1477 1478 bool Exists; 1479 if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists) 1480 return Exherbo; 1481 1482 if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists) 1483 return ArchLinux; 1484 1485 return UnknownDistro; 1486} 1487 1488/// \brief Trivial helper function to simplify code checking path existence. 1489static bool PathExists(StringRef Path) { 1490 bool Exists; 1491 if (!llvm::sys::fs::exists(Path, Exists)) 1492 return Exists; 1493 return false; 1494} 1495 1496namespace { 1497/// \brief This is a class to find a viable GCC installation for Clang to use. 1498/// 1499/// This class tries to find a GCC installation on the system, and report 1500/// information about it. It starts from the host information provided to the 1501/// Driver, and has logic for fuzzing that where appropriate. 1502class GCCInstallationDetector { 1503 /// \brief Struct to store and manipulate GCC versions. 1504 /// 1505 /// We rely on assumptions about the form and structure of GCC version 1506 /// numbers: they consist of at most three '.'-separated components, and each 1507 /// component is a non-negative integer. 1508 struct GCCVersion { 1509 unsigned Major, Minor, Patch; 1510 1511 static GCCVersion Parse(StringRef VersionText) { 1512 const GCCVersion BadVersion = {0, 0, 0}; 1513 std::pair<StringRef, StringRef> First = VersionText.split('.'); 1514 std::pair<StringRef, StringRef> Second = First.second.split('.'); 1515 1516 GCCVersion GoodVersion = {0, 0, 0}; 1517 if (First.first.getAsInteger(10, GoodVersion.Major)) 1518 return BadVersion; 1519 if (Second.first.getAsInteger(10, GoodVersion.Minor)) 1520 return BadVersion; 1521 // We accept a number, or a string for the patch version, in case there 1522 // is a strang suffix, or other mangling: '4.1.x', '4.1.2-rc3'. When it 1523 // isn't a number, we just use '0' as the number but accept it. 1524 if (Second.first.getAsInteger(10, GoodVersion.Patch)) 1525 GoodVersion.Patch = 0; 1526 return GoodVersion; 1527 } 1528 1529 bool operator<(const GCCVersion &RHS) const { 1530 if (Major < RHS.Major) return true; 1531 if (Major > RHS.Major) return false; 1532 if (Minor < RHS.Minor) return true; 1533 if (Minor > RHS.Minor) return false; 1534 return Patch < RHS.Patch; 1535 } 1536 bool operator>(const GCCVersion &RHS) const { return RHS < *this; } 1537 bool operator<=(const GCCVersion &RHS) const { return !(*this > RHS); } 1538 bool operator>=(const GCCVersion &RHS) const { return !(*this < RHS); } 1539 }; 1540 1541 bool IsValid; 1542 std::string GccTriple; 1543 1544 // FIXME: These might be better as path objects. 1545 std::string GccInstallPath; 1546 std::string GccParentLibPath; 1547 1548 llvm::SmallString<128> CxxIncludeRoot; 1549 1550public: 1551 /// \brief Construct a GCCInstallationDetector from the driver. 1552 /// 1553 /// This performs all of the autodetection and sets up the various paths. 1554 /// Once constructed, a GCCInstallation is esentially immutable. 1555 GCCInstallationDetector(const Driver &D) 1556 : IsValid(false), 1557 GccTriple(D.DefaultHostTriple), 1558 CxxIncludeRoot(CXX_INCLUDE_ROOT) { 1559 // FIXME: Using CXX_INCLUDE_ROOT is here is a bit of a hack, but 1560 // avoids adding yet another option to configure/cmake. 1561 // It would probably be cleaner to break it in two variables 1562 // CXX_GCC_ROOT with just /foo/bar 1563 // CXX_GCC_VER with 4.5.2 1564 // Then we would have 1565 // CXX_INCLUDE_ROOT = CXX_GCC_ROOT/include/c++/CXX_GCC_VER 1566 // and this function would return 1567 // CXX_GCC_ROOT/lib/gcc/CXX_INCLUDE_ARCH/CXX_GCC_VER 1568 if (CxxIncludeRoot != "") { 1569 // This is of the form /foo/bar/include/c++/4.5.2/ 1570 if (CxxIncludeRoot.back() == '/') 1571 llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the / 1572 StringRef Version = llvm::sys::path::filename(CxxIncludeRoot); 1573 llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the version 1574 llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the c++ 1575 llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the include 1576 GccInstallPath = CxxIncludeRoot.str(); 1577 GccInstallPath.append("/lib/gcc/"); 1578 GccInstallPath.append(CXX_INCLUDE_ARCH); 1579 GccInstallPath.append("/"); 1580 GccInstallPath.append(Version); 1581 GccParentLibPath = GccInstallPath + "/../../.."; 1582 IsValid = true; 1583 return; 1584 } 1585 1586 llvm::Triple::ArchType HostArch = llvm::Triple(GccTriple).getArch(); 1587 // The library directories which may contain GCC installations. 1588 SmallVector<StringRef, 4> CandidateLibDirs; 1589 // The compatible GCC triples for this particular architecture. 1590 SmallVector<StringRef, 10> CandidateTriples; 1591 CollectLibDirsAndTriples(HostArch, CandidateLibDirs, CandidateTriples); 1592 1593 // Always include the default host triple as the final fallback if no 1594 // specific triple is detected. 1595 CandidateTriples.push_back(D.DefaultHostTriple); 1596 1597 // Compute the set of prefixes for our search. 1598 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(), 1599 D.PrefixDirs.end()); 1600 Prefixes.push_back(D.SysRoot); 1601 Prefixes.push_back(D.SysRoot + "/usr"); 1602 Prefixes.push_back(D.InstalledDir + "/.."); 1603 1604 // Loop over the various components which exist and select the best GCC 1605 // installation available. GCC installs are ranked by version number. 1606 GCCVersion BestVersion = {0, 0, 0}; 1607 for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) { 1608 if (!PathExists(Prefixes[i])) 1609 continue; 1610 for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) { 1611 const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str(); 1612 if (!PathExists(LibDir)) 1613 continue; 1614 for (unsigned k = 0, ke = CandidateTriples.size(); k < ke; ++k) 1615 ScanLibDirForGCCTriple(LibDir, CandidateTriples[k], BestVersion); 1616 } 1617 } 1618 } 1619 1620 /// \brief Check whether we detected a valid GCC install. 1621 bool isValid() const { return IsValid; } 1622 1623 /// \brief Get the GCC triple for the detected install. 1624 const std::string &getTriple() const { return GccTriple; } 1625 1626 /// \brief Get the detected GCC installation path. 1627 const std::string &getInstallPath() const { return GccInstallPath; } 1628 1629 /// \brief Get the detected GCC parent lib path. 1630 const std::string &getParentLibPath() const { return GccParentLibPath; } 1631 1632private: 1633 static void CollectLibDirsAndTriples(llvm::Triple::ArchType HostArch, 1634 SmallVectorImpl<StringRef> &LibDirs, 1635 SmallVectorImpl<StringRef> &Triples) { 1636 if (HostArch == llvm::Triple::arm || HostArch == llvm::Triple::thumb) { 1637 static const char *const ARMLibDirs[] = { "/lib" }; 1638 static const char *const ARMTriples[] = { "arm-linux-gnueabi" }; 1639 LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs)); 1640 Triples.append(ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples)); 1641 } else if (HostArch == llvm::Triple::x86_64) { 1642 static const char *const X86_64LibDirs[] = { "/lib64", "/lib" }; 1643 static const char *const X86_64Triples[] = { 1644 "x86_64-linux-gnu", 1645 "x86_64-unknown-linux-gnu", 1646 "x86_64-pc-linux-gnu", 1647 "x86_64-redhat-linux6E", 1648 "x86_64-redhat-linux", 1649 "x86_64-suse-linux", 1650 "x86_64-manbo-linux-gnu", 1651 "x86_64-linux-gnu", 1652 "x86_64-slackware-linux" 1653 }; 1654 LibDirs.append(X86_64LibDirs, 1655 X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs)); 1656 Triples.append(X86_64Triples, 1657 X86_64Triples + llvm::array_lengthof(X86_64Triples)); 1658 } else if (HostArch == llvm::Triple::x86) { 1659 static const char *const X86LibDirs[] = { "/lib32", "/lib" }; 1660 static const char *const X86Triples[] = { 1661 "i686-linux-gnu", 1662 "i386-linux-gnu", 1663 "i686-pc-linux-gnu", 1664 "i486-linux-gnu", 1665 "i686-redhat-linux", 1666 "i386-redhat-linux", 1667 "i586-suse-linux", 1668 "i486-slackware-linux" 1669 }; 1670 LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs)); 1671 Triples.append(X86Triples, X86Triples + llvm::array_lengthof(X86Triples)); 1672 } else if (HostArch == llvm::Triple::ppc) { 1673 static const char *const PPCLibDirs[] = { "/lib32", "/lib" }; 1674 static const char *const PPCTriples[] = { 1675 "powerpc-linux-gnu", 1676 "powerpc-unknown-linux-gnu" 1677 }; 1678 LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs)); 1679 Triples.append(PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples)); 1680 } else if (HostArch == llvm::Triple::ppc64) { 1681 static const char *const PPC64LibDirs[] = { "/lib64", "/lib" }; 1682 static const char *const PPC64Triples[] = { 1683 "powerpc64-unknown-linux-gnu" 1684 }; 1685 LibDirs.append(PPC64LibDirs, 1686 PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs)); 1687 Triples.append(PPC64Triples, 1688 PPC64Triples + llvm::array_lengthof(PPC64Triples)); 1689 } 1690 } 1691 1692 void ScanLibDirForGCCTriple(const std::string &LibDir, 1693 StringRef CandidateTriple, 1694 GCCVersion &BestVersion) { 1695 // There are various different suffixes involving the triple we 1696 // check for. We also record what is necessary to walk from each back 1697 // up to the lib directory. 1698 const std::string Suffixes[] = { 1699 "/gcc/" + CandidateTriple.str(), 1700 "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(), 1701 1702 // Ubuntu has a strange mis-matched pair of triples that this happens to 1703 // match. 1704 // FIXME: It may be worthwhile to generalize this and look for a second 1705 // triple. 1706 "/" + CandidateTriple.str() + "/gcc/i686-linux-gnu" 1707 }; 1708 const std::string InstallSuffixes[] = { 1709 "/../../..", 1710 "/../../../..", 1711 "/../../../.." 1712 }; 1713 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu. 1714 const unsigned NumSuffixes = (llvm::array_lengthof(Suffixes) - 1715 (CandidateTriple != "i386-linux-gnu")); 1716 for (unsigned i = 0; i < NumSuffixes; ++i) { 1717 StringRef Suffix = Suffixes[i]; 1718 llvm::error_code EC; 1719 for (llvm::sys::fs::directory_iterator LI(LibDir + Suffix, EC), LE; 1720 !EC && LI != LE; LI = LI.increment(EC)) { 1721 StringRef VersionText = llvm::sys::path::filename(LI->path()); 1722 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText); 1723 static const GCCVersion MinVersion = { 4, 1, 1 }; 1724 if (CandidateVersion < MinVersion) 1725 continue; 1726 if (CandidateVersion <= BestVersion) 1727 continue; 1728 if (!PathExists(LI->path() + "/crtbegin.o")) 1729 continue; 1730 1731 BestVersion = CandidateVersion; 1732 GccTriple = CandidateTriple.str(); 1733 // FIXME: We hack together the directory name here instead of 1734 // using LI to ensure stable path separators across Windows and 1735 // Linux. 1736 GccInstallPath = LibDir + Suffixes[i] + "/" + VersionText.str(); 1737 GccParentLibPath = GccInstallPath + InstallSuffixes[i]; 1738 IsValid = true; 1739 } 1740 } 1741 } 1742}; 1743} 1744 1745static void addPathIfExists(const std::string &Path, 1746 ToolChain::path_list &Paths) { 1747 if (PathExists(Path)) Paths.push_back(Path); 1748} 1749 1750/// \brief Get our best guess at the multiarch triple for a target. 1751/// 1752/// Debian-based systems are starting to use a multiarch setup where they use 1753/// a target-triple directory in the library and header search paths. 1754/// Unfortunately, this triple does not align with the vanilla target triple, 1755/// so we provide a rough mapping here. 1756static std::string getMultiarchTriple(const llvm::Triple TargetTriple, 1757 StringRef SysRoot) { 1758 // For most architectures, just use whatever we have rather than trying to be 1759 // clever. 1760 switch (TargetTriple.getArch()) { 1761 default: 1762 return TargetTriple.str(); 1763 1764 // We use the existence of '/lib/<triple>' as a directory to detect some 1765 // common linux triples that don't quite match the Clang triple for both 1766 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these 1767 // regardless of what the actual target triple is. 1768 case llvm::Triple::x86: 1769 if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu")) 1770 return "i386-linux-gnu"; 1771 return TargetTriple.str(); 1772 case llvm::Triple::x86_64: 1773 if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu")) 1774 return "x86_64-linux-gnu"; 1775 return TargetTriple.str(); 1776 } 1777} 1778 1779Linux::Linux(const HostInfo &Host, const llvm::Triple &Triple) 1780 : Generic_ELF(Host, Triple) { 1781 llvm::Triple::ArchType Arch = 1782 llvm::Triple(getDriver().DefaultHostTriple).getArch(); 1783 const std::string &SysRoot = getDriver().SysRoot; 1784 GCCInstallationDetector GCCInstallation(getDriver()); 1785 1786 // OpenSuse stores the linker with the compiler, add that to the search 1787 // path. 1788 ToolChain::path_list &PPaths = getProgramPaths(); 1789 PPaths.push_back(GCCInstallation.getParentLibPath() + "/../" + 1790 GCCInstallation.getTriple() + "/bin"); 1791 1792 Linker = GetProgramPath("ld"); 1793 1794 LinuxDistro Distro = DetectLinuxDistro(Arch); 1795 1796 if (IsOpenSuse(Distro) || IsUbuntu(Distro)) { 1797 ExtraOpts.push_back("-z"); 1798 ExtraOpts.push_back("relro"); 1799 } 1800 1801 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) 1802 ExtraOpts.push_back("-X"); 1803 1804 if (IsRedhat(Distro) || IsOpenSuse(Distro) || Distro == UbuntuMaverick || 1805 Distro == UbuntuNatty || Distro == UbuntuOneiric) 1806 ExtraOpts.push_back("--hash-style=gnu"); 1807 1808 if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid || 1809 Distro == UbuntuJaunty || Distro == UbuntuKarmic) 1810 ExtraOpts.push_back("--hash-style=both"); 1811 1812 if (IsRedhat(Distro)) 1813 ExtraOpts.push_back("--no-add-needed"); 1814 1815 if (Distro == DebianSqueeze || Distro == DebianWheezy || 1816 IsOpenSuse(Distro) || 1817 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) || 1818 Distro == UbuntuLucid || 1819 Distro == UbuntuMaverick || Distro == UbuntuKarmic || 1820 Distro == UbuntuNatty || Distro == UbuntuOneiric) 1821 ExtraOpts.push_back("--build-id"); 1822 1823 if (IsOpenSuse(Distro)) 1824 ExtraOpts.push_back("--enable-new-dtags"); 1825 1826 // The selection of paths to try here is designed to match the patterns which 1827 // the GCC driver itself uses, as this is part of the GCC-compatible driver. 1828 // This was determined by running GCC in a fake filesystem, creating all 1829 // possible permutations of these directories, and seeing which ones it added 1830 // to the link paths. 1831 path_list &Paths = getFilePaths(); 1832 const bool Is32Bits = (getArch() == llvm::Triple::x86 || 1833 getArch() == llvm::Triple::ppc); 1834 1835 const std::string Suffix32 = Arch == llvm::Triple::x86_64 ? "/32" : ""; 1836 const std::string Suffix64 = Arch == llvm::Triple::x86_64 ? "" : "/64"; 1837 const std::string Suffix = Is32Bits ? Suffix32 : Suffix64; 1838 const std::string Multilib = Is32Bits ? "lib32" : "lib64"; 1839 const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot); 1840 1841 // FIXME: Because we add paths only when they exist on the system, I think we 1842 // should remove the concept of 'HasMultilib'. It's more likely to break the 1843 // behavior than to preserve any useful invariant on the system. 1844 if (HasMultilib(Arch, Distro)) { 1845 // Add the multilib suffixed paths. 1846 if (GCCInstallation.isValid()) { 1847 const std::string &LibPath = GCCInstallation.getParentLibPath(); 1848 const std::string &GccTriple = GCCInstallation.getTriple(); 1849 // FIXME: This OpenSuse-specific path shouldn't be needed any more, but 1850 // I don't want to remove it without finding someone to test. 1851 if (IsOpenSuse(Distro) && Is32Bits) 1852 Paths.push_back(LibPath + "/../" + GccTriple + "/lib/../lib"); 1853 1854 addPathIfExists(GCCInstallation.getInstallPath() + Suffix, Paths); 1855 addPathIfExists(LibPath + "/../" + GccTriple + "/lib/../" + Multilib, 1856 Paths); 1857 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths); 1858 addPathIfExists(LibPath + "/../" + Multilib, Paths); 1859 } 1860 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths); 1861 addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths); 1862 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths); 1863 addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths); 1864 1865 // Try walking via the GCC triple path in case of multiarch GCC 1866 // installations with strange symlinks. 1867 if (GCCInstallation.isValid()) 1868 addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple() + 1869 "/../../" + Multilib, Paths); 1870 } 1871 1872 // Add the non-multilib suffixed paths (if potentially different). 1873 if (GCCInstallation.isValid()) { 1874 const std::string &LibPath = GCCInstallation.getParentLibPath(); 1875 const std::string &GccTriple = GCCInstallation.getTriple(); 1876 if (!Suffix.empty() || !HasMultilib(Arch, Distro)) 1877 addPathIfExists(GCCInstallation.getInstallPath(), Paths); 1878 addPathIfExists(LibPath + "/../" + GccTriple + "/lib", Paths); 1879 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths); 1880 addPathIfExists(LibPath, Paths); 1881 } 1882 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths); 1883 addPathIfExists(SysRoot + "/lib", Paths); 1884 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths); 1885 addPathIfExists(SysRoot + "/usr/lib", Paths); 1886} 1887 1888bool Linux::HasNativeLLVMSupport() const { 1889 return true; 1890} 1891 1892Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA, 1893 const ActionList &Inputs) const { 1894 Action::ActionClass Key; 1895 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1896 Key = Action::AnalyzeJobClass; 1897 else 1898 Key = JA.getKind(); 1899 1900 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, 1901 options::OPT_no_integrated_as, 1902 IsIntegratedAssemblerDefault()); 1903 1904 Tool *&T = Tools[Key]; 1905 if (!T) { 1906 switch (Key) { 1907 case Action::AssembleJobClass: 1908 if (UseIntegratedAs) 1909 T = new tools::ClangAs(*this); 1910 else 1911 T = new tools::linuxtools::Assemble(*this); 1912 break; 1913 case Action::LinkJobClass: 1914 T = new tools::linuxtools::Link(*this); break; 1915 default: 1916 T = &Generic_GCC::SelectTool(C, JA, Inputs); 1917 } 1918 } 1919 1920 return *T; 1921} 1922 1923/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly. 1924 1925DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple) 1926 : Generic_ELF(Host, Triple) { 1927 1928 // Path mangling to find libexec 1929 getProgramPaths().push_back(getDriver().getInstalledDir()); 1930 if (getDriver().getInstalledDir() != getDriver().Dir) 1931 getProgramPaths().push_back(getDriver().Dir); 1932 1933 getFilePaths().push_back(getDriver().Dir + "/../lib"); 1934 getFilePaths().push_back("/usr/lib"); 1935 getFilePaths().push_back("/usr/lib/gcc41"); 1936} 1937 1938Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA, 1939 const ActionList &Inputs) const { 1940 Action::ActionClass Key; 1941 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1942 Key = Action::AnalyzeJobClass; 1943 else 1944 Key = JA.getKind(); 1945 1946 Tool *&T = Tools[Key]; 1947 if (!T) { 1948 switch (Key) { 1949 case Action::AssembleJobClass: 1950 T = new tools::dragonfly::Assemble(*this); break; 1951 case Action::LinkJobClass: 1952 T = new tools::dragonfly::Link(*this); break; 1953 default: 1954 T = &Generic_GCC::SelectTool(C, JA, Inputs); 1955 } 1956 } 1957 1958 return *T; 1959} 1960 1961Windows::Windows(const HostInfo &Host, const llvm::Triple& Triple) 1962 : ToolChain(Host, Triple) { 1963} 1964 1965Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA, 1966 const ActionList &Inputs) const { 1967 Action::ActionClass Key; 1968 if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) 1969 Key = Action::AnalyzeJobClass; 1970 else 1971 Key = JA.getKind(); 1972 1973 bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, 1974 options::OPT_no_integrated_as, 1975 IsIntegratedAssemblerDefault()); 1976 1977 Tool *&T = Tools[Key]; 1978 if (!T) { 1979 switch (Key) { 1980 case Action::InputClass: 1981 case Action::BindArchClass: 1982 case Action::LipoJobClass: 1983 case Action::DsymutilJobClass: 1984 case Action::VerifyJobClass: 1985 llvm_unreachable("Invalid tool kind."); 1986 case Action::PreprocessJobClass: 1987 case Action::PrecompileJobClass: 1988 case Action::AnalyzeJobClass: 1989 case Action::CompileJobClass: 1990 T = new tools::Clang(*this); break; 1991 case Action::AssembleJobClass: 1992 if (!UseIntegratedAs && getTriple().getEnvironment() == llvm::Triple::MachO) 1993 T = new tools::darwin::Assemble(*this); 1994 else 1995 T = new tools::ClangAs(*this); 1996 break; 1997 case Action::LinkJobClass: 1998 T = new tools::visualstudio::Link(*this); break; 1999 } 2000 } 2001 2002 return *T; 2003} 2004 2005bool Windows::IsIntegratedAssemblerDefault() const { 2006 return true; 2007} 2008 2009bool Windows::IsUnwindTablesDefault() const { 2010 // FIXME: Gross; we should probably have some separate target 2011 // definition, possibly even reusing the one in clang. 2012 return getArchName() == "x86_64"; 2013} 2014 2015const char *Windows::GetDefaultRelocationModel() const { 2016 return "static"; 2017} 2018 2019const char *Windows::GetForcedPicModel() const { 2020 if (getArchName() == "x86_64") 2021 return "pic"; 2022 return 0; 2023} 2024 2025// FIXME: This probably should goto to some platform utils place. 2026#ifdef _MSC_VER 2027 2028/// \brief Read registry string. 2029/// This also supports a means to look for high-versioned keys by use 2030/// of a $VERSION placeholder in the key path. 2031/// $VERSION in the key path is a placeholder for the version number, 2032/// causing the highest value path to be searched for and used. 2033/// I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION". 2034/// There can be additional characters in the component. Only the numberic 2035/// characters are compared. 2036static bool getSystemRegistryString(const char *keyPath, const char *valueName, 2037 char *value, size_t maxLength) { 2038 HKEY hRootKey = NULL; 2039 HKEY hKey = NULL; 2040 const char* subKey = NULL; 2041 DWORD valueType; 2042 DWORD valueSize = maxLength - 1; 2043 long lResult; 2044 bool returnValue = false; 2045 2046 if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) { 2047 hRootKey = HKEY_CLASSES_ROOT; 2048 subKey = keyPath + 18; 2049 } else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) { 2050 hRootKey = HKEY_USERS; 2051 subKey = keyPath + 11; 2052 } else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) { 2053 hRootKey = HKEY_LOCAL_MACHINE; 2054 subKey = keyPath + 19; 2055 } else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) { 2056 hRootKey = HKEY_CURRENT_USER; 2057 subKey = keyPath + 18; 2058 } else { 2059 return false; 2060 } 2061 2062 const char *placeHolder = strstr(subKey, "$VERSION"); 2063 char bestName[256]; 2064 bestName[0] = '\0'; 2065 // If we have a $VERSION placeholder, do the highest-version search. 2066 if (placeHolder) { 2067 const char *keyEnd = placeHolder - 1; 2068 const char *nextKey = placeHolder; 2069 // Find end of previous key. 2070 while ((keyEnd > subKey) && (*keyEnd != '\\')) 2071 keyEnd--; 2072 // Find end of key containing $VERSION. 2073 while (*nextKey && (*nextKey != '\\')) 2074 nextKey++; 2075 size_t partialKeyLength = keyEnd - subKey; 2076 char partialKey[256]; 2077 if (partialKeyLength > sizeof(partialKey)) 2078 partialKeyLength = sizeof(partialKey); 2079 strncpy(partialKey, subKey, partialKeyLength); 2080 partialKey[partialKeyLength] = '\0'; 2081 HKEY hTopKey = NULL; 2082 lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ, &hTopKey); 2083 if (lResult == ERROR_SUCCESS) { 2084 char keyName[256]; 2085 int bestIndex = -1; 2086 double bestValue = 0.0; 2087 DWORD index, size = sizeof(keyName) - 1; 2088 for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL, 2089 NULL, NULL, NULL) == ERROR_SUCCESS; index++) { 2090 const char *sp = keyName; 2091 while (*sp && !isdigit(*sp)) 2092 sp++; 2093 if (!*sp) 2094 continue; 2095 const char *ep = sp + 1; 2096 while (*ep && (isdigit(*ep) || (*ep == '.'))) 2097 ep++; 2098 char numBuf[32]; 2099 strncpy(numBuf, sp, sizeof(numBuf) - 1); 2100 numBuf[sizeof(numBuf) - 1] = '\0'; 2101 double value = strtod(numBuf, NULL); 2102 if (value > bestValue) { 2103 bestIndex = (int)index; 2104 bestValue = value; 2105 strcpy(bestName, keyName); 2106 } 2107 size = sizeof(keyName) - 1; 2108 } 2109 // If we found the highest versioned key, open the key and get the value. 2110 if (bestIndex != -1) { 2111 // Append rest of key. 2112 strncat(bestName, nextKey, sizeof(bestName) - 1); 2113 bestName[sizeof(bestName) - 1] = '\0'; 2114 // Open the chosen key path remainder. 2115 lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ, &hKey); 2116 if (lResult == ERROR_SUCCESS) { 2117 lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, 2118 (LPBYTE)value, &valueSize); 2119 if (lResult == ERROR_SUCCESS) 2120 returnValue = true; 2121 RegCloseKey(hKey); 2122 } 2123 } 2124 RegCloseKey(hTopKey); 2125 } 2126 } else { 2127 lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey); 2128 if (lResult == ERROR_SUCCESS) { 2129 lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, 2130 (LPBYTE)value, &valueSize); 2131 if (lResult == ERROR_SUCCESS) 2132 returnValue = true; 2133 RegCloseKey(hKey); 2134 } 2135 } 2136 return returnValue; 2137} 2138 2139/// \brief Get Windows SDK installation directory. 2140static bool getWindowsSDKDir(std::string &path) { 2141 char windowsSDKInstallDir[256]; 2142 // Try the Windows registry. 2143 bool hasSDKDir = getSystemRegistryString( 2144 "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION", 2145 "InstallationFolder", 2146 windowsSDKInstallDir, 2147 sizeof(windowsSDKInstallDir) - 1); 2148 // If we have both vc80 and vc90, pick version we were compiled with. 2149 if (hasSDKDir && windowsSDKInstallDir[0]) { 2150 path = windowsSDKInstallDir; 2151 return true; 2152 } 2153 return false; 2154} 2155 2156 // Get Visual Studio installation directory. 2157static bool getVisualStudioDir(std::string &path) { 2158 // First check the environment variables that vsvars32.bat sets. 2159 const char* vcinstalldir = getenv("VCINSTALLDIR"); 2160 if (vcinstalldir) { 2161 char *p = const_cast<char *>(strstr(vcinstalldir, "\\VC")); 2162 if (p) 2163 *p = '\0'; 2164 path = vcinstalldir; 2165 return true; 2166 } 2167 2168 char vsIDEInstallDir[256]; 2169 char vsExpressIDEInstallDir[256]; 2170 // Then try the windows registry. 2171 bool hasVCDir = getSystemRegistryString( 2172 "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION", 2173 "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1); 2174 bool hasVCExpressDir = getSystemRegistryString( 2175 "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\$VERSION", 2176 "InstallDir", vsExpressIDEInstallDir, sizeof(vsExpressIDEInstallDir) - 1); 2177 // If we have both vc80 and vc90, pick version we were compiled with. 2178 if (hasVCDir && vsIDEInstallDir[0]) { 2179 char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE"); 2180 if (p) 2181 *p = '\0'; 2182 path = vsIDEInstallDir; 2183 return true; 2184 } 2185 2186 if (hasVCExpressDir && vsExpressIDEInstallDir[0]) { 2187 char *p = (char*)strstr(vsExpressIDEInstallDir, "\\Common7\\IDE"); 2188 if (p) 2189 *p = '\0'; 2190 path = vsExpressIDEInstallDir; 2191 return true; 2192 } 2193 2194 // Try the environment. 2195 const char *vs100comntools = getenv("VS100COMNTOOLS"); 2196 const char *vs90comntools = getenv("VS90COMNTOOLS"); 2197 const char *vs80comntools = getenv("VS80COMNTOOLS"); 2198 const char *vscomntools = NULL; 2199 2200 // Try to find the version that we were compiled with 2201 if(false) {} 2202 #if (_MSC_VER >= 1600) // VC100 2203 else if(vs100comntools) { 2204 vscomntools = vs100comntools; 2205 } 2206 #elif (_MSC_VER == 1500) // VC80 2207 else if(vs90comntools) { 2208 vscomntools = vs90comntools; 2209 } 2210 #elif (_MSC_VER == 1400) // VC80 2211 else if(vs80comntools) { 2212 vscomntools = vs80comntools; 2213 } 2214 #endif 2215 // Otherwise find any version we can 2216 else if (vs100comntools) 2217 vscomntools = vs100comntools; 2218 else if (vs90comntools) 2219 vscomntools = vs90comntools; 2220 else if (vs80comntools) 2221 vscomntools = vs80comntools; 2222 2223 if (vscomntools && *vscomntools) { 2224 const char *p = strstr(vscomntools, "\\Common7\\Tools"); 2225 path = p ? std::string(vscomntools, p) : vscomntools; 2226 return true; 2227 } 2228 return false; 2229} 2230 2231// FIXME: Hoist this up, generalize, and document it as more stuff begins using 2232// it. 2233static void addSystemInclude(const ArgList &DriverArgs, ArgStringList &CC1Args, 2234 const Twine &Path) { 2235 CC1Args.push_back("-isystem"); 2236 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 2237} 2238 2239#endif // _MSC_VER 2240 2241// FIXME: Generalize this and document it as more clients begin to use it. 2242static void addSystemIncludes(const ArgList &DriverArgs, 2243 ArgStringList &CC1Args, 2244 ArrayRef<StringRef> Paths) { 2245 for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end(); 2246 I != E; ++I) { 2247 CC1Args.push_back("-isystem"); 2248 CC1Args.push_back(DriverArgs.MakeArgString(*I)); 2249 } 2250} 2251 2252void Windows::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 2253 ArgStringList &CC1Args) const { 2254 std::string VSDir; 2255 std::string WindowsSDKDir; 2256 2257#ifdef _MSC_VER 2258 // When built with access to the proper Windows APIs, try to actually find 2259 // the correct include paths first. 2260 if (getVisualStudioDir(VSDir)) { 2261 addSystemInclude(DriverArgs, CC1Args, VSDir + "\\VC\\include"); 2262 if (getWindowsSDKDir(WindowsSDKDir)) 2263 addSystemInclude(DriverArgs, CC1Args, WindowsSDKDir + "\\include"); 2264 else 2265 addSystemInclude(DriverArgs, CC1Args, 2266 VSDir + "\\VC\\PlatformSDK\\Include"); 2267 return; 2268 } 2269#endif // _MSC_VER 2270 2271 // As a fallback, select default install paths. 2272 const StringRef Paths[] = { 2273 "C:/Program Files/Microsoft Visual Studio 10.0/VC/include", 2274 "C:/Program Files/Microsoft Visual Studio 9.0/VC/include", 2275 "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include", 2276 "C:/Program Files/Microsoft Visual Studio 8/VC/include", 2277 "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include" 2278 }; 2279 addSystemIncludes(DriverArgs, CC1Args, Paths); 2280} 2281 2282void Windows::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2283 ArgStringList &CC1Args) const { 2284 // FIXME: There should probably be logic here to find libc++ on Windows. 2285} 2286