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