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