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