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 "HIP.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/SmallString.h" 38 #include "llvm/ADT/StringExtras.h" 39 #include "llvm/ADT/StringSwitch.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Config/llvm-config.h" 42 #include "llvm/Option/Arg.h" 43 #include "llvm/Option/ArgList.h" 44 #include "llvm/Option/Option.h" 45 #include "llvm/Support/CodeGen.h" 46 #include "llvm/Support/Compression.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Support/ErrorHandling.h" 49 #include "llvm/Support/FileSystem.h" 50 #include "llvm/Support/Host.h" 51 #include "llvm/Support/Path.h" 52 #include "llvm/Support/Process.h" 53 #include "llvm/Support/Program.h" 54 #include "llvm/Support/ScopedPrinter.h" 55 #include "llvm/Support/TargetParser.h" 56 #include "llvm/Support/Threading.h" 57 #include "llvm/Support/VirtualFileSystem.h" 58 #include "llvm/Support/YAMLParser.h" 59 60 using namespace clang::driver; 61 using namespace clang::driver::tools; 62 using namespace clang; 63 using namespace llvm::opt; 64 65 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) { 66 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ)) 67 CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") + 68 A->getValue())); 69 70 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ)) 71 CmdArgs.push_back(Args.MakeArgString( 72 Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue())); 73 74 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ)) 75 CmdArgs.push_back(Args.MakeArgString( 76 Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue())); 77 } 78 79 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, 80 const llvm::Triple &Triple, 81 const InputInfo &Input, 82 const InputInfo &Output) { 83 StringRef Format = "yaml"; 84 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) 85 Format = A->getValue(); 86 87 SmallString<128> F; 88 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ); 89 if (A) 90 F = A->getValue(); 91 else if (Output.isFilename()) 92 F = Output.getFilename(); 93 94 assert(!F.empty() && "Cannot determine remarks output name."); 95 // Append "opt.ld.<format>" to the end of the file name. 96 CmdArgs.push_back( 97 Args.MakeArgString(Twine("--plugin-opt=opt-remarks-filename=") + F + 98 Twine(".opt.ld.") + Format)); 99 100 if (const Arg *A = 101 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) 102 CmdArgs.push_back(Args.MakeArgString( 103 Twine("--plugin-opt=opt-remarks-passes=") + A->getValue())); 104 105 CmdArgs.push_back(Args.MakeArgString( 106 Twine("--plugin-opt=opt-remarks-format=") + Format.data())); 107 } 108 109 static void renderRemarksHotnessOptions(const ArgList &Args, 110 ArgStringList &CmdArgs) { 111 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness, 112 options::OPT_fno_diagnostics_show_hotness, false)) 113 CmdArgs.push_back("--plugin-opt=opt-remarks-with-hotness"); 114 115 if (const Arg *A = 116 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) 117 CmdArgs.push_back(Args.MakeArgString( 118 Twine("--plugin-opt=opt-remarks-hotness-threshold=") + A->getValue())); 119 } 120 121 void tools::addPathIfExists(const Driver &D, const Twine &Path, 122 ToolChain::path_list &Paths) { 123 if (D.getVFS().exists(Path)) 124 Paths.push_back(Path.str()); 125 } 126 127 void tools::handleTargetFeaturesGroup(const ArgList &Args, 128 std::vector<StringRef> &Features, 129 OptSpecifier Group) { 130 for (const Arg *A : Args.filtered(Group)) { 131 StringRef Name = A->getOption().getName(); 132 A->claim(); 133 134 // Skip over "-m". 135 assert(Name.startswith("m") && "Invalid feature name."); 136 Name = Name.substr(1); 137 138 bool IsNegative = Name.startswith("no-"); 139 if (IsNegative) 140 Name = Name.substr(3); 141 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); 142 } 143 } 144 145 std::vector<StringRef> 146 tools::unifyTargetFeatures(const std::vector<StringRef> &Features) { 147 std::vector<StringRef> UnifiedFeatures; 148 // Find the last of each feature. 149 llvm::StringMap<unsigned> LastOpt; 150 for (unsigned I = 0, N = Features.size(); I < N; ++I) { 151 StringRef Name = Features[I]; 152 assert(Name[0] == '-' || Name[0] == '+'); 153 LastOpt[Name.drop_front(1)] = I; 154 } 155 156 for (unsigned I = 0, N = Features.size(); I < N; ++I) { 157 // If this feature was overridden, ignore it. 158 StringRef Name = Features[I]; 159 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1)); 160 assert(LastI != LastOpt.end()); 161 unsigned Last = LastI->second; 162 if (Last != I) 163 continue; 164 165 UnifiedFeatures.push_back(Name); 166 } 167 return UnifiedFeatures; 168 } 169 170 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, 171 const char *ArgName, const char *EnvVar) { 172 const char *DirList = ::getenv(EnvVar); 173 bool CombinedArg = false; 174 175 if (!DirList) 176 return; // Nothing to do. 177 178 StringRef Name(ArgName); 179 if (Name.equals("-I") || Name.equals("-L") || Name.empty()) 180 CombinedArg = true; 181 182 StringRef Dirs(DirList); 183 if (Dirs.empty()) // Empty string should not add '.'. 184 return; 185 186 StringRef::size_type Delim; 187 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) { 188 if (Delim == 0) { // Leading colon. 189 if (CombinedArg) { 190 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 191 } else { 192 CmdArgs.push_back(ArgName); 193 CmdArgs.push_back("."); 194 } 195 } else { 196 if (CombinedArg) { 197 CmdArgs.push_back( 198 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); 199 } else { 200 CmdArgs.push_back(ArgName); 201 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); 202 } 203 } 204 Dirs = Dirs.substr(Delim + 1); 205 } 206 207 if (Dirs.empty()) { // Trailing colon. 208 if (CombinedArg) { 209 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 210 } else { 211 CmdArgs.push_back(ArgName); 212 CmdArgs.push_back("."); 213 } 214 } else { // Add the last path. 215 if (CombinedArg) { 216 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); 217 } else { 218 CmdArgs.push_back(ArgName); 219 CmdArgs.push_back(Args.MakeArgString(Dirs)); 220 } 221 } 222 } 223 224 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, 225 const ArgList &Args, ArgStringList &CmdArgs, 226 const JobAction &JA) { 227 const Driver &D = TC.getDriver(); 228 229 // Add extra linker input arguments which are not treated as inputs 230 // (constructed via -Xarch_). 231 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); 232 233 // LIBRARY_PATH are included before user inputs and only supported on native 234 // toolchains. 235 if (!TC.isCrossCompiling()) 236 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); 237 238 for (const auto &II : Inputs) { 239 // If the current tool chain refers to an OpenMP offloading host, we 240 // should ignore inputs that refer to OpenMP offloading devices - 241 // they will be embedded according to a proper linker script. 242 if (auto *IA = II.getAction()) 243 if ((JA.isHostOffloading(Action::OFK_OpenMP) && 244 IA->isDeviceOffloading(Action::OFK_OpenMP))) 245 continue; 246 247 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType())) 248 // Don't try to pass LLVM inputs unless we have native support. 249 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); 250 251 // Add filenames immediately. 252 if (II.isFilename()) { 253 CmdArgs.push_back(II.getFilename()); 254 continue; 255 } 256 257 // Otherwise, this is a linker input argument. 258 const Arg &A = II.getInputArg(); 259 260 // Handle reserved library options. 261 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) 262 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 263 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) 264 TC.AddCCKextLibArgs(Args, CmdArgs); 265 else if (A.getOption().matches(options::OPT_z)) { 266 // Pass -z prefix for gcc linker compatibility. 267 A.claim(); 268 A.render(Args, CmdArgs); 269 } else if (A.getOption().matches(options::OPT_b)) { 270 const llvm::Triple &T = TC.getTriple(); 271 if (!T.isOSAIX()) { 272 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 273 << A.getSpelling() << T.str(); 274 } 275 // Pass -b prefix for AIX linker. 276 A.claim(); 277 A.render(Args, CmdArgs); 278 } else { 279 A.renderAsInput(Args, CmdArgs); 280 } 281 } 282 } 283 284 void tools::addLinkerCompressDebugSectionsOption( 285 const ToolChain &TC, const llvm::opt::ArgList &Args, 286 llvm::opt::ArgStringList &CmdArgs) { 287 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi 288 // whereas zlib is an alias to zlib-gabi. Therefore -gz=none|zlib|zlib-gnu 289 // are translated to --compress-debug-sections=none|zlib|zlib-gnu. 290 // -gz is not translated since ld --compress-debug-sections option requires an 291 // argument. 292 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) { 293 StringRef V = A->getValue(); 294 if (V == "none" || V == "zlib" || V == "zlib-gnu") 295 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V)); 296 else 297 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument) 298 << A->getOption().getName() << V; 299 } 300 } 301 302 void tools::AddTargetFeature(const ArgList &Args, 303 std::vector<StringRef> &Features, 304 OptSpecifier OnOpt, OptSpecifier OffOpt, 305 StringRef FeatureName) { 306 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { 307 if (A->getOption().matches(OnOpt)) 308 Features.push_back(Args.MakeArgString("+" + FeatureName)); 309 else 310 Features.push_back(Args.MakeArgString("-" + FeatureName)); 311 } 312 } 313 314 /// Get the (LLVM) name of the AMDGPU gpu we are targeting. 315 static std::string getAMDGPUTargetGPU(const llvm::Triple &T, 316 const ArgList &Args) { 317 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 318 auto GPUName = getProcessorFromTargetID(T, A->getValue()); 319 return llvm::StringSwitch<std::string>(GPUName) 320 .Cases("rv630", "rv635", "r600") 321 .Cases("rv610", "rv620", "rs780", "rs880") 322 .Case("rv740", "rv770") 323 .Case("palm", "cedar") 324 .Cases("sumo", "sumo2", "sumo") 325 .Case("hemlock", "cypress") 326 .Case("aruba", "cayman") 327 .Default(GPUName.str()); 328 } 329 return ""; 330 } 331 332 static std::string getLanaiTargetCPU(const ArgList &Args) { 333 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 334 return A->getValue(); 335 } 336 return ""; 337 } 338 339 /// Get the (LLVM) name of the WebAssembly cpu we are targeting. 340 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { 341 // If we have -mcpu=, use that. 342 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 343 StringRef CPU = A->getValue(); 344 345 #ifdef __wasm__ 346 // Handle "native" by examining the host. "native" isn't meaningful when 347 // cross compiling, so only support this when the host is also WebAssembly. 348 if (CPU == "native") 349 return llvm::sys::getHostCPUName(); 350 #endif 351 352 return CPU; 353 } 354 355 return "generic"; 356 } 357 358 std::string tools::getCPUName(const Driver &D, const ArgList &Args, 359 const llvm::Triple &T, bool FromAs) { 360 Arg *A; 361 362 switch (T.getArch()) { 363 default: 364 return ""; 365 366 case llvm::Triple::aarch64: 367 case llvm::Triple::aarch64_32: 368 case llvm::Triple::aarch64_be: 369 return aarch64::getAArch64TargetCPU(Args, T, A); 370 371 case llvm::Triple::arm: 372 case llvm::Triple::armeb: 373 case llvm::Triple::thumb: 374 case llvm::Triple::thumbeb: { 375 StringRef MArch, MCPU; 376 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs); 377 return arm::getARMTargetCPU(MCPU, MArch, T); 378 } 379 380 case llvm::Triple::avr: 381 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ)) 382 return A->getValue(); 383 return ""; 384 385 case llvm::Triple::m68k: 386 return m68k::getM68kTargetCPU(Args); 387 388 case llvm::Triple::mips: 389 case llvm::Triple::mipsel: 390 case llvm::Triple::mips64: 391 case llvm::Triple::mips64el: { 392 StringRef CPUName; 393 StringRef ABIName; 394 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName); 395 return std::string(CPUName); 396 } 397 398 case llvm::Triple::nvptx: 399 case llvm::Triple::nvptx64: 400 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 401 return A->getValue(); 402 return ""; 403 404 case llvm::Triple::ppc: 405 case llvm::Triple::ppcle: 406 case llvm::Triple::ppc64: 407 case llvm::Triple::ppc64le: { 408 std::string TargetCPUName = ppc::getPPCTargetCPU(Args); 409 // LLVM may default to generating code for the native CPU, 410 // but, like gcc, we default to a more generic option for 411 // each architecture. (except on AIX) 412 if (!TargetCPUName.empty()) 413 return TargetCPUName; 414 415 if (T.isOSAIX()) 416 TargetCPUName = "pwr7"; 417 else if (T.getArch() == llvm::Triple::ppc64le) 418 TargetCPUName = "ppc64le"; 419 else if (T.getArch() == llvm::Triple::ppc64) 420 TargetCPUName = "ppc64"; 421 else 422 TargetCPUName = "ppc"; 423 424 return TargetCPUName; 425 } 426 case llvm::Triple::riscv32: 427 case llvm::Triple::riscv64: 428 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 429 return A->getValue(); 430 return ""; 431 432 case llvm::Triple::bpfel: 433 case llvm::Triple::bpfeb: 434 case llvm::Triple::sparc: 435 case llvm::Triple::sparcel: 436 case llvm::Triple::sparcv9: 437 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 438 return A->getValue(); 439 if (T.getArch() == llvm::Triple::sparc && T.isOSSolaris()) 440 return "v9"; 441 return ""; 442 443 case llvm::Triple::x86: 444 case llvm::Triple::x86_64: 445 return x86::getX86TargetCPU(D, Args, T); 446 447 case llvm::Triple::hexagon: 448 return "hexagon" + 449 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); 450 451 case llvm::Triple::lanai: 452 return getLanaiTargetCPU(Args); 453 454 case llvm::Triple::systemz: 455 return systemz::getSystemZTargetCPU(Args); 456 457 case llvm::Triple::r600: 458 case llvm::Triple::amdgcn: 459 return getAMDGPUTargetGPU(T, Args); 460 461 case llvm::Triple::wasm32: 462 case llvm::Triple::wasm64: 463 return std::string(getWebAssemblyTargetCPU(Args)); 464 } 465 } 466 467 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) { 468 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ); 469 if (!LtoJobsArg) 470 return {}; 471 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue())) 472 D.Diag(diag::err_drv_invalid_int_value) 473 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue(); 474 return LtoJobsArg->getValue(); 475 } 476 477 // CloudABI uses -ffunction-sections and -fdata-sections by default. 478 bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 479 return Triple.getOS() == llvm::Triple::CloudABI; 480 } 481 482 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args, 483 ArgStringList &CmdArgs, const InputInfo &Output, 484 const InputInfo &Input, bool IsThinLTO) { 485 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath()); 486 const Driver &D = ToolChain.getDriver(); 487 if (llvm::sys::path::filename(Linker) != "ld.lld" && 488 llvm::sys::path::stem(Linker) != "ld.lld") { 489 // Tell the linker to load the plugin. This has to come before 490 // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt 491 // that -Wl might forward. 492 CmdArgs.push_back("-plugin"); 493 494 #if defined(_WIN32) 495 const char *Suffix = ".dll"; 496 #elif defined(__APPLE__) 497 const char *Suffix = ".dylib"; 498 #else 499 const char *Suffix = ".so"; 500 #endif 501 502 SmallString<1024> Plugin; 503 llvm::sys::path::native( 504 Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix, 505 Plugin); 506 CmdArgs.push_back(Args.MakeArgString(Plugin)); 507 } 508 509 // Try to pass driver level flags relevant to LTO code generation down to 510 // the plugin. 511 512 // Handle flags for selecting CPU variants. 513 std::string CPU = getCPUName(D, Args, ToolChain.getTriple()); 514 if (!CPU.empty()) 515 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU)); 516 517 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 518 // The optimization level matches 519 // CompilerInvocation.cpp:getOptimizationLevel(). 520 StringRef OOpt; 521 if (A->getOption().matches(options::OPT_O4) || 522 A->getOption().matches(options::OPT_Ofast)) 523 OOpt = "3"; 524 else if (A->getOption().matches(options::OPT_O)) { 525 OOpt = A->getValue(); 526 if (OOpt == "g") 527 OOpt = "1"; 528 else if (OOpt == "s" || OOpt == "z") 529 OOpt = "2"; 530 } else if (A->getOption().matches(options::OPT_O0)) 531 OOpt = "0"; 532 if (!OOpt.empty()) 533 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt)); 534 } 535 536 if (Args.hasArg(options::OPT_gsplit_dwarf)) { 537 CmdArgs.push_back( 538 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") + 539 Output.getFilename() + "_dwo")); 540 } 541 542 if (IsThinLTO) 543 CmdArgs.push_back("-plugin-opt=thinlto"); 544 545 StringRef Parallelism = getLTOParallelism(Args, D); 546 if (!Parallelism.empty()) 547 CmdArgs.push_back( 548 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism))); 549 550 // If an explicit debugger tuning argument appeared, pass it along. 551 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group, 552 options::OPT_ggdbN_Group)) { 553 if (A->getOption().matches(options::OPT_glldb)) 554 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb"); 555 else if (A->getOption().matches(options::OPT_gsce)) 556 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce"); 557 else if (A->getOption().matches(options::OPT_gdbx)) 558 CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx"); 559 else 560 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb"); 561 } 562 563 bool UseSeparateSections = 564 isUseSeparateSections(ToolChain.getEffectiveTriple()); 565 566 if (Args.hasFlag(options::OPT_ffunction_sections, 567 options::OPT_fno_function_sections, UseSeparateSections)) { 568 CmdArgs.push_back("-plugin-opt=-function-sections"); 569 } 570 571 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 572 UseSeparateSections)) { 573 CmdArgs.push_back("-plugin-opt=-data-sections"); 574 } 575 576 if (Arg *A = getLastProfileSampleUseArg(Args)) { 577 StringRef FName = A->getValue(); 578 if (!llvm::sys::fs::exists(FName)) 579 D.Diag(diag::err_drv_no_such_file) << FName; 580 else 581 CmdArgs.push_back( 582 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName)); 583 } 584 585 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 586 options::OPT_fcs_profile_generate_EQ, 587 options::OPT_fno_profile_generate); 588 if (CSPGOGenerateArg && 589 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 590 CSPGOGenerateArg = nullptr; 591 592 auto *ProfileUseArg = getLastProfileUseArg(Args); 593 594 if (CSPGOGenerateArg) { 595 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate")); 596 if (CSPGOGenerateArg->getOption().matches( 597 options::OPT_fcs_profile_generate_EQ)) { 598 SmallString<128> Path(CSPGOGenerateArg->getValue()); 599 llvm::sys::path::append(Path, "default_%m.profraw"); 600 CmdArgs.push_back( 601 Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path)); 602 } else 603 CmdArgs.push_back( 604 Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw")); 605 } else if (ProfileUseArg) { 606 SmallString<128> Path( 607 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 608 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 609 llvm::sys::path::append(Path, "default.profdata"); 610 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + 611 Path)); 612 } 613 614 // Pass an option to enable/disable the new pass manager. 615 if (auto *A = Args.getLastArg(options::OPT_flegacy_pass_manager, 616 options::OPT_fno_legacy_pass_manager)) { 617 if (A->getOption().matches(options::OPT_flegacy_pass_manager)) 618 CmdArgs.push_back("-plugin-opt=legacy-pass-manager"); 619 else 620 CmdArgs.push_back("-plugin-opt=new-pass-manager"); 621 } 622 623 // Pass an option to enable pseudo probe emission. 624 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling, 625 options::OPT_fno_pseudo_probe_for_profiling, false)) 626 CmdArgs.push_back("-plugin-opt=pseudo-probe-for-profiling"); 627 628 // Setup statistics file output. 629 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 630 if (!StatsFile.empty()) 631 CmdArgs.push_back( 632 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile)); 633 634 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true); 635 636 // Handle remark diagnostics on screen options: '-Rpass-*'. 637 renderRpassOptions(Args, CmdArgs); 638 639 // Handle serialized remarks options: '-fsave-optimization-record' 640 // and '-foptimization-record-*'. 641 if (willEmitRemarks(Args)) 642 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input, 643 Output); 644 645 // Handle remarks hotness/threshold related options. 646 renderRemarksHotnessOptions(Args, CmdArgs); 647 648 addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(), 649 /*IsLTO=*/true); 650 } 651 652 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 653 ArgStringList &CmdArgs) { 654 // Enable -frtlib-add-rpath by default for the case of VE. 655 const bool IsVE = TC.getTriple().isVE(); 656 bool DefaultValue = IsVE; 657 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 658 options::OPT_fno_rtlib_add_rpath, DefaultValue)) 659 return; 660 661 std::string CandidateRPath = TC.getArchSpecificLibPath(); 662 if (TC.getVFS().exists(CandidateRPath)) { 663 CmdArgs.push_back("-rpath"); 664 CmdArgs.push_back(Args.MakeArgString(CandidateRPath)); 665 } 666 } 667 668 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, 669 const ArgList &Args, bool ForceStaticHostRuntime, 670 bool IsOffloadingHost, bool GompNeedsRT) { 671 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 672 options::OPT_fno_openmp, false)) 673 return false; 674 675 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 676 677 if (RTKind == Driver::OMPRT_Unknown) 678 // Already diagnosed. 679 return false; 680 681 if (ForceStaticHostRuntime) 682 CmdArgs.push_back("-Bstatic"); 683 684 switch (RTKind) { 685 case Driver::OMPRT_OMP: 686 CmdArgs.push_back("-lomp"); 687 break; 688 case Driver::OMPRT_GOMP: 689 CmdArgs.push_back("-lgomp"); 690 break; 691 case Driver::OMPRT_IOMP5: 692 CmdArgs.push_back("-liomp5"); 693 break; 694 case Driver::OMPRT_Unknown: 695 break; 696 } 697 698 if (ForceStaticHostRuntime) 699 CmdArgs.push_back("-Bdynamic"); 700 701 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 702 CmdArgs.push_back("-lrt"); 703 704 if (IsOffloadingHost) 705 CmdArgs.push_back("-lomptarget"); 706 707 addArchSpecificRPath(TC, Args, CmdArgs); 708 709 return true; 710 } 711 712 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 713 ArgStringList &CmdArgs, StringRef Sanitizer, 714 bool IsShared, bool IsWhole) { 715 // Wrap any static runtimes that must be forced into executable in 716 // whole-archive. 717 if (IsWhole) CmdArgs.push_back("--whole-archive"); 718 CmdArgs.push_back(TC.getCompilerRTArgString( 719 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 720 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 721 722 if (IsShared) { 723 addArchSpecificRPath(TC, Args, CmdArgs); 724 } 725 } 726 727 // Tries to use a file with the list of dynamic symbols that need to be exported 728 // from the runtime library. Returns true if the file was found. 729 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 730 ArgStringList &CmdArgs, 731 StringRef Sanitizer) { 732 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 733 // the option, so don't try to pass it. 734 if (TC.getTriple().getOS() == llvm::Triple::Solaris) 735 return true; 736 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 737 if (llvm::sys::fs::exists(SanRT + ".syms")) { 738 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 739 return true; 740 } 741 return false; 742 } 743 744 static const char *getAsNeededOption(const ToolChain &TC, bool as_needed) { 745 assert(!TC.getTriple().isOSAIX() && 746 "AIX linker does not support any form of --as-needed option yet."); 747 748 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases 749 // for the native forms -z ignore/-z record, they are missing in Illumos, 750 // so always use the native form. 751 if (TC.getTriple().isOSSolaris()) 752 return as_needed ? "-zignore" : "-zrecord"; 753 else 754 return as_needed ? "--as-needed" : "--no-as-needed"; 755 } 756 757 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 758 ArgStringList &CmdArgs) { 759 // Fuchsia never needs these. Any sanitizer runtimes with system 760 // dependencies use the `.deplibs` feature instead. 761 if (TC.getTriple().isOSFuchsia()) 762 return; 763 764 // Force linking against the system libraries sanitizers depends on 765 // (see PR15823 why this is necessary). 766 CmdArgs.push_back(getAsNeededOption(TC, false)); 767 // There's no libpthread or librt on RTEMS & Android. 768 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 769 !TC.getTriple().isAndroid()) { 770 CmdArgs.push_back("-lpthread"); 771 if (!TC.getTriple().isOSOpenBSD()) 772 CmdArgs.push_back("-lrt"); 773 } 774 CmdArgs.push_back("-lm"); 775 // There's no libdl on all OSes. 776 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() && 777 !TC.getTriple().isOSOpenBSD() && 778 TC.getTriple().getOS() != llvm::Triple::RTEMS) 779 CmdArgs.push_back("-ldl"); 780 // Required for backtrace on some OSes 781 if (TC.getTriple().isOSFreeBSD() || 782 TC.getTriple().isOSNetBSD() || 783 TC.getTriple().isOSOpenBSD()) 784 CmdArgs.push_back("-lexecinfo"); 785 } 786 787 static void 788 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 789 SmallVectorImpl<StringRef> &SharedRuntimes, 790 SmallVectorImpl<StringRef> &StaticRuntimes, 791 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 792 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 793 SmallVectorImpl<StringRef> &RequiredSymbols) { 794 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 795 // Collect shared runtimes. 796 if (SanArgs.needsSharedRt()) { 797 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 798 SharedRuntimes.push_back("asan"); 799 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 800 HelperStaticRuntimes.push_back("asan-preinit"); 801 } 802 if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) { 803 SharedRuntimes.push_back("memprof"); 804 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 805 HelperStaticRuntimes.push_back("memprof-preinit"); 806 } 807 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 808 if (SanArgs.requiresMinimalRuntime()) 809 SharedRuntimes.push_back("ubsan_minimal"); 810 else 811 SharedRuntimes.push_back("ubsan_standalone"); 812 } 813 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 814 if (SanArgs.requiresMinimalRuntime()) 815 SharedRuntimes.push_back("scudo_minimal"); 816 else 817 SharedRuntimes.push_back("scudo"); 818 } 819 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) 820 SharedRuntimes.push_back("tsan"); 821 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 822 if (SanArgs.needsHwasanAliasesRt()) 823 SharedRuntimes.push_back("hwasan_aliases"); 824 else 825 SharedRuntimes.push_back("hwasan"); 826 } 827 } 828 829 // The stats_client library is also statically linked into DSOs. 830 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) 831 StaticRuntimes.push_back("stats_client"); 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(); 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(); 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() && LastPICArg && 1194 LastPICArg == 1195 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 1196 options::OPT_fPIE, options::OPT_fpie)) { 1197 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1198 << LastPICArg->getSpelling() << Triple.str(); 1199 if (Triple.getArch() == llvm::Triple::x86_64) 1200 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 1201 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1202 } 1203 1204 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 1205 // is forced, then neither PIC nor PIE flags will have no effect. 1206 if (!ToolChain.isPICDefaultForced()) { 1207 if (LastPICArg) { 1208 Option O = LastPICArg->getOption(); 1209 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 1210 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 1211 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 1212 PIC = 1213 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 1214 IsPICLevelTwo = 1215 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 1216 } else { 1217 PIE = PIC = false; 1218 if (EffectiveTriple.isPS4CPU()) { 1219 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1220 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1221 if (Model != "kernel") { 1222 PIC = true; 1223 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic) 1224 << LastPICArg->getSpelling(); 1225 } 1226 } 1227 } 1228 } 1229 } 1230 1231 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the 1232 // PIC level would've been set to level 1, force it back to level 2 PIC 1233 // instead. 1234 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU())) 1235 IsPICLevelTwo |= ToolChain.isPICDefault(); 1236 1237 // This kernel flags are a trump-card: they will disable PIC/PIE 1238 // generation, independent of the argument order. 1239 if (KernelOrKext && 1240 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1241 !EffectiveTriple.isWatchOS())) 1242 PIC = PIE = false; 1243 1244 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1245 // This is a very special mode. It trumps the other modes, almost no one 1246 // uses it, and it isn't even valid on any OS but Darwin. 1247 if (!Triple.isOSDarwin()) 1248 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1249 << A->getSpelling() << Triple.str(); 1250 1251 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1252 1253 // Only a forced PIC mode can cause the actual compile to have PIC defines 1254 // etc., no flags are sufficient. This behavior was selected to closely 1255 // match that of llvm-gcc and Apple GCC before that. 1256 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1257 1258 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1259 } 1260 1261 bool EmbeddedPISupported; 1262 switch (Triple.getArch()) { 1263 case llvm::Triple::arm: 1264 case llvm::Triple::armeb: 1265 case llvm::Triple::thumb: 1266 case llvm::Triple::thumbeb: 1267 EmbeddedPISupported = true; 1268 break; 1269 default: 1270 EmbeddedPISupported = false; 1271 break; 1272 } 1273 1274 bool ROPI = false, RWPI = false; 1275 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1276 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1277 if (!EmbeddedPISupported) 1278 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1279 << LastROPIArg->getSpelling() << Triple.str(); 1280 ROPI = true; 1281 } 1282 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 1283 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 1284 if (!EmbeddedPISupported) 1285 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1286 << LastRWPIArg->getSpelling() << Triple.str(); 1287 RWPI = true; 1288 } 1289 1290 // ROPI and RWPI are not compatible with PIC or PIE. 1291 if ((ROPI || RWPI) && (PIC || PIE)) 1292 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 1293 1294 if (Triple.isMIPS()) { 1295 StringRef CPUName; 1296 StringRef ABIName; 1297 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1298 // When targeting the N64 ABI, PIC is the default, except in the case 1299 // when the -mno-abicalls option is used. In that case we exit 1300 // at next check regardless of PIC being set below. 1301 if (ABIName == "n64") 1302 PIC = true; 1303 // When targettng MIPS with -mno-abicalls, it's always static. 1304 if(Args.hasArg(options::OPT_mno_abicalls)) 1305 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1306 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 1307 // does not use PIC level 2 for historical reasons. 1308 IsPICLevelTwo = false; 1309 } 1310 1311 if (PIC) 1312 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 1313 1314 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 1315 if (ROPI && RWPI) 1316 RelocM = llvm::Reloc::ROPI_RWPI; 1317 else if (ROPI) 1318 RelocM = llvm::Reloc::ROPI; 1319 else if (RWPI) 1320 RelocM = llvm::Reloc::RWPI; 1321 1322 return std::make_tuple(RelocM, 0U, false); 1323 } 1324 1325 // `-falign-functions` indicates that the functions should be aligned to a 1326 // 16-byte boundary. 1327 // 1328 // `-falign-functions=1` is the same as `-fno-align-functions`. 1329 // 1330 // The scalar `n` in `-falign-functions=n` must be an integral value between 1331 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to 1332 // the nearest power-of-two. 1333 // 1334 // If we return `0`, the frontend will default to the backend's preferred 1335 // alignment. 1336 // 1337 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 1338 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred 1339 // alignment. For unaligned functions, we default to the backend's preferred 1340 // alignment. 1341 unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 1342 const ArgList &Args) { 1343 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 1344 options::OPT_falign_functions_EQ, 1345 options::OPT_fno_align_functions); 1346 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 1347 return 0; 1348 1349 if (A->getOption().matches(options::OPT_falign_functions)) 1350 return 0; 1351 1352 unsigned Value = 0; 1353 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 1354 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1355 << A->getAsString(Args) << A->getValue(); 1356 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 1357 } 1358 1359 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC, 1360 const ArgList &Args) { 1361 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version); 1362 1363 if (!A) 1364 return 0; 1365 1366 unsigned Value = 0; 1367 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 || 1368 Value < 2) 1369 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1370 << A->getAsString(Args) << A->getValue(); 1371 return Value; 1372 } 1373 1374 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 1375 ArgStringList &CmdArgs) { 1376 llvm::Reloc::Model RelocationModel; 1377 unsigned PICLevel; 1378 bool IsPIE; 1379 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 1380 1381 if (RelocationModel != llvm::Reloc::Static) 1382 CmdArgs.push_back("-KPIC"); 1383 } 1384 1385 /// Determine whether Objective-C automated reference counting is 1386 /// enabled. 1387 bool tools::isObjCAutoRefCount(const ArgList &Args) { 1388 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 1389 } 1390 1391 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 1392 1393 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, 1394 const ArgList &Args) { 1395 if (Args.hasArg(options::OPT_static_libgcc) || 1396 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie)) 1397 return LibGccType::StaticLibGcc; 1398 if (Args.hasArg(options::OPT_shared_libgcc)) 1399 return LibGccType::SharedLibGcc; 1400 // The Android NDK only provides libunwind.a, not libunwind.so. 1401 if (TC.getTriple().isAndroid()) 1402 return LibGccType::StaticLibGcc; 1403 // For MinGW, don't imply a shared libgcc here, we only want to return 1404 // SharedLibGcc if that was explicitly requested. 1405 if (D.CCCIsCXX() && !TC.getTriple().isOSCygMing()) 1406 return LibGccType::SharedLibGcc; 1407 return LibGccType::UnspecifiedLibGcc; 1408 } 1409 1410 // Gcc adds libgcc arguments in various ways: 1411 // 1412 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 1413 // g++ <none>: -lgcc_s -lgcc 1414 // gcc shared: -lgcc_s -lgcc 1415 // g++ shared: -lgcc_s -lgcc 1416 // gcc static: -lgcc -lgcc_eh 1417 // g++ static: -lgcc -lgcc_eh 1418 // gcc static-pie: -lgcc -lgcc_eh 1419 // g++ static-pie: -lgcc -lgcc_eh 1420 // 1421 // Also, certain targets need additional adjustments. 1422 1423 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 1424 ArgStringList &CmdArgs, const ArgList &Args) { 1425 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 1426 // Targets that don't use unwind libraries. 1427 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) || 1428 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() || 1429 UNW == ToolChain::UNW_None) 1430 return; 1431 1432 LibGccType LGT = getLibGccType(TC, D, Args); 1433 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 1434 !TC.getTriple().isAndroid() && 1435 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX(); 1436 if (AsNeeded) 1437 CmdArgs.push_back(getAsNeededOption(TC, true)); 1438 1439 switch (UNW) { 1440 case ToolChain::UNW_None: 1441 return; 1442 case ToolChain::UNW_Libgcc: { 1443 if (LGT == LibGccType::StaticLibGcc) 1444 CmdArgs.push_back("-lgcc_eh"); 1445 else 1446 CmdArgs.push_back("-lgcc_s"); 1447 break; 1448 } 1449 case ToolChain::UNW_CompilerRT: 1450 if (TC.getTriple().isOSAIX()) { 1451 // AIX only has libunwind as a shared library. So do not pass 1452 // anything in if -static is specified. 1453 if (LGT != LibGccType::StaticLibGcc) 1454 CmdArgs.push_back("-lunwind"); 1455 } else if (LGT == LibGccType::StaticLibGcc) { 1456 CmdArgs.push_back("-l:libunwind.a"); 1457 } else if (TC.getTriple().isOSCygMing()) { 1458 if (LGT == LibGccType::SharedLibGcc) 1459 CmdArgs.push_back("-l:libunwind.dll.a"); 1460 else 1461 // Let the linker choose between libunwind.dll.a and libunwind.a 1462 // depending on what's available, and depending on the -static flag 1463 CmdArgs.push_back("-lunwind"); 1464 } else { 1465 CmdArgs.push_back("-l:libunwind.so"); 1466 } 1467 break; 1468 } 1469 1470 if (AsNeeded) 1471 CmdArgs.push_back(getAsNeededOption(TC, false)); 1472 } 1473 1474 static void AddLibgcc(const ToolChain &TC, const Driver &D, 1475 ArgStringList &CmdArgs, const ArgList &Args) { 1476 LibGccType LGT = getLibGccType(TC, D, Args); 1477 if (LGT != LibGccType::SharedLibGcc) 1478 CmdArgs.push_back("-lgcc"); 1479 AddUnwindLibrary(TC, D, CmdArgs, Args); 1480 if (LGT == LibGccType::SharedLibGcc) 1481 CmdArgs.push_back("-lgcc"); 1482 } 1483 1484 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 1485 ArgStringList &CmdArgs, const ArgList &Args) { 1486 // Make use of compiler-rt if --rtlib option is used 1487 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 1488 1489 switch (RLT) { 1490 case ToolChain::RLT_CompilerRT: 1491 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 1492 AddUnwindLibrary(TC, D, CmdArgs, Args); 1493 break; 1494 case ToolChain::RLT_Libgcc: 1495 // Make sure libgcc is not used under MSVC environment by default 1496 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1497 // Issue error diagnostic if libgcc is explicitly specified 1498 // through command line as --rtlib option argument. 1499 if (Args.hasArg(options::OPT_rtlib_EQ)) { 1500 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 1501 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC"; 1502 } 1503 } else 1504 AddLibgcc(TC, D, CmdArgs, Args); 1505 break; 1506 } 1507 1508 // On Android, the unwinder uses dl_iterate_phdr (or one of 1509 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For 1510 // statically-linked executables, these functions come from libc.a instead. 1511 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) && 1512 !Args.hasArg(options::OPT_static_pie)) 1513 CmdArgs.push_back("-ldl"); 1514 } 1515 1516 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 1517 const InputInfo &Output, 1518 const InputInfo &Input, 1519 const Driver &D) { 1520 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 1521 if (!A) 1522 return {}; 1523 1524 StringRef SaveStats = A->getValue(); 1525 SmallString<128> StatsFile; 1526 if (SaveStats == "obj" && Output.isFilename()) { 1527 StatsFile.assign(Output.getFilename()); 1528 llvm::sys::path::remove_filename(StatsFile); 1529 } else if (SaveStats != "cwd") { 1530 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 1531 return {}; 1532 } 1533 1534 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 1535 llvm::sys::path::append(StatsFile, BaseName); 1536 llvm::sys::path::replace_extension(StatsFile, "stats"); 1537 return StatsFile; 1538 } 1539 1540 void tools::addMultilibFlag(bool Enabled, const char *const Flag, 1541 Multilib::flags_list &Flags) { 1542 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag); 1543 } 1544 1545 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args, 1546 ArgStringList &CmdArgs, bool IsLTO) { 1547 auto addArg = [&, IsLTO](const Twine &Arg) { 1548 if (IsLTO) { 1549 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg)); 1550 } else { 1551 CmdArgs.push_back("-mllvm"); 1552 CmdArgs.push_back(Args.MakeArgString(Arg)); 1553 } 1554 }; 1555 1556 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) { 1557 addArg(Twine("-x86-branches-within-32B-boundaries")); 1558 } 1559 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) { 1560 StringRef Value = A->getValue(); 1561 unsigned Boundary; 1562 if (Value.getAsInteger(10, Boundary) || Boundary < 16 || 1563 !llvm::isPowerOf2_64(Boundary)) { 1564 D.Diag(diag::err_drv_invalid_argument_to_option) 1565 << Value << A->getOption().getName(); 1566 } else { 1567 addArg("-x86-align-branch-boundary=" + Twine(Boundary)); 1568 } 1569 } 1570 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) { 1571 std::string AlignBranch; 1572 for (StringRef T : A->getValues()) { 1573 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" && 1574 T != "ret" && T != "indirect") 1575 D.Diag(diag::err_drv_invalid_malign_branch_EQ) 1576 << T << "fused, jcc, jmp, call, ret, indirect"; 1577 if (!AlignBranch.empty()) 1578 AlignBranch += '+'; 1579 AlignBranch += T; 1580 } 1581 addArg("-x86-align-branch=" + Twine(AlignBranch)); 1582 } 1583 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) { 1584 StringRef Value = A->getValue(); 1585 unsigned PrefixSize; 1586 if (Value.getAsInteger(10, PrefixSize)) { 1587 D.Diag(diag::err_drv_invalid_argument_to_option) 1588 << Value << A->getOption().getName(); 1589 } else { 1590 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize)); 1591 } 1592 } 1593 } 1594 1595 static llvm::opt::Arg * 1596 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) { 1597 // The last of -mcode-object-v3, -mno-code-object-v3 and 1598 // -mcode-object-version=<version> wins. 1599 return Args.getLastArg(options::OPT_mcode_object_v3_legacy, 1600 options::OPT_mno_code_object_v3_legacy, 1601 options::OPT_mcode_object_version_EQ); 1602 } 1603 1604 void tools::checkAMDGPUCodeObjectVersion(const Driver &D, 1605 const llvm::opt::ArgList &Args) { 1606 const unsigned MinCodeObjVer = 2; 1607 const unsigned MaxCodeObjVer = 4; 1608 1609 // Emit warnings for legacy options even if they are overridden. 1610 if (Args.hasArg(options::OPT_mno_code_object_v3_legacy)) 1611 D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3" 1612 << "-mcode-object-version=2"; 1613 1614 if (Args.hasArg(options::OPT_mcode_object_v3_legacy)) 1615 D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3" 1616 << "-mcode-object-version=3"; 1617 1618 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { 1619 if (CodeObjArg->getOption().getID() == 1620 options::OPT_mcode_object_version_EQ) { 1621 unsigned CodeObjVer = MaxCodeObjVer; 1622 auto Remnant = 1623 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 1624 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer) 1625 D.Diag(diag::err_drv_invalid_int_value) 1626 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue(); 1627 } 1628 } 1629 } 1630 1631 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D, 1632 const llvm::opt::ArgList &Args) { 1633 unsigned CodeObjVer = 4; // default 1634 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { 1635 if (CodeObjArg->getOption().getID() == 1636 options::OPT_mno_code_object_v3_legacy) { 1637 CodeObjVer = 2; 1638 } else if (CodeObjArg->getOption().getID() == 1639 options::OPT_mcode_object_v3_legacy) { 1640 CodeObjVer = 3; 1641 } else { 1642 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 1643 } 1644 } 1645 return CodeObjVer; 1646 } 1647 1648 bool tools::haveAMDGPUCodeObjectVersionArgument( 1649 const Driver &D, const llvm::opt::ArgList &Args) { 1650 return getAMDGPUCodeObjectArgument(D, Args) != nullptr; 1651 } 1652 1653 void tools::addMachineOutlinerArgs(const Driver &D, 1654 const llvm::opt::ArgList &Args, 1655 llvm::opt::ArgStringList &CmdArgs, 1656 const llvm::Triple &Triple, bool IsLTO) { 1657 auto addArg = [&, IsLTO](const Twine &Arg) { 1658 if (IsLTO) { 1659 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg)); 1660 } else { 1661 CmdArgs.push_back("-mllvm"); 1662 CmdArgs.push_back(Args.MakeArgString(Arg)); 1663 } 1664 }; 1665 1666 if (Arg *A = Args.getLastArg(options::OPT_moutline, 1667 options::OPT_mno_outline)) { 1668 if (A->getOption().matches(options::OPT_moutline)) { 1669 // We only support -moutline in AArch64 and ARM targets right now. If 1670 // we're not compiling for these, emit a warning and ignore the flag. 1671 // Otherwise, add the proper mllvm flags. 1672 if (!(Triple.isARM() || Triple.isThumb() || 1673 Triple.getArch() == llvm::Triple::aarch64 || 1674 Triple.getArch() == llvm::Triple::aarch64_32)) { 1675 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); 1676 } else { 1677 addArg(Twine("-enable-machine-outliner")); 1678 } 1679 } else { 1680 // Disable all outlining behaviour. 1681 addArg(Twine("-enable-machine-outliner=never")); 1682 } 1683 } 1684 } 1685 1686 void tools::addOpenMPDeviceRTL(const Driver &D, 1687 const llvm::opt::ArgList &DriverArgs, 1688 llvm::opt::ArgStringList &CC1Args, 1689 StringRef BitcodeSuffix, 1690 const llvm::Triple &Triple) { 1691 SmallVector<StringRef, 8> LibraryPaths; 1692 // Add user defined library paths from LIBRARY_PATH. 1693 llvm::Optional<std::string> LibPath = 1694 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 1695 if (LibPath) { 1696 SmallVector<StringRef, 8> Frags; 1697 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 1698 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 1699 for (StringRef Path : Frags) 1700 LibraryPaths.emplace_back(Path.trim()); 1701 } 1702 1703 // Add path to lib / lib64 folder. 1704 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir); 1705 llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX); 1706 LibraryPaths.emplace_back(DefaultLibPath.c_str()); 1707 1708 OptSpecifier LibomptargetBCPathOpt = 1709 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgcn_bc_path_EQ 1710 : options::OPT_libomptarget_nvptx_bc_path_EQ; 1711 1712 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgcn" : "nvptx"; 1713 std::string LibOmpTargetName = "libomptarget-" + BitcodeSuffix.str() + ".bc"; 1714 1715 // First check whether user specifies bc library 1716 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) { 1717 SmallString<128> LibOmpTargetFile(A->getValue()); 1718 if (llvm::sys::fs::exists(LibOmpTargetFile) && 1719 llvm::sys::fs::is_directory(LibOmpTargetFile)) { 1720 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 1721 } 1722 1723 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 1724 CC1Args.push_back("-mlink-builtin-bitcode"); 1725 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 1726 } else { 1727 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found) 1728 << LibOmpTargetFile; 1729 } 1730 } else { 1731 bool FoundBCLibrary = false; 1732 1733 for (StringRef LibraryPath : LibraryPaths) { 1734 SmallString<128> LibOmpTargetFile(LibraryPath); 1735 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 1736 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 1737 CC1Args.push_back("-mlink-builtin-bitcode"); 1738 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 1739 FoundBCLibrary = true; 1740 break; 1741 } 1742 } 1743 1744 if (!FoundBCLibrary) 1745 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime) 1746 << LibOmpTargetName << ArchPrefix; 1747 } 1748 } 1749