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/Mips.h" 13 #include "Arch/PPC.h" 14 #include "Arch/SystemZ.h" 15 #include "Arch/X86.h" 16 #include "HIP.h" 17 #include "Hexagon.h" 18 #include "InputInfo.h" 19 #include "clang/Basic/CharInfo.h" 20 #include "clang/Basic/LangOptions.h" 21 #include "clang/Basic/ObjCRuntime.h" 22 #include "clang/Basic/Version.h" 23 #include "clang/Config/config.h" 24 #include "clang/Driver/Action.h" 25 #include "clang/Driver/Compilation.h" 26 #include "clang/Driver/Driver.h" 27 #include "clang/Driver/DriverDiagnostic.h" 28 #include "clang/Driver/Job.h" 29 #include "clang/Driver/Options.h" 30 #include "clang/Driver/SanitizerArgs.h" 31 #include "clang/Driver/ToolChain.h" 32 #include "clang/Driver/Util.h" 33 #include "clang/Driver/XRayArgs.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallString.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/Twine.h" 39 #include "llvm/Option/Arg.h" 40 #include "llvm/Option/ArgList.h" 41 #include "llvm/Option/Option.h" 42 #include "llvm/Support/CodeGen.h" 43 #include "llvm/Support/Compression.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/ErrorHandling.h" 46 #include "llvm/Support/FileSystem.h" 47 #include "llvm/Support/Host.h" 48 #include "llvm/Support/Path.h" 49 #include "llvm/Support/Process.h" 50 #include "llvm/Support/Program.h" 51 #include "llvm/Support/ScopedPrinter.h" 52 #include "llvm/Support/TargetParser.h" 53 #include "llvm/Support/Threading.h" 54 #include "llvm/Support/VirtualFileSystem.h" 55 #include "llvm/Support/YAMLParser.h" 56 57 using namespace clang::driver; 58 using namespace clang::driver::tools; 59 using namespace clang; 60 using namespace llvm::opt; 61 62 void tools::addPathIfExists(const Driver &D, const Twine &Path, 63 ToolChain::path_list &Paths) { 64 if (D.getVFS().exists(Path)) 65 Paths.push_back(Path.str()); 66 } 67 68 void tools::handleTargetFeaturesGroup(const ArgList &Args, 69 std::vector<StringRef> &Features, 70 OptSpecifier Group) { 71 for (const Arg *A : Args.filtered(Group)) { 72 StringRef Name = A->getOption().getName(); 73 A->claim(); 74 75 // Skip over "-m". 76 assert(Name.startswith("m") && "Invalid feature name."); 77 Name = Name.substr(1); 78 79 bool IsNegative = Name.startswith("no-"); 80 if (IsNegative) 81 Name = Name.substr(3); 82 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); 83 } 84 } 85 86 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, 87 const char *ArgName, const char *EnvVar) { 88 const char *DirList = ::getenv(EnvVar); 89 bool CombinedArg = false; 90 91 if (!DirList) 92 return; // Nothing to do. 93 94 StringRef Name(ArgName); 95 if (Name.equals("-I") || Name.equals("-L") || Name.empty()) 96 CombinedArg = true; 97 98 StringRef Dirs(DirList); 99 if (Dirs.empty()) // Empty string should not add '.'. 100 return; 101 102 StringRef::size_type Delim; 103 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) { 104 if (Delim == 0) { // Leading colon. 105 if (CombinedArg) { 106 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 107 } else { 108 CmdArgs.push_back(ArgName); 109 CmdArgs.push_back("."); 110 } 111 } else { 112 if (CombinedArg) { 113 CmdArgs.push_back( 114 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); 115 } else { 116 CmdArgs.push_back(ArgName); 117 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); 118 } 119 } 120 Dirs = Dirs.substr(Delim + 1); 121 } 122 123 if (Dirs.empty()) { // Trailing colon. 124 if (CombinedArg) { 125 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 126 } else { 127 CmdArgs.push_back(ArgName); 128 CmdArgs.push_back("."); 129 } 130 } else { // Add the last path. 131 if (CombinedArg) { 132 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); 133 } else { 134 CmdArgs.push_back(ArgName); 135 CmdArgs.push_back(Args.MakeArgString(Dirs)); 136 } 137 } 138 } 139 140 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, 141 const ArgList &Args, ArgStringList &CmdArgs, 142 const JobAction &JA) { 143 const Driver &D = TC.getDriver(); 144 145 // Add extra linker input arguments which are not treated as inputs 146 // (constructed via -Xarch_). 147 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); 148 149 // LIBRARY_PATH are included before user inputs and only supported on native 150 // toolchains. 151 if (!TC.isCrossCompiling()) 152 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); 153 154 for (const auto &II : Inputs) { 155 // If the current tool chain refers to an OpenMP or HIP offloading host, we 156 // should ignore inputs that refer to OpenMP or HIP offloading devices - 157 // they will be embedded according to a proper linker script. 158 if (auto *IA = II.getAction()) 159 if ((JA.isHostOffloading(Action::OFK_OpenMP) && 160 IA->isDeviceOffloading(Action::OFK_OpenMP)) || 161 (JA.isHostOffloading(Action::OFK_HIP) && 162 IA->isDeviceOffloading(Action::OFK_HIP))) 163 continue; 164 165 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType())) 166 // Don't try to pass LLVM inputs unless we have native support. 167 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); 168 169 // Add filenames immediately. 170 if (II.isFilename()) { 171 CmdArgs.push_back(II.getFilename()); 172 continue; 173 } 174 175 // Otherwise, this is a linker input argument. 176 const Arg &A = II.getInputArg(); 177 178 // Handle reserved library options. 179 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) 180 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 181 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) 182 TC.AddCCKextLibArgs(Args, CmdArgs); 183 else if (A.getOption().matches(options::OPT_z)) { 184 // Pass -z prefix for gcc linker compatibility. 185 A.claim(); 186 A.render(Args, CmdArgs); 187 } else { 188 A.renderAsInput(Args, CmdArgs); 189 } 190 } 191 } 192 193 void tools::AddTargetFeature(const ArgList &Args, 194 std::vector<StringRef> &Features, 195 OptSpecifier OnOpt, OptSpecifier OffOpt, 196 StringRef FeatureName) { 197 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { 198 if (A->getOption().matches(OnOpt)) 199 Features.push_back(Args.MakeArgString("+" + FeatureName)); 200 else 201 Features.push_back(Args.MakeArgString("-" + FeatureName)); 202 } 203 } 204 205 /// Get the (LLVM) name of the R600 gpu we are targeting. 206 static std::string getR600TargetGPU(const ArgList &Args) { 207 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 208 const char *GPUName = A->getValue(); 209 return llvm::StringSwitch<const char *>(GPUName) 210 .Cases("rv630", "rv635", "r600") 211 .Cases("rv610", "rv620", "rs780", "rs880") 212 .Case("rv740", "rv770") 213 .Case("palm", "cedar") 214 .Cases("sumo", "sumo2", "sumo") 215 .Case("hemlock", "cypress") 216 .Case("aruba", "cayman") 217 .Default(GPUName); 218 } 219 return ""; 220 } 221 222 static std::string getLanaiTargetCPU(const ArgList &Args) { 223 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 224 return A->getValue(); 225 } 226 return ""; 227 } 228 229 /// Get the (LLVM) name of the WebAssembly cpu we are targeting. 230 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { 231 // If we have -mcpu=, use that. 232 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 233 StringRef CPU = A->getValue(); 234 235 #ifdef __wasm__ 236 // Handle "native" by examining the host. "native" isn't meaningful when 237 // cross compiling, so only support this when the host is also WebAssembly. 238 if (CPU == "native") 239 return llvm::sys::getHostCPUName(); 240 #endif 241 242 return CPU; 243 } 244 245 return "generic"; 246 } 247 248 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T, 249 bool FromAs) { 250 Arg *A; 251 252 switch (T.getArch()) { 253 default: 254 return ""; 255 256 case llvm::Triple::aarch64: 257 case llvm::Triple::aarch64_32: 258 case llvm::Triple::aarch64_be: 259 return aarch64::getAArch64TargetCPU(Args, T, A); 260 261 case llvm::Triple::arm: 262 case llvm::Triple::armeb: 263 case llvm::Triple::thumb: 264 case llvm::Triple::thumbeb: { 265 StringRef MArch, MCPU; 266 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs); 267 return arm::getARMTargetCPU(MCPU, MArch, T); 268 } 269 270 case llvm::Triple::avr: 271 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ)) 272 return A->getValue(); 273 return ""; 274 275 case llvm::Triple::mips: 276 case llvm::Triple::mipsel: 277 case llvm::Triple::mips64: 278 case llvm::Triple::mips64el: { 279 StringRef CPUName; 280 StringRef ABIName; 281 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName); 282 return std::string(CPUName); 283 } 284 285 case llvm::Triple::nvptx: 286 case llvm::Triple::nvptx64: 287 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 288 return A->getValue(); 289 return ""; 290 291 case llvm::Triple::ppc: 292 case llvm::Triple::ppc64: 293 case llvm::Triple::ppc64le: { 294 std::string TargetCPUName = ppc::getPPCTargetCPU(Args); 295 // LLVM may default to generating code for the native CPU, 296 // but, like gcc, we default to a more generic option for 297 // each architecture. (except on Darwin) 298 if (TargetCPUName.empty() && !T.isOSDarwin()) { 299 if (T.getArch() == llvm::Triple::ppc64) 300 TargetCPUName = "ppc64"; 301 else if (T.getArch() == llvm::Triple::ppc64le) 302 TargetCPUName = "ppc64le"; 303 else 304 TargetCPUName = "ppc"; 305 } 306 return TargetCPUName; 307 } 308 309 case llvm::Triple::bpfel: 310 case llvm::Triple::bpfeb: 311 case llvm::Triple::sparc: 312 case llvm::Triple::sparcel: 313 case llvm::Triple::sparcv9: 314 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 315 return A->getValue(); 316 return ""; 317 318 case llvm::Triple::x86: 319 case llvm::Triple::x86_64: 320 return x86::getX86TargetCPU(Args, T); 321 322 case llvm::Triple::hexagon: 323 return "hexagon" + 324 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); 325 326 case llvm::Triple::lanai: 327 return getLanaiTargetCPU(Args); 328 329 case llvm::Triple::systemz: 330 return systemz::getSystemZTargetCPU(Args); 331 332 case llvm::Triple::r600: 333 case llvm::Triple::amdgcn: 334 return getR600TargetGPU(Args); 335 336 case llvm::Triple::wasm32: 337 case llvm::Triple::wasm64: 338 return std::string(getWebAssemblyTargetCPU(Args)); 339 } 340 } 341 342 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) { 343 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ); 344 if (!LtoJobsArg) 345 return {}; 346 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue())) 347 D.Diag(diag::err_drv_invalid_int_value) 348 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue(); 349 return LtoJobsArg->getValue(); 350 } 351 352 // CloudABI uses -ffunction-sections and -fdata-sections by default. 353 bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 354 return Triple.getOS() == llvm::Triple::CloudABI; 355 } 356 357 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args, 358 ArgStringList &CmdArgs, const InputInfo &Output, 359 const InputInfo &Input, bool IsThinLTO) { 360 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath()); 361 if (llvm::sys::path::filename(Linker) != "ld.lld" && 362 llvm::sys::path::stem(Linker) != "ld.lld") { 363 // Tell the linker to load the plugin. This has to come before 364 // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt 365 // that -Wl might forward. 366 CmdArgs.push_back("-plugin"); 367 368 #if defined(_WIN32) 369 const char *Suffix = ".dll"; 370 #elif defined(__APPLE__) 371 const char *Suffix = ".dylib"; 372 #else 373 const char *Suffix = ".so"; 374 #endif 375 376 SmallString<1024> Plugin; 377 llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) + 378 "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + 379 Suffix, 380 Plugin); 381 CmdArgs.push_back(Args.MakeArgString(Plugin)); 382 } 383 384 // Try to pass driver level flags relevant to LTO code generation down to 385 // the plugin. 386 387 // Handle flags for selecting CPU variants. 388 std::string CPU = getCPUName(Args, ToolChain.getTriple()); 389 if (!CPU.empty()) 390 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU)); 391 392 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 393 StringRef OOpt; 394 if (A->getOption().matches(options::OPT_O4) || 395 A->getOption().matches(options::OPT_Ofast)) 396 OOpt = "3"; 397 else if (A->getOption().matches(options::OPT_O)) 398 OOpt = A->getValue(); 399 else if (A->getOption().matches(options::OPT_O0)) 400 OOpt = "0"; 401 if (!OOpt.empty()) 402 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt)); 403 } 404 405 if (Args.hasArg(options::OPT_gsplit_dwarf)) { 406 CmdArgs.push_back( 407 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") + 408 Output.getFilename() + "_dwo")); 409 } 410 411 if (IsThinLTO) 412 CmdArgs.push_back("-plugin-opt=thinlto"); 413 414 StringRef Parallelism = getLTOParallelism(Args, ToolChain.getDriver()); 415 if (!Parallelism.empty()) 416 CmdArgs.push_back( 417 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism))); 418 419 // If an explicit debugger tuning argument appeared, pass it along. 420 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group, 421 options::OPT_ggdbN_Group)) { 422 if (A->getOption().matches(options::OPT_glldb)) 423 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb"); 424 else if (A->getOption().matches(options::OPT_gsce)) 425 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce"); 426 else 427 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb"); 428 } 429 430 bool UseSeparateSections = 431 isUseSeparateSections(ToolChain.getEffectiveTriple()); 432 433 if (Args.hasFlag(options::OPT_ffunction_sections, 434 options::OPT_fno_function_sections, UseSeparateSections)) { 435 CmdArgs.push_back("-plugin-opt=-function-sections"); 436 } 437 438 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 439 UseSeparateSections)) { 440 CmdArgs.push_back("-plugin-opt=-data-sections"); 441 } 442 443 if (Arg *A = getLastProfileSampleUseArg(Args)) { 444 StringRef FName = A->getValue(); 445 if (!llvm::sys::fs::exists(FName)) 446 ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName; 447 else 448 CmdArgs.push_back( 449 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName)); 450 } 451 452 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 453 options::OPT_fcs_profile_generate_EQ, 454 options::OPT_fno_profile_generate); 455 if (CSPGOGenerateArg && 456 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 457 CSPGOGenerateArg = nullptr; 458 459 auto *ProfileUseArg = getLastProfileUseArg(Args); 460 461 if (CSPGOGenerateArg) { 462 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate")); 463 if (CSPGOGenerateArg->getOption().matches( 464 options::OPT_fcs_profile_generate_EQ)) { 465 SmallString<128> Path(CSPGOGenerateArg->getValue()); 466 llvm::sys::path::append(Path, "default_%m.profraw"); 467 CmdArgs.push_back( 468 Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path)); 469 } else 470 CmdArgs.push_back( 471 Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw")); 472 } else if (ProfileUseArg) { 473 SmallString<128> Path( 474 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 475 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 476 llvm::sys::path::append(Path, "default.profdata"); 477 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + 478 Path)); 479 } 480 481 // Need this flag to turn on new pass manager via Gold plugin. 482 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager, 483 options::OPT_fno_experimental_new_pass_manager, 484 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) { 485 CmdArgs.push_back("-plugin-opt=new-pass-manager"); 486 } 487 488 // Setup statistics file output. 489 SmallString<128> StatsFile = 490 getStatsFileName(Args, Output, Input, ToolChain.getDriver()); 491 if (!StatsFile.empty()) 492 CmdArgs.push_back( 493 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile)); 494 } 495 496 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 497 ArgStringList &CmdArgs) { 498 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 499 options::OPT_fno_rtlib_add_rpath, false)) 500 return; 501 502 std::string CandidateRPath = TC.getArchSpecificLibPath(); 503 if (TC.getVFS().exists(CandidateRPath)) { 504 CmdArgs.push_back("-rpath"); 505 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str())); 506 } 507 } 508 509 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, 510 const ArgList &Args, bool ForceStaticHostRuntime, 511 bool IsOffloadingHost, bool GompNeedsRT) { 512 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 513 options::OPT_fno_openmp, false)) 514 return false; 515 516 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 517 518 if (RTKind == Driver::OMPRT_Unknown) 519 // Already diagnosed. 520 return false; 521 522 if (ForceStaticHostRuntime) 523 CmdArgs.push_back("-Bstatic"); 524 525 switch (RTKind) { 526 case Driver::OMPRT_OMP: 527 CmdArgs.push_back("-lomp"); 528 break; 529 case Driver::OMPRT_GOMP: 530 CmdArgs.push_back("-lgomp"); 531 break; 532 case Driver::OMPRT_IOMP5: 533 CmdArgs.push_back("-liomp5"); 534 break; 535 case Driver::OMPRT_Unknown: 536 break; 537 } 538 539 if (ForceStaticHostRuntime) 540 CmdArgs.push_back("-Bdynamic"); 541 542 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 543 CmdArgs.push_back("-lrt"); 544 545 if (IsOffloadingHost) 546 CmdArgs.push_back("-lomptarget"); 547 548 addArchSpecificRPath(TC, Args, CmdArgs); 549 550 return true; 551 } 552 553 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 554 ArgStringList &CmdArgs, StringRef Sanitizer, 555 bool IsShared, bool IsWhole) { 556 // Wrap any static runtimes that must be forced into executable in 557 // whole-archive. 558 if (IsWhole) CmdArgs.push_back("--whole-archive"); 559 CmdArgs.push_back(TC.getCompilerRTArgString( 560 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 561 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 562 563 if (IsShared) { 564 addArchSpecificRPath(TC, Args, CmdArgs); 565 } 566 } 567 568 // Tries to use a file with the list of dynamic symbols that need to be exported 569 // from the runtime library. Returns true if the file was found. 570 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 571 ArgStringList &CmdArgs, 572 StringRef Sanitizer) { 573 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 574 // the option, so don't try to pass it. 575 if (TC.getTriple().getOS() == llvm::Triple::Solaris) 576 return true; 577 // Myriad is static linking only. Furthermore, some versions of its 578 // linker have the bug where --export-dynamic overrides -static, so 579 // don't use --export-dynamic on that platform. 580 if (TC.getTriple().getVendor() == llvm::Triple::Myriad) 581 return true; 582 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 583 if (llvm::sys::fs::exists(SanRT + ".syms")) { 584 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 585 return true; 586 } 587 return false; 588 } 589 590 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 591 ArgStringList &CmdArgs) { 592 // Fuchsia never needs these. Any sanitizer runtimes with system 593 // dependencies use the `.deplibs` feature instead. 594 if (TC.getTriple().isOSFuchsia()) 595 return; 596 597 // Force linking against the system libraries sanitizers depends on 598 // (see PR15823 why this is necessary). 599 CmdArgs.push_back("--no-as-needed"); 600 // There's no libpthread or librt on RTEMS & Android. 601 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 602 !TC.getTriple().isAndroid()) { 603 CmdArgs.push_back("-lpthread"); 604 if (!TC.getTriple().isOSOpenBSD()) 605 CmdArgs.push_back("-lrt"); 606 } 607 CmdArgs.push_back("-lm"); 608 // There's no libdl on all OSes. 609 if (!TC.getTriple().isOSFreeBSD() && 610 !TC.getTriple().isOSNetBSD() && 611 !TC.getTriple().isOSOpenBSD() && 612 TC.getTriple().getOS() != llvm::Triple::RTEMS) 613 CmdArgs.push_back("-ldl"); 614 // Required for backtrace on some OSes 615 if (TC.getTriple().isOSFreeBSD() || 616 TC.getTriple().isOSNetBSD()) 617 CmdArgs.push_back("-lexecinfo"); 618 } 619 620 static void 621 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 622 SmallVectorImpl<StringRef> &SharedRuntimes, 623 SmallVectorImpl<StringRef> &StaticRuntimes, 624 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 625 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 626 SmallVectorImpl<StringRef> &RequiredSymbols) { 627 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 628 // Collect shared runtimes. 629 if (SanArgs.needsSharedRt()) { 630 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 631 SharedRuntimes.push_back("asan"); 632 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 633 HelperStaticRuntimes.push_back("asan-preinit"); 634 } 635 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 636 if (SanArgs.requiresMinimalRuntime()) 637 SharedRuntimes.push_back("ubsan_minimal"); 638 else 639 SharedRuntimes.push_back("ubsan_standalone"); 640 } 641 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 642 if (SanArgs.requiresMinimalRuntime()) 643 SharedRuntimes.push_back("scudo_minimal"); 644 else 645 SharedRuntimes.push_back("scudo"); 646 } 647 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) 648 SharedRuntimes.push_back("hwasan"); 649 } 650 651 // The stats_client library is also statically linked into DSOs. 652 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) 653 StaticRuntimes.push_back("stats_client"); 654 655 // Collect static runtimes. 656 if (Args.hasArg(options::OPT_shared)) { 657 // Don't link static runtimes into DSOs. 658 return; 659 } 660 661 // Each static runtime that has a DSO counterpart above is excluded below, 662 // but runtimes that exist only as static are not affected by needsSharedRt. 663 664 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 665 StaticRuntimes.push_back("asan"); 666 if (SanArgs.linkCXXRuntimes()) 667 StaticRuntimes.push_back("asan_cxx"); 668 } 669 670 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 671 StaticRuntimes.push_back("hwasan"); 672 if (SanArgs.linkCXXRuntimes()) 673 StaticRuntimes.push_back("hwasan_cxx"); 674 } 675 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes()) 676 StaticRuntimes.push_back("dfsan"); 677 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes()) 678 StaticRuntimes.push_back("lsan"); 679 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) { 680 StaticRuntimes.push_back("msan"); 681 if (SanArgs.linkCXXRuntimes()) 682 StaticRuntimes.push_back("msan_cxx"); 683 } 684 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) { 685 StaticRuntimes.push_back("tsan"); 686 if (SanArgs.linkCXXRuntimes()) 687 StaticRuntimes.push_back("tsan_cxx"); 688 } 689 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 690 if (SanArgs.requiresMinimalRuntime()) { 691 StaticRuntimes.push_back("ubsan_minimal"); 692 } else { 693 StaticRuntimes.push_back("ubsan_standalone"); 694 if (SanArgs.linkCXXRuntimes()) 695 StaticRuntimes.push_back("ubsan_standalone_cxx"); 696 } 697 } 698 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) { 699 NonWholeStaticRuntimes.push_back("safestack"); 700 RequiredSymbols.push_back("__safestack_init"); 701 } 702 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) { 703 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes()) 704 StaticRuntimes.push_back("cfi"); 705 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) { 706 StaticRuntimes.push_back("cfi_diag"); 707 if (SanArgs.linkCXXRuntimes()) 708 StaticRuntimes.push_back("ubsan_standalone_cxx"); 709 } 710 } 711 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) { 712 NonWholeStaticRuntimes.push_back("stats"); 713 RequiredSymbols.push_back("__sanitizer_stats_register"); 714 } 715 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 716 if (SanArgs.requiresMinimalRuntime()) { 717 StaticRuntimes.push_back("scudo_minimal"); 718 if (SanArgs.linkCXXRuntimes()) 719 StaticRuntimes.push_back("scudo_cxx_minimal"); 720 } else { 721 StaticRuntimes.push_back("scudo"); 722 if (SanArgs.linkCXXRuntimes()) 723 StaticRuntimes.push_back("scudo_cxx"); 724 } 725 } 726 } 727 728 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++, 729 // C runtime, etc). Returns true if sanitizer system deps need to be linked in. 730 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 731 ArgStringList &CmdArgs) { 732 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, 733 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; 734 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, 735 NonWholeStaticRuntimes, HelperStaticRuntimes, 736 RequiredSymbols); 737 738 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 739 // Inject libfuzzer dependencies. 740 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && 741 !Args.hasArg(options::OPT_shared)) { 742 743 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true); 744 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) 745 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 746 } 747 748 for (auto RT : SharedRuntimes) 749 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false); 750 for (auto RT : HelperStaticRuntimes) 751 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 752 bool AddExportDynamic = false; 753 for (auto RT : StaticRuntimes) { 754 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 755 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 756 } 757 for (auto RT : NonWholeStaticRuntimes) { 758 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false); 759 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 760 } 761 for (auto S : RequiredSymbols) { 762 CmdArgs.push_back("-u"); 763 CmdArgs.push_back(Args.MakeArgString(S)); 764 } 765 // If there is a static runtime with no dynamic list, force all the symbols 766 // to be dynamic to be sure we export sanitizer interface functions. 767 if (AddExportDynamic) 768 CmdArgs.push_back("--export-dynamic"); 769 770 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) 771 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check"); 772 773 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); 774 } 775 776 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { 777 if (Args.hasArg(options::OPT_shared)) 778 return false; 779 780 if (TC.getXRayArgs().needsXRayRt()) { 781 CmdArgs.push_back("-whole-archive"); 782 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray")); 783 for (const auto &Mode : TC.getXRayArgs().modeList()) 784 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode)); 785 CmdArgs.push_back("-no-whole-archive"); 786 return true; 787 } 788 789 return false; 790 } 791 792 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) { 793 CmdArgs.push_back("--no-as-needed"); 794 CmdArgs.push_back("-lpthread"); 795 if (!TC.getTriple().isOSOpenBSD()) 796 CmdArgs.push_back("-lrt"); 797 CmdArgs.push_back("-lm"); 798 799 if (!TC.getTriple().isOSFreeBSD() && 800 !TC.getTriple().isOSNetBSD() && 801 !TC.getTriple().isOSOpenBSD()) 802 CmdArgs.push_back("-ldl"); 803 } 804 805 bool tools::areOptimizationsEnabled(const ArgList &Args) { 806 // Find the last -O arg and see if it is non-zero. 807 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 808 return !A->getOption().matches(options::OPT_O0); 809 // Defaults to -O0. 810 return false; 811 } 812 813 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input, 814 const InputInfo &Output) { 815 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ)) 816 if (StringRef(A->getValue()) == "single") 817 return Args.MakeArgString(Output.getFilename()); 818 819 Arg *FinalOutput = Args.getLastArg(options::OPT_o); 820 if (FinalOutput && Args.hasArg(options::OPT_c)) { 821 SmallString<128> T(FinalOutput->getValue()); 822 llvm::sys::path::replace_extension(T, "dwo"); 823 return Args.MakeArgString(T); 824 } else { 825 // Use the compilation dir. 826 SmallString<128> T( 827 Args.getLastArgValue(options::OPT_fdebug_compilation_dir)); 828 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput())); 829 llvm::sys::path::replace_extension(F, "dwo"); 830 T += F; 831 return Args.MakeArgString(F); 832 } 833 } 834 835 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, 836 const JobAction &JA, const ArgList &Args, 837 const InputInfo &Output, const char *OutFile) { 838 ArgStringList ExtractArgs; 839 ExtractArgs.push_back("--extract-dwo"); 840 841 ArgStringList StripArgs; 842 StripArgs.push_back("--strip-dwo"); 843 844 // Grabbing the output of the earlier compile step. 845 StripArgs.push_back(Output.getFilename()); 846 ExtractArgs.push_back(Output.getFilename()); 847 ExtractArgs.push_back(OutFile); 848 849 const char *Exec = 850 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); 851 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); 852 853 // First extract the dwo sections. 854 C.addCommand(std::make_unique<Command>(JA, T, Exec, ExtractArgs, II)); 855 856 // Then remove them from the original .o file. 857 C.addCommand(std::make_unique<Command>(JA, T, Exec, StripArgs, II)); 858 } 859 860 // Claim options we don't want to warn if they are unused. We do this for 861 // options that build systems might add but are unused when assembling or only 862 // running the preprocessor for example. 863 void tools::claimNoWarnArgs(const ArgList &Args) { 864 // Don't warn about unused -f(no-)?lto. This can happen when we're 865 // preprocessing, precompiling or assembling. 866 Args.ClaimAllArgs(options::OPT_flto_EQ); 867 Args.ClaimAllArgs(options::OPT_flto); 868 Args.ClaimAllArgs(options::OPT_fno_lto); 869 } 870 871 Arg *tools::getLastProfileUseArg(const ArgList &Args) { 872 auto *ProfileUseArg = Args.getLastArg( 873 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ, 874 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ, 875 options::OPT_fno_profile_instr_use); 876 877 if (ProfileUseArg && 878 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)) 879 ProfileUseArg = nullptr; 880 881 return ProfileUseArg; 882 } 883 884 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { 885 auto *ProfileSampleUseArg = Args.getLastArg( 886 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ, 887 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ, 888 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile); 889 890 if (ProfileSampleUseArg && 891 (ProfileSampleUseArg->getOption().matches( 892 options::OPT_fno_profile_sample_use) || 893 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile))) 894 return nullptr; 895 896 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ, 897 options::OPT_fauto_profile_EQ); 898 } 899 900 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, 901 /// smooshes them together with platform defaults, to decide whether 902 /// this compile should be using PIC mode or not. Returns a tuple of 903 /// (RelocationModel, PICLevel, IsPIE). 904 std::tuple<llvm::Reloc::Model, unsigned, bool> 905 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { 906 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); 907 const llvm::Triple &Triple = ToolChain.getTriple(); 908 909 bool PIE = ToolChain.isPIEDefault(); 910 bool PIC = PIE || ToolChain.isPICDefault(); 911 // The Darwin/MachO default to use PIC does not apply when using -static. 912 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static)) 913 PIE = PIC = false; 914 bool IsPICLevelTwo = PIC; 915 916 bool KernelOrKext = 917 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 918 919 // Android-specific defaults for PIC/PIE 920 if (Triple.isAndroid()) { 921 switch (Triple.getArch()) { 922 case llvm::Triple::arm: 923 case llvm::Triple::armeb: 924 case llvm::Triple::thumb: 925 case llvm::Triple::thumbeb: 926 case llvm::Triple::aarch64: 927 case llvm::Triple::mips: 928 case llvm::Triple::mipsel: 929 case llvm::Triple::mips64: 930 case llvm::Triple::mips64el: 931 PIC = true; // "-fpic" 932 break; 933 934 case llvm::Triple::x86: 935 case llvm::Triple::x86_64: 936 PIC = true; // "-fPIC" 937 IsPICLevelTwo = true; 938 break; 939 940 default: 941 break; 942 } 943 } 944 945 // OpenBSD-specific defaults for PIE 946 if (Triple.isOSOpenBSD()) { 947 switch (ToolChain.getArch()) { 948 case llvm::Triple::arm: 949 case llvm::Triple::aarch64: 950 case llvm::Triple::mips64: 951 case llvm::Triple::mips64el: 952 case llvm::Triple::x86: 953 case llvm::Triple::x86_64: 954 IsPICLevelTwo = false; // "-fpie" 955 break; 956 957 case llvm::Triple::ppc: 958 case llvm::Triple::sparc: 959 case llvm::Triple::sparcel: 960 case llvm::Triple::sparcv9: 961 IsPICLevelTwo = true; // "-fPIE" 962 break; 963 964 default: 965 break; 966 } 967 } 968 969 // AMDGPU-specific defaults for PIC. 970 if (Triple.getArch() == llvm::Triple::amdgcn) 971 PIC = true; 972 973 // The last argument relating to either PIC or PIE wins, and no 974 // other argument is used. If the last argument is any flavor of the 975 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE 976 // option implicitly enables PIC at the same level. 977 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, 978 options::OPT_fpic, options::OPT_fno_pic, 979 options::OPT_fPIE, options::OPT_fno_PIE, 980 options::OPT_fpie, options::OPT_fno_pie); 981 if (Triple.isOSWindows() && LastPICArg && 982 LastPICArg == 983 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 984 options::OPT_fPIE, options::OPT_fpie)) { 985 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 986 << LastPICArg->getSpelling() << Triple.str(); 987 if (Triple.getArch() == llvm::Triple::x86_64) 988 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 989 return std::make_tuple(llvm::Reloc::Static, 0U, false); 990 } 991 992 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 993 // is forced, then neither PIC nor PIE flags will have no effect. 994 if (!ToolChain.isPICDefaultForced()) { 995 if (LastPICArg) { 996 Option O = LastPICArg->getOption(); 997 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 998 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 999 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 1000 PIC = 1001 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 1002 IsPICLevelTwo = 1003 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 1004 } else { 1005 PIE = PIC = false; 1006 if (EffectiveTriple.isPS4CPU()) { 1007 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1008 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1009 if (Model != "kernel") { 1010 PIC = true; 1011 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic) 1012 << LastPICArg->getSpelling(); 1013 } 1014 } 1015 } 1016 } 1017 } 1018 1019 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the 1020 // PIC level would've been set to level 1, force it back to level 2 PIC 1021 // instead. 1022 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU())) 1023 IsPICLevelTwo |= ToolChain.isPICDefault(); 1024 1025 // This kernel flags are a trump-card: they will disable PIC/PIE 1026 // generation, independent of the argument order. 1027 if (KernelOrKext && 1028 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1029 !EffectiveTriple.isWatchOS())) 1030 PIC = PIE = false; 1031 1032 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1033 // This is a very special mode. It trumps the other modes, almost no one 1034 // uses it, and it isn't even valid on any OS but Darwin. 1035 if (!Triple.isOSDarwin()) 1036 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1037 << A->getSpelling() << Triple.str(); 1038 1039 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1040 1041 // Only a forced PIC mode can cause the actual compile to have PIC defines 1042 // etc., no flags are sufficient. This behavior was selected to closely 1043 // match that of llvm-gcc and Apple GCC before that. 1044 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1045 1046 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1047 } 1048 1049 bool EmbeddedPISupported; 1050 switch (Triple.getArch()) { 1051 case llvm::Triple::arm: 1052 case llvm::Triple::armeb: 1053 case llvm::Triple::thumb: 1054 case llvm::Triple::thumbeb: 1055 EmbeddedPISupported = true; 1056 break; 1057 default: 1058 EmbeddedPISupported = false; 1059 break; 1060 } 1061 1062 bool ROPI = false, RWPI = false; 1063 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1064 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1065 if (!EmbeddedPISupported) 1066 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1067 << LastROPIArg->getSpelling() << Triple.str(); 1068 ROPI = true; 1069 } 1070 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 1071 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 1072 if (!EmbeddedPISupported) 1073 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1074 << LastRWPIArg->getSpelling() << Triple.str(); 1075 RWPI = true; 1076 } 1077 1078 // ROPI and RWPI are not compatible with PIC or PIE. 1079 if ((ROPI || RWPI) && (PIC || PIE)) 1080 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 1081 1082 if (Triple.isMIPS()) { 1083 StringRef CPUName; 1084 StringRef ABIName; 1085 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1086 // When targeting the N64 ABI, PIC is the default, except in the case 1087 // when the -mno-abicalls option is used. In that case we exit 1088 // at next check regardless of PIC being set below. 1089 if (ABIName == "n64") 1090 PIC = true; 1091 // When targettng MIPS with -mno-abicalls, it's always static. 1092 if(Args.hasArg(options::OPT_mno_abicalls)) 1093 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1094 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 1095 // does not use PIC level 2 for historical reasons. 1096 IsPICLevelTwo = false; 1097 } 1098 1099 if (PIC) 1100 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 1101 1102 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 1103 if (ROPI && RWPI) 1104 RelocM = llvm::Reloc::ROPI_RWPI; 1105 else if (ROPI) 1106 RelocM = llvm::Reloc::ROPI; 1107 else if (RWPI) 1108 RelocM = llvm::Reloc::RWPI; 1109 1110 return std::make_tuple(RelocM, 0U, false); 1111 } 1112 1113 // `-falign-functions` indicates that the functions should be aligned to a 1114 // 16-byte boundary. 1115 // 1116 // `-falign-functions=1` is the same as `-fno-align-functions`. 1117 // 1118 // The scalar `n` in `-falign-functions=n` must be an integral value between 1119 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to 1120 // the nearest power-of-two. 1121 // 1122 // If we return `0`, the frontend will default to the backend's preferred 1123 // alignment. 1124 // 1125 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 1126 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred 1127 // alignment. For unaligned functions, we default to the backend's preferred 1128 // alignment. 1129 unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 1130 const ArgList &Args) { 1131 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 1132 options::OPT_falign_functions_EQ, 1133 options::OPT_fno_align_functions); 1134 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 1135 return 0; 1136 1137 if (A->getOption().matches(options::OPT_falign_functions)) 1138 return 0; 1139 1140 unsigned Value = 0; 1141 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 1142 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1143 << A->getAsString(Args) << A->getValue(); 1144 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 1145 } 1146 1147 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC, 1148 const ArgList &Args) { 1149 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version); 1150 1151 if (!A) 1152 return 0; 1153 1154 unsigned Value = 0; 1155 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 || 1156 Value < 2) 1157 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1158 << A->getAsString(Args) << A->getValue(); 1159 return Value; 1160 } 1161 1162 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 1163 ArgStringList &CmdArgs) { 1164 llvm::Reloc::Model RelocationModel; 1165 unsigned PICLevel; 1166 bool IsPIE; 1167 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 1168 1169 if (RelocationModel != llvm::Reloc::Static) 1170 CmdArgs.push_back("-KPIC"); 1171 } 1172 1173 /// Determine whether Objective-C automated reference counting is 1174 /// enabled. 1175 bool tools::isObjCAutoRefCount(const ArgList &Args) { 1176 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 1177 } 1178 1179 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 1180 1181 static LibGccType getLibGccType(const Driver &D, const ArgList &Args) { 1182 if (Args.hasArg(options::OPT_static_libgcc) || 1183 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie)) 1184 return LibGccType::StaticLibGcc; 1185 if (Args.hasArg(options::OPT_shared_libgcc) || D.CCCIsCXX()) 1186 return LibGccType::SharedLibGcc; 1187 return LibGccType::UnspecifiedLibGcc; 1188 } 1189 1190 // Gcc adds libgcc arguments in various ways: 1191 // 1192 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 1193 // g++ <none>: -lgcc_s -lgcc 1194 // gcc shared: -lgcc_s -lgcc 1195 // g++ shared: -lgcc_s -lgcc 1196 // gcc static: -lgcc -lgcc_eh 1197 // g++ static: -lgcc -lgcc_eh 1198 // gcc static-pie: -lgcc -lgcc_eh 1199 // g++ static-pie: -lgcc -lgcc_eh 1200 // 1201 // Also, certain targets need additional adjustments. 1202 1203 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 1204 ArgStringList &CmdArgs, const ArgList &Args) { 1205 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 1206 // Targets that don't use unwind libraries. 1207 if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() || 1208 TC.getTriple().isOSBinFormatWasm() || 1209 UNW == ToolChain::UNW_None) 1210 return; 1211 1212 LibGccType LGT = getLibGccType(D, Args); 1213 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 1214 !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing(); 1215 if (AsNeeded) 1216 CmdArgs.push_back("--as-needed"); 1217 1218 switch (UNW) { 1219 case ToolChain::UNW_None: 1220 return; 1221 case ToolChain::UNW_Libgcc: { 1222 if (LGT == LibGccType::StaticLibGcc) 1223 CmdArgs.push_back("-lgcc_eh"); 1224 else 1225 CmdArgs.push_back("-lgcc_s"); 1226 break; 1227 } 1228 case ToolChain::UNW_CompilerRT: 1229 if (LGT == LibGccType::StaticLibGcc) 1230 CmdArgs.push_back("-l:libunwind.a"); 1231 else 1232 CmdArgs.push_back("-l:libunwind.so"); 1233 break; 1234 } 1235 1236 if (AsNeeded) 1237 CmdArgs.push_back("--no-as-needed"); 1238 } 1239 1240 static void AddLibgcc(const ToolChain &TC, const Driver &D, 1241 ArgStringList &CmdArgs, const ArgList &Args) { 1242 LibGccType LGT = getLibGccType(D, Args); 1243 if (LGT != LibGccType::SharedLibGcc) 1244 CmdArgs.push_back("-lgcc"); 1245 AddUnwindLibrary(TC, D, CmdArgs, Args); 1246 if (LGT == LibGccType::SharedLibGcc) 1247 CmdArgs.push_back("-lgcc"); 1248 1249 // According to Android ABI, we have to link with libdl if we are 1250 // linking with non-static libgcc. 1251 // 1252 // NOTE: This fixes a link error on Android MIPS as well. The non-static 1253 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl. 1254 if (TC.getTriple().isAndroid() && LGT != LibGccType::StaticLibGcc) 1255 CmdArgs.push_back("-ldl"); 1256 } 1257 1258 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 1259 ArgStringList &CmdArgs, const ArgList &Args) { 1260 // Make use of compiler-rt if --rtlib option is used 1261 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 1262 1263 switch (RLT) { 1264 case ToolChain::RLT_CompilerRT: 1265 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 1266 AddUnwindLibrary(TC, D, CmdArgs, Args); 1267 break; 1268 case ToolChain::RLT_Libgcc: 1269 // Make sure libgcc is not used under MSVC environment by default 1270 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1271 // Issue error diagnostic if libgcc is explicitly specified 1272 // through command line as --rtlib option argument. 1273 if (Args.hasArg(options::OPT_rtlib_EQ)) { 1274 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 1275 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC"; 1276 } 1277 } else 1278 AddLibgcc(TC, D, CmdArgs, Args); 1279 break; 1280 } 1281 } 1282 1283 /// Add HIP linker script arguments at the end of the argument list so that 1284 /// the fat binary is built by embedding the device images into the host. The 1285 /// linker script also defines a symbol required by the code generation so that 1286 /// the image can be retrieved at runtime. This should be used only in tool 1287 /// chains that support linker scripts. 1288 void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C, 1289 const InputInfo &Output, 1290 const InputInfoList &Inputs, const ArgList &Args, 1291 ArgStringList &CmdArgs, const JobAction &JA, 1292 const Tool &T) { 1293 1294 // If this is not a HIP host toolchain, we don't need to do anything. 1295 if (!JA.isHostOffloading(Action::OFK_HIP)) 1296 return; 1297 1298 InputInfoList DeviceInputs; 1299 for (const auto &II : Inputs) { 1300 const Action *A = II.getAction(); 1301 // Is this a device linking action? 1302 if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) { 1303 DeviceInputs.push_back(II); 1304 } 1305 } 1306 1307 if (DeviceInputs.empty()) 1308 return; 1309 1310 // Create temporary linker script. Keep it if save-temps is enabled. 1311 const char *LKS; 1312 std::string Name = 1313 std::string(llvm::sys::path::filename(Output.getFilename())); 1314 if (C.getDriver().isSaveTempsEnabled()) { 1315 LKS = C.getArgs().MakeArgString(Name + ".lk"); 1316 } else { 1317 auto TmpName = C.getDriver().GetTemporaryPath(Name, "lk"); 1318 LKS = C.addTempFile(C.getArgs().MakeArgString(TmpName)); 1319 } 1320 1321 // Add linker script option to the command. 1322 CmdArgs.push_back("-T"); 1323 CmdArgs.push_back(LKS); 1324 1325 // Create a buffer to write the contents of the linker script. 1326 std::string LksBuffer; 1327 llvm::raw_string_ostream LksStream(LksBuffer); 1328 1329 // Get the HIP offload tool chain. 1330 auto *HIPTC = static_cast<const toolchains::CudaToolChain *>( 1331 C.getSingleOffloadToolChain<Action::OFK_HIP>()); 1332 assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn && 1333 "Wrong platform"); 1334 (void)HIPTC; 1335 1336 const char *BundleFile; 1337 if (C.getDriver().isSaveTempsEnabled()) { 1338 BundleFile = C.getArgs().MakeArgString(Name + ".hipfb"); 1339 } else { 1340 auto TmpName = C.getDriver().GetTemporaryPath(Name, "hipfb"); 1341 BundleFile = C.addTempFile(C.getArgs().MakeArgString(TmpName)); 1342 } 1343 AMDGCN::constructHIPFatbinCommand(C, JA, BundleFile, DeviceInputs, Args, T); 1344 1345 // Add commands to embed target binaries. We ensure that each section and 1346 // image is 16-byte aligned. This is not mandatory, but increases the 1347 // likelihood of data to be aligned with a cache block in several main host 1348 // machines. 1349 LksStream << "/*\n"; 1350 LksStream << " HIP Offload Linker Script\n"; 1351 LksStream << " *** Automatically generated by Clang ***\n"; 1352 LksStream << "*/\n"; 1353 LksStream << "TARGET(binary)\n"; 1354 LksStream << "INPUT(" << BundleFile << ")\n"; 1355 LksStream << "SECTIONS\n"; 1356 LksStream << "{\n"; 1357 LksStream << " .hip_fatbin :\n"; 1358 LksStream << " ALIGN(0x10)\n"; 1359 LksStream << " {\n"; 1360 LksStream << " PROVIDE_HIDDEN(__hip_fatbin = .);\n"; 1361 LksStream << " " << BundleFile << "\n"; 1362 LksStream << " }\n"; 1363 LksStream << " /DISCARD/ :\n"; 1364 LksStream << " {\n"; 1365 LksStream << " * ( __CLANG_OFFLOAD_BUNDLE__* )\n"; 1366 LksStream << " }\n"; 1367 LksStream << "}\n"; 1368 LksStream << "INSERT BEFORE .data\n"; 1369 LksStream.flush(); 1370 1371 // Dump the contents of the linker script if the user requested that. We 1372 // support this option to enable testing of behavior with -###. 1373 if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script)) 1374 llvm::errs() << LksBuffer; 1375 1376 // If this is a dry run, do not create the linker script file. 1377 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) 1378 return; 1379 1380 // Open script file and write the contents. 1381 std::error_code EC; 1382 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::OF_None); 1383 1384 if (EC) { 1385 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 1386 return; 1387 } 1388 1389 Lksf << LksBuffer; 1390 } 1391 1392 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 1393 const InputInfo &Output, 1394 const InputInfo &Input, 1395 const Driver &D) { 1396 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 1397 if (!A) 1398 return {}; 1399 1400 StringRef SaveStats = A->getValue(); 1401 SmallString<128> StatsFile; 1402 if (SaveStats == "obj" && Output.isFilename()) { 1403 StatsFile.assign(Output.getFilename()); 1404 llvm::sys::path::remove_filename(StatsFile); 1405 } else if (SaveStats != "cwd") { 1406 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 1407 return {}; 1408 } 1409 1410 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 1411 llvm::sys::path::append(StatsFile, BaseName); 1412 llvm::sys::path::replace_extension(StatsFile, "stats"); 1413 return StatsFile; 1414 } 1415 1416 void tools::addMultilibFlag(bool Enabled, const char *const Flag, 1417 Multilib::flags_list &Flags) { 1418 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag); 1419 } 1420