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