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