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/CSKY.h" 13 #include "Arch/LoongArch.h" 14 #include "Arch/M68k.h" 15 #include "Arch/Mips.h" 16 #include "Arch/PPC.h" 17 #include "Arch/RISCV.h" 18 #include "Arch/Sparc.h" 19 #include "Arch/SystemZ.h" 20 #include "Arch/VE.h" 21 #include "Arch/X86.h" 22 #include "HIPAMD.h" 23 #include "Hexagon.h" 24 #include "MSP430.h" 25 #include "clang/Basic/CharInfo.h" 26 #include "clang/Basic/LangOptions.h" 27 #include "clang/Basic/ObjCRuntime.h" 28 #include "clang/Basic/Version.h" 29 #include "clang/Config/config.h" 30 #include "clang/Driver/Action.h" 31 #include "clang/Driver/Compilation.h" 32 #include "clang/Driver/Driver.h" 33 #include "clang/Driver/DriverDiagnostic.h" 34 #include "clang/Driver/InputInfo.h" 35 #include "clang/Driver/Job.h" 36 #include "clang/Driver/Options.h" 37 #include "clang/Driver/SanitizerArgs.h" 38 #include "clang/Driver/ToolChain.h" 39 #include "clang/Driver/Util.h" 40 #include "clang/Driver/XRayArgs.h" 41 #include "llvm/ADT/STLExtras.h" 42 #include "llvm/ADT/SmallSet.h" 43 #include "llvm/ADT/SmallString.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include "llvm/ADT/StringSwitch.h" 46 #include "llvm/ADT/Twine.h" 47 #include "llvm/BinaryFormat/Magic.h" 48 #include "llvm/Config/llvm-config.h" 49 #include "llvm/Option/Arg.h" 50 #include "llvm/Option/ArgList.h" 51 #include "llvm/Option/Option.h" 52 #include "llvm/Support/CodeGen.h" 53 #include "llvm/Support/Compression.h" 54 #include "llvm/Support/Debug.h" 55 #include "llvm/Support/ErrorHandling.h" 56 #include "llvm/Support/FileSystem.h" 57 #include "llvm/Support/Host.h" 58 #include "llvm/Support/Path.h" 59 #include "llvm/Support/Process.h" 60 #include "llvm/Support/Program.h" 61 #include "llvm/Support/ScopedPrinter.h" 62 #include "llvm/Support/TargetParser.h" 63 #include "llvm/Support/Threading.h" 64 #include "llvm/Support/VirtualFileSystem.h" 65 #include "llvm/Support/YAMLParser.h" 66 #include <optional> 67 68 using namespace clang::driver; 69 using namespace clang::driver::tools; 70 using namespace clang; 71 using namespace llvm::opt; 72 73 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs, 74 const StringRef PluginOptPrefix) { 75 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ)) 76 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 77 "-pass-remarks=" + A->getValue())); 78 79 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ)) 80 CmdArgs.push_back(Args.MakeArgString( 81 Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue())); 82 83 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ)) 84 CmdArgs.push_back(Args.MakeArgString( 85 Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue())); 86 } 87 88 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, 89 const llvm::Triple &Triple, 90 const InputInfo &Input, 91 const InputInfo &Output, 92 const StringRef PluginOptPrefix) { 93 StringRef Format = "yaml"; 94 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) 95 Format = A->getValue(); 96 97 SmallString<128> F; 98 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ); 99 if (A) 100 F = A->getValue(); 101 else if (Output.isFilename()) 102 F = Output.getFilename(); 103 104 assert(!F.empty() && "Cannot determine remarks output name."); 105 // Append "opt.ld.<format>" to the end of the file name. 106 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 107 "opt-remarks-filename=" + F + 108 ".opt.ld." + Format)); 109 110 if (const Arg *A = 111 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) 112 CmdArgs.push_back(Args.MakeArgString( 113 Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue())); 114 115 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 116 "opt-remarks-format=" + Format.data())); 117 } 118 119 static void renderRemarksHotnessOptions(const ArgList &Args, 120 ArgStringList &CmdArgs, 121 const StringRef PluginOptPrefix) { 122 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness, 123 options::OPT_fno_diagnostics_show_hotness, false)) 124 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 125 "opt-remarks-with-hotness")); 126 127 if (const Arg *A = 128 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) 129 CmdArgs.push_back( 130 Args.MakeArgString(Twine(PluginOptPrefix) + 131 "opt-remarks-hotness-threshold=" + A->getValue())); 132 } 133 134 void tools::addPathIfExists(const Driver &D, const Twine &Path, 135 ToolChain::path_list &Paths) { 136 if (D.getVFS().exists(Path)) 137 Paths.push_back(Path.str()); 138 } 139 140 void tools::handleTargetFeaturesGroup(const ArgList &Args, 141 std::vector<StringRef> &Features, 142 OptSpecifier Group) { 143 for (const Arg *A : Args.filtered(Group)) { 144 StringRef Name = A->getOption().getName(); 145 A->claim(); 146 147 // Skip over "-m". 148 assert(Name.startswith("m") && "Invalid feature name."); 149 Name = Name.substr(1); 150 151 bool IsNegative = Name.startswith("no-"); 152 if (IsNegative) 153 Name = Name.substr(3); 154 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); 155 } 156 } 157 158 SmallVector<StringRef> 159 tools::unifyTargetFeatures(ArrayRef<StringRef> Features) { 160 // Only add a feature if it hasn't been seen before starting from the end. 161 SmallVector<StringRef> UnifiedFeatures; 162 llvm::DenseSet<StringRef> UsedFeatures; 163 for (StringRef Feature : llvm::reverse(Features)) { 164 if (UsedFeatures.insert(Feature.drop_front()).second) 165 UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature); 166 } 167 168 return UnifiedFeatures; 169 } 170 171 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, 172 const char *ArgName, const char *EnvVar) { 173 const char *DirList = ::getenv(EnvVar); 174 bool CombinedArg = false; 175 176 if (!DirList) 177 return; // Nothing to do. 178 179 StringRef Name(ArgName); 180 if (Name.equals("-I") || Name.equals("-L") || Name.empty()) 181 CombinedArg = true; 182 183 StringRef Dirs(DirList); 184 if (Dirs.empty()) // Empty string should not add '.'. 185 return; 186 187 StringRef::size_type Delim; 188 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) { 189 if (Delim == 0) { // Leading colon. 190 if (CombinedArg) { 191 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 192 } else { 193 CmdArgs.push_back(ArgName); 194 CmdArgs.push_back("."); 195 } 196 } else { 197 if (CombinedArg) { 198 CmdArgs.push_back( 199 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); 200 } else { 201 CmdArgs.push_back(ArgName); 202 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); 203 } 204 } 205 Dirs = Dirs.substr(Delim + 1); 206 } 207 208 if (Dirs.empty()) { // Trailing colon. 209 if (CombinedArg) { 210 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 211 } else { 212 CmdArgs.push_back(ArgName); 213 CmdArgs.push_back("."); 214 } 215 } else { // Add the last path. 216 if (CombinedArg) { 217 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); 218 } else { 219 CmdArgs.push_back(ArgName); 220 CmdArgs.push_back(Args.MakeArgString(Dirs)); 221 } 222 } 223 } 224 225 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, 226 const ArgList &Args, ArgStringList &CmdArgs, 227 const JobAction &JA) { 228 const Driver &D = TC.getDriver(); 229 230 // Add extra linker input arguments which are not treated as inputs 231 // (constructed via -Xarch_). 232 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); 233 234 // LIBRARY_PATH are included before user inputs and only supported on native 235 // toolchains. 236 if (!TC.isCrossCompiling()) 237 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); 238 239 for (const auto &II : Inputs) { 240 // If the current tool chain refers to an OpenMP offloading host, we 241 // should ignore inputs that refer to OpenMP offloading devices - 242 // they will be embedded according to a proper linker script. 243 if (auto *IA = II.getAction()) 244 if ((JA.isHostOffloading(Action::OFK_OpenMP) && 245 IA->isDeviceOffloading(Action::OFK_OpenMP))) 246 continue; 247 248 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType())) 249 // Don't try to pass LLVM inputs unless we have native support. 250 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); 251 252 // Add filenames immediately. 253 if (II.isFilename()) { 254 CmdArgs.push_back(II.getFilename()); 255 continue; 256 } 257 258 // In some error cases, the input could be Nothing; skip those. 259 if (II.isNothing()) 260 continue; 261 262 // Otherwise, this is a linker input argument. 263 const Arg &A = II.getInputArg(); 264 265 // Handle reserved library options. 266 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) 267 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 268 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) 269 TC.AddCCKextLibArgs(Args, CmdArgs); 270 else if (A.getOption().matches(options::OPT_z)) { 271 // Pass -z prefix for gcc linker compatibility. 272 A.claim(); 273 A.render(Args, CmdArgs); 274 } else if (A.getOption().matches(options::OPT_b)) { 275 const llvm::Triple &T = TC.getTriple(); 276 if (!T.isOSAIX()) { 277 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 278 << A.getSpelling() << T.str(); 279 } 280 // Pass -b prefix for AIX linker. 281 A.claim(); 282 A.render(Args, CmdArgs); 283 } else { 284 A.renderAsInput(Args, CmdArgs); 285 } 286 } 287 } 288 289 void tools::addLinkerCompressDebugSectionsOption( 290 const ToolChain &TC, const llvm::opt::ArgList &Args, 291 llvm::opt::ArgStringList &CmdArgs) { 292 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi 293 // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore 294 // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz 295 // is not translated since ld --compress-debug-sections option requires an 296 // argument. 297 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) { 298 StringRef V = A->getValue(); 299 if (V == "none" || V == "zlib" || V == "zstd") 300 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V)); 301 else 302 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument) 303 << A->getSpelling() << V; 304 } 305 } 306 307 void tools::AddTargetFeature(const ArgList &Args, 308 std::vector<StringRef> &Features, 309 OptSpecifier OnOpt, OptSpecifier OffOpt, 310 StringRef FeatureName) { 311 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { 312 if (A->getOption().matches(OnOpt)) 313 Features.push_back(Args.MakeArgString("+" + FeatureName)); 314 else 315 Features.push_back(Args.MakeArgString("-" + FeatureName)); 316 } 317 } 318 319 /// Get the (LLVM) name of the AMDGPU gpu we are targeting. 320 static std::string getAMDGPUTargetGPU(const llvm::Triple &T, 321 const ArgList &Args) { 322 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 323 auto GPUName = getProcessorFromTargetID(T, A->getValue()); 324 return llvm::StringSwitch<std::string>(GPUName) 325 .Cases("rv630", "rv635", "r600") 326 .Cases("rv610", "rv620", "rs780", "rs880") 327 .Case("rv740", "rv770") 328 .Case("palm", "cedar") 329 .Cases("sumo", "sumo2", "sumo") 330 .Case("hemlock", "cypress") 331 .Case("aruba", "cayman") 332 .Default(GPUName.str()); 333 } 334 return ""; 335 } 336 337 static std::string getLanaiTargetCPU(const ArgList &Args) { 338 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 339 return A->getValue(); 340 } 341 return ""; 342 } 343 344 /// Get the (LLVM) name of the WebAssembly cpu we are targeting. 345 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { 346 // If we have -mcpu=, use that. 347 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 348 StringRef CPU = A->getValue(); 349 350 #ifdef __wasm__ 351 // Handle "native" by examining the host. "native" isn't meaningful when 352 // cross compiling, so only support this when the host is also WebAssembly. 353 if (CPU == "native") 354 return llvm::sys::getHostCPUName(); 355 #endif 356 357 return CPU; 358 } 359 360 return "generic"; 361 } 362 363 std::string tools::getCPUName(const Driver &D, const ArgList &Args, 364 const llvm::Triple &T, bool FromAs) { 365 Arg *A; 366 367 switch (T.getArch()) { 368 default: 369 return ""; 370 371 case llvm::Triple::aarch64: 372 case llvm::Triple::aarch64_32: 373 case llvm::Triple::aarch64_be: 374 return aarch64::getAArch64TargetCPU(Args, T, A); 375 376 case llvm::Triple::arm: 377 case llvm::Triple::armeb: 378 case llvm::Triple::thumb: 379 case llvm::Triple::thumbeb: { 380 StringRef MArch, MCPU; 381 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs); 382 return arm::getARMTargetCPU(MCPU, MArch, T); 383 } 384 385 case llvm::Triple::avr: 386 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ)) 387 return A->getValue(); 388 return ""; 389 390 case llvm::Triple::m68k: 391 return m68k::getM68kTargetCPU(Args); 392 393 case llvm::Triple::mips: 394 case llvm::Triple::mipsel: 395 case llvm::Triple::mips64: 396 case llvm::Triple::mips64el: { 397 StringRef CPUName; 398 StringRef ABIName; 399 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName); 400 return std::string(CPUName); 401 } 402 403 case llvm::Triple::nvptx: 404 case llvm::Triple::nvptx64: 405 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 406 return A->getValue(); 407 return ""; 408 409 case llvm::Triple::ppc: 410 case llvm::Triple::ppcle: 411 case llvm::Triple::ppc64: 412 case llvm::Triple::ppc64le: 413 return ppc::getPPCTargetCPU(Args, T); 414 415 case llvm::Triple::csky: 416 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 417 return A->getValue(); 418 else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 419 return A->getValue(); 420 else 421 return "ck810"; 422 case llvm::Triple::riscv32: 423 case llvm::Triple::riscv64: 424 return riscv::getRISCVTargetCPU(Args, T); 425 426 case llvm::Triple::bpfel: 427 case llvm::Triple::bpfeb: 428 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 429 return A->getValue(); 430 return ""; 431 432 case llvm::Triple::sparc: 433 case llvm::Triple::sparcel: 434 case llvm::Triple::sparcv9: 435 return sparc::getSparcTargetCPU(D, Args, T); 436 437 case llvm::Triple::x86: 438 case llvm::Triple::x86_64: 439 return x86::getX86TargetCPU(D, Args, T); 440 441 case llvm::Triple::hexagon: 442 return "hexagon" + 443 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); 444 445 case llvm::Triple::lanai: 446 return getLanaiTargetCPU(Args); 447 448 case llvm::Triple::systemz: 449 return systemz::getSystemZTargetCPU(Args); 450 451 case llvm::Triple::r600: 452 case llvm::Triple::amdgcn: 453 return getAMDGPUTargetGPU(T, Args); 454 455 case llvm::Triple::wasm32: 456 case llvm::Triple::wasm64: 457 return std::string(getWebAssemblyTargetCPU(Args)); 458 } 459 } 460 461 static void getWebAssemblyTargetFeatures(const ArgList &Args, 462 std::vector<StringRef> &Features) { 463 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group); 464 } 465 466 void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple, 467 const ArgList &Args, ArgStringList &CmdArgs, 468 bool ForAS, bool IsAux) { 469 std::vector<StringRef> Features; 470 switch (Triple.getArch()) { 471 default: 472 break; 473 case llvm::Triple::mips: 474 case llvm::Triple::mipsel: 475 case llvm::Triple::mips64: 476 case llvm::Triple::mips64el: 477 mips::getMIPSTargetFeatures(D, Triple, Args, Features); 478 break; 479 case llvm::Triple::arm: 480 case llvm::Triple::armeb: 481 case llvm::Triple::thumb: 482 case llvm::Triple::thumbeb: 483 arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS); 484 break; 485 case llvm::Triple::ppc: 486 case llvm::Triple::ppcle: 487 case llvm::Triple::ppc64: 488 case llvm::Triple::ppc64le: 489 ppc::getPPCTargetFeatures(D, Triple, Args, Features); 490 break; 491 case llvm::Triple::riscv32: 492 case llvm::Triple::riscv64: 493 riscv::getRISCVTargetFeatures(D, Triple, Args, Features); 494 break; 495 case llvm::Triple::systemz: 496 systemz::getSystemZTargetFeatures(D, Args, Features); 497 break; 498 case llvm::Triple::aarch64: 499 case llvm::Triple::aarch64_32: 500 case llvm::Triple::aarch64_be: 501 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS); 502 break; 503 case llvm::Triple::x86: 504 case llvm::Triple::x86_64: 505 x86::getX86TargetFeatures(D, Triple, Args, Features); 506 break; 507 case llvm::Triple::hexagon: 508 hexagon::getHexagonTargetFeatures(D, Args, Features); 509 break; 510 case llvm::Triple::wasm32: 511 case llvm::Triple::wasm64: 512 getWebAssemblyTargetFeatures(Args, Features); 513 break; 514 case llvm::Triple::sparc: 515 case llvm::Triple::sparcel: 516 case llvm::Triple::sparcv9: 517 sparc::getSparcTargetFeatures(D, Args, Features); 518 break; 519 case llvm::Triple::r600: 520 case llvm::Triple::amdgcn: 521 amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features); 522 break; 523 case llvm::Triple::nvptx: 524 case llvm::Triple::nvptx64: 525 NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features); 526 break; 527 case llvm::Triple::m68k: 528 m68k::getM68kTargetFeatures(D, Triple, Args, Features); 529 break; 530 case llvm::Triple::msp430: 531 msp430::getMSP430TargetFeatures(D, Args, Features); 532 break; 533 case llvm::Triple::ve: 534 ve::getVETargetFeatures(D, Args, Features); 535 break; 536 case llvm::Triple::csky: 537 csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features); 538 break; 539 case llvm::Triple::loongarch32: 540 case llvm::Triple::loongarch64: 541 loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features); 542 break; 543 } 544 545 for (auto Feature : unifyTargetFeatures(Features)) { 546 CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature"); 547 CmdArgs.push_back(Feature.data()); 548 } 549 } 550 551 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) { 552 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ); 553 if (!LtoJobsArg) 554 return {}; 555 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue())) 556 D.Diag(diag::err_drv_invalid_int_value) 557 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue(); 558 return LtoJobsArg->getValue(); 559 } 560 561 // CloudABI and PS4/PS5 use -ffunction-sections and -fdata-sections by default. 562 bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 563 return Triple.getOS() == llvm::Triple::CloudABI || Triple.isPS(); 564 } 565 566 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args, 567 ArgStringList &CmdArgs, const InputInfo &Output, 568 const InputInfo &Input, bool IsThinLTO) { 569 const bool IsOSAIX = ToolChain.getTriple().isOSAIX(); 570 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath()); 571 const Driver &D = ToolChain.getDriver(); 572 if (llvm::sys::path::filename(Linker) != "ld.lld" && 573 llvm::sys::path::stem(Linker) != "ld.lld") { 574 // Tell the linker to load the plugin. This has to come before 575 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to 576 // come before any -plugin-opt/-bplugin_opt that -Wl might forward. 577 const char *PluginPrefix = IsOSAIX ? "-bplugin:" : ""; 578 const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold"; 579 580 if (!IsOSAIX) 581 CmdArgs.push_back("-plugin"); 582 583 #if defined(_WIN32) 584 const char *Suffix = ".dll"; 585 #elif defined(__APPLE__) 586 const char *Suffix = ".dylib"; 587 #else 588 const char *Suffix = ".so"; 589 #endif 590 591 SmallString<1024> Plugin; 592 llvm::sys::path::native(Twine(D.Dir) + 593 "/../" CLANG_INSTALL_LIBDIR_BASENAME + 594 PluginName + Suffix, 595 Plugin); 596 CmdArgs.push_back(Args.MakeArgString(Twine(PluginPrefix) + Plugin)); 597 } 598 599 const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt="; 600 const char *ExtraDash = IsOSAIX ? "-" : ""; 601 602 // Note, this solution is far from perfect, better to encode it into IR 603 // metadata, but this may not be worth it, since it looks like aranges is on 604 // the way out. 605 if (Args.hasArg(options::OPT_gdwarf_aranges)) { 606 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 607 "-generate-arange-section")); 608 } 609 610 // Try to pass driver level flags relevant to LTO code generation down to 611 // the plugin. 612 613 // Handle flags for selecting CPU variants. 614 std::string CPU = getCPUName(D, Args, ToolChain.getTriple()); 615 if (!CPU.empty()) 616 CmdArgs.push_back( 617 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU)); 618 619 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 620 // The optimization level matches 621 // CompilerInvocation.cpp:getOptimizationLevel(). 622 StringRef OOpt; 623 if (A->getOption().matches(options::OPT_O4) || 624 A->getOption().matches(options::OPT_Ofast)) 625 OOpt = "3"; 626 else if (A->getOption().matches(options::OPT_O)) { 627 OOpt = A->getValue(); 628 if (OOpt == "g") 629 OOpt = "1"; 630 else if (OOpt == "s" || OOpt == "z") 631 OOpt = "2"; 632 } else if (A->getOption().matches(options::OPT_O0)) 633 OOpt = "0"; 634 if (!OOpt.empty()) 635 CmdArgs.push_back( 636 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt)); 637 } 638 639 if (Args.hasArg(options::OPT_gsplit_dwarf)) 640 CmdArgs.push_back(Args.MakeArgString( 641 Twine(PluginOptPrefix) + "dwo_dir=" + Output.getFilename() + "_dwo")); 642 643 if (IsThinLTO) 644 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "thinlto")); 645 646 StringRef Parallelism = getLTOParallelism(Args, D); 647 if (!Parallelism.empty()) 648 CmdArgs.push_back( 649 Args.MakeArgString(Twine(PluginOptPrefix) + "jobs=" + Parallelism)); 650 651 // If an explicit debugger tuning argument appeared, pass it along. 652 if (Arg *A = 653 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) { 654 if (A->getOption().matches(options::OPT_glldb)) 655 CmdArgs.push_back( 656 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=lldb")); 657 else if (A->getOption().matches(options::OPT_gsce)) 658 CmdArgs.push_back( 659 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=sce")); 660 else if (A->getOption().matches(options::OPT_gdbx)) 661 CmdArgs.push_back( 662 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=dbx")); 663 else 664 CmdArgs.push_back( 665 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=gdb")); 666 } 667 668 if (IsOSAIX) { 669 // On AIX, clang assumes strict-dwarf is true if any debug option is 670 // specified, unless it is told explicitly not to assume so. 671 Arg *A = Args.getLastArg(options::OPT_g_Group); 672 bool EnableDebugInfo = A && !A->getOption().matches(options::OPT_g0) && 673 !A->getOption().matches(options::OPT_ggdb0); 674 if (EnableDebugInfo && Args.hasFlag(options::OPT_gstrict_dwarf, 675 options::OPT_gno_strict_dwarf, true)) 676 CmdArgs.push_back( 677 Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true")); 678 679 if (Args.getLastArg(options::OPT_mabi_EQ_vec_extabi)) 680 CmdArgs.push_back( 681 Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi")); 682 } 683 684 bool UseSeparateSections = 685 isUseSeparateSections(ToolChain.getEffectiveTriple()); 686 687 if (Args.hasFlag(options::OPT_ffunction_sections, 688 options::OPT_fno_function_sections, UseSeparateSections)) 689 CmdArgs.push_back( 690 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=1")); 691 else if (Args.hasArg(options::OPT_fno_function_sections)) 692 CmdArgs.push_back( 693 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=0")); 694 695 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 696 UseSeparateSections)) 697 CmdArgs.push_back( 698 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1")); 699 else if (Args.hasArg(options::OPT_fno_data_sections)) 700 CmdArgs.push_back( 701 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=0")); 702 703 // Pass an option to enable split machine functions. 704 if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions, 705 options::OPT_fno_split_machine_functions)) { 706 if (A->getOption().matches(options::OPT_fsplit_machine_functions)) 707 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 708 "-split-machine-functions")); 709 } 710 711 if (Arg *A = getLastProfileSampleUseArg(Args)) { 712 StringRef FName = A->getValue(); 713 if (!llvm::sys::fs::exists(FName)) 714 D.Diag(diag::err_drv_no_such_file) << FName; 715 else 716 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 717 "sample-profile=" + FName)); 718 } 719 720 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 721 options::OPT_fcs_profile_generate_EQ, 722 options::OPT_fno_profile_generate); 723 if (CSPGOGenerateArg && 724 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 725 CSPGOGenerateArg = nullptr; 726 727 auto *ProfileUseArg = getLastProfileUseArg(Args); 728 729 if (CSPGOGenerateArg) { 730 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 731 "cs-profile-generate")); 732 if (CSPGOGenerateArg->getOption().matches( 733 options::OPT_fcs_profile_generate_EQ)) { 734 SmallString<128> Path(CSPGOGenerateArg->getValue()); 735 llvm::sys::path::append(Path, "default_%m.profraw"); 736 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 737 "cs-profile-path=" + Path)); 738 } else 739 CmdArgs.push_back( 740 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 741 "cs-profile-path=default_%m.profraw")); 742 } else if (ProfileUseArg) { 743 SmallString<128> Path( 744 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 745 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 746 llvm::sys::path::append(Path, "default.profdata"); 747 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 748 "cs-profile-path=" + Path)); 749 } 750 751 // This controls whether or not we perform JustMyCode instrumentation. 752 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) { 753 if (ToolChain.getEffectiveTriple().isOSBinFormatELF()) 754 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 755 "-enable-jmc-instrument")); 756 else 757 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only); 758 } 759 760 if (Arg *A = Args.getLastArg(options::OPT_femulated_tls, 761 options::OPT_fno_emulated_tls)) { 762 bool Enable = A->getOption().getID() == options::OPT_femulated_tls; 763 CmdArgs.push_back(Args.MakeArgString( 764 Twine(PluginOptPrefix) + "-emulated-tls=" + (Enable ? "1" : "0"))); 765 } 766 767 if (Args.hasFlag(options::OPT_fstack_size_section, 768 options::OPT_fno_stack_size_section, false)) 769 CmdArgs.push_back( 770 Args.MakeArgString(Twine(PluginOptPrefix) + "-stack-size-section")); 771 772 // Setup statistics file output. 773 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 774 if (!StatsFile.empty()) 775 CmdArgs.push_back( 776 Args.MakeArgString(Twine(PluginOptPrefix) + "stats-file=" + StatsFile)); 777 778 // Setup crash diagnostics dir. 779 if (Arg *A = Args.getLastArg(options::OPT_fcrash_diagnostics_dir)) 780 CmdArgs.push_back(Args.MakeArgString( 781 Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue())); 782 783 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix); 784 785 // Handle remark diagnostics on screen options: '-Rpass-*'. 786 renderRpassOptions(Args, CmdArgs, PluginOptPrefix); 787 788 // Handle serialized remarks options: '-fsave-optimization-record' 789 // and '-foptimization-record-*'. 790 if (willEmitRemarks(Args)) 791 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input, 792 Output, PluginOptPrefix); 793 794 // Handle remarks hotness/threshold related options. 795 renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix); 796 797 addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(), 798 /*IsLTO=*/true, PluginOptPrefix); 799 } 800 801 void tools::addOpenMPRuntimeSpecificRPath(const ToolChain &TC, 802 const ArgList &Args, 803 ArgStringList &CmdArgs) { 804 805 if (Args.hasFlag(options::OPT_fopenmp_implicit_rpath, 806 options::OPT_fno_openmp_implicit_rpath, true)) { 807 // Default to clang lib / lib64 folder, i.e. the same location as device 808 // runtime 809 SmallString<256> DefaultLibPath = 810 llvm::sys::path::parent_path(TC.getDriver().Dir); 811 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 812 CmdArgs.push_back("-rpath"); 813 CmdArgs.push_back(Args.MakeArgString(DefaultLibPath)); 814 } 815 } 816 817 void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC, 818 const ArgList &Args, 819 ArgStringList &CmdArgs) { 820 // Default to clang lib / lib64 folder, i.e. the same location as device 821 // runtime. 822 SmallString<256> DefaultLibPath = 823 llvm::sys::path::parent_path(TC.getDriver().Dir); 824 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 825 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath)); 826 } 827 828 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 829 ArgStringList &CmdArgs) { 830 // Enable -frtlib-add-rpath by default for the case of VE. 831 const bool IsVE = TC.getTriple().isVE(); 832 bool DefaultValue = IsVE; 833 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 834 options::OPT_fno_rtlib_add_rpath, DefaultValue)) 835 return; 836 837 std::string CandidateRPath = TC.getArchSpecificLibPath(); 838 if (TC.getVFS().exists(CandidateRPath)) { 839 CmdArgs.push_back("-rpath"); 840 CmdArgs.push_back(Args.MakeArgString(CandidateRPath)); 841 } 842 } 843 844 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, 845 const ArgList &Args, bool ForceStaticHostRuntime, 846 bool IsOffloadingHost, bool GompNeedsRT) { 847 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 848 options::OPT_fno_openmp, false)) 849 return false; 850 851 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 852 853 if (RTKind == Driver::OMPRT_Unknown) 854 // Already diagnosed. 855 return false; 856 857 if (ForceStaticHostRuntime) 858 CmdArgs.push_back("-Bstatic"); 859 860 switch (RTKind) { 861 case Driver::OMPRT_OMP: 862 CmdArgs.push_back("-lomp"); 863 break; 864 case Driver::OMPRT_GOMP: 865 CmdArgs.push_back("-lgomp"); 866 break; 867 case Driver::OMPRT_IOMP5: 868 CmdArgs.push_back("-liomp5"); 869 break; 870 case Driver::OMPRT_Unknown: 871 break; 872 } 873 874 if (ForceStaticHostRuntime) 875 CmdArgs.push_back("-Bdynamic"); 876 877 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 878 CmdArgs.push_back("-lrt"); 879 880 if (IsOffloadingHost) 881 CmdArgs.push_back("-lomptarget"); 882 883 if (IsOffloadingHost && !Args.hasArg(options::OPT_nogpulib)) 884 CmdArgs.push_back("-lomptarget.devicertl"); 885 886 addArchSpecificRPath(TC, Args, CmdArgs); 887 888 if (RTKind == Driver::OMPRT_OMP) 889 addOpenMPRuntimeSpecificRPath(TC, Args, CmdArgs); 890 addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs); 891 892 return true; 893 } 894 895 void tools::addFortranRuntimeLibs(const ToolChain &TC, 896 llvm::opt::ArgStringList &CmdArgs) { 897 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 898 CmdArgs.push_back("Fortran_main.lib"); 899 CmdArgs.push_back("FortranRuntime.lib"); 900 CmdArgs.push_back("FortranDecimal.lib"); 901 } else { 902 CmdArgs.push_back("-lFortran_main"); 903 CmdArgs.push_back("-lFortranRuntime"); 904 CmdArgs.push_back("-lFortranDecimal"); 905 } 906 } 907 908 void tools::addFortranRuntimeLibraryPath(const ToolChain &TC, 909 const llvm::opt::ArgList &Args, 910 ArgStringList &CmdArgs) { 911 // NOTE: Generating executables by Flang is considered an "experimental" 912 // feature and hence this is guarded with a command line option. 913 // TODO: Make this work unconditionally once Flang is mature enough. 914 if (!Args.hasArg(options::OPT_flang_experimental_exec)) 915 return; 916 917 // Default to the <driver-path>/../lib directory. This works fine on the 918 // platforms that we have tested so far. We will probably have to re-fine 919 // this in the future. In particular, on some platforms, we may need to use 920 // lib64 instead of lib. 921 SmallString<256> DefaultLibPath = 922 llvm::sys::path::parent_path(TC.getDriver().Dir); 923 llvm::sys::path::append(DefaultLibPath, "lib"); 924 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) 925 CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath)); 926 else 927 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath)); 928 } 929 930 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 931 ArgStringList &CmdArgs, StringRef Sanitizer, 932 bool IsShared, bool IsWhole) { 933 // Wrap any static runtimes that must be forced into executable in 934 // whole-archive. 935 if (IsWhole) CmdArgs.push_back("--whole-archive"); 936 CmdArgs.push_back(TC.getCompilerRTArgString( 937 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 938 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 939 940 if (IsShared) { 941 addArchSpecificRPath(TC, Args, CmdArgs); 942 } 943 } 944 945 // Tries to use a file with the list of dynamic symbols that need to be exported 946 // from the runtime library. Returns true if the file was found. 947 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 948 ArgStringList &CmdArgs, 949 StringRef Sanitizer) { 950 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 951 // the option, so don't try to pass it. 952 if (TC.getTriple().getOS() == llvm::Triple::Solaris) 953 return true; 954 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 955 if (llvm::sys::fs::exists(SanRT + ".syms")) { 956 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 957 return true; 958 } 959 return false; 960 } 961 962 const char *tools::getAsNeededOption(const ToolChain &TC, bool as_needed) { 963 assert(!TC.getTriple().isOSAIX() && 964 "AIX linker does not support any form of --as-needed option yet."); 965 966 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases 967 // for the native forms -z ignore/-z record, they are missing in Illumos, 968 // so always use the native form. 969 if (TC.getTriple().isOSSolaris()) 970 return as_needed ? "-zignore" : "-zrecord"; 971 else 972 return as_needed ? "--as-needed" : "--no-as-needed"; 973 } 974 975 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 976 ArgStringList &CmdArgs) { 977 // Force linking against the system libraries sanitizers depends on 978 // (see PR15823 why this is necessary). 979 CmdArgs.push_back(getAsNeededOption(TC, false)); 980 // There's no libpthread or librt on RTEMS & Android. 981 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 982 !TC.getTriple().isAndroid()) { 983 CmdArgs.push_back("-lpthread"); 984 if (!TC.getTriple().isOSOpenBSD()) 985 CmdArgs.push_back("-lrt"); 986 } 987 CmdArgs.push_back("-lm"); 988 // There's no libdl on all OSes. 989 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() && 990 !TC.getTriple().isOSOpenBSD() && 991 TC.getTriple().getOS() != llvm::Triple::RTEMS) 992 CmdArgs.push_back("-ldl"); 993 // Required for backtrace on some OSes 994 if (TC.getTriple().isOSFreeBSD() || 995 TC.getTriple().isOSNetBSD() || 996 TC.getTriple().isOSOpenBSD()) 997 CmdArgs.push_back("-lexecinfo"); 998 // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl 999 // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv 1000 // requirement. 1001 if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() && 1002 !TC.getTriple().isMusl()) 1003 CmdArgs.push_back("-lresolv"); 1004 } 1005 1006 static void 1007 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 1008 SmallVectorImpl<StringRef> &SharedRuntimes, 1009 SmallVectorImpl<StringRef> &StaticRuntimes, 1010 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 1011 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 1012 SmallVectorImpl<StringRef> &RequiredSymbols) { 1013 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args); 1014 // Collect shared runtimes. 1015 if (SanArgs.needsSharedRt()) { 1016 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 1017 SharedRuntimes.push_back("asan"); 1018 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 1019 HelperStaticRuntimes.push_back("asan-preinit"); 1020 } 1021 if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) { 1022 SharedRuntimes.push_back("memprof"); 1023 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 1024 HelperStaticRuntimes.push_back("memprof-preinit"); 1025 } 1026 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 1027 if (SanArgs.requiresMinimalRuntime()) 1028 SharedRuntimes.push_back("ubsan_minimal"); 1029 else 1030 SharedRuntimes.push_back("ubsan_standalone"); 1031 } 1032 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 1033 SharedRuntimes.push_back("scudo_standalone"); 1034 } 1035 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) 1036 SharedRuntimes.push_back("tsan"); 1037 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 1038 if (SanArgs.needsHwasanAliasesRt()) 1039 SharedRuntimes.push_back("hwasan_aliases"); 1040 else 1041 SharedRuntimes.push_back("hwasan"); 1042 if (!Args.hasArg(options::OPT_shared)) 1043 HelperStaticRuntimes.push_back("hwasan-preinit"); 1044 } 1045 } 1046 1047 // The stats_client library is also statically linked into DSOs. 1048 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) 1049 StaticRuntimes.push_back("stats_client"); 1050 1051 // Always link the static runtime regardless of DSO or executable. 1052 if (SanArgs.needsAsanRt()) 1053 HelperStaticRuntimes.push_back("asan_static"); 1054 1055 // Collect static runtimes. 1056 if (Args.hasArg(options::OPT_shared)) { 1057 // Don't link static runtimes into DSOs. 1058 return; 1059 } 1060 1061 // Each static runtime that has a DSO counterpart above is excluded below, 1062 // but runtimes that exist only as static are not affected by needsSharedRt. 1063 1064 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 1065 StaticRuntimes.push_back("asan"); 1066 if (SanArgs.linkCXXRuntimes()) 1067 StaticRuntimes.push_back("asan_cxx"); 1068 } 1069 1070 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() && 1071 SanArgs.linkRuntimes()) { 1072 StaticRuntimes.push_back("memprof"); 1073 if (SanArgs.linkCXXRuntimes()) 1074 StaticRuntimes.push_back("memprof_cxx"); 1075 } 1076 1077 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 1078 if (SanArgs.needsHwasanAliasesRt()) { 1079 StaticRuntimes.push_back("hwasan_aliases"); 1080 if (SanArgs.linkCXXRuntimes()) 1081 StaticRuntimes.push_back("hwasan_aliases_cxx"); 1082 } else { 1083 StaticRuntimes.push_back("hwasan"); 1084 if (SanArgs.linkCXXRuntimes()) 1085 StaticRuntimes.push_back("hwasan_cxx"); 1086 } 1087 } 1088 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes()) 1089 StaticRuntimes.push_back("dfsan"); 1090 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes()) 1091 StaticRuntimes.push_back("lsan"); 1092 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) { 1093 StaticRuntimes.push_back("msan"); 1094 if (SanArgs.linkCXXRuntimes()) 1095 StaticRuntimes.push_back("msan_cxx"); 1096 } 1097 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() && 1098 SanArgs.linkRuntimes()) { 1099 StaticRuntimes.push_back("tsan"); 1100 if (SanArgs.linkCXXRuntimes()) 1101 StaticRuntimes.push_back("tsan_cxx"); 1102 } 1103 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 1104 if (SanArgs.requiresMinimalRuntime()) { 1105 StaticRuntimes.push_back("ubsan_minimal"); 1106 } else { 1107 StaticRuntimes.push_back("ubsan_standalone"); 1108 if (SanArgs.linkCXXRuntimes()) 1109 StaticRuntimes.push_back("ubsan_standalone_cxx"); 1110 } 1111 } 1112 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) { 1113 NonWholeStaticRuntimes.push_back("safestack"); 1114 RequiredSymbols.push_back("__safestack_init"); 1115 } 1116 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) { 1117 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes()) 1118 StaticRuntimes.push_back("cfi"); 1119 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) { 1120 StaticRuntimes.push_back("cfi_diag"); 1121 if (SanArgs.linkCXXRuntimes()) 1122 StaticRuntimes.push_back("ubsan_standalone_cxx"); 1123 } 1124 } 1125 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) { 1126 NonWholeStaticRuntimes.push_back("stats"); 1127 RequiredSymbols.push_back("__sanitizer_stats_register"); 1128 } 1129 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 1130 StaticRuntimes.push_back("scudo_standalone"); 1131 if (SanArgs.linkCXXRuntimes()) 1132 StaticRuntimes.push_back("scudo_standalone_cxx"); 1133 } 1134 } 1135 1136 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++, 1137 // C runtime, etc). Returns true if sanitizer system deps need to be linked in. 1138 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 1139 ArgStringList &CmdArgs) { 1140 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, 1141 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; 1142 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, 1143 NonWholeStaticRuntimes, HelperStaticRuntimes, 1144 RequiredSymbols); 1145 1146 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args); 1147 // Inject libfuzzer dependencies. 1148 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && 1149 !Args.hasArg(options::OPT_shared)) { 1150 1151 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true); 1152 if (SanArgs.needsFuzzerInterceptors()) 1153 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false, 1154 true); 1155 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) { 1156 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) && 1157 !Args.hasArg(options::OPT_static); 1158 if (OnlyLibstdcxxStatic) 1159 CmdArgs.push_back("-Bstatic"); 1160 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 1161 if (OnlyLibstdcxxStatic) 1162 CmdArgs.push_back("-Bdynamic"); 1163 } 1164 } 1165 1166 for (auto RT : SharedRuntimes) 1167 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false); 1168 for (auto RT : HelperStaticRuntimes) 1169 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 1170 bool AddExportDynamic = false; 1171 for (auto RT : StaticRuntimes) { 1172 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 1173 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 1174 } 1175 for (auto RT : NonWholeStaticRuntimes) { 1176 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false); 1177 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 1178 } 1179 for (auto S : RequiredSymbols) { 1180 CmdArgs.push_back("-u"); 1181 CmdArgs.push_back(Args.MakeArgString(S)); 1182 } 1183 // If there is a static runtime with no dynamic list, force all the symbols 1184 // to be dynamic to be sure we export sanitizer interface functions. 1185 if (AddExportDynamic) 1186 CmdArgs.push_back("--export-dynamic"); 1187 1188 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) 1189 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check"); 1190 1191 if (SanArgs.hasMemTag()) { 1192 if (!TC.getTriple().isAndroid()) { 1193 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1194 << "-fsanitize=memtag*" << TC.getTriple().str(); 1195 } 1196 CmdArgs.push_back( 1197 Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode())); 1198 if (SanArgs.hasMemtagHeap()) 1199 CmdArgs.push_back("--android-memtag-heap"); 1200 if (SanArgs.hasMemtagStack()) 1201 CmdArgs.push_back("--android-memtag-stack"); 1202 } 1203 1204 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); 1205 } 1206 1207 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { 1208 if (Args.hasArg(options::OPT_shared)) 1209 return false; 1210 1211 if (TC.getXRayArgs().needsXRayRt()) { 1212 CmdArgs.push_back("-whole-archive"); 1213 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray")); 1214 for (const auto &Mode : TC.getXRayArgs().modeList()) 1215 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode)); 1216 CmdArgs.push_back("-no-whole-archive"); 1217 return true; 1218 } 1219 1220 return false; 1221 } 1222 1223 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) { 1224 CmdArgs.push_back(getAsNeededOption(TC, false)); 1225 CmdArgs.push_back("-lpthread"); 1226 if (!TC.getTriple().isOSOpenBSD()) 1227 CmdArgs.push_back("-lrt"); 1228 CmdArgs.push_back("-lm"); 1229 1230 if (!TC.getTriple().isOSFreeBSD() && 1231 !TC.getTriple().isOSNetBSD() && 1232 !TC.getTriple().isOSOpenBSD()) 1233 CmdArgs.push_back("-ldl"); 1234 } 1235 1236 bool tools::areOptimizationsEnabled(const ArgList &Args) { 1237 // Find the last -O arg and see if it is non-zero. 1238 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 1239 return !A->getOption().matches(options::OPT_O0); 1240 // Defaults to -O0. 1241 return false; 1242 } 1243 1244 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args, 1245 const InputInfo &Input, 1246 const InputInfo &Output) { 1247 auto AddPostfix = [JA](auto &F) { 1248 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP) 1249 F += (Twine("_") + JA.getOffloadingArch()).str(); 1250 F += ".dwo"; 1251 }; 1252 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ)) 1253 if (StringRef(A->getValue()) == "single") 1254 return Args.MakeArgString(Output.getFilename()); 1255 1256 Arg *FinalOutput = Args.getLastArg(options::OPT_o); 1257 if (FinalOutput && Args.hasArg(options::OPT_c)) { 1258 SmallString<128> T(FinalOutput->getValue()); 1259 llvm::sys::path::remove_filename(T); 1260 llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue())); 1261 AddPostfix(T); 1262 return Args.MakeArgString(T); 1263 } else { 1264 // Use the compilation dir. 1265 Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ, 1266 options::OPT_fdebug_compilation_dir_EQ); 1267 SmallString<128> T(A ? A->getValue() : ""); 1268 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput())); 1269 AddPostfix(F); 1270 T += F; 1271 return Args.MakeArgString(T); 1272 } 1273 } 1274 1275 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, 1276 const JobAction &JA, const ArgList &Args, 1277 const InputInfo &Output, const char *OutFile) { 1278 ArgStringList ExtractArgs; 1279 ExtractArgs.push_back("--extract-dwo"); 1280 1281 ArgStringList StripArgs; 1282 StripArgs.push_back("--strip-dwo"); 1283 1284 // Grabbing the output of the earlier compile step. 1285 StripArgs.push_back(Output.getFilename()); 1286 ExtractArgs.push_back(Output.getFilename()); 1287 ExtractArgs.push_back(OutFile); 1288 1289 const char *Exec = 1290 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); 1291 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); 1292 1293 // First extract the dwo sections. 1294 C.addCommand(std::make_unique<Command>(JA, T, 1295 ResponseFileSupport::AtFileCurCP(), 1296 Exec, ExtractArgs, II, Output)); 1297 1298 // Then remove them from the original .o file. 1299 C.addCommand(std::make_unique<Command>( 1300 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output)); 1301 } 1302 1303 // Claim options we don't want to warn if they are unused. We do this for 1304 // options that build systems might add but are unused when assembling or only 1305 // running the preprocessor for example. 1306 void tools::claimNoWarnArgs(const ArgList &Args) { 1307 // Don't warn about unused -f(no-)?lto. This can happen when we're 1308 // preprocessing, precompiling or assembling. 1309 Args.ClaimAllArgs(options::OPT_flto_EQ); 1310 Args.ClaimAllArgs(options::OPT_flto); 1311 Args.ClaimAllArgs(options::OPT_fno_lto); 1312 } 1313 1314 Arg *tools::getLastProfileUseArg(const ArgList &Args) { 1315 auto *ProfileUseArg = Args.getLastArg( 1316 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ, 1317 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ, 1318 options::OPT_fno_profile_instr_use); 1319 1320 if (ProfileUseArg && 1321 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)) 1322 ProfileUseArg = nullptr; 1323 1324 return ProfileUseArg; 1325 } 1326 1327 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { 1328 auto *ProfileSampleUseArg = Args.getLastArg( 1329 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ, 1330 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ, 1331 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile); 1332 1333 if (ProfileSampleUseArg && 1334 (ProfileSampleUseArg->getOption().matches( 1335 options::OPT_fno_profile_sample_use) || 1336 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile))) 1337 return nullptr; 1338 1339 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ, 1340 options::OPT_fauto_profile_EQ); 1341 } 1342 1343 const char *tools::RelocationModelName(llvm::Reloc::Model Model) { 1344 switch (Model) { 1345 case llvm::Reloc::Static: 1346 return "static"; 1347 case llvm::Reloc::PIC_: 1348 return "pic"; 1349 case llvm::Reloc::DynamicNoPIC: 1350 return "dynamic-no-pic"; 1351 case llvm::Reloc::ROPI: 1352 return "ropi"; 1353 case llvm::Reloc::RWPI: 1354 return "rwpi"; 1355 case llvm::Reloc::ROPI_RWPI: 1356 return "ropi-rwpi"; 1357 } 1358 llvm_unreachable("Unknown Reloc::Model kind"); 1359 } 1360 1361 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, 1362 /// smooshes them together with platform defaults, to decide whether 1363 /// this compile should be using PIC mode or not. Returns a tuple of 1364 /// (RelocationModel, PICLevel, IsPIE). 1365 std::tuple<llvm::Reloc::Model, unsigned, bool> 1366 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { 1367 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); 1368 const llvm::Triple &Triple = ToolChain.getTriple(); 1369 1370 bool PIE = ToolChain.isPIEDefault(Args); 1371 bool PIC = PIE || ToolChain.isPICDefault(); 1372 // The Darwin/MachO default to use PIC does not apply when using -static. 1373 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static)) 1374 PIE = PIC = false; 1375 bool IsPICLevelTwo = PIC; 1376 1377 bool KernelOrKext = 1378 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 1379 1380 // Android-specific defaults for PIC/PIE 1381 if (Triple.isAndroid()) { 1382 switch (Triple.getArch()) { 1383 case llvm::Triple::arm: 1384 case llvm::Triple::armeb: 1385 case llvm::Triple::thumb: 1386 case llvm::Triple::thumbeb: 1387 case llvm::Triple::aarch64: 1388 case llvm::Triple::mips: 1389 case llvm::Triple::mipsel: 1390 case llvm::Triple::mips64: 1391 case llvm::Triple::mips64el: 1392 PIC = true; // "-fpic" 1393 break; 1394 1395 case llvm::Triple::x86: 1396 case llvm::Triple::x86_64: 1397 PIC = true; // "-fPIC" 1398 IsPICLevelTwo = true; 1399 break; 1400 1401 default: 1402 break; 1403 } 1404 } 1405 1406 // OpenBSD-specific defaults for PIE 1407 if (Triple.isOSOpenBSD()) { 1408 switch (ToolChain.getArch()) { 1409 case llvm::Triple::arm: 1410 case llvm::Triple::aarch64: 1411 case llvm::Triple::mips64: 1412 case llvm::Triple::mips64el: 1413 case llvm::Triple::x86: 1414 case llvm::Triple::x86_64: 1415 IsPICLevelTwo = false; // "-fpie" 1416 break; 1417 1418 case llvm::Triple::ppc: 1419 case llvm::Triple::sparcv9: 1420 IsPICLevelTwo = true; // "-fPIE" 1421 break; 1422 1423 default: 1424 break; 1425 } 1426 } 1427 1428 // AMDGPU-specific defaults for PIC. 1429 if (Triple.getArch() == llvm::Triple::amdgcn) 1430 PIC = true; 1431 1432 // The last argument relating to either PIC or PIE wins, and no 1433 // other argument is used. If the last argument is any flavor of the 1434 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE 1435 // option implicitly enables PIC at the same level. 1436 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, 1437 options::OPT_fpic, options::OPT_fno_pic, 1438 options::OPT_fPIE, options::OPT_fno_PIE, 1439 options::OPT_fpie, options::OPT_fno_pie); 1440 if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg && 1441 LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 1442 options::OPT_fPIE, options::OPT_fpie)) { 1443 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1444 << LastPICArg->getSpelling() << Triple.str(); 1445 if (Triple.getArch() == llvm::Triple::x86_64) 1446 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 1447 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1448 } 1449 1450 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 1451 // is forced, then neither PIC nor PIE flags will have no effect. 1452 if (!ToolChain.isPICDefaultForced()) { 1453 if (LastPICArg) { 1454 Option O = LastPICArg->getOption(); 1455 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 1456 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 1457 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 1458 PIC = 1459 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 1460 IsPICLevelTwo = 1461 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 1462 } else { 1463 PIE = PIC = false; 1464 if (EffectiveTriple.isPS()) { 1465 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1466 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1467 if (Model != "kernel") { 1468 PIC = true; 1469 ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic) 1470 << LastPICArg->getSpelling() 1471 << (EffectiveTriple.isPS4() ? "PS4" : "PS5"); 1472 } 1473 } 1474 } 1475 } 1476 } 1477 1478 // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but 1479 // the PIC level would've been set to level 1, force it back to level 2 PIC 1480 // instead. 1481 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS())) 1482 IsPICLevelTwo |= ToolChain.isPICDefault(); 1483 1484 // This kernel flags are a trump-card: they will disable PIC/PIE 1485 // generation, independent of the argument order. 1486 if (KernelOrKext && 1487 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1488 !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit())) 1489 PIC = PIE = false; 1490 1491 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1492 // This is a very special mode. It trumps the other modes, almost no one 1493 // uses it, and it isn't even valid on any OS but Darwin. 1494 if (!Triple.isOSDarwin()) 1495 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1496 << A->getSpelling() << Triple.str(); 1497 1498 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1499 1500 // Only a forced PIC mode can cause the actual compile to have PIC defines 1501 // etc., no flags are sufficient. This behavior was selected to closely 1502 // match that of llvm-gcc and Apple GCC before that. 1503 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1504 1505 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1506 } 1507 1508 bool EmbeddedPISupported; 1509 switch (Triple.getArch()) { 1510 case llvm::Triple::arm: 1511 case llvm::Triple::armeb: 1512 case llvm::Triple::thumb: 1513 case llvm::Triple::thumbeb: 1514 EmbeddedPISupported = true; 1515 break; 1516 default: 1517 EmbeddedPISupported = false; 1518 break; 1519 } 1520 1521 bool ROPI = false, RWPI = false; 1522 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1523 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1524 if (!EmbeddedPISupported) 1525 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1526 << LastROPIArg->getSpelling() << Triple.str(); 1527 ROPI = true; 1528 } 1529 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 1530 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 1531 if (!EmbeddedPISupported) 1532 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1533 << LastRWPIArg->getSpelling() << Triple.str(); 1534 RWPI = true; 1535 } 1536 1537 // ROPI and RWPI are not compatible with PIC or PIE. 1538 if ((ROPI || RWPI) && (PIC || PIE)) 1539 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 1540 1541 if (Triple.isMIPS()) { 1542 StringRef CPUName; 1543 StringRef ABIName; 1544 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1545 // When targeting the N64 ABI, PIC is the default, except in the case 1546 // when the -mno-abicalls option is used. In that case we exit 1547 // at next check regardless of PIC being set below. 1548 if (ABIName == "n64") 1549 PIC = true; 1550 // When targettng MIPS with -mno-abicalls, it's always static. 1551 if(Args.hasArg(options::OPT_mno_abicalls)) 1552 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1553 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 1554 // does not use PIC level 2 for historical reasons. 1555 IsPICLevelTwo = false; 1556 } 1557 1558 if (PIC) 1559 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 1560 1561 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 1562 if (ROPI && RWPI) 1563 RelocM = llvm::Reloc::ROPI_RWPI; 1564 else if (ROPI) 1565 RelocM = llvm::Reloc::ROPI; 1566 else if (RWPI) 1567 RelocM = llvm::Reloc::RWPI; 1568 1569 return std::make_tuple(RelocM, 0U, false); 1570 } 1571 1572 // `-falign-functions` indicates that the functions should be aligned to a 1573 // 16-byte boundary. 1574 // 1575 // `-falign-functions=1` is the same as `-fno-align-functions`. 1576 // 1577 // The scalar `n` in `-falign-functions=n` must be an integral value between 1578 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to 1579 // the nearest power-of-two. 1580 // 1581 // If we return `0`, the frontend will default to the backend's preferred 1582 // alignment. 1583 // 1584 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 1585 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred 1586 // alignment. For unaligned functions, we default to the backend's preferred 1587 // alignment. 1588 unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 1589 const ArgList &Args) { 1590 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 1591 options::OPT_falign_functions_EQ, 1592 options::OPT_fno_align_functions); 1593 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 1594 return 0; 1595 1596 if (A->getOption().matches(options::OPT_falign_functions)) 1597 return 0; 1598 1599 unsigned Value = 0; 1600 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 1601 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1602 << A->getAsString(Args) << A->getValue(); 1603 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 1604 } 1605 1606 static unsigned ParseDebugDefaultVersion(const ToolChain &TC, 1607 const ArgList &Args) { 1608 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version); 1609 1610 if (!A) 1611 return 0; 1612 1613 unsigned Value = 0; 1614 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 || 1615 Value < 2) 1616 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1617 << A->getAsString(Args) << A->getValue(); 1618 return Value; 1619 } 1620 1621 unsigned tools::DwarfVersionNum(StringRef ArgValue) { 1622 return llvm::StringSwitch<unsigned>(ArgValue) 1623 .Case("-gdwarf-2", 2) 1624 .Case("-gdwarf-3", 3) 1625 .Case("-gdwarf-4", 4) 1626 .Case("-gdwarf-5", 5) 1627 .Default(0); 1628 } 1629 1630 const Arg *tools::getDwarfNArg(const ArgList &Args) { 1631 return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3, 1632 options::OPT_gdwarf_4, options::OPT_gdwarf_5, 1633 options::OPT_gdwarf); 1634 } 1635 1636 unsigned tools::getDwarfVersion(const ToolChain &TC, 1637 const llvm::opt::ArgList &Args) { 1638 unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args); 1639 if (const Arg *GDwarfN = getDwarfNArg(Args)) 1640 if (int N = DwarfVersionNum(GDwarfN->getSpelling())) 1641 DwarfVersion = N; 1642 if (DwarfVersion == 0) { 1643 DwarfVersion = TC.GetDefaultDwarfVersion(); 1644 assert(DwarfVersion && "toolchain default DWARF version must be nonzero"); 1645 } 1646 return DwarfVersion; 1647 } 1648 1649 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 1650 ArgStringList &CmdArgs) { 1651 llvm::Reloc::Model RelocationModel; 1652 unsigned PICLevel; 1653 bool IsPIE; 1654 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 1655 1656 if (RelocationModel != llvm::Reloc::Static) 1657 CmdArgs.push_back("-KPIC"); 1658 } 1659 1660 /// Determine whether Objective-C automated reference counting is 1661 /// enabled. 1662 bool tools::isObjCAutoRefCount(const ArgList &Args) { 1663 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 1664 } 1665 1666 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 1667 1668 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, 1669 const ArgList &Args) { 1670 if (Args.hasArg(options::OPT_static_libgcc) || 1671 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) || 1672 // The Android NDK only provides libunwind.a, not libunwind.so. 1673 TC.getTriple().isAndroid()) 1674 return LibGccType::StaticLibGcc; 1675 if (Args.hasArg(options::OPT_shared_libgcc)) 1676 return LibGccType::SharedLibGcc; 1677 return LibGccType::UnspecifiedLibGcc; 1678 } 1679 1680 // Gcc adds libgcc arguments in various ways: 1681 // 1682 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 1683 // g++ <none>: -lgcc_s -lgcc 1684 // gcc shared: -lgcc_s -lgcc 1685 // g++ shared: -lgcc_s -lgcc 1686 // gcc static: -lgcc -lgcc_eh 1687 // g++ static: -lgcc -lgcc_eh 1688 // gcc static-pie: -lgcc -lgcc_eh 1689 // g++ static-pie: -lgcc -lgcc_eh 1690 // 1691 // Also, certain targets need additional adjustments. 1692 1693 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 1694 ArgStringList &CmdArgs, const ArgList &Args) { 1695 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 1696 // Targets that don't use unwind libraries. 1697 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) || 1698 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() || 1699 TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None) 1700 return; 1701 1702 LibGccType LGT = getLibGccType(TC, D, Args); 1703 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 1704 (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) && 1705 !TC.getTriple().isAndroid() && 1706 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX(); 1707 if (AsNeeded) 1708 CmdArgs.push_back(getAsNeededOption(TC, true)); 1709 1710 switch (UNW) { 1711 case ToolChain::UNW_None: 1712 return; 1713 case ToolChain::UNW_Libgcc: { 1714 if (LGT == LibGccType::StaticLibGcc) 1715 CmdArgs.push_back("-lgcc_eh"); 1716 else 1717 CmdArgs.push_back("-lgcc_s"); 1718 break; 1719 } 1720 case ToolChain::UNW_CompilerRT: 1721 if (TC.getTriple().isOSAIX()) { 1722 // AIX only has libunwind as a shared library. So do not pass 1723 // anything in if -static is specified. 1724 if (LGT != LibGccType::StaticLibGcc) 1725 CmdArgs.push_back("-lunwind"); 1726 } else if (LGT == LibGccType::StaticLibGcc) { 1727 CmdArgs.push_back("-l:libunwind.a"); 1728 } else if (LGT == LibGccType::SharedLibGcc) { 1729 if (TC.getTriple().isOSCygMing()) 1730 CmdArgs.push_back("-l:libunwind.dll.a"); 1731 else 1732 CmdArgs.push_back("-l:libunwind.so"); 1733 } else { 1734 // Let the linker choose between libunwind.so and libunwind.a 1735 // depending on what's available, and depending on the -static flag 1736 CmdArgs.push_back("-lunwind"); 1737 } 1738 break; 1739 } 1740 1741 if (AsNeeded) 1742 CmdArgs.push_back(getAsNeededOption(TC, false)); 1743 } 1744 1745 static void AddLibgcc(const ToolChain &TC, const Driver &D, 1746 ArgStringList &CmdArgs, const ArgList &Args) { 1747 LibGccType LGT = getLibGccType(TC, D, Args); 1748 if (LGT == LibGccType::StaticLibGcc || 1749 (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX())) 1750 CmdArgs.push_back("-lgcc"); 1751 AddUnwindLibrary(TC, D, CmdArgs, Args); 1752 if (LGT == LibGccType::SharedLibGcc || 1753 (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX())) 1754 CmdArgs.push_back("-lgcc"); 1755 } 1756 1757 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 1758 ArgStringList &CmdArgs, const ArgList &Args) { 1759 // Make use of compiler-rt if --rtlib option is used 1760 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 1761 1762 switch (RLT) { 1763 case ToolChain::RLT_CompilerRT: 1764 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 1765 AddUnwindLibrary(TC, D, CmdArgs, Args); 1766 break; 1767 case ToolChain::RLT_Libgcc: 1768 // Make sure libgcc is not used under MSVC environment by default 1769 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1770 // Issue error diagnostic if libgcc is explicitly specified 1771 // through command line as --rtlib option argument. 1772 Arg *A = Args.getLastArg(options::OPT_rtlib_EQ); 1773 if (A && A->getValue() != StringRef("platform")) { 1774 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 1775 << A->getValue() << "MSVC"; 1776 } 1777 } else 1778 AddLibgcc(TC, D, CmdArgs, Args); 1779 break; 1780 } 1781 1782 // On Android, the unwinder uses dl_iterate_phdr (or one of 1783 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For 1784 // statically-linked executables, these functions come from libc.a instead. 1785 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) && 1786 !Args.hasArg(options::OPT_static_pie)) 1787 CmdArgs.push_back("-ldl"); 1788 } 1789 1790 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 1791 const InputInfo &Output, 1792 const InputInfo &Input, 1793 const Driver &D) { 1794 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 1795 if (!A) 1796 return {}; 1797 1798 StringRef SaveStats = A->getValue(); 1799 SmallString<128> StatsFile; 1800 if (SaveStats == "obj" && Output.isFilename()) { 1801 StatsFile.assign(Output.getFilename()); 1802 llvm::sys::path::remove_filename(StatsFile); 1803 } else if (SaveStats != "cwd") { 1804 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 1805 return {}; 1806 } 1807 1808 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 1809 llvm::sys::path::append(StatsFile, BaseName); 1810 llvm::sys::path::replace_extension(StatsFile, "stats"); 1811 return StatsFile; 1812 } 1813 1814 void tools::addMultilibFlag(bool Enabled, const char *const Flag, 1815 Multilib::flags_list &Flags) { 1816 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag); 1817 } 1818 1819 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args, 1820 ArgStringList &CmdArgs, bool IsLTO, 1821 const StringRef PluginOptPrefix) { 1822 auto addArg = [&, IsLTO](const Twine &Arg) { 1823 if (IsLTO) { 1824 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!"); 1825 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg)); 1826 } else { 1827 CmdArgs.push_back("-mllvm"); 1828 CmdArgs.push_back(Args.MakeArgString(Arg)); 1829 } 1830 }; 1831 1832 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) { 1833 addArg(Twine("-x86-branches-within-32B-boundaries")); 1834 } 1835 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) { 1836 StringRef Value = A->getValue(); 1837 unsigned Boundary; 1838 if (Value.getAsInteger(10, Boundary) || Boundary < 16 || 1839 !llvm::isPowerOf2_64(Boundary)) { 1840 D.Diag(diag::err_drv_invalid_argument_to_option) 1841 << Value << A->getOption().getName(); 1842 } else { 1843 addArg("-x86-align-branch-boundary=" + Twine(Boundary)); 1844 } 1845 } 1846 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) { 1847 std::string AlignBranch; 1848 for (StringRef T : A->getValues()) { 1849 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" && 1850 T != "ret" && T != "indirect") 1851 D.Diag(diag::err_drv_invalid_malign_branch_EQ) 1852 << T << "fused, jcc, jmp, call, ret, indirect"; 1853 if (!AlignBranch.empty()) 1854 AlignBranch += '+'; 1855 AlignBranch += T; 1856 } 1857 addArg("-x86-align-branch=" + Twine(AlignBranch)); 1858 } 1859 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) { 1860 StringRef Value = A->getValue(); 1861 unsigned PrefixSize; 1862 if (Value.getAsInteger(10, PrefixSize)) { 1863 D.Diag(diag::err_drv_invalid_argument_to_option) 1864 << Value << A->getOption().getName(); 1865 } else { 1866 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize)); 1867 } 1868 } 1869 } 1870 1871 /// SDLSearch: Search for Static Device Library 1872 /// The search for SDL bitcode files is consistent with how static host 1873 /// libraries are discovered. That is, the -l option triggers a search for 1874 /// files in a set of directories called the LINKPATH. The host library search 1875 /// procedure looks for a specific filename in the LINKPATH. The filename for 1876 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an 1877 /// ordered-set of filenames that are searched. We call this ordered-set of 1878 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific, 1879 /// architecture specific, or generic across all architectures, a naming 1880 /// convention and search order is used where the file name embeds the 1881 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type 1882 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of 1883 /// device-independent SDLs. To reduce congestion in host library directories, 1884 /// the search first looks for files in the “libdevice” subdirectory. SDLs that 1885 /// are bc files begin with the prefix “lib”. 1886 /// 1887 /// Machine-code SDLs can also be managed as an archive (*.a file). The 1888 /// convention has been to use the prefix “lib”. To avoid confusion with host 1889 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives. 1890 /// 1891 bool tools::SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs, 1892 llvm::opt::ArgStringList &CC1Args, 1893 SmallVector<std::string, 8> LibraryPaths, std::string Lib, 1894 StringRef Arch, StringRef Target, bool isBitCodeSDL, 1895 bool postClangLink) { 1896 SmallVector<std::string, 12> SDLs; 1897 1898 std::string LibDeviceLoc = "/libdevice"; 1899 std::string LibBcPrefix = "/libbc-"; 1900 std::string LibPrefix = "/lib"; 1901 1902 if (isBitCodeSDL) { 1903 // SEARCH-ORDER for Bitcode SDLs: 1904 // libdevice/libbc-<libname>-<arch-name>-<device-type>.a 1905 // libbc-<libname>-<arch-name>-<device-type>.a 1906 // libdevice/libbc-<libname>-<arch-name>.a 1907 // libbc-<libname>-<arch-name>.a 1908 // libdevice/libbc-<libname>.a 1909 // libbc-<libname>.a 1910 // libdevice/lib<libname>-<arch-name>-<device-type>.bc 1911 // lib<libname>-<arch-name>-<device-type>.bc 1912 // libdevice/lib<libname>-<arch-name>.bc 1913 // lib<libname>-<arch-name>.bc 1914 // libdevice/lib<libname>.bc 1915 // lib<libname>.bc 1916 1917 for (StringRef Base : {LibBcPrefix, LibPrefix}) { 1918 const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc"; 1919 1920 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(), 1921 Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) { 1922 SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str()); 1923 SDLs.push_back(Twine(Base + Suffix + Ext).str()); 1924 } 1925 } 1926 } else { 1927 // SEARCH-ORDER for Machine-code SDLs: 1928 // libdevice/lib<libname>-<arch-name>-<device-type>.a 1929 // lib<libname>-<arch-name>-<device-type>.a 1930 // libdevice/lib<libname>-<arch-name>.a 1931 // lib<libname>-<arch-name>.a 1932 1933 const auto *Ext = ".a"; 1934 1935 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(), 1936 Twine(Lib + "-" + Arch).str()}) { 1937 SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str()); 1938 SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str()); 1939 } 1940 } 1941 1942 // The CUDA toolchain does not use a global device llvm-link before the LLVM 1943 // backend generates ptx. So currently, the use of bitcode SDL for nvptx is 1944 // only possible with post-clang-cc1 linking. Clang cc1 has a feature that 1945 // will link libraries after clang compilation while the LLVM IR is still in 1946 // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”. 1947 // This is a clang -cc1 option that is generated by the clang driver. The 1948 // option value must a full path to an existing file. 1949 bool FoundSDL = false; 1950 for (auto LPath : LibraryPaths) { 1951 for (auto SDL : SDLs) { 1952 auto FullName = Twine(LPath + SDL).str(); 1953 if (llvm::sys::fs::exists(FullName)) { 1954 if (postClangLink) 1955 CC1Args.push_back("-mlink-builtin-bitcode"); 1956 CC1Args.push_back(DriverArgs.MakeArgString(FullName)); 1957 FoundSDL = true; 1958 break; 1959 } 1960 } 1961 if (FoundSDL) 1962 break; 1963 } 1964 return FoundSDL; 1965 } 1966 1967 /// Search if a user provided archive file lib<libname>.a exists in any of 1968 /// the library paths. If so, add a new command to clang-offload-bundler to 1969 /// unbundle this archive and create a temporary device specific archive. Name 1970 /// of this SDL is passed to the llvm-link tool. 1971 bool tools::GetSDLFromOffloadArchive( 1972 Compilation &C, const Driver &D, const Tool &T, const JobAction &JA, 1973 const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, 1974 llvm::opt::ArgStringList &CC1Args, SmallVector<std::string, 8> LibraryPaths, 1975 StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL, 1976 bool postClangLink) { 1977 1978 // We don't support bitcode archive bundles for nvptx 1979 if (isBitCodeSDL && Arch.contains("nvptx")) 1980 return false; 1981 1982 bool FoundAOB = false; 1983 std::string ArchiveOfBundles; 1984 1985 llvm::Triple Triple(D.getTargetTriple()); 1986 bool IsMSVC = Triple.isWindowsMSVCEnvironment(); 1987 auto Ext = IsMSVC ? ".lib" : ".a"; 1988 if (!Lib.startswith(":") && !Lib.startswith("-l")) { 1989 if (llvm::sys::fs::exists(Lib)) { 1990 ArchiveOfBundles = Lib; 1991 FoundAOB = true; 1992 } 1993 } else { 1994 if (Lib.startswith("-l")) 1995 Lib = Lib.drop_front(2); 1996 for (auto LPath : LibraryPaths) { 1997 ArchiveOfBundles.clear(); 1998 SmallVector<std::string, 2> AOBFileNames; 1999 auto LibFile = 2000 (Lib.startswith(":") ? Lib.drop_front() 2001 : IsMSVC ? Lib + Ext : "lib" + Lib + Ext) 2002 .str(); 2003 for (auto Prefix : {"/libdevice/", "/"}) { 2004 auto AOB = Twine(LPath + Prefix + LibFile).str(); 2005 if (llvm::sys::fs::exists(AOB)) { 2006 ArchiveOfBundles = AOB; 2007 FoundAOB = true; 2008 break; 2009 } 2010 } 2011 if (FoundAOB) 2012 break; 2013 } 2014 } 2015 2016 if (!FoundAOB) 2017 return false; 2018 2019 llvm::file_magic Magic; 2020 auto EC = llvm::identify_magic(ArchiveOfBundles, Magic); 2021 if (EC || Magic != llvm::file_magic::archive) 2022 return false; 2023 2024 StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib"; 2025 std::string OutputLib = 2026 D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" + 2027 Arch + "-" + Target) 2028 .str(), 2029 "a"); 2030 2031 C.addTempFile(C.getArgs().MakeArgString(OutputLib)); 2032 2033 ArgStringList CmdArgs; 2034 SmallString<128> DeviceTriple; 2035 DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind()); 2036 DeviceTriple += '-'; 2037 std::string NormalizedTriple = T.getToolChain().getTriple().normalize(); 2038 DeviceTriple += NormalizedTriple; 2039 if (!Target.empty()) { 2040 DeviceTriple += '-'; 2041 DeviceTriple += Target; 2042 } 2043 2044 std::string UnbundleArg("-unbundle"); 2045 std::string TypeArg("-type=a"); 2046 std::string InputArg("-input=" + ArchiveOfBundles); 2047 std::string OffloadArg("-targets=" + std::string(DeviceTriple)); 2048 std::string OutputArg("-output=" + OutputLib); 2049 2050 const char *UBProgram = DriverArgs.MakeArgString( 2051 T.getToolChain().GetProgramPath("clang-offload-bundler")); 2052 2053 ArgStringList UBArgs; 2054 UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg)); 2055 UBArgs.push_back(C.getArgs().MakeArgString(TypeArg)); 2056 UBArgs.push_back(C.getArgs().MakeArgString(InputArg)); 2057 UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg)); 2058 UBArgs.push_back(C.getArgs().MakeArgString(OutputArg)); 2059 2060 // Add this flag to not exit from clang-offload-bundler if no compatible 2061 // code object is found in heterogenous archive library. 2062 std::string AdditionalArgs("-allow-missing-bundles"); 2063 UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs)); 2064 2065 // Add this flag to treat hip and hipv4 offload kinds as compatible with 2066 // openmp offload kind while extracting code objects from a heterogenous 2067 // archive library. Vice versa is also considered compatible. 2068 std::string HipCompatibleArgs("-hip-openmp-compatible"); 2069 UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs)); 2070 2071 C.addCommand(std::make_unique<Command>( 2072 JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs, 2073 InputInfo(&JA, C.getArgs().MakeArgString(OutputLib)))); 2074 if (postClangLink) 2075 CC1Args.push_back("-mlink-builtin-bitcode"); 2076 2077 CC1Args.push_back(DriverArgs.MakeArgString(OutputLib)); 2078 2079 return true; 2080 } 2081 2082 // Wrapper function used by driver for adding SDLs during link phase. 2083 void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T, 2084 const JobAction &JA, 2085 const InputInfoList &Inputs, 2086 const llvm::opt::ArgList &DriverArgs, 2087 llvm::opt::ArgStringList &CC1Args, 2088 StringRef Arch, StringRef Target, 2089 bool isBitCodeSDL, bool postClangLink) { 2090 AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args, 2091 Arch, Target, isBitCodeSDL, postClangLink); 2092 } 2093 2094 // User defined Static Device Libraries(SDLs) can be passed to clang for 2095 // offloading GPU compilers. Like static host libraries, the use of a SDL is 2096 // specified with the -l command line option. The primary difference between 2097 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs 2098 // and SEARCH-ORDER for Machine-code SDLs for the naming convention). 2099 // SDLs are of following types: 2100 // 2101 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files. 2102 // For NVPTX, these libraries are post-clang linked following each 2103 // compilation. For AMDGPU, these libraries are linked one time 2104 // during the application link phase. 2105 // 2106 // * Machine-code SDLs: They are archive files. For AMDGPU, the process for 2107 // machine code SDLs is still in development. But they will be linked 2108 // by the LLVM tool lld. 2109 // 2110 // * Bundled objects that contain both host and device codes: Bundled objects 2111 // may also contain library code compiled from source. For NVPTX, the 2112 // bundle contains cubin. For AMDGPU, the bundle contains bitcode. 2113 // 2114 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the 2115 // inclusion of specific SDLs such as math libraries and the OpenMP device 2116 // library libomptarget. 2117 void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T, 2118 const JobAction *JA, 2119 const InputInfoList *Inputs, const Driver &D, 2120 const llvm::opt::ArgList &DriverArgs, 2121 llvm::opt::ArgStringList &CC1Args, 2122 StringRef Arch, StringRef Target, 2123 bool isBitCodeSDL, bool postClangLink) { 2124 2125 SmallVector<std::string, 8> LibraryPaths; 2126 // Add search directories from LIBRARY_PATH env variable 2127 std::optional<std::string> LibPath = 2128 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 2129 if (LibPath) { 2130 SmallVector<StringRef, 8> Frags; 2131 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 2132 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 2133 for (StringRef Path : Frags) 2134 LibraryPaths.emplace_back(Path.trim()); 2135 } 2136 2137 // Add directories from user-specified -L options 2138 for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L)) 2139 LibraryPaths.emplace_back(Search_Dir); 2140 2141 // Add path to lib-debug folders 2142 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir); 2143 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 2144 LibraryPaths.emplace_back(DefaultLibPath.c_str()); 2145 2146 // Build list of Static Device Libraries SDLs specified by -l option 2147 llvm::SmallSet<std::string, 16> SDLNames; 2148 static const StringRef HostOnlyArchives[] = { 2149 "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"}; 2150 for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) { 2151 if (!HostOnlyArchives->contains(SDLName)) { 2152 SDLNames.insert(std::string("-l") + SDLName); 2153 } 2154 } 2155 2156 for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) { 2157 auto FileName = StringRef(Input); 2158 // Clang treats any unknown file types as archives and passes them to the 2159 // linker. Files with extension 'lib' are classified as TY_Object by clang 2160 // but they are usually archives. It is OK if the file is not really an 2161 // archive since GetSDLFromOffloadArchive will check the magic of the file 2162 // and only unbundle it if it is really an archive. 2163 const StringRef LibFileExt = ".lib"; 2164 if (!llvm::sys::path::has_extension(FileName) || 2165 types::lookupTypeForExtension( 2166 llvm::sys::path::extension(FileName).drop_front()) == 2167 types::TY_INVALID || 2168 llvm::sys::path::extension(FileName) == LibFileExt) 2169 SDLNames.insert(Input); 2170 } 2171 2172 // The search stops as soon as an SDL file is found. The driver then provides 2173 // the full filename of the SDL to the llvm-link command. If no SDL is found 2174 // after searching each LINKPATH with SEARCH-ORDER, it is possible that an 2175 // archive file lib<libname>.a exists and may contain bundled object files. 2176 for (auto SDLName : SDLNames) { 2177 // This is the only call to SDLSearch 2178 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target, 2179 isBitCodeSDL, postClangLink)) { 2180 GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args, 2181 LibraryPaths, SDLName, Arch, Target, 2182 isBitCodeSDL, postClangLink); 2183 } 2184 } 2185 } 2186 2187 static llvm::opt::Arg * 2188 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) { 2189 // The last of -mcode-object-v3, -mno-code-object-v3 and 2190 // -mcode-object-version=<version> wins. 2191 return Args.getLastArg(options::OPT_mcode_object_v3_legacy, 2192 options::OPT_mno_code_object_v3_legacy, 2193 options::OPT_mcode_object_version_EQ); 2194 } 2195 2196 void tools::checkAMDGPUCodeObjectVersion(const Driver &D, 2197 const llvm::opt::ArgList &Args) { 2198 const unsigned MinCodeObjVer = 2; 2199 const unsigned MaxCodeObjVer = 5; 2200 2201 // Emit warnings for legacy options even if they are overridden. 2202 if (Args.hasArg(options::OPT_mno_code_object_v3_legacy)) 2203 D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3" 2204 << "-mcode-object-version=2"; 2205 2206 if (Args.hasArg(options::OPT_mcode_object_v3_legacy)) 2207 D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3" 2208 << "-mcode-object-version=3"; 2209 2210 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { 2211 if (CodeObjArg->getOption().getID() == 2212 options::OPT_mcode_object_version_EQ) { 2213 unsigned CodeObjVer = MaxCodeObjVer; 2214 auto Remnant = 2215 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 2216 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer) 2217 D.Diag(diag::err_drv_invalid_int_value) 2218 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue(); 2219 } 2220 } 2221 } 2222 2223 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D, 2224 const llvm::opt::ArgList &Args) { 2225 unsigned CodeObjVer = 4; // default 2226 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { 2227 if (CodeObjArg->getOption().getID() == 2228 options::OPT_mno_code_object_v3_legacy) { 2229 CodeObjVer = 2; 2230 } else if (CodeObjArg->getOption().getID() == 2231 options::OPT_mcode_object_v3_legacy) { 2232 CodeObjVer = 3; 2233 } else { 2234 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 2235 } 2236 } 2237 return CodeObjVer; 2238 } 2239 2240 bool tools::haveAMDGPUCodeObjectVersionArgument( 2241 const Driver &D, const llvm::opt::ArgList &Args) { 2242 return getAMDGPUCodeObjectArgument(D, Args) != nullptr; 2243 } 2244 2245 void tools::addMachineOutlinerArgs(const Driver &D, 2246 const llvm::opt::ArgList &Args, 2247 llvm::opt::ArgStringList &CmdArgs, 2248 const llvm::Triple &Triple, bool IsLTO, 2249 const StringRef PluginOptPrefix) { 2250 auto addArg = [&, IsLTO](const Twine &Arg) { 2251 if (IsLTO) { 2252 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!"); 2253 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg)); 2254 } else { 2255 CmdArgs.push_back("-mllvm"); 2256 CmdArgs.push_back(Args.MakeArgString(Arg)); 2257 } 2258 }; 2259 2260 if (Arg *A = Args.getLastArg(options::OPT_moutline, 2261 options::OPT_mno_outline)) { 2262 if (A->getOption().matches(options::OPT_moutline)) { 2263 // We only support -moutline in AArch64 and ARM targets right now. If 2264 // we're not compiling for these, emit a warning and ignore the flag. 2265 // Otherwise, add the proper mllvm flags. 2266 if (!(Triple.isARM() || Triple.isThumb() || 2267 Triple.getArch() == llvm::Triple::aarch64 || 2268 Triple.getArch() == llvm::Triple::aarch64_32)) { 2269 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); 2270 } else { 2271 addArg(Twine("-enable-machine-outliner")); 2272 } 2273 } else { 2274 // Disable all outlining behaviour. 2275 addArg(Twine("-enable-machine-outliner=never")); 2276 } 2277 } 2278 } 2279 2280 void tools::addOpenMPDeviceRTL(const Driver &D, 2281 const llvm::opt::ArgList &DriverArgs, 2282 llvm::opt::ArgStringList &CC1Args, 2283 StringRef BitcodeSuffix, 2284 const llvm::Triple &Triple) { 2285 SmallVector<StringRef, 8> LibraryPaths; 2286 2287 // Add path to clang lib / lib64 folder. 2288 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir); 2289 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 2290 LibraryPaths.emplace_back(DefaultLibPath.c_str()); 2291 2292 // Add user defined library paths from LIBRARY_PATH. 2293 std::optional<std::string> LibPath = 2294 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 2295 if (LibPath) { 2296 SmallVector<StringRef, 8> Frags; 2297 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 2298 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 2299 for (StringRef Path : Frags) 2300 LibraryPaths.emplace_back(Path.trim()); 2301 } 2302 2303 OptSpecifier LibomptargetBCPathOpt = 2304 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ 2305 : options::OPT_libomptarget_nvptx_bc_path_EQ; 2306 2307 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx"; 2308 std::string LibOmpTargetName = 2309 ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str(); 2310 2311 // First check whether user specifies bc library 2312 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) { 2313 SmallString<128> LibOmpTargetFile(A->getValue()); 2314 if (llvm::sys::fs::exists(LibOmpTargetFile) && 2315 llvm::sys::fs::is_directory(LibOmpTargetFile)) { 2316 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 2317 } 2318 2319 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 2320 CC1Args.push_back("-mlink-builtin-bitcode"); 2321 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 2322 } else { 2323 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found) 2324 << LibOmpTargetFile; 2325 } 2326 } else { 2327 bool FoundBCLibrary = false; 2328 2329 for (StringRef LibraryPath : LibraryPaths) { 2330 SmallString<128> LibOmpTargetFile(LibraryPath); 2331 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 2332 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 2333 CC1Args.push_back("-mlink-builtin-bitcode"); 2334 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 2335 FoundBCLibrary = true; 2336 break; 2337 } 2338 } 2339 2340 if (!FoundBCLibrary) 2341 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime) 2342 << LibOmpTargetName << ArchPrefix; 2343 } 2344 } 2345 void tools::addHIPRuntimeLibArgs(const ToolChain &TC, 2346 const llvm::opt::ArgList &Args, 2347 llvm::opt::ArgStringList &CmdArgs) { 2348 if (Args.hasArg(options::OPT_hip_link) && 2349 !Args.hasArg(options::OPT_nostdlib) && 2350 !Args.hasArg(options::OPT_no_hip_rt)) { 2351 TC.AddHIPRuntimeLibArgs(Args, CmdArgs); 2352 } else { 2353 // Claim "no HIP libraries" arguments if any 2354 for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) { 2355 Arg->claim(); 2356 } 2357 } 2358 } 2359