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