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