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