1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===// 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 "CommonArgs.h" 10 #include "Arch/AArch64.h" 11 #include "Arch/ARM.h" 12 #include "Arch/Mips.h" 13 #include "Arch/PPC.h" 14 #include "Arch/RISCV.h" 15 #include "Arch/Sparc.h" 16 #include "Arch/SystemZ.h" 17 #include "Arch/X86.h" 18 #include "AMDGPU.h" 19 #include "MSP430.h" 20 #include "HIP.h" 21 #include "Hexagon.h" 22 #include "InputInfo.h" 23 #include "clang/Basic/CharInfo.h" 24 #include "clang/Basic/LangOptions.h" 25 #include "clang/Basic/ObjCRuntime.h" 26 #include "clang/Basic/Version.h" 27 #include "clang/Config/config.h" 28 #include "clang/Driver/Action.h" 29 #include "clang/Driver/Compilation.h" 30 #include "clang/Driver/Driver.h" 31 #include "clang/Driver/DriverDiagnostic.h" 32 #include "clang/Driver/Job.h" 33 #include "clang/Driver/Options.h" 34 #include "clang/Driver/SanitizerArgs.h" 35 #include "clang/Driver/ToolChain.h" 36 #include "clang/Driver/Util.h" 37 #include "clang/Driver/XRayArgs.h" 38 #include "llvm/ADT/STLExtras.h" 39 #include "llvm/ADT/SmallString.h" 40 #include "llvm/ADT/StringExtras.h" 41 #include "llvm/ADT/StringSwitch.h" 42 #include "llvm/ADT/Twine.h" 43 #include "llvm/Option/Arg.h" 44 #include "llvm/Option/ArgList.h" 45 #include "llvm/Option/Option.h" 46 #include "llvm/Support/CodeGen.h" 47 #include "llvm/Support/Compression.h" 48 #include "llvm/Support/Debug.h" 49 #include "llvm/Support/ErrorHandling.h" 50 #include "llvm/Support/FileSystem.h" 51 #include "llvm/Support/Host.h" 52 #include "llvm/Support/Path.h" 53 #include "llvm/Support/Process.h" 54 #include "llvm/Support/Program.h" 55 #include "llvm/Support/ScopedPrinter.h" 56 #include "llvm/Support/TargetParser.h" 57 #include "llvm/Support/VirtualFileSystem.h" 58 #include "llvm/Support/YAMLParser.h" 59 60 using namespace clang::driver; 61 using namespace clang::driver::tools; 62 using namespace clang; 63 using namespace llvm::opt; 64 65 void tools::addPathIfExists(const Driver &D, const Twine &Path, 66 ToolChain::path_list &Paths) { 67 if (D.getVFS().exists(Path)) 68 Paths.push_back(Path.str()); 69 } 70 71 void tools::handleTargetFeaturesGroup(const ArgList &Args, 72 std::vector<StringRef> &Features, 73 OptSpecifier Group) { 74 for (const Arg *A : Args.filtered(Group)) { 75 StringRef Name = A->getOption().getName(); 76 A->claim(); 77 78 // Skip over "-m". 79 assert(Name.startswith("m") && "Invalid feature name."); 80 Name = Name.substr(1); 81 82 bool IsNegative = Name.startswith("no-"); 83 if (IsNegative) 84 Name = Name.substr(3); 85 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); 86 } 87 } 88 89 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, 90 const char *ArgName, const char *EnvVar) { 91 const char *DirList = ::getenv(EnvVar); 92 bool CombinedArg = false; 93 94 if (!DirList) 95 return; // Nothing to do. 96 97 StringRef Name(ArgName); 98 if (Name.equals("-I") || Name.equals("-L")) 99 CombinedArg = true; 100 101 StringRef Dirs(DirList); 102 if (Dirs.empty()) // Empty string should not add '.'. 103 return; 104 105 StringRef::size_type Delim; 106 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) { 107 if (Delim == 0) { // Leading colon. 108 if (CombinedArg) { 109 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 110 } else { 111 CmdArgs.push_back(ArgName); 112 CmdArgs.push_back("."); 113 } 114 } else { 115 if (CombinedArg) { 116 CmdArgs.push_back( 117 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); 118 } else { 119 CmdArgs.push_back(ArgName); 120 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); 121 } 122 } 123 Dirs = Dirs.substr(Delim + 1); 124 } 125 126 if (Dirs.empty()) { // Trailing colon. 127 if (CombinedArg) { 128 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 129 } else { 130 CmdArgs.push_back(ArgName); 131 CmdArgs.push_back("."); 132 } 133 } else { // Add the last path. 134 if (CombinedArg) { 135 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); 136 } else { 137 CmdArgs.push_back(ArgName); 138 CmdArgs.push_back(Args.MakeArgString(Dirs)); 139 } 140 } 141 } 142 143 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, 144 const ArgList &Args, ArgStringList &CmdArgs, 145 const JobAction &JA) { 146 const Driver &D = TC.getDriver(); 147 148 // Add extra linker input arguments which are not treated as inputs 149 // (constructed via -Xarch_). 150 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); 151 152 // LIBRARY_PATH are included before user inputs and only supported on native 153 // toolchains. 154 if (!TC.isCrossCompiling()) 155 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); 156 157 for (const auto &II : Inputs) { 158 // If the current tool chain refers to an OpenMP or HIP offloading host, we 159 // should ignore inputs that refer to OpenMP or HIP offloading devices - 160 // they will be embedded according to a proper linker script. 161 if (auto *IA = II.getAction()) 162 if ((JA.isHostOffloading(Action::OFK_OpenMP) && 163 IA->isDeviceOffloading(Action::OFK_OpenMP)) || 164 (JA.isHostOffloading(Action::OFK_HIP) && 165 IA->isDeviceOffloading(Action::OFK_HIP))) 166 continue; 167 168 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType())) 169 // Don't try to pass LLVM inputs unless we have native support. 170 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); 171 172 // Add filenames immediately. 173 if (II.isFilename()) { 174 CmdArgs.push_back(II.getFilename()); 175 continue; 176 } 177 178 // Otherwise, this is a linker input argument. 179 const Arg &A = II.getInputArg(); 180 181 // Handle reserved library options. 182 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) 183 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 184 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) 185 TC.AddCCKextLibArgs(Args, CmdArgs); 186 else if (A.getOption().matches(options::OPT_z)) { 187 // Pass -z prefix for gcc linker compatibility. 188 A.claim(); 189 A.render(Args, CmdArgs); 190 } else { 191 A.renderAsInput(Args, CmdArgs); 192 } 193 } 194 } 195 196 void tools::AddTargetFeature(const ArgList &Args, 197 std::vector<StringRef> &Features, 198 OptSpecifier OnOpt, OptSpecifier OffOpt, 199 StringRef FeatureName) { 200 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { 201 if (A->getOption().matches(OnOpt)) 202 Features.push_back(Args.MakeArgString("+" + FeatureName)); 203 else 204 Features.push_back(Args.MakeArgString("-" + FeatureName)); 205 } 206 } 207 208 /// Get the (LLVM) name of the R600 gpu we are targeting. 209 static std::string getR600TargetGPU(const ArgList &Args) { 210 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 211 const char *GPUName = A->getValue(); 212 return llvm::StringSwitch<const char *>(GPUName) 213 .Cases("rv630", "rv635", "r600") 214 .Cases("rv610", "rv620", "rs780", "rs880") 215 .Case("rv740", "rv770") 216 .Case("palm", "cedar") 217 .Cases("sumo", "sumo2", "sumo") 218 .Case("hemlock", "cypress") 219 .Case("aruba", "cayman") 220 .Default(GPUName); 221 } 222 return ""; 223 } 224 225 static std::string getLanaiTargetCPU(const ArgList &Args) { 226 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 227 return A->getValue(); 228 } 229 return ""; 230 } 231 232 /// Get the (LLVM) name of the WebAssembly cpu we are targeting. 233 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { 234 // If we have -mcpu=, use that. 235 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 236 StringRef CPU = A->getValue(); 237 238 #ifdef __wasm__ 239 // Handle "native" by examining the host. "native" isn't meaningful when 240 // cross compiling, so only support this when the host is also WebAssembly. 241 if (CPU == "native") 242 return llvm::sys::getHostCPUName(); 243 #endif 244 245 return CPU; 246 } 247 248 return "generic"; 249 } 250 251 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T, 252 bool FromAs) { 253 Arg *A; 254 255 switch (T.getArch()) { 256 default: 257 return ""; 258 259 case llvm::Triple::aarch64: 260 case llvm::Triple::aarch64_be: 261 return aarch64::getAArch64TargetCPU(Args, T, A); 262 263 case llvm::Triple::arm: 264 case llvm::Triple::armeb: 265 case llvm::Triple::thumb: 266 case llvm::Triple::thumbeb: { 267 StringRef MArch, MCPU; 268 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs); 269 return arm::getARMTargetCPU(MCPU, MArch, T); 270 } 271 272 case llvm::Triple::avr: 273 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ)) 274 return A->getValue(); 275 return ""; 276 277 case llvm::Triple::mips: 278 case llvm::Triple::mipsel: 279 case llvm::Triple::mips64: 280 case llvm::Triple::mips64el: { 281 StringRef CPUName; 282 StringRef ABIName; 283 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName); 284 return CPUName; 285 } 286 287 case llvm::Triple::nvptx: 288 case llvm::Triple::nvptx64: 289 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 290 return A->getValue(); 291 return ""; 292 293 case llvm::Triple::ppc: 294 case llvm::Triple::ppc64: 295 case llvm::Triple::ppc64le: { 296 std::string TargetCPUName = ppc::getPPCTargetCPU(Args); 297 // LLVM may default to generating code for the native CPU, 298 // but, like gcc, we default to a more generic option for 299 // each architecture. (except on Darwin) 300 if (TargetCPUName.empty() && !T.isOSDarwin()) { 301 if (T.getArch() == llvm::Triple::ppc64) 302 TargetCPUName = "ppc64"; 303 else if (T.getArch() == llvm::Triple::ppc64le) 304 TargetCPUName = "ppc64le"; 305 else 306 TargetCPUName = "ppc"; 307 } 308 return TargetCPUName; 309 } 310 311 case llvm::Triple::bpfel: 312 case llvm::Triple::bpfeb: 313 case llvm::Triple::sparc: 314 case llvm::Triple::sparcel: 315 case llvm::Triple::sparcv9: 316 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 317 return A->getValue(); 318 return ""; 319 320 case llvm::Triple::x86: 321 case llvm::Triple::x86_64: 322 return x86::getX86TargetCPU(Args, T); 323 324 case llvm::Triple::hexagon: 325 return "hexagon" + 326 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); 327 328 case llvm::Triple::lanai: 329 return getLanaiTargetCPU(Args); 330 331 case llvm::Triple::systemz: 332 return systemz::getSystemZTargetCPU(Args); 333 334 case llvm::Triple::r600: 335 case llvm::Triple::amdgcn: 336 return getR600TargetGPU(Args); 337 338 case llvm::Triple::wasm32: 339 case llvm::Triple::wasm64: 340 return getWebAssemblyTargetCPU(Args); 341 } 342 } 343 344 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) { 345 unsigned Parallelism = 0; 346 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ); 347 if (LtoJobsArg && 348 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism)) 349 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args) 350 << LtoJobsArg->getValue(); 351 return Parallelism; 352 } 353 354 // CloudABI uses -ffunction-sections and -fdata-sections by default. 355 bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 356 return Triple.getOS() == llvm::Triple::CloudABI; 357 } 358 359 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args, 360 ArgStringList &CmdArgs, const InputInfo &Output, 361 const InputInfo &Input, bool IsThinLTO) { 362 // Tell the linker to load the plugin. This has to come before AddLinkerInputs 363 // as gold requires -plugin to come before any -plugin-opt that -Wl might 364 // forward. 365 CmdArgs.push_back("-plugin"); 366 367 #if defined(_WIN32) 368 const char *Suffix = ".dll"; 369 #elif defined(__APPLE__) 370 const char *Suffix = ".dylib"; 371 #else 372 const char *Suffix = ".so"; 373 #endif 374 375 SmallString<1024> Plugin; 376 llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) + 377 "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + 378 Suffix, 379 Plugin); 380 CmdArgs.push_back(Args.MakeArgString(Plugin)); 381 382 // Try to pass driver level flags relevant to LTO code generation down to 383 // the plugin. 384 385 // Handle flags for selecting CPU variants. 386 std::string CPU = getCPUName(Args, ToolChain.getTriple()); 387 if (!CPU.empty()) 388 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU)); 389 390 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 391 StringRef OOpt; 392 if (A->getOption().matches(options::OPT_O4) || 393 A->getOption().matches(options::OPT_Ofast)) 394 OOpt = "3"; 395 else if (A->getOption().matches(options::OPT_O)) 396 OOpt = A->getValue(); 397 else if (A->getOption().matches(options::OPT_O0)) 398 OOpt = "0"; 399 if (!OOpt.empty()) 400 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt)); 401 } 402 403 if (Args.hasArg(options::OPT_gsplit_dwarf)) { 404 CmdArgs.push_back( 405 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") + 406 Output.getFilename() + "_dwo")); 407 } 408 409 if (IsThinLTO) 410 CmdArgs.push_back("-plugin-opt=thinlto"); 411 412 if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver())) 413 CmdArgs.push_back( 414 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism))); 415 416 // If an explicit debugger tuning argument appeared, pass it along. 417 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group, 418 options::OPT_ggdbN_Group)) { 419 if (A->getOption().matches(options::OPT_glldb)) 420 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb"); 421 else if (A->getOption().matches(options::OPT_gsce)) 422 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce"); 423 else 424 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb"); 425 } 426 427 bool UseSeparateSections = 428 isUseSeparateSections(ToolChain.getEffectiveTriple()); 429 430 if (Args.hasFlag(options::OPT_ffunction_sections, 431 options::OPT_fno_function_sections, UseSeparateSections)) { 432 CmdArgs.push_back("-plugin-opt=-function-sections"); 433 } 434 435 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 436 UseSeparateSections)) { 437 CmdArgs.push_back("-plugin-opt=-data-sections"); 438 } 439 440 if (Arg *A = getLastProfileSampleUseArg(Args)) { 441 StringRef FName = A->getValue(); 442 if (!llvm::sys::fs::exists(FName)) 443 ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName; 444 else 445 CmdArgs.push_back( 446 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName)); 447 } 448 449 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 450 options::OPT_fcs_profile_generate_EQ, 451 options::OPT_fno_profile_generate); 452 if (CSPGOGenerateArg && 453 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 454 CSPGOGenerateArg = nullptr; 455 456 auto *ProfileUseArg = getLastProfileUseArg(Args); 457 458 if (CSPGOGenerateArg) { 459 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate")); 460 if (CSPGOGenerateArg->getOption().matches( 461 options::OPT_fcs_profile_generate_EQ)) { 462 SmallString<128> Path(CSPGOGenerateArg->getValue()); 463 llvm::sys::path::append(Path, "default_%m.profraw"); 464 CmdArgs.push_back( 465 Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path)); 466 } else 467 CmdArgs.push_back( 468 Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw")); 469 } else if (ProfileUseArg) { 470 SmallString<128> Path( 471 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 472 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 473 llvm::sys::path::append(Path, "default.profdata"); 474 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + 475 Path)); 476 } 477 478 // Need this flag to turn on new pass manager via Gold plugin. 479 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager, 480 options::OPT_fno_experimental_new_pass_manager, 481 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) { 482 CmdArgs.push_back("-plugin-opt=new-pass-manager"); 483 } 484 485 // Setup statistics file output. 486 SmallString<128> StatsFile = 487 getStatsFileName(Args, Output, Input, ToolChain.getDriver()); 488 if (!StatsFile.empty()) 489 CmdArgs.push_back( 490 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile)); 491 492 getTargetFeatures(ToolChain, ToolChain.getTriple(), Args, CmdArgs, 493 /* ForAS= */ false, /* ForLTOPlugin= */ true); 494 495 StringRef ABIName = tools::getTargetABI(Args, ToolChain.getTriple()); 496 if (!ABIName.empty()) 497 CmdArgs.push_back( 498 Args.MakeArgString(Twine("-plugin-opt=-target-abi=") + ABIName)); 499 } 500 501 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 502 ArgStringList &CmdArgs) { 503 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 504 options::OPT_fno_rtlib_add_rpath, false)) 505 return; 506 507 std::string CandidateRPath = TC.getArchSpecificLibPath(); 508 if (TC.getVFS().exists(CandidateRPath)) { 509 CmdArgs.push_back("-rpath"); 510 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str())); 511 } 512 } 513 514 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, 515 const ArgList &Args, bool ForceStaticHostRuntime, 516 bool IsOffloadingHost, bool GompNeedsRT) { 517 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 518 options::OPT_fno_openmp, false)) 519 return false; 520 521 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 522 523 if (RTKind == Driver::OMPRT_Unknown) 524 // Already diagnosed. 525 return false; 526 527 if (ForceStaticHostRuntime) 528 CmdArgs.push_back("-Bstatic"); 529 530 switch (RTKind) { 531 case Driver::OMPRT_OMP: 532 CmdArgs.push_back("-lomp"); 533 break; 534 case Driver::OMPRT_GOMP: 535 CmdArgs.push_back("-lgomp"); 536 break; 537 case Driver::OMPRT_IOMP5: 538 CmdArgs.push_back("-liomp5"); 539 break; 540 case Driver::OMPRT_Unknown: 541 break; 542 } 543 544 if (ForceStaticHostRuntime) 545 CmdArgs.push_back("-Bdynamic"); 546 547 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 548 CmdArgs.push_back("-lrt"); 549 550 if (IsOffloadingHost) 551 CmdArgs.push_back("-lomptarget"); 552 553 addArchSpecificRPath(TC, Args, CmdArgs); 554 555 return true; 556 } 557 558 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 559 ArgStringList &CmdArgs, StringRef Sanitizer, 560 bool IsShared, bool IsWhole) { 561 // Wrap any static runtimes that must be forced into executable in 562 // whole-archive. 563 if (IsWhole) CmdArgs.push_back("--whole-archive"); 564 CmdArgs.push_back(TC.getCompilerRTArgString( 565 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 566 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 567 568 if (IsShared) { 569 addArchSpecificRPath(TC, Args, CmdArgs); 570 } 571 } 572 573 // Tries to use a file with the list of dynamic symbols that need to be exported 574 // from the runtime library. Returns true if the file was found. 575 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 576 ArgStringList &CmdArgs, 577 StringRef Sanitizer) { 578 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 579 // the option, so don't try to pass it. 580 if (TC.getTriple().getOS() == llvm::Triple::Solaris) 581 return true; 582 // Myriad is static linking only. Furthermore, some versions of its 583 // linker have the bug where --export-dynamic overrides -static, so 584 // don't use --export-dynamic on that platform. 585 if (TC.getTriple().getVendor() == llvm::Triple::Myriad) 586 return true; 587 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 588 if (llvm::sys::fs::exists(SanRT + ".syms")) { 589 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 590 return true; 591 } 592 return false; 593 } 594 595 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 596 ArgStringList &CmdArgs) { 597 // Force linking against the system libraries sanitizers depends on 598 // (see PR15823 why this is necessary). 599 CmdArgs.push_back("--no-as-needed"); 600 // There's no libpthread or librt on RTEMS & Android. 601 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 602 !TC.getTriple().isAndroid()) { 603 CmdArgs.push_back("-lpthread"); 604 if (!TC.getTriple().isOSOpenBSD()) 605 CmdArgs.push_back("-lrt"); 606 } 607 CmdArgs.push_back("-lm"); 608 // There's no libdl on all OSes. 609 if (!TC.getTriple().isOSFreeBSD() && 610 !TC.getTriple().isOSNetBSD() && 611 !TC.getTriple().isOSOpenBSD() && 612 TC.getTriple().getOS() != llvm::Triple::RTEMS) 613 CmdArgs.push_back("-ldl"); 614 // Required for backtrace on some OSes 615 if (TC.getTriple().isOSFreeBSD() || 616 TC.getTriple().isOSNetBSD()) 617 CmdArgs.push_back("-lexecinfo"); 618 } 619 620 static void 621 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 622 SmallVectorImpl<StringRef> &SharedRuntimes, 623 SmallVectorImpl<StringRef> &StaticRuntimes, 624 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 625 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 626 SmallVectorImpl<StringRef> &RequiredSymbols) { 627 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 628 // Collect shared runtimes. 629 if (SanArgs.needsSharedRt()) { 630 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 631 SharedRuntimes.push_back("asan"); 632 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 633 HelperStaticRuntimes.push_back("asan-preinit"); 634 } 635 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 636 if (SanArgs.requiresMinimalRuntime()) 637 SharedRuntimes.push_back("ubsan_minimal"); 638 else 639 SharedRuntimes.push_back("ubsan_standalone"); 640 } 641 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 642 if (SanArgs.requiresMinimalRuntime()) 643 SharedRuntimes.push_back("scudo_minimal"); 644 else 645 SharedRuntimes.push_back("scudo"); 646 } 647 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) 648 SharedRuntimes.push_back("hwasan"); 649 } 650 651 // The stats_client library is also statically linked into DSOs. 652 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) 653 StaticRuntimes.push_back("stats_client"); 654 655 // Collect static runtimes. 656 if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) { 657 // Don't link static runtimes into DSOs or if -shared-libasan. 658 return; 659 } 660 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 661 StaticRuntimes.push_back("asan"); 662 if (SanArgs.linkCXXRuntimes()) 663 StaticRuntimes.push_back("asan_cxx"); 664 } 665 666 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 667 StaticRuntimes.push_back("hwasan"); 668 if (SanArgs.linkCXXRuntimes()) 669 StaticRuntimes.push_back("hwasan_cxx"); 670 } 671 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes()) 672 StaticRuntimes.push_back("dfsan"); 673 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes()) 674 StaticRuntimes.push_back("lsan"); 675 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) { 676 StaticRuntimes.push_back("msan"); 677 if (SanArgs.linkCXXRuntimes()) 678 StaticRuntimes.push_back("msan_cxx"); 679 } 680 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) { 681 StaticRuntimes.push_back("tsan"); 682 if (SanArgs.linkCXXRuntimes()) 683 StaticRuntimes.push_back("tsan_cxx"); 684 } 685 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 686 if (SanArgs.requiresMinimalRuntime()) { 687 StaticRuntimes.push_back("ubsan_minimal"); 688 } else { 689 StaticRuntimes.push_back("ubsan_standalone"); 690 if (SanArgs.linkCXXRuntimes()) 691 StaticRuntimes.push_back("ubsan_standalone_cxx"); 692 } 693 } 694 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) { 695 NonWholeStaticRuntimes.push_back("safestack"); 696 RequiredSymbols.push_back("__safestack_init"); 697 } 698 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes()) 699 StaticRuntimes.push_back("cfi"); 700 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) { 701 StaticRuntimes.push_back("cfi_diag"); 702 if (SanArgs.linkCXXRuntimes()) 703 StaticRuntimes.push_back("ubsan_standalone_cxx"); 704 } 705 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) { 706 NonWholeStaticRuntimes.push_back("stats"); 707 RequiredSymbols.push_back("__sanitizer_stats_register"); 708 } 709 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 710 if (SanArgs.requiresMinimalRuntime()) { 711 StaticRuntimes.push_back("scudo_minimal"); 712 if (SanArgs.linkCXXRuntimes()) 713 StaticRuntimes.push_back("scudo_cxx_minimal"); 714 } else { 715 StaticRuntimes.push_back("scudo"); 716 if (SanArgs.linkCXXRuntimes()) 717 StaticRuntimes.push_back("scudo_cxx"); 718 } 719 } 720 } 721 722 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++, 723 // C runtime, etc). Returns true if sanitizer system deps need to be linked in. 724 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 725 ArgStringList &CmdArgs) { 726 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, 727 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; 728 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, 729 NonWholeStaticRuntimes, HelperStaticRuntimes, 730 RequiredSymbols); 731 732 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 733 // Inject libfuzzer dependencies. 734 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && 735 !Args.hasArg(options::OPT_shared)) { 736 737 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true); 738 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) 739 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 740 } 741 742 for (auto RT : SharedRuntimes) 743 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false); 744 for (auto RT : HelperStaticRuntimes) 745 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 746 bool AddExportDynamic = false; 747 for (auto RT : StaticRuntimes) { 748 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 749 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 750 } 751 for (auto RT : NonWholeStaticRuntimes) { 752 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false); 753 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 754 } 755 for (auto S : RequiredSymbols) { 756 CmdArgs.push_back("-u"); 757 CmdArgs.push_back(Args.MakeArgString(S)); 758 } 759 // If there is a static runtime with no dynamic list, force all the symbols 760 // to be dynamic to be sure we export sanitizer interface functions. 761 if (AddExportDynamic) 762 CmdArgs.push_back("--export-dynamic"); 763 764 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) 765 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check"); 766 767 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); 768 } 769 770 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { 771 if (Args.hasArg(options::OPT_shared)) 772 return false; 773 774 if (TC.getXRayArgs().needsXRayRt()) { 775 CmdArgs.push_back("-whole-archive"); 776 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray")); 777 for (const auto &Mode : TC.getXRayArgs().modeList()) 778 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode)); 779 CmdArgs.push_back("-no-whole-archive"); 780 return true; 781 } 782 783 return false; 784 } 785 786 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) { 787 CmdArgs.push_back("--no-as-needed"); 788 CmdArgs.push_back("-lpthread"); 789 if (!TC.getTriple().isOSOpenBSD()) 790 CmdArgs.push_back("-lrt"); 791 CmdArgs.push_back("-lm"); 792 793 if (!TC.getTriple().isOSFreeBSD() && 794 !TC.getTriple().isOSNetBSD() && 795 !TC.getTriple().isOSOpenBSD()) 796 CmdArgs.push_back("-ldl"); 797 } 798 799 bool tools::areOptimizationsEnabled(const ArgList &Args) { 800 // Find the last -O arg and see if it is non-zero. 801 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 802 return !A->getOption().matches(options::OPT_O0); 803 // Defaults to -O0. 804 return false; 805 } 806 807 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input, 808 const InputInfo &Output) { 809 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ)) 810 if (StringRef(A->getValue()) == "single") 811 return Args.MakeArgString(Output.getFilename()); 812 813 Arg *FinalOutput = Args.getLastArg(options::OPT_o); 814 if (FinalOutput && Args.hasArg(options::OPT_c)) { 815 SmallString<128> T(FinalOutput->getValue()); 816 llvm::sys::path::replace_extension(T, "dwo"); 817 return Args.MakeArgString(T); 818 } else { 819 // Use the compilation dir. 820 SmallString<128> T( 821 Args.getLastArgValue(options::OPT_fdebug_compilation_dir)); 822 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput())); 823 llvm::sys::path::replace_extension(F, "dwo"); 824 T += F; 825 return Args.MakeArgString(F); 826 } 827 } 828 829 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, 830 const JobAction &JA, const ArgList &Args, 831 const InputInfo &Output, const char *OutFile) { 832 ArgStringList ExtractArgs; 833 ExtractArgs.push_back("--extract-dwo"); 834 835 ArgStringList StripArgs; 836 StripArgs.push_back("--strip-dwo"); 837 838 // Grabbing the output of the earlier compile step. 839 StripArgs.push_back(Output.getFilename()); 840 ExtractArgs.push_back(Output.getFilename()); 841 ExtractArgs.push_back(OutFile); 842 843 const char *Exec = 844 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); 845 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); 846 847 // First extract the dwo sections. 848 C.addCommand(std::make_unique<Command>(JA, T, Exec, ExtractArgs, II)); 849 850 // Then remove them from the original .o file. 851 C.addCommand(std::make_unique<Command>(JA, T, Exec, StripArgs, II)); 852 } 853 854 // Claim options we don't want to warn if they are unused. We do this for 855 // options that build systems might add but are unused when assembling or only 856 // running the preprocessor for example. 857 void tools::claimNoWarnArgs(const ArgList &Args) { 858 // Don't warn about unused -f(no-)?lto. This can happen when we're 859 // preprocessing, precompiling or assembling. 860 Args.ClaimAllArgs(options::OPT_flto_EQ); 861 Args.ClaimAllArgs(options::OPT_flto); 862 Args.ClaimAllArgs(options::OPT_fno_lto); 863 } 864 865 Arg *tools::getLastProfileUseArg(const ArgList &Args) { 866 auto *ProfileUseArg = Args.getLastArg( 867 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ, 868 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ, 869 options::OPT_fno_profile_instr_use); 870 871 if (ProfileUseArg && 872 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)) 873 ProfileUseArg = nullptr; 874 875 return ProfileUseArg; 876 } 877 878 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { 879 auto *ProfileSampleUseArg = Args.getLastArg( 880 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ, 881 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ, 882 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile); 883 884 if (ProfileSampleUseArg && 885 (ProfileSampleUseArg->getOption().matches( 886 options::OPT_fno_profile_sample_use) || 887 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile))) 888 return nullptr; 889 890 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ, 891 options::OPT_fauto_profile_EQ); 892 } 893 894 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, 895 /// smooshes them together with platform defaults, to decide whether 896 /// this compile should be using PIC mode or not. Returns a tuple of 897 /// (RelocationModel, PICLevel, IsPIE). 898 std::tuple<llvm::Reloc::Model, unsigned, bool> 899 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { 900 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); 901 const llvm::Triple &Triple = ToolChain.getTriple(); 902 903 bool PIE = ToolChain.isPIEDefault(); 904 bool PIC = PIE || ToolChain.isPICDefault(); 905 // The Darwin/MachO default to use PIC does not apply when using -static. 906 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static)) 907 PIE = PIC = false; 908 bool IsPICLevelTwo = PIC; 909 910 bool KernelOrKext = 911 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 912 913 // Android-specific defaults for PIC/PIE 914 if (Triple.isAndroid()) { 915 switch (Triple.getArch()) { 916 case llvm::Triple::arm: 917 case llvm::Triple::armeb: 918 case llvm::Triple::thumb: 919 case llvm::Triple::thumbeb: 920 case llvm::Triple::aarch64: 921 case llvm::Triple::mips: 922 case llvm::Triple::mipsel: 923 case llvm::Triple::mips64: 924 case llvm::Triple::mips64el: 925 PIC = true; // "-fpic" 926 break; 927 928 case llvm::Triple::x86: 929 case llvm::Triple::x86_64: 930 PIC = true; // "-fPIC" 931 IsPICLevelTwo = true; 932 break; 933 934 default: 935 break; 936 } 937 } 938 939 // OpenBSD-specific defaults for PIE 940 if (Triple.isOSOpenBSD()) { 941 switch (ToolChain.getArch()) { 942 case llvm::Triple::arm: 943 case llvm::Triple::aarch64: 944 case llvm::Triple::mips64: 945 case llvm::Triple::mips64el: 946 case llvm::Triple::x86: 947 case llvm::Triple::x86_64: 948 IsPICLevelTwo = false; // "-fpie" 949 break; 950 951 case llvm::Triple::ppc: 952 case llvm::Triple::sparc: 953 case llvm::Triple::sparcel: 954 case llvm::Triple::sparcv9: 955 IsPICLevelTwo = true; // "-fPIE" 956 break; 957 958 default: 959 break; 960 } 961 } 962 963 // AMDGPU-specific defaults for PIC. 964 if (Triple.getArch() == llvm::Triple::amdgcn) 965 PIC = true; 966 967 // The last argument relating to either PIC or PIE wins, and no 968 // other argument is used. If the last argument is any flavor of the 969 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE 970 // option implicitly enables PIC at the same level. 971 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, 972 options::OPT_fpic, options::OPT_fno_pic, 973 options::OPT_fPIE, options::OPT_fno_PIE, 974 options::OPT_fpie, options::OPT_fno_pie); 975 if (Triple.isOSWindows() && LastPICArg && 976 LastPICArg == 977 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 978 options::OPT_fPIE, options::OPT_fpie)) { 979 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 980 << LastPICArg->getSpelling() << Triple.str(); 981 if (Triple.getArch() == llvm::Triple::x86_64) 982 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 983 return std::make_tuple(llvm::Reloc::Static, 0U, false); 984 } 985 986 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 987 // is forced, then neither PIC nor PIE flags will have no effect. 988 if (!ToolChain.isPICDefaultForced()) { 989 if (LastPICArg) { 990 Option O = LastPICArg->getOption(); 991 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 992 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 993 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 994 PIC = 995 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 996 IsPICLevelTwo = 997 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 998 } else { 999 PIE = PIC = false; 1000 if (EffectiveTriple.isPS4CPU()) { 1001 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1002 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1003 if (Model != "kernel") { 1004 PIC = true; 1005 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic) 1006 << LastPICArg->getSpelling(); 1007 } 1008 } 1009 } 1010 } 1011 } 1012 1013 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the 1014 // PIC level would've been set to level 1, force it back to level 2 PIC 1015 // instead. 1016 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU())) 1017 IsPICLevelTwo |= ToolChain.isPICDefault(); 1018 1019 // This kernel flags are a trump-card: they will disable PIC/PIE 1020 // generation, independent of the argument order. 1021 if (KernelOrKext && 1022 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1023 !EffectiveTriple.isWatchOS())) 1024 PIC = PIE = false; 1025 1026 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1027 // This is a very special mode. It trumps the other modes, almost no one 1028 // uses it, and it isn't even valid on any OS but Darwin. 1029 if (!Triple.isOSDarwin()) 1030 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1031 << A->getSpelling() << Triple.str(); 1032 1033 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1034 1035 // Only a forced PIC mode can cause the actual compile to have PIC defines 1036 // etc., no flags are sufficient. This behavior was selected to closely 1037 // match that of llvm-gcc and Apple GCC before that. 1038 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1039 1040 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1041 } 1042 1043 bool EmbeddedPISupported; 1044 switch (Triple.getArch()) { 1045 case llvm::Triple::arm: 1046 case llvm::Triple::armeb: 1047 case llvm::Triple::thumb: 1048 case llvm::Triple::thumbeb: 1049 EmbeddedPISupported = true; 1050 break; 1051 default: 1052 EmbeddedPISupported = false; 1053 break; 1054 } 1055 1056 bool ROPI = false, RWPI = false; 1057 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1058 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1059 if (!EmbeddedPISupported) 1060 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1061 << LastROPIArg->getSpelling() << Triple.str(); 1062 ROPI = true; 1063 } 1064 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 1065 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 1066 if (!EmbeddedPISupported) 1067 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1068 << LastRWPIArg->getSpelling() << Triple.str(); 1069 RWPI = true; 1070 } 1071 1072 // ROPI and RWPI are not compatible with PIC or PIE. 1073 if ((ROPI || RWPI) && (PIC || PIE)) 1074 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 1075 1076 if (Triple.isMIPS()) { 1077 StringRef CPUName; 1078 StringRef ABIName; 1079 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1080 // When targeting the N64 ABI, PIC is the default, except in the case 1081 // when the -mno-abicalls option is used. In that case we exit 1082 // at next check regardless of PIC being set below. 1083 if (ABIName == "n64") 1084 PIC = true; 1085 // When targettng MIPS with -mno-abicalls, it's always static. 1086 if(Args.hasArg(options::OPT_mno_abicalls)) 1087 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1088 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 1089 // does not use PIC level 2 for historical reasons. 1090 IsPICLevelTwo = false; 1091 } 1092 1093 if (PIC) 1094 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 1095 1096 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 1097 if (ROPI && RWPI) 1098 RelocM = llvm::Reloc::ROPI_RWPI; 1099 else if (ROPI) 1100 RelocM = llvm::Reloc::ROPI; 1101 else if (RWPI) 1102 RelocM = llvm::Reloc::RWPI; 1103 1104 return std::make_tuple(RelocM, 0U, false); 1105 } 1106 1107 // `-falign-functions` indicates that the functions should be aligned to a 1108 // 16-byte boundary. 1109 // 1110 // `-falign-functions=1` is the same as `-fno-align-functions`. 1111 // 1112 // The scalar `n` in `-falign-functions=n` must be an integral value between 1113 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to 1114 // the nearest power-of-two. 1115 // 1116 // If we return `0`, the frontend will default to the backend's preferred 1117 // alignment. 1118 // 1119 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 1120 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred 1121 // alignment. For unaligned functions, we default to the backend's preferred 1122 // alignment. 1123 unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 1124 const ArgList &Args) { 1125 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 1126 options::OPT_falign_functions_EQ, 1127 options::OPT_fno_align_functions); 1128 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 1129 return 0; 1130 1131 if (A->getOption().matches(options::OPT_falign_functions)) 1132 return 0; 1133 1134 unsigned Value = 0; 1135 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 1136 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1137 << A->getAsString(Args) << A->getValue(); 1138 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 1139 } 1140 1141 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 1142 ArgStringList &CmdArgs) { 1143 llvm::Reloc::Model RelocationModel; 1144 unsigned PICLevel; 1145 bool IsPIE; 1146 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 1147 1148 if (RelocationModel != llvm::Reloc::Static) 1149 CmdArgs.push_back("-KPIC"); 1150 } 1151 1152 /// Determine whether Objective-C automated reference counting is 1153 /// enabled. 1154 bool tools::isObjCAutoRefCount(const ArgList &Args) { 1155 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 1156 } 1157 1158 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 1159 1160 static LibGccType getLibGccType(const Driver &D, const ArgList &Args) { 1161 if (Args.hasArg(options::OPT_static_libgcc) || 1162 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie)) 1163 return LibGccType::StaticLibGcc; 1164 if (Args.hasArg(options::OPT_shared_libgcc) || D.CCCIsCXX()) 1165 return LibGccType::SharedLibGcc; 1166 return LibGccType::UnspecifiedLibGcc; 1167 } 1168 1169 // Gcc adds libgcc arguments in various ways: 1170 // 1171 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 1172 // g++ <none>: -lgcc_s -lgcc 1173 // gcc shared: -lgcc_s -lgcc 1174 // g++ shared: -lgcc_s -lgcc 1175 // gcc static: -lgcc -lgcc_eh 1176 // g++ static: -lgcc -lgcc_eh 1177 // gcc static-pie: -lgcc -lgcc_eh 1178 // g++ static-pie: -lgcc -lgcc_eh 1179 // 1180 // Also, certain targets need additional adjustments. 1181 1182 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 1183 ArgStringList &CmdArgs, const ArgList &Args) { 1184 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 1185 // Targets that don't use unwind libraries. 1186 if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() || 1187 TC.getTriple().isOSBinFormatWasm() || 1188 UNW == ToolChain::UNW_None) 1189 return; 1190 1191 LibGccType LGT = getLibGccType(D, Args); 1192 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 1193 !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing(); 1194 if (AsNeeded) 1195 CmdArgs.push_back("--as-needed"); 1196 1197 switch (UNW) { 1198 case ToolChain::UNW_None: 1199 return; 1200 case ToolChain::UNW_Libgcc: { 1201 if (LGT == LibGccType::StaticLibGcc) 1202 CmdArgs.push_back("-lgcc_eh"); 1203 else 1204 CmdArgs.push_back("-lgcc_s"); 1205 break; 1206 } 1207 case ToolChain::UNW_CompilerRT: 1208 CmdArgs.push_back("-lunwind"); 1209 break; 1210 } 1211 1212 if (AsNeeded) 1213 CmdArgs.push_back("--no-as-needed"); 1214 } 1215 1216 static void AddLibgcc(const ToolChain &TC, const Driver &D, 1217 ArgStringList &CmdArgs, const ArgList &Args) { 1218 LibGccType LGT = getLibGccType(D, Args); 1219 if (LGT != LibGccType::SharedLibGcc) 1220 CmdArgs.push_back("-lgcc"); 1221 AddUnwindLibrary(TC, D, CmdArgs, Args); 1222 if (LGT == LibGccType::SharedLibGcc) 1223 CmdArgs.push_back("-lgcc"); 1224 1225 // According to Android ABI, we have to link with libdl if we are 1226 // linking with non-static libgcc. 1227 // 1228 // NOTE: This fixes a link error on Android MIPS as well. The non-static 1229 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl. 1230 if (TC.getTriple().isAndroid() && LGT != LibGccType::StaticLibGcc) 1231 CmdArgs.push_back("-ldl"); 1232 } 1233 1234 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 1235 ArgStringList &CmdArgs, const ArgList &Args) { 1236 // Make use of compiler-rt if --rtlib option is used 1237 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 1238 1239 switch (RLT) { 1240 case ToolChain::RLT_CompilerRT: 1241 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 1242 AddUnwindLibrary(TC, D, CmdArgs, Args); 1243 break; 1244 case ToolChain::RLT_Libgcc: 1245 // Make sure libgcc is not used under MSVC environment by default 1246 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1247 // Issue error diagnostic if libgcc is explicitly specified 1248 // through command line as --rtlib option argument. 1249 if (Args.hasArg(options::OPT_rtlib_EQ)) { 1250 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 1251 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC"; 1252 } 1253 } else 1254 AddLibgcc(TC, D, CmdArgs, Args); 1255 break; 1256 } 1257 } 1258 1259 /// Add HIP linker script arguments at the end of the argument list so that 1260 /// the fat binary is built by embedding the device images into the host. The 1261 /// linker script also defines a symbol required by the code generation so that 1262 /// the image can be retrieved at runtime. This should be used only in tool 1263 /// chains that support linker scripts. 1264 void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C, 1265 const InputInfo &Output, 1266 const InputInfoList &Inputs, const ArgList &Args, 1267 ArgStringList &CmdArgs, const JobAction &JA, 1268 const Tool &T) { 1269 1270 // If this is not a HIP host toolchain, we don't need to do anything. 1271 if (!JA.isHostOffloading(Action::OFK_HIP)) 1272 return; 1273 1274 InputInfoList DeviceInputs; 1275 for (const auto &II : Inputs) { 1276 const Action *A = II.getAction(); 1277 // Is this a device linking action? 1278 if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) { 1279 DeviceInputs.push_back(II); 1280 } 1281 } 1282 1283 if (DeviceInputs.empty()) 1284 return; 1285 1286 // Create temporary linker script. Keep it if save-temps is enabled. 1287 const char *LKS; 1288 std::string Name = llvm::sys::path::filename(Output.getFilename()); 1289 if (C.getDriver().isSaveTempsEnabled()) { 1290 LKS = C.getArgs().MakeArgString(Name + ".lk"); 1291 } else { 1292 auto TmpName = C.getDriver().GetTemporaryPath(Name, "lk"); 1293 LKS = C.addTempFile(C.getArgs().MakeArgString(TmpName)); 1294 } 1295 1296 // Add linker script option to the command. 1297 CmdArgs.push_back("-T"); 1298 CmdArgs.push_back(LKS); 1299 1300 // Create a buffer to write the contents of the linker script. 1301 std::string LksBuffer; 1302 llvm::raw_string_ostream LksStream(LksBuffer); 1303 1304 // Get the HIP offload tool chain. 1305 auto *HIPTC = static_cast<const toolchains::CudaToolChain *>( 1306 C.getSingleOffloadToolChain<Action::OFK_HIP>()); 1307 assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn && 1308 "Wrong platform"); 1309 (void)HIPTC; 1310 1311 const char *BundleFile; 1312 if (C.getDriver().isSaveTempsEnabled()) { 1313 BundleFile = C.getArgs().MakeArgString(Name + ".hipfb"); 1314 } else { 1315 auto TmpName = C.getDriver().GetTemporaryPath(Name, "hipfb"); 1316 BundleFile = C.addTempFile(C.getArgs().MakeArgString(TmpName)); 1317 } 1318 AMDGCN::constructHIPFatbinCommand(C, JA, BundleFile, DeviceInputs, Args, T); 1319 1320 // Add commands to embed target binaries. We ensure that each section and 1321 // image is 16-byte aligned. This is not mandatory, but increases the 1322 // likelihood of data to be aligned with a cache block in several main host 1323 // machines. 1324 LksStream << "/*\n"; 1325 LksStream << " HIP Offload Linker Script\n"; 1326 LksStream << " *** Automatically generated by Clang ***\n"; 1327 LksStream << "*/\n"; 1328 LksStream << "TARGET(binary)\n"; 1329 LksStream << "INPUT(" << BundleFile << ")\n"; 1330 LksStream << "SECTIONS\n"; 1331 LksStream << "{\n"; 1332 LksStream << " .hip_fatbin :\n"; 1333 LksStream << " ALIGN(0x10)\n"; 1334 LksStream << " {\n"; 1335 LksStream << " PROVIDE_HIDDEN(__hip_fatbin = .);\n"; 1336 LksStream << " " << BundleFile << "\n"; 1337 LksStream << " }\n"; 1338 LksStream << " /DISCARD/ :\n"; 1339 LksStream << " {\n"; 1340 LksStream << " * ( __CLANG_OFFLOAD_BUNDLE__* )\n"; 1341 LksStream << " }\n"; 1342 LksStream << "}\n"; 1343 LksStream << "INSERT BEFORE .data\n"; 1344 LksStream.flush(); 1345 1346 // Dump the contents of the linker script if the user requested that. We 1347 // support this option to enable testing of behavior with -###. 1348 if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script)) 1349 llvm::errs() << LksBuffer; 1350 1351 // If this is a dry run, do not create the linker script file. 1352 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) 1353 return; 1354 1355 // Open script file and write the contents. 1356 std::error_code EC; 1357 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::OF_None); 1358 1359 if (EC) { 1360 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 1361 return; 1362 } 1363 1364 Lksf << LksBuffer; 1365 } 1366 1367 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 1368 const InputInfo &Output, 1369 const InputInfo &Input, 1370 const Driver &D) { 1371 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 1372 if (!A) 1373 return {}; 1374 1375 StringRef SaveStats = A->getValue(); 1376 SmallString<128> StatsFile; 1377 if (SaveStats == "obj" && Output.isFilename()) { 1378 StatsFile.assign(Output.getFilename()); 1379 llvm::sys::path::remove_filename(StatsFile); 1380 } else if (SaveStats != "cwd") { 1381 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 1382 return {}; 1383 } 1384 1385 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 1386 llvm::sys::path::append(StatsFile, BaseName); 1387 llvm::sys::path::replace_extension(StatsFile, "stats"); 1388 return StatsFile; 1389 } 1390 1391 void tools::addMultilibFlag(bool Enabled, const char *const Flag, 1392 Multilib::flags_list &Flags) { 1393 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag); 1394 } 1395 1396 static void getWebAssemblyTargetFeatures(const ArgList &Args, 1397 std::vector<StringRef> &Features) { 1398 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group); 1399 } 1400 1401 void tools::getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple, 1402 const ArgList &Args, ArgStringList &CmdArgs, bool ForAS, 1403 bool ForLTOPlugin) { 1404 1405 const Driver &D = TC.getDriver(); 1406 std::vector<StringRef> Features; 1407 switch (Triple.getArch()) { 1408 default: 1409 break; 1410 case llvm::Triple::mips: 1411 case llvm::Triple::mipsel: 1412 case llvm::Triple::mips64: 1413 case llvm::Triple::mips64el: 1414 mips::getMIPSTargetFeatures(D, Triple, Args, Features); 1415 break; 1416 1417 case llvm::Triple::arm: 1418 case llvm::Triple::armeb: 1419 case llvm::Triple::thumb: 1420 case llvm::Triple::thumbeb: 1421 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS); 1422 break; 1423 1424 case llvm::Triple::ppc: 1425 case llvm::Triple::ppc64: 1426 case llvm::Triple::ppc64le: 1427 ppc::getPPCTargetFeatures(D, Triple, Args, Features); 1428 break; 1429 case llvm::Triple::riscv32: 1430 case llvm::Triple::riscv64: 1431 riscv::getRISCVTargetFeatures(D, Triple, Args, Features); 1432 break; 1433 case llvm::Triple::systemz: 1434 systemz::getSystemZTargetFeatures(Args, Features); 1435 break; 1436 case llvm::Triple::aarch64: 1437 case llvm::Triple::aarch64_be: 1438 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features); 1439 break; 1440 case llvm::Triple::x86: 1441 case llvm::Triple::x86_64: 1442 x86::getX86TargetFeatures(D, Triple, Args, Features); 1443 break; 1444 case llvm::Triple::hexagon: 1445 hexagon::getHexagonTargetFeatures(D, Args, Features); 1446 break; 1447 case llvm::Triple::wasm32: 1448 case llvm::Triple::wasm64: 1449 getWebAssemblyTargetFeatures(Args, Features); 1450 break; 1451 case llvm::Triple::sparc: 1452 case llvm::Triple::sparcel: 1453 case llvm::Triple::sparcv9: 1454 sparc::getSparcTargetFeatures(D, Args, Features); 1455 break; 1456 case llvm::Triple::r600: 1457 case llvm::Triple::amdgcn: 1458 amdgpu::getAMDGPUTargetFeatures(D, Args, Features); 1459 break; 1460 case llvm::Triple::msp430: 1461 msp430::getMSP430TargetFeatures(D, Args, Features); 1462 } 1463 1464 // Find the last of each feature. 1465 llvm::StringMap<unsigned> LastOpt; 1466 for (unsigned I = 0, N = Features.size(); I < N; ++I) { 1467 StringRef Name = Features[I]; 1468 assert(Name[0] == '-' || Name[0] == '+'); 1469 LastOpt[Name.drop_front(1)] = I; 1470 } 1471 1472 for (unsigned I = 0, N = Features.size(); I < N; ++I) { 1473 // If this feature was overridden, ignore it. 1474 StringRef Name = Features[I]; 1475 llvm::StringMap<unsigned>::iterator LastI = 1476 LastOpt.find(Name.drop_front(1)); 1477 assert(LastI != LastOpt.end()); 1478 unsigned Last = LastI->second; 1479 if (Last != I) 1480 continue; 1481 if (!ForLTOPlugin) { 1482 CmdArgs.push_back("-target-feature"); 1483 CmdArgs.push_back(Name.data()); 1484 } else { 1485 CmdArgs.push_back( 1486 Args.MakeArgString(Twine("-plugin-opt=-mattr=") + Name)); 1487 } 1488 } 1489 } 1490 1491 StringRef tools::getTargetABI(const ArgList &Args, const llvm::Triple &Triple) { 1492 // TODO: Support the other target ABI 1493 switch (Triple.getArch()) { 1494 default: 1495 break; 1496 case llvm::Triple::riscv32: 1497 case llvm::Triple::riscv64: 1498 return tools::riscv::getRISCVABI(Args, Triple); 1499 break; 1500 } 1501 return StringRef(); 1502 } 1503