1 //===- ToolChain.cpp - Collections of tools for one platform --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Driver/ToolChain.h" 10 #include "InputInfo.h" 11 #include "ToolChains/Arch/ARM.h" 12 #include "ToolChains/Clang.h" 13 #include "ToolChains/InterfaceStubs.h" 14 #include "ToolChains/Flang.h" 15 #include "clang/Basic/ObjCRuntime.h" 16 #include "clang/Basic/Sanitizers.h" 17 #include "clang/Config/config.h" 18 #include "clang/Driver/Action.h" 19 #include "clang/Driver/Driver.h" 20 #include "clang/Driver/DriverDiagnostic.h" 21 #include "clang/Driver/Job.h" 22 #include "clang/Driver/Options.h" 23 #include "clang/Driver/SanitizerArgs.h" 24 #include "clang/Driver/XRayArgs.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallString.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/Config/llvm-config.h" 31 #include "llvm/MC/MCTargetOptions.h" 32 #include "llvm/Option/Arg.h" 33 #include "llvm/Option/ArgList.h" 34 #include "llvm/Option/OptTable.h" 35 #include "llvm/Option/Option.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Support/TargetParser.h" 40 #include "llvm/Support/TargetRegistry.h" 41 #include "llvm/Support/VersionTuple.h" 42 #include "llvm/Support/VirtualFileSystem.h" 43 #include <cassert> 44 #include <cstddef> 45 #include <cstring> 46 #include <string> 47 48 using namespace clang; 49 using namespace driver; 50 using namespace tools; 51 using namespace llvm; 52 using namespace llvm::opt; 53 54 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) { 55 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext, 56 options::OPT_fno_rtti, options::OPT_frtti); 57 } 58 59 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, 60 const llvm::Triple &Triple, 61 const Arg *CachedRTTIArg) { 62 // Explicit rtti/no-rtti args 63 if (CachedRTTIArg) { 64 if (CachedRTTIArg->getOption().matches(options::OPT_frtti)) 65 return ToolChain::RM_Enabled; 66 else 67 return ToolChain::RM_Disabled; 68 } 69 70 // -frtti is default, except for the PS4 CPU. 71 return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled; 72 } 73 74 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T, 75 const ArgList &Args) 76 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)), 77 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) { 78 if (D.CCCIsCXX()) { 79 if (auto CXXStdlibPath = getCXXStdlibPath()) 80 getFilePaths().push_back(*CXXStdlibPath); 81 } 82 83 if (auto RuntimePath = getRuntimePath()) 84 getLibraryPaths().push_back(*RuntimePath); 85 86 std::string CandidateLibPath = getArchSpecificLibPath(); 87 if (getVFS().exists(CandidateLibPath)) 88 getFilePaths().push_back(CandidateLibPath); 89 } 90 91 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) { 92 Triple.setEnvironment(Env); 93 if (EffectiveTriple != llvm::Triple()) 94 EffectiveTriple.setEnvironment(Env); 95 } 96 97 ToolChain::~ToolChain() = default; 98 99 llvm::vfs::FileSystem &ToolChain::getVFS() const { 100 return getDriver().getVFS(); 101 } 102 103 bool ToolChain::useIntegratedAs() const { 104 return Args.hasFlag(options::OPT_fintegrated_as, 105 options::OPT_fno_integrated_as, 106 IsIntegratedAssemblerDefault()); 107 } 108 109 bool ToolChain::useRelaxRelocations() const { 110 return ENABLE_X86_RELAX_RELOCATIONS; 111 } 112 113 bool ToolChain::isNoExecStackDefault() const { 114 return false; 115 } 116 117 const SanitizerArgs& ToolChain::getSanitizerArgs() const { 118 if (!SanitizerArguments.get()) 119 SanitizerArguments.reset(new SanitizerArgs(*this, Args)); 120 return *SanitizerArguments.get(); 121 } 122 123 const XRayArgs& ToolChain::getXRayArgs() const { 124 if (!XRayArguments.get()) 125 XRayArguments.reset(new XRayArgs(*this, Args)); 126 return *XRayArguments.get(); 127 } 128 129 namespace { 130 131 struct DriverSuffix { 132 const char *Suffix; 133 const char *ModeFlag; 134 }; 135 136 } // namespace 137 138 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) { 139 // A list of known driver suffixes. Suffixes are compared against the 140 // program name in order. If there is a match, the frontend type is updated as 141 // necessary by applying the ModeFlag. 142 static const DriverSuffix DriverSuffixes[] = { 143 {"clang", nullptr}, 144 {"clang++", "--driver-mode=g++"}, 145 {"clang-c++", "--driver-mode=g++"}, 146 {"clang-cc", nullptr}, 147 {"clang-cpp", "--driver-mode=cpp"}, 148 {"clang-g++", "--driver-mode=g++"}, 149 {"clang-gcc", nullptr}, 150 {"clang-cl", "--driver-mode=cl"}, 151 {"cc", nullptr}, 152 {"cpp", "--driver-mode=cpp"}, 153 {"cl", "--driver-mode=cl"}, 154 {"++", "--driver-mode=g++"}, 155 {"flang", "--driver-mode=flang"}, 156 }; 157 158 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) { 159 StringRef Suffix(DriverSuffixes[i].Suffix); 160 if (ProgName.endswith(Suffix)) { 161 Pos = ProgName.size() - Suffix.size(); 162 return &DriverSuffixes[i]; 163 } 164 } 165 return nullptr; 166 } 167 168 /// Normalize the program name from argv[0] by stripping the file extension if 169 /// present and lower-casing the string on Windows. 170 static std::string normalizeProgramName(llvm::StringRef Argv0) { 171 std::string ProgName = llvm::sys::path::stem(Argv0); 172 #ifdef _WIN32 173 // Transform to lowercase for case insensitive file systems. 174 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower); 175 #endif 176 return ProgName; 177 } 178 179 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) { 180 // Try to infer frontend type and default target from the program name by 181 // comparing it against DriverSuffixes in order. 182 183 // If there is a match, the function tries to identify a target as prefix. 184 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target 185 // prefix "x86_64-linux". If such a target prefix is found, it may be 186 // added via -target as implicit first argument. 187 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos); 188 189 if (!DS) { 190 // Try again after stripping any trailing version number: 191 // clang++3.5 -> clang++ 192 ProgName = ProgName.rtrim("0123456789."); 193 DS = FindDriverSuffix(ProgName, Pos); 194 } 195 196 if (!DS) { 197 // Try again after stripping trailing -component. 198 // clang++-tot -> clang++ 199 ProgName = ProgName.slice(0, ProgName.rfind('-')); 200 DS = FindDriverSuffix(ProgName, Pos); 201 } 202 return DS; 203 } 204 205 ParsedClangName 206 ToolChain::getTargetAndModeFromProgramName(StringRef PN) { 207 std::string ProgName = normalizeProgramName(PN); 208 size_t SuffixPos; 209 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos); 210 if (!DS) 211 return {}; 212 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix); 213 214 size_t LastComponent = ProgName.rfind('-', SuffixPos); 215 if (LastComponent == std::string::npos) 216 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag); 217 std::string ModeSuffix = ProgName.substr(LastComponent + 1, 218 SuffixEnd - LastComponent - 1); 219 220 // Infer target from the prefix. 221 StringRef Prefix(ProgName); 222 Prefix = Prefix.slice(0, LastComponent); 223 std::string IgnoredError; 224 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError); 225 return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered}; 226 } 227 228 StringRef ToolChain::getDefaultUniversalArchName() const { 229 // In universal driver terms, the arch name accepted by -arch isn't exactly 230 // the same as the ones that appear in the triple. Roughly speaking, this is 231 // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the 232 // only interesting special case is powerpc. 233 switch (Triple.getArch()) { 234 case llvm::Triple::ppc: 235 return "ppc"; 236 case llvm::Triple::ppc64: 237 return "ppc64"; 238 case llvm::Triple::ppc64le: 239 return "ppc64le"; 240 default: 241 return Triple.getArchName(); 242 } 243 } 244 245 std::string ToolChain::getInputFilename(const InputInfo &Input) const { 246 return Input.getFilename(); 247 } 248 249 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const { 250 return false; 251 } 252 253 Tool *ToolChain::getClang() const { 254 if (!Clang) 255 Clang.reset(new tools::Clang(*this)); 256 return Clang.get(); 257 } 258 259 Tool *ToolChain::getFlang() const { 260 if (!Flang) 261 Flang.reset(new tools::Flang(*this)); 262 return Flang.get(); 263 } 264 265 Tool *ToolChain::buildAssembler() const { 266 return new tools::ClangAs(*this); 267 } 268 269 Tool *ToolChain::buildLinker() const { 270 llvm_unreachable("Linking is not supported by this toolchain"); 271 } 272 273 Tool *ToolChain::getAssemble() const { 274 if (!Assemble) 275 Assemble.reset(buildAssembler()); 276 return Assemble.get(); 277 } 278 279 Tool *ToolChain::getClangAs() const { 280 if (!Assemble) 281 Assemble.reset(new tools::ClangAs(*this)); 282 return Assemble.get(); 283 } 284 285 Tool *ToolChain::getLink() const { 286 if (!Link) 287 Link.reset(buildLinker()); 288 return Link.get(); 289 } 290 291 Tool *ToolChain::getIfsMerge() const { 292 if (!IfsMerge) 293 IfsMerge.reset(new tools::ifstool::Merger(*this)); 294 return IfsMerge.get(); 295 } 296 297 Tool *ToolChain::getOffloadBundler() const { 298 if (!OffloadBundler) 299 OffloadBundler.reset(new tools::OffloadBundler(*this)); 300 return OffloadBundler.get(); 301 } 302 303 Tool *ToolChain::getOffloadWrapper() const { 304 if (!OffloadWrapper) 305 OffloadWrapper.reset(new tools::OffloadWrapper(*this)); 306 return OffloadWrapper.get(); 307 } 308 309 Tool *ToolChain::getTool(Action::ActionClass AC) const { 310 switch (AC) { 311 case Action::AssembleJobClass: 312 return getAssemble(); 313 314 case Action::IfsMergeJobClass: 315 return getIfsMerge(); 316 317 case Action::LinkJobClass: 318 return getLink(); 319 320 case Action::InputClass: 321 case Action::BindArchClass: 322 case Action::OffloadClass: 323 case Action::LipoJobClass: 324 case Action::DsymutilJobClass: 325 case Action::VerifyDebugInfoJobClass: 326 llvm_unreachable("Invalid tool kind."); 327 328 case Action::CompileJobClass: 329 case Action::PrecompileJobClass: 330 case Action::HeaderModulePrecompileJobClass: 331 case Action::PreprocessJobClass: 332 case Action::AnalyzeJobClass: 333 case Action::MigrateJobClass: 334 case Action::VerifyPCHJobClass: 335 case Action::BackendJobClass: 336 return getClang(); 337 338 case Action::OffloadBundlingJobClass: 339 case Action::OffloadUnbundlingJobClass: 340 return getOffloadBundler(); 341 342 case Action::OffloadWrapperJobClass: 343 return getOffloadWrapper(); 344 } 345 346 llvm_unreachable("Invalid tool kind."); 347 } 348 349 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, 350 const ArgList &Args) { 351 const llvm::Triple &Triple = TC.getTriple(); 352 bool IsWindows = Triple.isOSWindows(); 353 354 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb) 355 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) 356 ? "armhf" 357 : "arm"; 358 359 // For historic reasons, Android library is using i686 instead of i386. 360 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid()) 361 return "i686"; 362 363 return llvm::Triple::getArchTypeName(TC.getArch()); 364 } 365 366 StringRef ToolChain::getOSLibName() const { 367 switch (Triple.getOS()) { 368 case llvm::Triple::FreeBSD: 369 return "freebsd"; 370 case llvm::Triple::NetBSD: 371 return "netbsd"; 372 case llvm::Triple::OpenBSD: 373 return "openbsd"; 374 case llvm::Triple::Solaris: 375 return "sunos"; 376 default: 377 return getOS(); 378 } 379 } 380 381 std::string ToolChain::getCompilerRTPath() const { 382 SmallString<128> Path(getDriver().ResourceDir); 383 if (Triple.isOSUnknown()) { 384 llvm::sys::path::append(Path, "lib"); 385 } else { 386 llvm::sys::path::append(Path, "lib", getOSLibName()); 387 } 388 return Path.str(); 389 } 390 391 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component, 392 FileType Type) const { 393 const llvm::Triple &TT = getTriple(); 394 bool IsITANMSVCWindows = 395 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment(); 396 397 const char *Prefix = 398 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib"; 399 const char *Suffix; 400 switch (Type) { 401 case ToolChain::FT_Object: 402 Suffix = IsITANMSVCWindows ? ".obj" : ".o"; 403 break; 404 case ToolChain::FT_Static: 405 Suffix = IsITANMSVCWindows ? ".lib" : ".a"; 406 break; 407 case ToolChain::FT_Shared: 408 Suffix = Triple.isOSWindows() 409 ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib") 410 : ".so"; 411 break; 412 } 413 414 for (const auto &LibPath : getLibraryPaths()) { 415 SmallString<128> P(LibPath); 416 llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix); 417 if (getVFS().exists(P)) 418 return P.str(); 419 } 420 421 StringRef Arch = getArchNameForCompilerRTLib(*this, Args); 422 const char *Env = TT.isAndroid() ? "-android" : ""; 423 SmallString<128> Path(getCompilerRTPath()); 424 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" + 425 Arch + Env + Suffix); 426 return Path.str(); 427 } 428 429 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args, 430 StringRef Component, 431 FileType Type) const { 432 return Args.MakeArgString(getCompilerRT(Args, Component, Type)); 433 } 434 435 436 Optional<std::string> ToolChain::getRuntimePath() const { 437 SmallString<128> P; 438 439 // First try the triple passed to driver as --target=<triple>. 440 P.assign(D.ResourceDir); 441 llvm::sys::path::append(P, "lib", D.getTargetTriple()); 442 if (getVFS().exists(P)) 443 return llvm::Optional<std::string>(P.str()); 444 445 // Second try the normalized triple. 446 P.assign(D.ResourceDir); 447 llvm::sys::path::append(P, "lib", Triple.str()); 448 if (getVFS().exists(P)) 449 return llvm::Optional<std::string>(P.str()); 450 451 return None; 452 } 453 454 Optional<std::string> ToolChain::getCXXStdlibPath() const { 455 SmallString<128> P; 456 457 // First try the triple passed to driver as --target=<triple>. 458 P.assign(D.Dir); 459 llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++"); 460 if (getVFS().exists(P)) 461 return llvm::Optional<std::string>(P.str()); 462 463 // Second try the normalized triple. 464 P.assign(D.Dir); 465 llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++"); 466 if (getVFS().exists(P)) 467 return llvm::Optional<std::string>(P.str()); 468 469 return None; 470 } 471 472 std::string ToolChain::getArchSpecificLibPath() const { 473 SmallString<128> Path(getDriver().ResourceDir); 474 llvm::sys::path::append(Path, "lib", getOSLibName(), 475 llvm::Triple::getArchTypeName(getArch())); 476 return Path.str(); 477 } 478 479 bool ToolChain::needsProfileRT(const ArgList &Args) { 480 if (Args.hasArg(options::OPT_noprofilelib)) 481 return false; 482 483 if (needsGCovInstrumentation(Args) || 484 Args.hasArg(options::OPT_fprofile_generate) || 485 Args.hasArg(options::OPT_fprofile_generate_EQ) || 486 Args.hasArg(options::OPT_fcs_profile_generate) || 487 Args.hasArg(options::OPT_fcs_profile_generate_EQ) || 488 Args.hasArg(options::OPT_fprofile_instr_generate) || 489 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) || 490 Args.hasArg(options::OPT_fcreate_profile) || 491 Args.hasArg(options::OPT_forder_file_instrumentation)) 492 return true; 493 494 return false; 495 } 496 497 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) { 498 return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, 499 false) || 500 Args.hasArg(options::OPT_coverage); 501 } 502 503 Tool *ToolChain::SelectTool(const JobAction &JA) const { 504 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang(); 505 if (getDriver().ShouldUseClangCompiler(JA)) return getClang(); 506 Action::ActionClass AC = JA.getKind(); 507 if (AC == Action::AssembleJobClass && useIntegratedAs()) 508 return getClangAs(); 509 return getTool(AC); 510 } 511 512 std::string ToolChain::GetFilePath(const char *Name) const { 513 return D.GetFilePath(Name, *this); 514 } 515 516 std::string ToolChain::GetProgramPath(const char *Name) const { 517 return D.GetProgramPath(Name, *this); 518 } 519 520 std::string ToolChain::GetLinkerPath() const { 521 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ); 522 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER; 523 524 if (llvm::sys::path::is_absolute(UseLinker)) { 525 // If we're passed what looks like an absolute path, don't attempt to 526 // second-guess that. 527 if (llvm::sys::fs::can_execute(UseLinker)) 528 return UseLinker; 529 } else if (UseLinker.empty() || UseLinker == "ld") { 530 // If we're passed -fuse-ld= with no argument, or with the argument ld, 531 // then use whatever the default system linker is. 532 return GetProgramPath(getDefaultLinker()); 533 } else { 534 llvm::SmallString<8> LinkerName; 535 if (Triple.isOSDarwin()) 536 LinkerName.append("ld64."); 537 else 538 LinkerName.append("ld."); 539 LinkerName.append(UseLinker); 540 541 std::string LinkerPath(GetProgramPath(LinkerName.c_str())); 542 if (llvm::sys::fs::can_execute(LinkerPath)) 543 return LinkerPath; 544 } 545 546 if (A) 547 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); 548 549 return GetProgramPath(getDefaultLinker()); 550 } 551 552 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { 553 types::ID id = types::lookupTypeForExtension(Ext); 554 555 // Flang always runs the preprocessor and has no notion of "preprocessed 556 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating 557 // them differently. 558 if (D.IsFlangMode() && id == types::TY_PP_Fortran) 559 id = types::TY_Fortran; 560 561 return id; 562 } 563 564 bool ToolChain::HasNativeLLVMSupport() const { 565 return false; 566 } 567 568 bool ToolChain::isCrossCompiling() const { 569 llvm::Triple HostTriple(LLVM_HOST_TRIPLE); 570 switch (HostTriple.getArch()) { 571 // The A32/T32/T16 instruction sets are not separate architectures in this 572 // context. 573 case llvm::Triple::arm: 574 case llvm::Triple::armeb: 575 case llvm::Triple::thumb: 576 case llvm::Triple::thumbeb: 577 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb && 578 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb; 579 default: 580 return HostTriple.getArch() != getArch(); 581 } 582 } 583 584 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { 585 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, 586 VersionTuple()); 587 } 588 589 llvm::ExceptionHandling 590 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const { 591 return llvm::ExceptionHandling::None; 592 } 593 594 bool ToolChain::isThreadModelSupported(const StringRef Model) const { 595 if (Model == "single") { 596 // FIXME: 'single' is only supported on ARM and WebAssembly so far. 597 return Triple.getArch() == llvm::Triple::arm || 598 Triple.getArch() == llvm::Triple::armeb || 599 Triple.getArch() == llvm::Triple::thumb || 600 Triple.getArch() == llvm::Triple::thumbeb || 601 Triple.getArch() == llvm::Triple::wasm32 || 602 Triple.getArch() == llvm::Triple::wasm64; 603 } else if (Model == "posix") 604 return true; 605 606 return false; 607 } 608 609 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, 610 types::ID InputType) const { 611 switch (getTriple().getArch()) { 612 default: 613 return getTripleString(); 614 615 case llvm::Triple::x86_64: { 616 llvm::Triple Triple = getTriple(); 617 if (!Triple.isOSBinFormatMachO()) 618 return getTripleString(); 619 620 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { 621 // x86_64h goes in the triple. Other -march options just use the 622 // vanilla triple we already have. 623 StringRef MArch = A->getValue(); 624 if (MArch == "x86_64h") 625 Triple.setArchName(MArch); 626 } 627 return Triple.getTriple(); 628 } 629 case llvm::Triple::aarch64: { 630 llvm::Triple Triple = getTriple(); 631 if (!Triple.isOSBinFormatMachO()) 632 return getTripleString(); 633 634 // FIXME: older versions of ld64 expect the "arm64" component in the actual 635 // triple string and query it to determine whether an LTO file can be 636 // handled. Remove this when we don't care any more. 637 Triple.setArchName("arm64"); 638 return Triple.getTriple(); 639 } 640 case llvm::Triple::arm: 641 case llvm::Triple::armeb: 642 case llvm::Triple::thumb: 643 case llvm::Triple::thumbeb: { 644 // FIXME: Factor into subclasses. 645 llvm::Triple Triple = getTriple(); 646 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb || 647 getTriple().getArch() == llvm::Triple::thumbeb; 648 649 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 650 // '-mbig-endian'/'-EB'. 651 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 652 options::OPT_mbig_endian)) { 653 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian); 654 } 655 656 // Thumb2 is the default for V7 on Darwin. 657 // 658 // FIXME: Thumb should just be another -target-feaure, not in the triple. 659 StringRef MCPU, MArch; 660 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 661 MCPU = A->getValue(); 662 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 663 MArch = A->getValue(); 664 std::string CPU = 665 Triple.isOSBinFormatMachO() 666 ? tools::arm::getARMCPUForMArch(MArch, Triple).str() 667 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple); 668 StringRef Suffix = 669 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple); 670 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M; 671 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 && 672 getTriple().isOSBinFormatMachO()); 673 // FIXME: this is invalid for WindowsCE 674 if (getTriple().isOSWindows()) 675 ThumbDefault = true; 676 std::string ArchName; 677 if (IsBigEndian) 678 ArchName = "armeb"; 679 else 680 ArchName = "arm"; 681 682 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for 683 // M-Class CPUs/architecture variants, which is not supported. 684 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb, 685 options::OPT_mno_thumb, ThumbDefault); 686 if (IsMProfile && ARMModeRequested) { 687 if (!MCPU.empty()) 688 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM"; 689 else 690 getDriver().Diag(diag::err_arch_unsupported_isa) 691 << tools::arm::getARMArch(MArch, getTriple()) << "ARM"; 692 } 693 694 // Check to see if an explicit choice to use thumb has been made via 695 // -mthumb. For assembler files we must check for -mthumb in the options 696 // passed to the assembler via -Wa or -Xassembler. 697 bool IsThumb = false; 698 if (InputType != types::TY_PP_Asm) 699 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, 700 ThumbDefault); 701 else { 702 // Ideally we would check for these flags in 703 // CollectArgsForIntegratedAssembler but we can't change the ArchName at 704 // that point. There is no assembler equivalent of -mno-thumb, -marm, or 705 // -mno-arm. 706 for (const auto *A : 707 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) { 708 for (StringRef Value : A->getValues()) { 709 if (Value == "-mthumb") 710 IsThumb = true; 711 } 712 } 713 } 714 // Assembly files should start in ARM mode, unless arch is M-profile, or 715 // -mthumb has been passed explicitly to the assembler. Windows is always 716 // thumb. 717 if (IsThumb || IsMProfile || getTriple().isOSWindows()) { 718 if (IsBigEndian) 719 ArchName = "thumbeb"; 720 else 721 ArchName = "thumb"; 722 } 723 Triple.setArchName(ArchName + Suffix.str()); 724 725 return Triple.getTriple(); 726 } 727 } 728 } 729 730 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, 731 types::ID InputType) const { 732 return ComputeLLVMTriple(Args, InputType); 733 } 734 735 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 736 ArgStringList &CC1Args) const { 737 // Each toolchain should provide the appropriate include flags. 738 } 739 740 void ToolChain::addClangTargetOptions( 741 const ArgList &DriverArgs, ArgStringList &CC1Args, 742 Action::OffloadKind DeviceOffloadKind) const {} 743 744 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {} 745 746 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args, 747 llvm::opt::ArgStringList &CmdArgs) const { 748 if (!needsProfileRT(Args)) return; 749 750 CmdArgs.push_back(getCompilerRTArgString(Args, "profile")); 751 } 752 753 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( 754 const ArgList &Args) const { 755 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ); 756 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB; 757 758 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB! 759 if (LibName == "compiler-rt") 760 return ToolChain::RLT_CompilerRT; 761 else if (LibName == "libgcc") 762 return ToolChain::RLT_Libgcc; 763 else if (LibName == "platform") 764 return GetDefaultRuntimeLibType(); 765 766 if (A) 767 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args); 768 769 return GetDefaultRuntimeLibType(); 770 } 771 772 ToolChain::UnwindLibType ToolChain::GetUnwindLibType( 773 const ArgList &Args) const { 774 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ); 775 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB; 776 777 if (LibName == "none") 778 return ToolChain::UNW_None; 779 else if (LibName == "platform" || LibName == "") { 780 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args); 781 if (RtLibType == ToolChain::RLT_CompilerRT) 782 return ToolChain::UNW_None; 783 else if (RtLibType == ToolChain::RLT_Libgcc) 784 return ToolChain::UNW_Libgcc; 785 } else if (LibName == "libunwind") { 786 if (GetRuntimeLibType(Args) == RLT_Libgcc) 787 getDriver().Diag(diag::err_drv_incompatible_unwindlib); 788 return ToolChain::UNW_CompilerRT; 789 } else if (LibName == "libgcc") 790 return ToolChain::UNW_Libgcc; 791 792 if (A) 793 getDriver().Diag(diag::err_drv_invalid_unwindlib_name) 794 << A->getAsString(Args); 795 796 return GetDefaultUnwindLibType(); 797 } 798 799 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ 800 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 801 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB; 802 803 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB! 804 if (LibName == "libc++") 805 return ToolChain::CST_Libcxx; 806 else if (LibName == "libstdc++") 807 return ToolChain::CST_Libstdcxx; 808 else if (LibName == "platform") 809 return GetDefaultCXXStdlibType(); 810 811 if (A) 812 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 813 814 return GetDefaultCXXStdlibType(); 815 } 816 817 /// Utility function to add a system include directory to CC1 arguments. 818 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, 819 ArgStringList &CC1Args, 820 const Twine &Path) { 821 CC1Args.push_back("-internal-isystem"); 822 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 823 } 824 825 /// Utility function to add a system include directory with extern "C" 826 /// semantics to CC1 arguments. 827 /// 828 /// Note that this should be used rarely, and only for directories that 829 /// historically and for legacy reasons are treated as having implicit extern 830 /// "C" semantics. These semantics are *ignored* by and large today, but its 831 /// important to preserve the preprocessor changes resulting from the 832 /// classification. 833 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, 834 ArgStringList &CC1Args, 835 const Twine &Path) { 836 CC1Args.push_back("-internal-externc-isystem"); 837 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 838 } 839 840 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs, 841 ArgStringList &CC1Args, 842 const Twine &Path) { 843 if (llvm::sys::fs::exists(Path)) 844 addExternCSystemInclude(DriverArgs, CC1Args, Path); 845 } 846 847 /// Utility function to add a list of system include directories to CC1. 848 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, 849 ArgStringList &CC1Args, 850 ArrayRef<StringRef> Paths) { 851 for (const auto Path : Paths) { 852 CC1Args.push_back("-internal-isystem"); 853 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 854 } 855 } 856 857 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 858 ArgStringList &CC1Args) const { 859 // Header search paths should be handled by each of the subclasses. 860 // Historically, they have not been, and instead have been handled inside of 861 // the CC1-layer frontend. As the logic is hoisted out, this generic function 862 // will slowly stop being called. 863 // 864 // While it is being called, replicate a bit of a hack to propagate the 865 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ 866 // header search paths with it. Once all systems are overriding this 867 // function, the CC1 flag and this line can be removed. 868 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); 869 } 870 871 void ToolChain::AddClangCXXStdlibIsystemArgs( 872 const llvm::opt::ArgList &DriverArgs, 873 llvm::opt::ArgStringList &CC1Args) const { 874 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem); 875 if (!DriverArgs.hasArg(options::OPT_nostdincxx)) 876 for (const auto &P : 877 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem)) 878 addSystemInclude(DriverArgs, CC1Args, P); 879 } 880 881 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const { 882 return getDriver().CCCIsCXX() && 883 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs, 884 options::OPT_nostdlibxx); 885 } 886 887 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, 888 ArgStringList &CmdArgs) const { 889 assert(!Args.hasArg(options::OPT_nostdlibxx) && 890 "should not have called this"); 891 CXXStdlibType Type = GetCXXStdlibType(Args); 892 893 switch (Type) { 894 case ToolChain::CST_Libcxx: 895 CmdArgs.push_back("-lc++"); 896 break; 897 898 case ToolChain::CST_Libstdcxx: 899 CmdArgs.push_back("-lstdc++"); 900 break; 901 } 902 } 903 904 void ToolChain::AddFilePathLibArgs(const ArgList &Args, 905 ArgStringList &CmdArgs) const { 906 for (const auto &LibPath : getFilePaths()) 907 if(LibPath.length() > 0) 908 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath)); 909 } 910 911 void ToolChain::AddCCKextLibArgs(const ArgList &Args, 912 ArgStringList &CmdArgs) const { 913 CmdArgs.push_back("-lcc_kext"); 914 } 915 916 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args, 917 ArgStringList &CmdArgs) const { 918 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed 919 // (to keep the linker options consistent with gcc and clang itself). 920 if (!isOptimizationLevelFast(Args)) { 921 // Check if -ffast-math or -funsafe-math. 922 Arg *A = 923 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, 924 options::OPT_funsafe_math_optimizations, 925 options::OPT_fno_unsafe_math_optimizations); 926 927 if (!A || A->getOption().getID() == options::OPT_fno_fast_math || 928 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) 929 return false; 930 } 931 // If crtfastmath.o exists add it to the arguments. 932 std::string Path = GetFilePath("crtfastmath.o"); 933 if (Path == "crtfastmath.o") // Not found. 934 return false; 935 936 CmdArgs.push_back(Args.MakeArgString(Path)); 937 return true; 938 } 939 940 SanitizerMask ToolChain::getSupportedSanitizers() const { 941 // Return sanitizers which don't require runtime support and are not 942 // platform dependent. 943 944 SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr & 945 ~SanitizerKind::Function) | 946 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) | 947 SanitizerKind::CFICastStrict | 948 SanitizerKind::FloatDivideByZero | 949 SanitizerKind::UnsignedIntegerOverflow | 950 SanitizerKind::ImplicitConversion | 951 SanitizerKind::Nullability | SanitizerKind::LocalBounds; 952 if (getTriple().getArch() == llvm::Triple::x86 || 953 getTriple().getArch() == llvm::Triple::x86_64 || 954 getTriple().getArch() == llvm::Triple::arm || 955 getTriple().getArch() == llvm::Triple::aarch64 || 956 getTriple().getArch() == llvm::Triple::wasm32 || 957 getTriple().getArch() == llvm::Triple::wasm64) 958 Res |= SanitizerKind::CFIICall; 959 if (getTriple().getArch() == llvm::Triple::x86_64 || 960 getTriple().getArch() == llvm::Triple::aarch64) 961 Res |= SanitizerKind::ShadowCallStack; 962 if (getTriple().getArch() == llvm::Triple::aarch64 || 963 getTriple().getArch() == llvm::Triple::aarch64_be) 964 Res |= SanitizerKind::MemTag; 965 return Res; 966 } 967 968 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, 969 ArgStringList &CC1Args) const {} 970 971 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs, 972 ArgStringList &CC1Args) const {} 973 974 static VersionTuple separateMSVCFullVersion(unsigned Version) { 975 if (Version < 100) 976 return VersionTuple(Version); 977 978 if (Version < 10000) 979 return VersionTuple(Version / 100, Version % 100); 980 981 unsigned Build = 0, Factor = 1; 982 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10) 983 Build = Build + (Version % 10) * Factor; 984 return VersionTuple(Version / 100, Version % 100, Build); 985 } 986 987 VersionTuple 988 ToolChain::computeMSVCVersion(const Driver *D, 989 const llvm::opt::ArgList &Args) const { 990 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version); 991 const Arg *MSCompatibilityVersion = 992 Args.getLastArg(options::OPT_fms_compatibility_version); 993 994 if (MSCVersion && MSCompatibilityVersion) { 995 if (D) 996 D->Diag(diag::err_drv_argument_not_allowed_with) 997 << MSCVersion->getAsString(Args) 998 << MSCompatibilityVersion->getAsString(Args); 999 return VersionTuple(); 1000 } 1001 1002 if (MSCompatibilityVersion) { 1003 VersionTuple MSVT; 1004 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) { 1005 if (D) 1006 D->Diag(diag::err_drv_invalid_value) 1007 << MSCompatibilityVersion->getAsString(Args) 1008 << MSCompatibilityVersion->getValue(); 1009 } else { 1010 return MSVT; 1011 } 1012 } 1013 1014 if (MSCVersion) { 1015 unsigned Version = 0; 1016 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) { 1017 if (D) 1018 D->Diag(diag::err_drv_invalid_value) 1019 << MSCVersion->getAsString(Args) << MSCVersion->getValue(); 1020 } else { 1021 return separateMSVCFullVersion(Version); 1022 } 1023 } 1024 1025 return VersionTuple(); 1026 } 1027 1028 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs( 1029 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, 1030 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const { 1031 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 1032 const OptTable &Opts = getDriver().getOpts(); 1033 bool Modified = false; 1034 1035 // Handle -Xopenmp-target flags 1036 for (auto *A : Args) { 1037 // Exclude flags which may only apply to the host toolchain. 1038 // Do not exclude flags when the host triple (AuxTriple) 1039 // matches the current toolchain triple. If it is not present 1040 // at all, target and host share a toolchain. 1041 if (A->getOption().matches(options::OPT_m_Group)) { 1042 if (SameTripleAsHost) 1043 DAL->append(A); 1044 else 1045 Modified = true; 1046 continue; 1047 } 1048 1049 unsigned Index; 1050 unsigned Prev; 1051 bool XOpenMPTargetNoTriple = 1052 A->getOption().matches(options::OPT_Xopenmp_target); 1053 1054 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) { 1055 // Passing device args: -Xopenmp-target=<triple> -opt=val. 1056 if (A->getValue(0) == getTripleString()) 1057 Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); 1058 else 1059 continue; 1060 } else if (XOpenMPTargetNoTriple) { 1061 // Passing device args: -Xopenmp-target -opt=val. 1062 Index = Args.getBaseArgs().MakeIndex(A->getValue(0)); 1063 } else { 1064 DAL->append(A); 1065 continue; 1066 } 1067 1068 // Parse the argument to -Xopenmp-target. 1069 Prev = Index; 1070 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index)); 1071 if (!XOpenMPTargetArg || Index > Prev + 1) { 1072 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args) 1073 << A->getAsString(Args); 1074 continue; 1075 } 1076 if (XOpenMPTargetNoTriple && XOpenMPTargetArg && 1077 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) { 1078 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple); 1079 continue; 1080 } 1081 XOpenMPTargetArg->setBaseArg(A); 1082 A = XOpenMPTargetArg.release(); 1083 AllocatedArgs.push_back(A); 1084 DAL->append(A); 1085 Modified = true; 1086 } 1087 1088 if (Modified) 1089 return DAL; 1090 1091 delete DAL; 1092 return nullptr; 1093 } 1094