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 "ToolChains/Arch/ARM.h" 11 #include "ToolChains/Clang.h" 12 #include "ToolChains/Flang.h" 13 #include "ToolChains/InterfaceStubs.h" 14 #include "clang/Basic/ObjCRuntime.h" 15 #include "clang/Basic/Sanitizers.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/InputInfo.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/MC/TargetRegistry.h" 33 #include "llvm/Option/Arg.h" 34 #include "llvm/Option/ArgList.h" 35 #include "llvm/Option/OptTable.h" 36 #include "llvm/Option/Option.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/FileSystem.h" 39 #include "llvm/Support/Path.h" 40 #include "llvm/Support/TargetParser.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 std::string RuntimePath = getRuntimePath(); 79 if (getVFS().exists(RuntimePath)) 80 getLibraryPaths().push_back(RuntimePath); 81 82 std::string StdlibPath = getStdlibPath(); 83 if (getVFS().exists(StdlibPath)) 84 getFilePaths().push_back(StdlibPath); 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 SanitizerArgs 118 ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const { 119 SanitizerArgs SanArgs(*this, JobArgs, !SanitizerArgsChecked); 120 SanitizerArgsChecked = true; 121 return SanArgs; 122 } 123 124 const XRayArgs& ToolChain::getXRayArgs() const { 125 if (!XRayArguments.get()) 126 XRayArguments.reset(new XRayArgs(*this, Args)); 127 return *XRayArguments.get(); 128 } 129 130 namespace { 131 132 struct DriverSuffix { 133 const char *Suffix; 134 const char *ModeFlag; 135 }; 136 137 } // namespace 138 139 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) { 140 // A list of known driver suffixes. Suffixes are compared against the 141 // program name in order. If there is a match, the frontend type is updated as 142 // necessary by applying the ModeFlag. 143 static const DriverSuffix DriverSuffixes[] = { 144 {"clang", nullptr}, 145 {"clang++", "--driver-mode=g++"}, 146 {"clang-c++", "--driver-mode=g++"}, 147 {"clang-cc", nullptr}, 148 {"clang-cpp", "--driver-mode=cpp"}, 149 {"clang-g++", "--driver-mode=g++"}, 150 {"clang-gcc", nullptr}, 151 {"clang-cl", "--driver-mode=cl"}, 152 {"cc", nullptr}, 153 {"cpp", "--driver-mode=cpp"}, 154 {"cl", "--driver-mode=cl"}, 155 {"++", "--driver-mode=g++"}, 156 {"flang", "--driver-mode=flang"}, 157 }; 158 159 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) { 160 StringRef Suffix(DriverSuffixes[i].Suffix); 161 if (ProgName.endswith(Suffix)) { 162 Pos = ProgName.size() - Suffix.size(); 163 return &DriverSuffixes[i]; 164 } 165 } 166 return nullptr; 167 } 168 169 /// Normalize the program name from argv[0] by stripping the file extension if 170 /// present and lower-casing the string on Windows. 171 static std::string normalizeProgramName(llvm::StringRef Argv0) { 172 std::string ProgName = std::string(llvm::sys::path::stem(Argv0)); 173 if (is_style_windows(llvm::sys::path::Style::native)) { 174 // Transform to lowercase for case insensitive file systems. 175 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), 176 ::tolower); 177 } 178 return ProgName; 179 } 180 181 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) { 182 // Try to infer frontend type and default target from the program name by 183 // comparing it against DriverSuffixes in order. 184 185 // If there is a match, the function tries to identify a target as prefix. 186 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target 187 // prefix "x86_64-linux". If such a target prefix is found, it may be 188 // added via -target as implicit first argument. 189 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos); 190 191 if (!DS) { 192 // Try again after stripping any trailing version number: 193 // clang++3.5 -> clang++ 194 ProgName = ProgName.rtrim("0123456789."); 195 DS = FindDriverSuffix(ProgName, Pos); 196 } 197 198 if (!DS) { 199 // Try again after stripping trailing -component. 200 // clang++-tot -> clang++ 201 ProgName = ProgName.slice(0, ProgName.rfind('-')); 202 DS = FindDriverSuffix(ProgName, Pos); 203 } 204 return DS; 205 } 206 207 ParsedClangName 208 ToolChain::getTargetAndModeFromProgramName(StringRef PN) { 209 std::string ProgName = normalizeProgramName(PN); 210 size_t SuffixPos; 211 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos); 212 if (!DS) 213 return {}; 214 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix); 215 216 size_t LastComponent = ProgName.rfind('-', SuffixPos); 217 if (LastComponent == std::string::npos) 218 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag); 219 std::string ModeSuffix = ProgName.substr(LastComponent + 1, 220 SuffixEnd - LastComponent - 1); 221 222 // Infer target from the prefix. 223 StringRef Prefix(ProgName); 224 Prefix = Prefix.slice(0, LastComponent); 225 std::string IgnoredError; 226 bool IsRegistered = 227 llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError); 228 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag, 229 IsRegistered}; 230 } 231 232 StringRef ToolChain::getDefaultUniversalArchName() const { 233 // In universal driver terms, the arch name accepted by -arch isn't exactly 234 // the same as the ones that appear in the triple. Roughly speaking, this is 235 // an inverse of the darwin::getArchTypeForDarwinArchName() function. 236 switch (Triple.getArch()) { 237 case llvm::Triple::aarch64: { 238 if (getTriple().isArm64e()) 239 return "arm64e"; 240 return "arm64"; 241 } 242 case llvm::Triple::aarch64_32: 243 return "arm64_32"; 244 case llvm::Triple::ppc: 245 return "ppc"; 246 case llvm::Triple::ppcle: 247 return "ppcle"; 248 case llvm::Triple::ppc64: 249 return "ppc64"; 250 case llvm::Triple::ppc64le: 251 return "ppc64le"; 252 default: 253 return Triple.getArchName(); 254 } 255 } 256 257 std::string ToolChain::getInputFilename(const InputInfo &Input) const { 258 return Input.getFilename(); 259 } 260 261 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const { 262 return false; 263 } 264 265 Tool *ToolChain::getClang() const { 266 if (!Clang) 267 Clang.reset(new tools::Clang(*this)); 268 return Clang.get(); 269 } 270 271 Tool *ToolChain::getFlang() const { 272 if (!Flang) 273 Flang.reset(new tools::Flang(*this)); 274 return Flang.get(); 275 } 276 277 Tool *ToolChain::buildAssembler() const { 278 return new tools::ClangAs(*this); 279 } 280 281 Tool *ToolChain::buildLinker() const { 282 llvm_unreachable("Linking is not supported by this toolchain"); 283 } 284 285 Tool *ToolChain::buildStaticLibTool() const { 286 llvm_unreachable("Creating static lib is not supported by this toolchain"); 287 } 288 289 Tool *ToolChain::getAssemble() const { 290 if (!Assemble) 291 Assemble.reset(buildAssembler()); 292 return Assemble.get(); 293 } 294 295 Tool *ToolChain::getClangAs() const { 296 if (!Assemble) 297 Assemble.reset(new tools::ClangAs(*this)); 298 return Assemble.get(); 299 } 300 301 Tool *ToolChain::getLink() const { 302 if (!Link) 303 Link.reset(buildLinker()); 304 return Link.get(); 305 } 306 307 Tool *ToolChain::getStaticLibTool() const { 308 if (!StaticLibTool) 309 StaticLibTool.reset(buildStaticLibTool()); 310 return StaticLibTool.get(); 311 } 312 313 Tool *ToolChain::getIfsMerge() const { 314 if (!IfsMerge) 315 IfsMerge.reset(new tools::ifstool::Merger(*this)); 316 return IfsMerge.get(); 317 } 318 319 Tool *ToolChain::getOffloadBundler() const { 320 if (!OffloadBundler) 321 OffloadBundler.reset(new tools::OffloadBundler(*this)); 322 return OffloadBundler.get(); 323 } 324 325 Tool *ToolChain::getOffloadWrapper() const { 326 if (!OffloadWrapper) 327 OffloadWrapper.reset(new tools::OffloadWrapper(*this)); 328 return OffloadWrapper.get(); 329 } 330 331 Tool *ToolChain::getTool(Action::ActionClass AC) const { 332 switch (AC) { 333 case Action::AssembleJobClass: 334 return getAssemble(); 335 336 case Action::IfsMergeJobClass: 337 return getIfsMerge(); 338 339 case Action::LinkJobClass: 340 return getLink(); 341 342 case Action::StaticLibJobClass: 343 return getStaticLibTool(); 344 345 case Action::InputClass: 346 case Action::BindArchClass: 347 case Action::OffloadClass: 348 case Action::LipoJobClass: 349 case Action::DsymutilJobClass: 350 case Action::VerifyDebugInfoJobClass: 351 llvm_unreachable("Invalid tool kind."); 352 353 case Action::CompileJobClass: 354 case Action::PrecompileJobClass: 355 case Action::HeaderModulePrecompileJobClass: 356 case Action::PreprocessJobClass: 357 case Action::AnalyzeJobClass: 358 case Action::MigrateJobClass: 359 case Action::VerifyPCHJobClass: 360 case Action::BackendJobClass: 361 return getClang(); 362 363 case Action::OffloadBundlingJobClass: 364 case Action::OffloadUnbundlingJobClass: 365 return getOffloadBundler(); 366 367 case Action::OffloadWrapperJobClass: 368 return getOffloadWrapper(); 369 } 370 371 llvm_unreachable("Invalid tool kind."); 372 } 373 374 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, 375 const ArgList &Args) { 376 const llvm::Triple &Triple = TC.getTriple(); 377 bool IsWindows = Triple.isOSWindows(); 378 379 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb) 380 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) 381 ? "armhf" 382 : "arm"; 383 384 // For historic reasons, Android library is using i686 instead of i386. 385 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid()) 386 return "i686"; 387 388 if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32()) 389 return "x32"; 390 391 return llvm::Triple::getArchTypeName(TC.getArch()); 392 } 393 394 StringRef ToolChain::getOSLibName() const { 395 if (Triple.isOSDarwin()) 396 return "darwin"; 397 398 switch (Triple.getOS()) { 399 case llvm::Triple::FreeBSD: 400 return "freebsd"; 401 case llvm::Triple::NetBSD: 402 return "netbsd"; 403 case llvm::Triple::OpenBSD: 404 return "openbsd"; 405 case llvm::Triple::Solaris: 406 return "sunos"; 407 case llvm::Triple::AIX: 408 return "aix"; 409 default: 410 return getOS(); 411 } 412 } 413 414 std::string ToolChain::getCompilerRTPath() const { 415 SmallString<128> Path(getDriver().ResourceDir); 416 if (Triple.isOSUnknown()) { 417 llvm::sys::path::append(Path, "lib"); 418 } else { 419 llvm::sys::path::append(Path, "lib", getOSLibName()); 420 } 421 return std::string(Path.str()); 422 } 423 424 std::string ToolChain::getCompilerRTBasename(const ArgList &Args, 425 StringRef Component, 426 FileType Type) const { 427 std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type); 428 return llvm::sys::path::filename(CRTAbsolutePath).str(); 429 } 430 431 std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args, 432 StringRef Component, 433 FileType Type, 434 bool AddArch) const { 435 const llvm::Triple &TT = getTriple(); 436 bool IsITANMSVCWindows = 437 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment(); 438 439 const char *Prefix = 440 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib"; 441 const char *Suffix; 442 switch (Type) { 443 case ToolChain::FT_Object: 444 Suffix = IsITANMSVCWindows ? ".obj" : ".o"; 445 break; 446 case ToolChain::FT_Static: 447 Suffix = IsITANMSVCWindows ? ".lib" : ".a"; 448 break; 449 case ToolChain::FT_Shared: 450 Suffix = TT.isOSWindows() 451 ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib") 452 : ".so"; 453 break; 454 } 455 456 std::string ArchAndEnv; 457 if (AddArch) { 458 StringRef Arch = getArchNameForCompilerRTLib(*this, Args); 459 const char *Env = TT.isAndroid() ? "-android" : ""; 460 ArchAndEnv = ("-" + Arch + Env).str(); 461 } 462 return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str(); 463 } 464 465 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component, 466 FileType Type) const { 467 // Check for runtime files in the new layout without the architecture first. 468 std::string CRTBasename = 469 buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false); 470 for (const auto &LibPath : getLibraryPaths()) { 471 SmallString<128> P(LibPath); 472 llvm::sys::path::append(P, CRTBasename); 473 if (getVFS().exists(P)) 474 return std::string(P.str()); 475 } 476 477 // Fall back to the old expected compiler-rt name if the new one does not 478 // exist. 479 CRTBasename = 480 buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true); 481 SmallString<128> Path(getCompilerRTPath()); 482 llvm::sys::path::append(Path, CRTBasename); 483 return std::string(Path.str()); 484 } 485 486 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args, 487 StringRef Component, 488 FileType Type) const { 489 return Args.MakeArgString(getCompilerRT(Args, Component, Type)); 490 } 491 492 std::string ToolChain::getRuntimePath() const { 493 SmallString<128> P(D.ResourceDir); 494 llvm::sys::path::append(P, "lib", getTripleString()); 495 return std::string(P.str()); 496 } 497 498 std::string ToolChain::getStdlibPath() const { 499 SmallString<128> P(D.Dir); 500 llvm::sys::path::append(P, "..", "lib", getTripleString()); 501 return std::string(P.str()); 502 } 503 504 std::string ToolChain::getArchSpecificLibPath() const { 505 SmallString<128> Path(getDriver().ResourceDir); 506 llvm::sys::path::append(Path, "lib", getOSLibName(), 507 llvm::Triple::getArchTypeName(getArch())); 508 return std::string(Path.str()); 509 } 510 511 bool ToolChain::needsProfileRT(const ArgList &Args) { 512 if (Args.hasArg(options::OPT_noprofilelib)) 513 return false; 514 515 return Args.hasArg(options::OPT_fprofile_generate) || 516 Args.hasArg(options::OPT_fprofile_generate_EQ) || 517 Args.hasArg(options::OPT_fcs_profile_generate) || 518 Args.hasArg(options::OPT_fcs_profile_generate_EQ) || 519 Args.hasArg(options::OPT_fprofile_instr_generate) || 520 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) || 521 Args.hasArg(options::OPT_fcreate_profile) || 522 Args.hasArg(options::OPT_forder_file_instrumentation); 523 } 524 525 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) { 526 return Args.hasArg(options::OPT_coverage) || 527 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, 528 false); 529 } 530 531 Tool *ToolChain::SelectTool(const JobAction &JA) const { 532 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang(); 533 if (getDriver().ShouldUseClangCompiler(JA)) return getClang(); 534 Action::ActionClass AC = JA.getKind(); 535 if (AC == Action::AssembleJobClass && useIntegratedAs()) 536 return getClangAs(); 537 return getTool(AC); 538 } 539 540 std::string ToolChain::GetFilePath(const char *Name) const { 541 return D.GetFilePath(Name, *this); 542 } 543 544 std::string ToolChain::GetProgramPath(const char *Name) const { 545 return D.GetProgramPath(Name, *this); 546 } 547 548 std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD, 549 bool *LinkerIsLLDDarwinNew) const { 550 if (LinkerIsLLD) 551 *LinkerIsLLD = false; 552 if (LinkerIsLLDDarwinNew) 553 *LinkerIsLLDDarwinNew = false; 554 555 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is 556 // considered as the linker flavor, e.g. "bfd", "gold", or "lld". 557 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ); 558 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER; 559 560 // --ld-path= takes precedence over -fuse-ld= and specifies the executable 561 // name. -B, COMPILER_PATH and PATH and consulted if the value does not 562 // contain a path component separator. 563 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) { 564 std::string Path(A->getValue()); 565 if (!Path.empty()) { 566 if (llvm::sys::path::parent_path(Path).empty()) 567 Path = GetProgramPath(A->getValue()); 568 if (llvm::sys::fs::can_execute(Path)) 569 return std::string(Path); 570 } 571 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); 572 return GetProgramPath(getDefaultLinker()); 573 } 574 // If we're passed -fuse-ld= with no argument, or with the argument ld, 575 // then use whatever the default system linker is. 576 if (UseLinker.empty() || UseLinker == "ld") { 577 const char *DefaultLinker = getDefaultLinker(); 578 if (llvm::sys::path::is_absolute(DefaultLinker)) 579 return std::string(DefaultLinker); 580 else 581 return GetProgramPath(DefaultLinker); 582 } 583 584 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking 585 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64." 586 // to a relative path is surprising. This is more complex due to priorities 587 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead. 588 if (UseLinker.contains('/')) 589 getDriver().Diag(diag::warn_drv_fuse_ld_path); 590 591 if (llvm::sys::path::is_absolute(UseLinker)) { 592 // If we're passed what looks like an absolute path, don't attempt to 593 // second-guess that. 594 if (llvm::sys::fs::can_execute(UseLinker)) 595 return std::string(UseLinker); 596 } else { 597 llvm::SmallString<8> LinkerName; 598 if (Triple.isOSDarwin()) 599 LinkerName.append("ld64."); 600 else 601 LinkerName.append("ld."); 602 LinkerName.append(UseLinker); 603 604 std::string LinkerPath(GetProgramPath(LinkerName.c_str())); 605 if (llvm::sys::fs::can_execute(LinkerPath)) { 606 // FIXME: Remove LinkerIsLLDDarwinNew once there's only one MachO lld. 607 if (LinkerIsLLD) 608 *LinkerIsLLD = UseLinker == "lld" || UseLinker == "lld.darwinold"; 609 if (LinkerIsLLDDarwinNew) 610 *LinkerIsLLDDarwinNew = UseLinker == "lld"; 611 return LinkerPath; 612 } 613 } 614 615 if (A) 616 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); 617 618 return GetProgramPath(getDefaultLinker()); 619 } 620 621 std::string ToolChain::GetStaticLibToolPath() const { 622 // TODO: Add support for static lib archiving on Windows 623 if (Triple.isOSDarwin()) 624 return GetProgramPath("libtool"); 625 return GetProgramPath("llvm-ar"); 626 } 627 628 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { 629 types::ID id = types::lookupTypeForExtension(Ext); 630 631 // Flang always runs the preprocessor and has no notion of "preprocessed 632 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating 633 // them differently. 634 if (D.IsFlangMode() && id == types::TY_PP_Fortran) 635 id = types::TY_Fortran; 636 637 return id; 638 } 639 640 bool ToolChain::HasNativeLLVMSupport() const { 641 return false; 642 } 643 644 bool ToolChain::isCrossCompiling() const { 645 llvm::Triple HostTriple(LLVM_HOST_TRIPLE); 646 switch (HostTriple.getArch()) { 647 // The A32/T32/T16 instruction sets are not separate architectures in this 648 // context. 649 case llvm::Triple::arm: 650 case llvm::Triple::armeb: 651 case llvm::Triple::thumb: 652 case llvm::Triple::thumbeb: 653 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb && 654 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb; 655 default: 656 return HostTriple.getArch() != getArch(); 657 } 658 } 659 660 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { 661 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, 662 VersionTuple()); 663 } 664 665 llvm::ExceptionHandling 666 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const { 667 return llvm::ExceptionHandling::None; 668 } 669 670 bool ToolChain::isThreadModelSupported(const StringRef Model) const { 671 if (Model == "single") { 672 // FIXME: 'single' is only supported on ARM and WebAssembly so far. 673 return Triple.getArch() == llvm::Triple::arm || 674 Triple.getArch() == llvm::Triple::armeb || 675 Triple.getArch() == llvm::Triple::thumb || 676 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm(); 677 } else if (Model == "posix") 678 return true; 679 680 return false; 681 } 682 683 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, 684 types::ID InputType) const { 685 switch (getTriple().getArch()) { 686 default: 687 return getTripleString(); 688 689 case llvm::Triple::x86_64: { 690 llvm::Triple Triple = getTriple(); 691 if (!Triple.isOSBinFormatMachO()) 692 return getTripleString(); 693 694 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { 695 // x86_64h goes in the triple. Other -march options just use the 696 // vanilla triple we already have. 697 StringRef MArch = A->getValue(); 698 if (MArch == "x86_64h") 699 Triple.setArchName(MArch); 700 } 701 return Triple.getTriple(); 702 } 703 case llvm::Triple::aarch64: { 704 llvm::Triple Triple = getTriple(); 705 if (!Triple.isOSBinFormatMachO()) 706 return getTripleString(); 707 708 if (Triple.isArm64e()) 709 return getTripleString(); 710 711 // FIXME: older versions of ld64 expect the "arm64" component in the actual 712 // triple string and query it to determine whether an LTO file can be 713 // handled. Remove this when we don't care any more. 714 Triple.setArchName("arm64"); 715 return Triple.getTriple(); 716 } 717 case llvm::Triple::aarch64_32: 718 return getTripleString(); 719 case llvm::Triple::arm: 720 case llvm::Triple::armeb: 721 case llvm::Triple::thumb: 722 case llvm::Triple::thumbeb: { 723 llvm::Triple Triple = getTriple(); 724 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple); 725 tools::arm::setFloatABIInTriple(getDriver(), Args, Triple); 726 return Triple.getTriple(); 727 } 728 } 729 } 730 731 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, 732 types::ID InputType) const { 733 return ComputeLLVMTriple(Args, InputType); 734 } 735 736 std::string ToolChain::computeSysRoot() const { 737 return D.SysRoot; 738 } 739 740 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 741 ArgStringList &CC1Args) const { 742 // Each toolchain should provide the appropriate include flags. 743 } 744 745 void ToolChain::addClangTargetOptions( 746 const ArgList &DriverArgs, ArgStringList &CC1Args, 747 Action::OffloadKind DeviceOffloadKind) const {} 748 749 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {} 750 751 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args, 752 llvm::opt::ArgStringList &CmdArgs) const { 753 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args)) 754 return; 755 756 CmdArgs.push_back(getCompilerRTArgString(Args, "profile")); 757 } 758 759 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( 760 const ArgList &Args) const { 761 if (runtimeLibType) 762 return *runtimeLibType; 763 764 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ); 765 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB; 766 767 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB! 768 if (LibName == "compiler-rt") 769 runtimeLibType = ToolChain::RLT_CompilerRT; 770 else if (LibName == "libgcc") 771 runtimeLibType = ToolChain::RLT_Libgcc; 772 else if (LibName == "platform") 773 runtimeLibType = GetDefaultRuntimeLibType(); 774 else { 775 if (A) 776 getDriver().Diag(diag::err_drv_invalid_rtlib_name) 777 << A->getAsString(Args); 778 779 runtimeLibType = GetDefaultRuntimeLibType(); 780 } 781 782 return *runtimeLibType; 783 } 784 785 ToolChain::UnwindLibType ToolChain::GetUnwindLibType( 786 const ArgList &Args) const { 787 if (unwindLibType) 788 return *unwindLibType; 789 790 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ); 791 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB; 792 793 if (LibName == "none") 794 unwindLibType = ToolChain::UNW_None; 795 else if (LibName == "platform" || LibName == "") { 796 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args); 797 if (RtLibType == ToolChain::RLT_CompilerRT) { 798 if (getTriple().isAndroid() || getTriple().isOSAIX()) 799 unwindLibType = ToolChain::UNW_CompilerRT; 800 else 801 unwindLibType = ToolChain::UNW_None; 802 } else if (RtLibType == ToolChain::RLT_Libgcc) 803 unwindLibType = ToolChain::UNW_Libgcc; 804 } else if (LibName == "libunwind") { 805 if (GetRuntimeLibType(Args) == RLT_Libgcc) 806 getDriver().Diag(diag::err_drv_incompatible_unwindlib); 807 unwindLibType = ToolChain::UNW_CompilerRT; 808 } else if (LibName == "libgcc") 809 unwindLibType = ToolChain::UNW_Libgcc; 810 else { 811 if (A) 812 getDriver().Diag(diag::err_drv_invalid_unwindlib_name) 813 << A->getAsString(Args); 814 815 unwindLibType = GetDefaultUnwindLibType(); 816 } 817 818 return *unwindLibType; 819 } 820 821 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ 822 if (cxxStdlibType) 823 return *cxxStdlibType; 824 825 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 826 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB; 827 828 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB! 829 if (LibName == "libc++") 830 cxxStdlibType = ToolChain::CST_Libcxx; 831 else if (LibName == "libstdc++") 832 cxxStdlibType = ToolChain::CST_Libstdcxx; 833 else if (LibName == "platform") 834 cxxStdlibType = GetDefaultCXXStdlibType(); 835 else { 836 if (A) 837 getDriver().Diag(diag::err_drv_invalid_stdlib_name) 838 << A->getAsString(Args); 839 840 cxxStdlibType = GetDefaultCXXStdlibType(); 841 } 842 843 return *cxxStdlibType; 844 } 845 846 /// Utility function to add a system include directory to CC1 arguments. 847 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, 848 ArgStringList &CC1Args, 849 const Twine &Path) { 850 CC1Args.push_back("-internal-isystem"); 851 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 852 } 853 854 /// Utility function to add a system include directory with extern "C" 855 /// semantics to CC1 arguments. 856 /// 857 /// Note that this should be used rarely, and only for directories that 858 /// historically and for legacy reasons are treated as having implicit extern 859 /// "C" semantics. These semantics are *ignored* by and large today, but its 860 /// important to preserve the preprocessor changes resulting from the 861 /// classification. 862 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, 863 ArgStringList &CC1Args, 864 const Twine &Path) { 865 CC1Args.push_back("-internal-externc-isystem"); 866 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 867 } 868 869 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs, 870 ArgStringList &CC1Args, 871 const Twine &Path) { 872 if (llvm::sys::fs::exists(Path)) 873 addExternCSystemInclude(DriverArgs, CC1Args, Path); 874 } 875 876 /// Utility function to add a list of system include directories to CC1. 877 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, 878 ArgStringList &CC1Args, 879 ArrayRef<StringRef> Paths) { 880 for (const auto &Path : Paths) { 881 CC1Args.push_back("-internal-isystem"); 882 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 883 } 884 } 885 886 std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const { 887 std::error_code EC; 888 int MaxVersion = 0; 889 std::string MaxVersionString; 890 SmallString<128> Path(IncludePath); 891 llvm::sys::path::append(Path, "c++"); 892 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE; 893 !EC && LI != LE; LI = LI.increment(EC)) { 894 StringRef VersionText = llvm::sys::path::filename(LI->path()); 895 int Version; 896 if (VersionText[0] == 'v' && 897 !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) { 898 if (Version > MaxVersion) { 899 MaxVersion = Version; 900 MaxVersionString = std::string(VersionText); 901 } 902 } 903 } 904 if (!MaxVersion) 905 return ""; 906 return MaxVersionString; 907 } 908 909 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 910 ArgStringList &CC1Args) const { 911 // Header search paths should be handled by each of the subclasses. 912 // Historically, they have not been, and instead have been handled inside of 913 // the CC1-layer frontend. As the logic is hoisted out, this generic function 914 // will slowly stop being called. 915 // 916 // While it is being called, replicate a bit of a hack to propagate the 917 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ 918 // header search paths with it. Once all systems are overriding this 919 // function, the CC1 flag and this line can be removed. 920 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); 921 } 922 923 void ToolChain::AddClangCXXStdlibIsystemArgs( 924 const llvm::opt::ArgList &DriverArgs, 925 llvm::opt::ArgStringList &CC1Args) const { 926 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem); 927 if (!DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx, 928 options::OPT_nostdlibinc)) 929 for (const auto &P : 930 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem)) 931 addSystemInclude(DriverArgs, CC1Args, P); 932 } 933 934 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const { 935 return getDriver().CCCIsCXX() && 936 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs, 937 options::OPT_nostdlibxx); 938 } 939 940 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, 941 ArgStringList &CmdArgs) const { 942 assert(!Args.hasArg(options::OPT_nostdlibxx) && 943 "should not have called this"); 944 CXXStdlibType Type = GetCXXStdlibType(Args); 945 946 switch (Type) { 947 case ToolChain::CST_Libcxx: 948 CmdArgs.push_back("-lc++"); 949 break; 950 951 case ToolChain::CST_Libstdcxx: 952 CmdArgs.push_back("-lstdc++"); 953 break; 954 } 955 } 956 957 void ToolChain::AddFilePathLibArgs(const ArgList &Args, 958 ArgStringList &CmdArgs) const { 959 for (const auto &LibPath : getFilePaths()) 960 if(LibPath.length() > 0) 961 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath)); 962 } 963 964 void ToolChain::AddCCKextLibArgs(const ArgList &Args, 965 ArgStringList &CmdArgs) const { 966 CmdArgs.push_back("-lcc_kext"); 967 } 968 969 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args, 970 std::string &Path) const { 971 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed 972 // (to keep the linker options consistent with gcc and clang itself). 973 if (!isOptimizationLevelFast(Args)) { 974 // Check if -ffast-math or -funsafe-math. 975 Arg *A = 976 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, 977 options::OPT_funsafe_math_optimizations, 978 options::OPT_fno_unsafe_math_optimizations); 979 980 if (!A || A->getOption().getID() == options::OPT_fno_fast_math || 981 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) 982 return false; 983 } 984 // If crtfastmath.o exists add it to the arguments. 985 Path = GetFilePath("crtfastmath.o"); 986 return (Path != "crtfastmath.o"); // Not found. 987 } 988 989 bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args, 990 ArgStringList &CmdArgs) const { 991 std::string Path; 992 if (isFastMathRuntimeAvailable(Args, Path)) { 993 CmdArgs.push_back(Args.MakeArgString(Path)); 994 return true; 995 } 996 997 return false; 998 } 999 1000 SanitizerMask ToolChain::getSupportedSanitizers() const { 1001 // Return sanitizers which don't require runtime support and are not 1002 // platform dependent. 1003 1004 SanitizerMask Res = 1005 (SanitizerKind::Undefined & ~SanitizerKind::Vptr & 1006 ~SanitizerKind::Function) | 1007 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) | 1008 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero | 1009 SanitizerKind::UnsignedIntegerOverflow | 1010 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion | 1011 SanitizerKind::Nullability | SanitizerKind::LocalBounds; 1012 if (getTriple().getArch() == llvm::Triple::x86 || 1013 getTriple().getArch() == llvm::Triple::x86_64 || 1014 getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() || 1015 getTriple().isAArch64()) 1016 Res |= SanitizerKind::CFIICall; 1017 if (getTriple().getArch() == llvm::Triple::x86_64 || 1018 getTriple().isAArch64(64) || getTriple().isRISCV()) 1019 Res |= SanitizerKind::ShadowCallStack; 1020 if (getTriple().isAArch64(64)) 1021 Res |= SanitizerKind::MemTag; 1022 return Res; 1023 } 1024 1025 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, 1026 ArgStringList &CC1Args) const {} 1027 1028 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs, 1029 ArgStringList &CC1Args) const {} 1030 1031 llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12> 1032 ToolChain::getHIPDeviceLibs(const ArgList &DriverArgs) const { 1033 return {}; 1034 } 1035 1036 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs, 1037 ArgStringList &CC1Args) const {} 1038 1039 static VersionTuple separateMSVCFullVersion(unsigned Version) { 1040 if (Version < 100) 1041 return VersionTuple(Version); 1042 1043 if (Version < 10000) 1044 return VersionTuple(Version / 100, Version % 100); 1045 1046 unsigned Build = 0, Factor = 1; 1047 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10) 1048 Build = Build + (Version % 10) * Factor; 1049 return VersionTuple(Version / 100, Version % 100, Build); 1050 } 1051 1052 VersionTuple 1053 ToolChain::computeMSVCVersion(const Driver *D, 1054 const llvm::opt::ArgList &Args) const { 1055 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version); 1056 const Arg *MSCompatibilityVersion = 1057 Args.getLastArg(options::OPT_fms_compatibility_version); 1058 1059 if (MSCVersion && MSCompatibilityVersion) { 1060 if (D) 1061 D->Diag(diag::err_drv_argument_not_allowed_with) 1062 << MSCVersion->getAsString(Args) 1063 << MSCompatibilityVersion->getAsString(Args); 1064 return VersionTuple(); 1065 } 1066 1067 if (MSCompatibilityVersion) { 1068 VersionTuple MSVT; 1069 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) { 1070 if (D) 1071 D->Diag(diag::err_drv_invalid_value) 1072 << MSCompatibilityVersion->getAsString(Args) 1073 << MSCompatibilityVersion->getValue(); 1074 } else { 1075 return MSVT; 1076 } 1077 } 1078 1079 if (MSCVersion) { 1080 unsigned Version = 0; 1081 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) { 1082 if (D) 1083 D->Diag(diag::err_drv_invalid_value) 1084 << MSCVersion->getAsString(Args) << MSCVersion->getValue(); 1085 } else { 1086 return separateMSVCFullVersion(Version); 1087 } 1088 } 1089 1090 return VersionTuple(); 1091 } 1092 1093 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs( 1094 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, 1095 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const { 1096 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 1097 const OptTable &Opts = getDriver().getOpts(); 1098 bool Modified = false; 1099 1100 // Handle -Xopenmp-target flags 1101 for (auto *A : Args) { 1102 // Exclude flags which may only apply to the host toolchain. 1103 // Do not exclude flags when the host triple (AuxTriple) 1104 // matches the current toolchain triple. If it is not present 1105 // at all, target and host share a toolchain. 1106 if (A->getOption().matches(options::OPT_m_Group)) { 1107 if (SameTripleAsHost) 1108 DAL->append(A); 1109 else 1110 Modified = true; 1111 continue; 1112 } 1113 1114 unsigned Index; 1115 unsigned Prev; 1116 bool XOpenMPTargetNoTriple = 1117 A->getOption().matches(options::OPT_Xopenmp_target); 1118 1119 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) { 1120 // Passing device args: -Xopenmp-target=<triple> -opt=val. 1121 if (A->getValue(0) == getTripleString()) 1122 Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); 1123 else 1124 continue; 1125 } else if (XOpenMPTargetNoTriple) { 1126 // Passing device args: -Xopenmp-target -opt=val. 1127 Index = Args.getBaseArgs().MakeIndex(A->getValue(0)); 1128 } else { 1129 DAL->append(A); 1130 continue; 1131 } 1132 1133 // Parse the argument to -Xopenmp-target. 1134 Prev = Index; 1135 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index)); 1136 if (!XOpenMPTargetArg || Index > Prev + 1) { 1137 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args) 1138 << A->getAsString(Args); 1139 continue; 1140 } 1141 if (XOpenMPTargetNoTriple && XOpenMPTargetArg && 1142 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) { 1143 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple); 1144 continue; 1145 } 1146 XOpenMPTargetArg->setBaseArg(A); 1147 A = XOpenMPTargetArg.release(); 1148 AllocatedArgs.push_back(A); 1149 DAL->append(A); 1150 Modified = true; 1151 } 1152 1153 if (Modified) 1154 return DAL; 1155 1156 delete DAL; 1157 return nullptr; 1158 } 1159 1160 // TODO: Currently argument values separated by space e.g. 1161 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be 1162 // fixed. 1163 void ToolChain::TranslateXarchArgs( 1164 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, 1165 llvm::opt::DerivedArgList *DAL, 1166 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const { 1167 const OptTable &Opts = getDriver().getOpts(); 1168 unsigned ValuePos = 1; 1169 if (A->getOption().matches(options::OPT_Xarch_device) || 1170 A->getOption().matches(options::OPT_Xarch_host)) 1171 ValuePos = 0; 1172 1173 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos)); 1174 unsigned Prev = Index; 1175 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index)); 1176 1177 // If the argument parsing failed or more than one argument was 1178 // consumed, the -Xarch_ argument's parameter tried to consume 1179 // extra arguments. Emit an error and ignore. 1180 // 1181 // We also want to disallow any options which would alter the 1182 // driver behavior; that isn't going to work in our model. We 1183 // use options::NoXarchOption to control this. 1184 if (!XarchArg || Index > Prev + 1) { 1185 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args) 1186 << A->getAsString(Args); 1187 return; 1188 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) { 1189 auto &Diags = getDriver().getDiags(); 1190 unsigned DiagID = 1191 Diags.getCustomDiagID(DiagnosticsEngine::Error, 1192 "invalid Xarch argument: '%0', not all driver " 1193 "options can be forwared via Xarch argument"); 1194 Diags.Report(DiagID) << A->getAsString(Args); 1195 return; 1196 } 1197 XarchArg->setBaseArg(A); 1198 A = XarchArg.release(); 1199 if (!AllocatedArgs) 1200 DAL->AddSynthesizedArg(A); 1201 else 1202 AllocatedArgs->push_back(A); 1203 } 1204 1205 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs( 1206 const llvm::opt::DerivedArgList &Args, StringRef BoundArch, 1207 Action::OffloadKind OFK, 1208 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const { 1209 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 1210 bool Modified = false; 1211 1212 bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP; 1213 for (Arg *A : Args) { 1214 bool NeedTrans = false; 1215 bool Skip = false; 1216 if (A->getOption().matches(options::OPT_Xarch_device)) { 1217 NeedTrans = IsGPU; 1218 Skip = !IsGPU; 1219 } else if (A->getOption().matches(options::OPT_Xarch_host)) { 1220 NeedTrans = !IsGPU; 1221 Skip = IsGPU; 1222 } else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) { 1223 // Do not translate -Xarch_ options for non CUDA/HIP toolchain since 1224 // they may need special translation. 1225 // Skip this argument unless the architecture matches BoundArch 1226 if (BoundArch.empty() || A->getValue(0) != BoundArch) 1227 Skip = true; 1228 else 1229 NeedTrans = true; 1230 } 1231 if (NeedTrans || Skip) 1232 Modified = true; 1233 if (NeedTrans) 1234 TranslateXarchArgs(Args, A, DAL, AllocatedArgs); 1235 if (!Skip) 1236 DAL->append(A); 1237 } 1238 1239 if (Modified) 1240 return DAL; 1241 1242 delete DAL; 1243 return nullptr; 1244 } 1245