1 //===--- ToolChain.cpp - Collections of tools for one platform ------------===// 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 "clang/Driver/ToolChain.h" 11 #include "ToolChains/CommonArgs.h" 12 #include "ToolChains/Arch/ARM.h" 13 #include "ToolChains/Clang.h" 14 #include "clang/Basic/ObjCRuntime.h" 15 #include "clang/Basic/VirtualFileSystem.h" 16 #include "clang/Config/config.h" 17 #include "clang/Driver/Action.h" 18 #include "clang/Driver/Driver.h" 19 #include "clang/Driver/DriverDiagnostic.h" 20 #include "clang/Driver/Options.h" 21 #include "clang/Driver/SanitizerArgs.h" 22 #include "clang/Driver/XRayArgs.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/Option/Arg.h" 25 #include "llvm/Option/ArgList.h" 26 #include "llvm/Option/Option.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/FileSystem.h" 29 #include "llvm/Support/Path.h" 30 #include "llvm/Support/TargetParser.h" 31 #include "llvm/Support/TargetRegistry.h" 32 33 using namespace clang::driver; 34 using namespace clang::driver::tools; 35 using namespace clang; 36 using namespace llvm; 37 using namespace llvm::opt; 38 39 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) { 40 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext, 41 options::OPT_fno_rtti, options::OPT_frtti); 42 } 43 44 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, 45 const llvm::Triple &Triple, 46 const Arg *CachedRTTIArg) { 47 // Explicit rtti/no-rtti args 48 if (CachedRTTIArg) { 49 if (CachedRTTIArg->getOption().matches(options::OPT_frtti)) 50 return ToolChain::RM_EnabledExplicitly; 51 else 52 return ToolChain::RM_DisabledExplicitly; 53 } 54 55 // -frtti is default, except for the PS4 CPU. 56 if (!Triple.isPS4CPU()) 57 return ToolChain::RM_EnabledImplicitly; 58 59 // On the PS4, turning on c++ exceptions turns on rtti. 60 // We're assuming that, if we see -fexceptions, rtti gets turned on. 61 Arg *Exceptions = Args.getLastArgNoClaim( 62 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions, 63 options::OPT_fexceptions, options::OPT_fno_exceptions); 64 if (Exceptions && 65 (Exceptions->getOption().matches(options::OPT_fexceptions) || 66 Exceptions->getOption().matches(options::OPT_fcxx_exceptions))) 67 return ToolChain::RM_EnabledImplicitly; 68 69 return ToolChain::RM_DisabledImplicitly; 70 } 71 72 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T, 73 const ArgList &Args) 74 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)), 75 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)), 76 EffectiveTriple() { 77 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) 78 if (!isThreadModelSupported(A->getValue())) 79 D.Diag(diag::err_drv_invalid_thread_model_for_target) 80 << A->getValue() << A->getAsString(Args); 81 82 std::string CandidateLibPath = getArchSpecificLibPath(); 83 if (getVFS().exists(CandidateLibPath)) 84 getFilePaths().push_back(CandidateLibPath); 85 } 86 87 ToolChain::~ToolChain() { 88 } 89 90 vfs::FileSystem &ToolChain::getVFS() const { return getDriver().getVFS(); } 91 92 bool ToolChain::useIntegratedAs() const { 93 return Args.hasFlag(options::OPT_fintegrated_as, 94 options::OPT_fno_integrated_as, 95 IsIntegratedAssemblerDefault()); 96 } 97 98 const SanitizerArgs& ToolChain::getSanitizerArgs() const { 99 if (!SanitizerArguments.get()) 100 SanitizerArguments.reset(new SanitizerArgs(*this, Args)); 101 return *SanitizerArguments.get(); 102 } 103 104 const XRayArgs& ToolChain::getXRayArgs() const { 105 if (!XRayArguments.get()) 106 XRayArguments.reset(new XRayArgs(*this, Args)); 107 return *XRayArguments.get(); 108 } 109 110 namespace { 111 struct DriverSuffix { 112 const char *Suffix; 113 const char *ModeFlag; 114 }; 115 116 const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) { 117 // A list of known driver suffixes. Suffixes are compared against the 118 // program name in order. If there is a match, the frontend type is updated as 119 // necessary by applying the ModeFlag. 120 static const DriverSuffix DriverSuffixes[] = { 121 {"clang", nullptr}, 122 {"clang++", "--driver-mode=g++"}, 123 {"clang-c++", "--driver-mode=g++"}, 124 {"clang-cc", nullptr}, 125 {"clang-cpp", "--driver-mode=cpp"}, 126 {"clang-g++", "--driver-mode=g++"}, 127 {"clang-gcc", nullptr}, 128 {"clang-cl", "--driver-mode=cl"}, 129 {"cc", nullptr}, 130 {"cpp", "--driver-mode=cpp"}, 131 {"cl", "--driver-mode=cl"}, 132 {"++", "--driver-mode=g++"}, 133 }; 134 135 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) { 136 StringRef Suffix(DriverSuffixes[i].Suffix); 137 if (ProgName.endswith(Suffix)) { 138 Pos = ProgName.size() - Suffix.size(); 139 return &DriverSuffixes[i]; 140 } 141 } 142 return nullptr; 143 } 144 145 /// Normalize the program name from argv[0] by stripping the file extension if 146 /// present and lower-casing the string on Windows. 147 std::string normalizeProgramName(llvm::StringRef Argv0) { 148 std::string ProgName = llvm::sys::path::stem(Argv0); 149 #ifdef LLVM_ON_WIN32 150 // Transform to lowercase for case insensitive file systems. 151 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower); 152 #endif 153 return ProgName; 154 } 155 156 const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) { 157 // Try to infer frontend type and default target from the program name by 158 // comparing it against DriverSuffixes in order. 159 160 // If there is a match, the function tries to identify a target as prefix. 161 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target 162 // prefix "x86_64-linux". If such a target prefix is found, it may be 163 // added via -target as implicit first argument. 164 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos); 165 166 if (!DS) { 167 // Try again after stripping any trailing version number: 168 // clang++3.5 -> clang++ 169 ProgName = ProgName.rtrim("0123456789."); 170 DS = FindDriverSuffix(ProgName, Pos); 171 } 172 173 if (!DS) { 174 // Try again after stripping trailing -component. 175 // clang++-tot -> clang++ 176 ProgName = ProgName.slice(0, ProgName.rfind('-')); 177 DS = FindDriverSuffix(ProgName, Pos); 178 } 179 return DS; 180 } 181 } // anonymous namespace 182 183 ParsedClangName 184 ToolChain::getTargetAndModeFromProgramName(StringRef PN) { 185 std::string ProgName = normalizeProgramName(PN); 186 size_t SuffixPos; 187 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos); 188 if (!DS) 189 return ParsedClangName(); 190 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix); 191 192 size_t LastComponent = ProgName.rfind('-', SuffixPos); 193 if (LastComponent == std::string::npos) 194 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag); 195 std::string ModeSuffix = ProgName.substr(LastComponent + 1, 196 SuffixEnd - LastComponent - 1); 197 198 // Infer target from the prefix. 199 StringRef Prefix(ProgName); 200 Prefix = Prefix.slice(0, LastComponent); 201 std::string IgnoredError; 202 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError); 203 return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered}; 204 } 205 206 StringRef ToolChain::getDefaultUniversalArchName() const { 207 // In universal driver terms, the arch name accepted by -arch isn't exactly 208 // the same as the ones that appear in the triple. Roughly speaking, this is 209 // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the 210 // only interesting special case is powerpc. 211 switch (Triple.getArch()) { 212 case llvm::Triple::ppc: 213 return "ppc"; 214 case llvm::Triple::ppc64: 215 return "ppc64"; 216 case llvm::Triple::ppc64le: 217 return "ppc64le"; 218 default: 219 return Triple.getArchName(); 220 } 221 } 222 223 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const { 224 return false; 225 } 226 227 Tool *ToolChain::getClang() const { 228 if (!Clang) 229 Clang.reset(new tools::Clang(*this)); 230 return Clang.get(); 231 } 232 233 Tool *ToolChain::buildAssembler() const { 234 return new tools::ClangAs(*this); 235 } 236 237 Tool *ToolChain::buildLinker() const { 238 llvm_unreachable("Linking is not supported by this toolchain"); 239 } 240 241 Tool *ToolChain::getAssemble() const { 242 if (!Assemble) 243 Assemble.reset(buildAssembler()); 244 return Assemble.get(); 245 } 246 247 Tool *ToolChain::getClangAs() const { 248 if (!Assemble) 249 Assemble.reset(new tools::ClangAs(*this)); 250 return Assemble.get(); 251 } 252 253 Tool *ToolChain::getLink() const { 254 if (!Link) 255 Link.reset(buildLinker()); 256 return Link.get(); 257 } 258 259 Tool *ToolChain::getOffloadBundler() const { 260 if (!OffloadBundler) 261 OffloadBundler.reset(new tools::OffloadBundler(*this)); 262 return OffloadBundler.get(); 263 } 264 265 Tool *ToolChain::getTool(Action::ActionClass AC) const { 266 switch (AC) { 267 case Action::AssembleJobClass: 268 return getAssemble(); 269 270 case Action::LinkJobClass: 271 return getLink(); 272 273 case Action::InputClass: 274 case Action::BindArchClass: 275 case Action::OffloadClass: 276 case Action::LipoJobClass: 277 case Action::DsymutilJobClass: 278 case Action::VerifyDebugInfoJobClass: 279 llvm_unreachable("Invalid tool kind."); 280 281 case Action::CompileJobClass: 282 case Action::PrecompileJobClass: 283 case Action::PreprocessJobClass: 284 case Action::AnalyzeJobClass: 285 case Action::MigrateJobClass: 286 case Action::VerifyPCHJobClass: 287 case Action::BackendJobClass: 288 return getClang(); 289 290 case Action::OffloadBundlingJobClass: 291 case Action::OffloadUnbundlingJobClass: 292 return getOffloadBundler(); 293 } 294 295 llvm_unreachable("Invalid tool kind."); 296 } 297 298 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, 299 const ArgList &Args) { 300 const llvm::Triple &Triple = TC.getTriple(); 301 bool IsWindows = Triple.isOSWindows(); 302 303 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb) 304 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) 305 ? "armhf" 306 : "arm"; 307 308 // For historic reasons, Android library is using i686 instead of i386. 309 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid()) 310 return "i686"; 311 312 return llvm::Triple::getArchTypeName(TC.getArch()); 313 } 314 315 std::string ToolChain::getCompilerRTPath() const { 316 SmallString<128> Path(getDriver().ResourceDir); 317 StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS(); 318 llvm::sys::path::append(Path, "lib", OSLibName); 319 return Path.str(); 320 } 321 322 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component, 323 bool Shared) const { 324 const llvm::Triple &TT = getTriple(); 325 const char *Env = TT.isAndroid() ? "-android" : ""; 326 bool IsITANMSVCWindows = 327 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment(); 328 329 StringRef Arch = getArchNameForCompilerRTLib(*this, Args); 330 const char *Prefix = IsITANMSVCWindows ? "" : "lib"; 331 const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so") 332 : (IsITANMSVCWindows ? ".lib" : ".a"); 333 334 SmallString<128> Path(getCompilerRTPath()); 335 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" + 336 Arch + Env + Suffix); 337 return Path.str(); 338 } 339 340 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args, 341 StringRef Component, 342 bool Shared) const { 343 return Args.MakeArgString(getCompilerRT(Args, Component, Shared)); 344 } 345 346 std::string ToolChain::getArchSpecificLibPath() const { 347 SmallString<128> Path(getDriver().ResourceDir); 348 StringRef OSLibName = getTriple().isOSFreeBSD() ? "freebsd" : getOS(); 349 llvm::sys::path::append(Path, "lib", OSLibName, 350 llvm::Triple::getArchTypeName(getArch())); 351 return Path.str(); 352 } 353 354 bool ToolChain::needsProfileRT(const ArgList &Args) { 355 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, 356 false) || 357 Args.hasArg(options::OPT_fprofile_generate) || 358 Args.hasArg(options::OPT_fprofile_generate_EQ) || 359 Args.hasArg(options::OPT_fprofile_instr_generate) || 360 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) || 361 Args.hasArg(options::OPT_fcreate_profile) || 362 Args.hasArg(options::OPT_coverage)) 363 return true; 364 365 return false; 366 } 367 368 Tool *ToolChain::SelectTool(const JobAction &JA) const { 369 if (getDriver().ShouldUseClangCompiler(JA)) return getClang(); 370 Action::ActionClass AC = JA.getKind(); 371 if (AC == Action::AssembleJobClass && useIntegratedAs()) 372 return getClangAs(); 373 return getTool(AC); 374 } 375 376 std::string ToolChain::GetFilePath(const char *Name) const { 377 return D.GetFilePath(Name, *this); 378 } 379 380 std::string ToolChain::GetProgramPath(const char *Name) const { 381 return D.GetProgramPath(Name, *this); 382 } 383 384 std::string ToolChain::GetLinkerPath() const { 385 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ); 386 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER; 387 388 if (llvm::sys::path::is_absolute(UseLinker)) { 389 // If we're passed what looks like an absolute path, don't attempt to 390 // second-guess that. 391 if (llvm::sys::fs::exists(UseLinker)) 392 return UseLinker; 393 } else if (UseLinker.empty() || UseLinker == "ld") { 394 // If we're passed -fuse-ld= with no argument, or with the argument ld, 395 // then use whatever the default system linker is. 396 return GetProgramPath(getDefaultLinker()); 397 } else { 398 llvm::SmallString<8> LinkerName("ld."); 399 LinkerName.append(UseLinker); 400 401 std::string LinkerPath(GetProgramPath(LinkerName.c_str())); 402 if (llvm::sys::fs::exists(LinkerPath)) 403 return LinkerPath; 404 } 405 406 if (A) 407 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); 408 409 return GetProgramPath(getDefaultLinker()); 410 } 411 412 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { 413 return types::lookupTypeForExtension(Ext); 414 } 415 416 bool ToolChain::HasNativeLLVMSupport() const { 417 return false; 418 } 419 420 bool ToolChain::isCrossCompiling() const { 421 llvm::Triple HostTriple(LLVM_HOST_TRIPLE); 422 switch (HostTriple.getArch()) { 423 // The A32/T32/T16 instruction sets are not separate architectures in this 424 // context. 425 case llvm::Triple::arm: 426 case llvm::Triple::armeb: 427 case llvm::Triple::thumb: 428 case llvm::Triple::thumbeb: 429 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb && 430 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb; 431 default: 432 return HostTriple.getArch() != getArch(); 433 } 434 } 435 436 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { 437 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, 438 VersionTuple()); 439 } 440 441 bool ToolChain::isThreadModelSupported(const StringRef Model) const { 442 if (Model == "single") { 443 // FIXME: 'single' is only supported on ARM and WebAssembly so far. 444 return Triple.getArch() == llvm::Triple::arm || 445 Triple.getArch() == llvm::Triple::armeb || 446 Triple.getArch() == llvm::Triple::thumb || 447 Triple.getArch() == llvm::Triple::thumbeb || 448 Triple.getArch() == llvm::Triple::wasm32 || 449 Triple.getArch() == llvm::Triple::wasm64; 450 } else if (Model == "posix") 451 return true; 452 453 return false; 454 } 455 456 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, 457 types::ID InputType) const { 458 switch (getTriple().getArch()) { 459 default: 460 return getTripleString(); 461 462 case llvm::Triple::x86_64: { 463 llvm::Triple Triple = getTriple(); 464 if (!Triple.isOSBinFormatMachO()) 465 return getTripleString(); 466 467 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { 468 // x86_64h goes in the triple. Other -march options just use the 469 // vanilla triple we already have. 470 StringRef MArch = A->getValue(); 471 if (MArch == "x86_64h") 472 Triple.setArchName(MArch); 473 } 474 return Triple.getTriple(); 475 } 476 case llvm::Triple::aarch64: { 477 llvm::Triple Triple = getTriple(); 478 if (!Triple.isOSBinFormatMachO()) 479 return getTripleString(); 480 481 // FIXME: older versions of ld64 expect the "arm64" component in the actual 482 // triple string and query it to determine whether an LTO file can be 483 // handled. Remove this when we don't care any more. 484 Triple.setArchName("arm64"); 485 return Triple.getTriple(); 486 } 487 case llvm::Triple::arm: 488 case llvm::Triple::armeb: 489 case llvm::Triple::thumb: 490 case llvm::Triple::thumbeb: { 491 // FIXME: Factor into subclasses. 492 llvm::Triple Triple = getTriple(); 493 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb || 494 getTriple().getArch() == llvm::Triple::thumbeb; 495 496 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 497 // '-mbig-endian'/'-EB'. 498 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 499 options::OPT_mbig_endian)) { 500 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian); 501 } 502 503 // Thumb2 is the default for V7 on Darwin. 504 // 505 // FIXME: Thumb should just be another -target-feaure, not in the triple. 506 StringRef MCPU, MArch; 507 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 508 MCPU = A->getValue(); 509 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 510 MArch = A->getValue(); 511 std::string CPU = 512 Triple.isOSBinFormatMachO() 513 ? tools::arm::getARMCPUForMArch(MArch, Triple).str() 514 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple); 515 StringRef Suffix = 516 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple); 517 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M; 518 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 && 519 getTriple().isOSBinFormatMachO()); 520 // FIXME: this is invalid for WindowsCE 521 if (getTriple().isOSWindows()) 522 ThumbDefault = true; 523 std::string ArchName; 524 if (IsBigEndian) 525 ArchName = "armeb"; 526 else 527 ArchName = "arm"; 528 529 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for 530 // M-Class CPUs/architecture variants, which is not supported. 531 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb, 532 options::OPT_mno_thumb, ThumbDefault); 533 if (IsMProfile && ARMModeRequested) { 534 if (!MCPU.empty()) 535 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM"; 536 else 537 getDriver().Diag(diag::err_arch_unsupported_isa) 538 << tools::arm::getARMArch(MArch, getTriple()) << "ARM"; 539 } 540 541 // Assembly files should start in ARM mode, unless arch is M-profile. 542 // Windows is always thumb. 543 if ((InputType != types::TY_PP_Asm && Args.hasFlag(options::OPT_mthumb, 544 options::OPT_mno_thumb, ThumbDefault)) || IsMProfile || 545 getTriple().isOSWindows()) { 546 if (IsBigEndian) 547 ArchName = "thumbeb"; 548 else 549 ArchName = "thumb"; 550 } 551 Triple.setArchName(ArchName + Suffix.str()); 552 553 return Triple.getTriple(); 554 } 555 } 556 } 557 558 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, 559 types::ID InputType) const { 560 return ComputeLLVMTriple(Args, InputType); 561 } 562 563 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 564 ArgStringList &CC1Args) const { 565 // Each toolchain should provide the appropriate include flags. 566 } 567 568 void ToolChain::addClangTargetOptions( 569 const ArgList &DriverArgs, ArgStringList &CC1Args, 570 Action::OffloadKind DeviceOffloadKind) const {} 571 572 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {} 573 574 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args, 575 llvm::opt::ArgStringList &CmdArgs) const { 576 if (!needsProfileRT(Args)) return; 577 578 CmdArgs.push_back(getCompilerRTArgString(Args, "profile")); 579 } 580 581 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( 582 const ArgList &Args) const { 583 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ); 584 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB; 585 586 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB! 587 if (LibName == "compiler-rt") 588 return ToolChain::RLT_CompilerRT; 589 else if (LibName == "libgcc") 590 return ToolChain::RLT_Libgcc; 591 else if (LibName == "platform") 592 return GetDefaultRuntimeLibType(); 593 594 if (A) 595 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args); 596 597 return GetDefaultRuntimeLibType(); 598 } 599 600 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ 601 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 602 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB; 603 604 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB! 605 if (LibName == "libc++") 606 return ToolChain::CST_Libcxx; 607 else if (LibName == "libstdc++") 608 return ToolChain::CST_Libstdcxx; 609 else if (LibName == "platform") 610 return GetDefaultCXXStdlibType(); 611 612 if (A) 613 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 614 615 return GetDefaultCXXStdlibType(); 616 } 617 618 /// \brief Utility function to add a system include directory to CC1 arguments. 619 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, 620 ArgStringList &CC1Args, 621 const Twine &Path) { 622 CC1Args.push_back("-internal-isystem"); 623 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 624 } 625 626 /// \brief Utility function to add a system include directory with extern "C" 627 /// semantics to CC1 arguments. 628 /// 629 /// Note that this should be used rarely, and only for directories that 630 /// historically and for legacy reasons are treated as having implicit extern 631 /// "C" semantics. These semantics are *ignored* by and large today, but its 632 /// important to preserve the preprocessor changes resulting from the 633 /// classification. 634 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, 635 ArgStringList &CC1Args, 636 const Twine &Path) { 637 CC1Args.push_back("-internal-externc-isystem"); 638 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 639 } 640 641 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs, 642 ArgStringList &CC1Args, 643 const Twine &Path) { 644 if (llvm::sys::fs::exists(Path)) 645 addExternCSystemInclude(DriverArgs, CC1Args, Path); 646 } 647 648 /// \brief Utility function to add a list of system include directories to CC1. 649 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, 650 ArgStringList &CC1Args, 651 ArrayRef<StringRef> Paths) { 652 for (StringRef Path : Paths) { 653 CC1Args.push_back("-internal-isystem"); 654 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 655 } 656 } 657 658 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 659 ArgStringList &CC1Args) const { 660 // Header search paths should be handled by each of the subclasses. 661 // Historically, they have not been, and instead have been handled inside of 662 // the CC1-layer frontend. As the logic is hoisted out, this generic function 663 // will slowly stop being called. 664 // 665 // While it is being called, replicate a bit of a hack to propagate the 666 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ 667 // header search paths with it. Once all systems are overriding this 668 // function, the CC1 flag and this line can be removed. 669 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); 670 } 671 672 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const { 673 return getDriver().CCCIsCXX() && 674 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs, 675 options::OPT_nostdlibxx); 676 } 677 678 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, 679 ArgStringList &CmdArgs) const { 680 assert(!Args.hasArg(options::OPT_nostdlibxx) && 681 "should not have called this"); 682 CXXStdlibType Type = GetCXXStdlibType(Args); 683 684 switch (Type) { 685 case ToolChain::CST_Libcxx: 686 CmdArgs.push_back("-lc++"); 687 break; 688 689 case ToolChain::CST_Libstdcxx: 690 CmdArgs.push_back("-lstdc++"); 691 break; 692 } 693 } 694 695 void ToolChain::AddFilePathLibArgs(const ArgList &Args, 696 ArgStringList &CmdArgs) const { 697 for (const auto &LibPath : getFilePaths()) 698 if(LibPath.length() > 0) 699 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath)); 700 } 701 702 void ToolChain::AddCCKextLibArgs(const ArgList &Args, 703 ArgStringList &CmdArgs) const { 704 CmdArgs.push_back("-lcc_kext"); 705 } 706 707 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args, 708 ArgStringList &CmdArgs) const { 709 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed 710 // (to keep the linker options consistent with gcc and clang itself). 711 if (!isOptimizationLevelFast(Args)) { 712 // Check if -ffast-math or -funsafe-math. 713 Arg *A = 714 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, 715 options::OPT_funsafe_math_optimizations, 716 options::OPT_fno_unsafe_math_optimizations); 717 718 if (!A || A->getOption().getID() == options::OPT_fno_fast_math || 719 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) 720 return false; 721 } 722 // If crtfastmath.o exists add it to the arguments. 723 std::string Path = GetFilePath("crtfastmath.o"); 724 if (Path == "crtfastmath.o") // Not found. 725 return false; 726 727 CmdArgs.push_back(Args.MakeArgString(Path)); 728 return true; 729 } 730 731 SanitizerMask ToolChain::getSupportedSanitizers() const { 732 // Return sanitizers which don't require runtime support and are not 733 // platform dependent. 734 using namespace SanitizerKind; 735 SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) | 736 CFICastStrict | UnsignedIntegerOverflow | Nullability | 737 LocalBounds; 738 if (getTriple().getArch() == llvm::Triple::x86 || 739 getTriple().getArch() == llvm::Triple::x86_64 || 740 getTriple().getArch() == llvm::Triple::arm || 741 getTriple().getArch() == llvm::Triple::aarch64 || 742 getTriple().getArch() == llvm::Triple::wasm32 || 743 getTriple().getArch() == llvm::Triple::wasm64) 744 Res |= CFIICall; 745 return Res; 746 } 747 748 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, 749 ArgStringList &CC1Args) const {} 750 751 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs, 752 ArgStringList &CC1Args) const {} 753 754 static VersionTuple separateMSVCFullVersion(unsigned Version) { 755 if (Version < 100) 756 return VersionTuple(Version); 757 758 if (Version < 10000) 759 return VersionTuple(Version / 100, Version % 100); 760 761 unsigned Build = 0, Factor = 1; 762 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10) 763 Build = Build + (Version % 10) * Factor; 764 return VersionTuple(Version / 100, Version % 100, Build); 765 } 766 767 VersionTuple 768 ToolChain::computeMSVCVersion(const Driver *D, 769 const llvm::opt::ArgList &Args) const { 770 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version); 771 const Arg *MSCompatibilityVersion = 772 Args.getLastArg(options::OPT_fms_compatibility_version); 773 774 if (MSCVersion && MSCompatibilityVersion) { 775 if (D) 776 D->Diag(diag::err_drv_argument_not_allowed_with) 777 << MSCVersion->getAsString(Args) 778 << MSCompatibilityVersion->getAsString(Args); 779 return VersionTuple(); 780 } 781 782 if (MSCompatibilityVersion) { 783 VersionTuple MSVT; 784 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) { 785 if (D) 786 D->Diag(diag::err_drv_invalid_value) 787 << MSCompatibilityVersion->getAsString(Args) 788 << MSCompatibilityVersion->getValue(); 789 } else { 790 return MSVT; 791 } 792 } 793 794 if (MSCVersion) { 795 unsigned Version = 0; 796 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) { 797 if (D) 798 D->Diag(diag::err_drv_invalid_value) 799 << MSCVersion->getAsString(Args) << MSCVersion->getValue(); 800 } else { 801 return separateMSVCFullVersion(Version); 802 } 803 } 804 805 return VersionTuple(); 806 } 807 808 llvm::opt::DerivedArgList * 809 ToolChain::TranslateOpenMPTargetArgs(const llvm::opt::DerivedArgList &Args, 810 Action::OffloadKind DeviceOffloadKind) const { 811 if (DeviceOffloadKind == Action::OFK_OpenMP) { 812 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 813 const OptTable &Opts = getDriver().getOpts(); 814 bool NewArgAdded = false; 815 816 // Handle -Xopenmp-target flags 817 for (Arg *A : Args) { 818 // Exclude flags which may only apply to the host toolchain. 819 // Do not exclude flags when the host triple (AuxTriple), 820 // matches the current toolchain triple. 821 if (A->getOption().matches(options::OPT_m_Group)) { 822 if (getAuxTriple() && getAuxTriple()->str() == getTriple().str()) 823 DAL->append(A); 824 continue; 825 } 826 827 unsigned Index; 828 unsigned Prev; 829 bool XOpenMPTargetNoTriple = A->getOption().matches( 830 options::OPT_Xopenmp_target); 831 832 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) { 833 // Passing device args: -Xopenmp-target=<triple> -opt=val. 834 if (A->getValue(0) == getTripleString()) 835 Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); 836 else 837 continue; 838 } else if (XOpenMPTargetNoTriple) { 839 // Passing device args: -Xopenmp-target -opt=val. 840 Index = Args.getBaseArgs().MakeIndex(A->getValue(0)); 841 } else { 842 DAL->append(A); 843 continue; 844 } 845 846 // Parse the argument to -Xopenmp-target. 847 Prev = Index; 848 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index)); 849 if (!XOpenMPTargetArg || Index > Prev + 1) { 850 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args) 851 << A->getAsString(Args); 852 continue; 853 } 854 if (XOpenMPTargetNoTriple && XOpenMPTargetArg && 855 Args.getAllArgValues( 856 options::OPT_fopenmp_targets_EQ).size() != 1) { 857 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple); 858 continue; 859 } 860 XOpenMPTargetArg->setBaseArg(A); 861 A = XOpenMPTargetArg.release(); 862 DAL->append(A); 863 NewArgAdded = true; 864 } 865 866 if (NewArgAdded) { 867 return DAL; 868 } else { 869 delete DAL; 870 } 871 } 872 873 return nullptr; 874 } 875