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