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