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