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