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