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