1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CommonArgs.h"
11 #include "Arch/AArch64.h"
13 #include "Arch/Mips.h"
15 #include "Arch/SystemZ.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"
57 using namespace clang::driver;
58 using namespace clang::driver::tools;
59 using namespace clang;
60 using namespace llvm::opt;
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());
68 void tools::handleTargetFeaturesGroup(const ArgList &Args,
69 std::vector<StringRef> &Features,
71 for (const Arg *A : Args.filtered(Group)) {
72 StringRef Name = A->getOption().getName();
76 assert(Name.startswith("m") && "Invalid feature name.");
77 Name = Name.substr(1);
79 bool IsNegative = Name.startswith("no-");
81 Name = Name.substr(3);
82 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
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;
92 return; // Nothing to do.
94 StringRef Name(ArgName);
95 if (Name.equals("-I") || Name.equals("-L"))
98 StringRef Dirs(DirList);
99 if (Dirs.empty()) // Empty string should not add '.'.
102 StringRef::size_type Delim;
103 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
104 if (Delim == 0) { // Leading colon.
106 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
108 CmdArgs.push_back(ArgName);
109 CmdArgs.push_back(".");
114 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
116 CmdArgs.push_back(ArgName);
117 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
120 Dirs = Dirs.substr(Delim + 1);
123 if (Dirs.empty()) { // Trailing colon.
125 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
127 CmdArgs.push_back(ArgName);
128 CmdArgs.push_back(".");
130 } else { // Add the last path.
132 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
134 CmdArgs.push_back(ArgName);
135 CmdArgs.push_back(Args.MakeArgString(Dirs));
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();
145 // Add extra linker input arguments which are not treated as inputs
146 // (constructed via -Xarch_).
147 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
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)))
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();
164 // Add filenames immediately.
165 if (II.isFilename()) {
166 CmdArgs.push_back(II.getFilename());
170 // Otherwise, this is a linker input argument.
171 const Arg &A = II.getInputArg();
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.
181 A.render(Args, CmdArgs);
183 A.renderAsInput(Args, CmdArgs);
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");
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));
202 Features.push_back(Args.MakeArgString("-" + FeatureName));
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")
223 static std::string getLanaiTargetCPU(const ArgList &Args) {
224 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
225 return A->getValue();
230 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
231 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
232 // If we have -mcpu=, use that.
233 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
234 StringRef CPU = A->getValue();
237 // Handle "native" by examining the host. "native" isn't meaningful when
238 // cross compiling, so only support this when the host is also WebAssembly.
240 return llvm::sys::getHostCPUName();
249 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
253 switch (T.getArch()) {
257 case llvm::Triple::aarch64:
258 case llvm::Triple::aarch64_be:
259 return aarch64::getAArch64TargetCPU(Args, T, A);
261 case llvm::Triple::arm:
262 case llvm::Triple::armeb:
263 case llvm::Triple::thumb:
264 case llvm::Triple::thumbeb: {
265 StringRef MArch, MCPU;
266 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
267 return arm::getARMTargetCPU(MCPU, MArch, T);
270 case llvm::Triple::avr:
271 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
272 return A->getValue();
275 case llvm::Triple::mips:
276 case llvm::Triple::mipsel:
277 case llvm::Triple::mips64:
278 case llvm::Triple::mips64el: {
281 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
285 case llvm::Triple::nvptx:
286 case llvm::Triple::nvptx64:
287 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
288 return A->getValue();
291 case llvm::Triple::ppc:
292 case llvm::Triple::ppc64:
293 case llvm::Triple::ppc64le: {
294 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
295 // LLVM may default to generating code for the native CPU,
296 // but, like gcc, we default to a more generic option for
297 // each architecture. (except on Darwin)
298 if (TargetCPUName.empty() && !T.isOSDarwin()) {
299 if (T.getArch() == llvm::Triple::ppc64)
300 TargetCPUName = "ppc64";
301 else if (T.getArch() == llvm::Triple::ppc64le)
302 TargetCPUName = "ppc64le";
304 TargetCPUName = "ppc";
306 return TargetCPUName;
309 case llvm::Triple::bpfel:
310 case llvm::Triple::bpfeb:
311 case llvm::Triple::sparc:
312 case llvm::Triple::sparcel:
313 case llvm::Triple::sparcv9:
314 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
315 return A->getValue();
318 case llvm::Triple::x86:
319 case llvm::Triple::x86_64:
320 return x86::getX86TargetCPU(Args, T);
322 case llvm::Triple::hexagon:
324 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
326 case llvm::Triple::lanai:
327 return getLanaiTargetCPU(Args);
329 case llvm::Triple::systemz:
330 return systemz::getSystemZTargetCPU(Args);
332 case llvm::Triple::r600:
333 case llvm::Triple::amdgcn:
334 return getR600TargetGPU(Args);
336 case llvm::Triple::wasm32:
337 case llvm::Triple::wasm64:
338 return getWebAssemblyTargetCPU(Args);
342 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
343 unsigned Parallelism = 0;
344 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
346 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
347 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
348 << LtoJobsArg->getValue();
352 // CloudABI uses -ffunction-sections and -fdata-sections by default.
353 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
354 return Triple.getOS() == llvm::Triple::CloudABI;
357 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
358 ArgStringList &CmdArgs, const InputInfo &Output,
359 const InputInfo &Input, bool IsThinLTO) {
360 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
361 // as gold requires -plugin to come before any -plugin-opt that -Wl might
363 CmdArgs.push_back("-plugin");
366 const char *Suffix = ".dll";
367 #elif defined(__APPLE__)
368 const char *Suffix = ".dylib";
370 const char *Suffix = ".so";
373 SmallString<1024> Plugin;
374 llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
375 "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
378 CmdArgs.push_back(Args.MakeArgString(Plugin));
380 // Try to pass driver level flags relevant to LTO code generation down to
383 // Handle flags for selecting CPU variants.
384 std::string CPU = getCPUName(Args, ToolChain.getTriple());
386 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
388 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
390 if (A->getOption().matches(options::OPT_O4) ||
391 A->getOption().matches(options::OPT_Ofast))
393 else if (A->getOption().matches(options::OPT_O))
394 OOpt = A->getValue();
395 else if (A->getOption().matches(options::OPT_O0))
398 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
401 if (Args.hasArg(options::OPT_gsplit_dwarf)) {
403 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
404 Output.getFilename() + "_dwo"));
408 CmdArgs.push_back("-plugin-opt=thinlto");
410 if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver()))
412 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
414 // If an explicit debugger tuning argument appeared, pass it along.
415 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
416 options::OPT_ggdbN_Group)) {
417 if (A->getOption().matches(options::OPT_glldb))
418 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
419 else if (A->getOption().matches(options::OPT_gsce))
420 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
422 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
425 bool UseSeparateSections =
426 isUseSeparateSections(ToolChain.getEffectiveTriple());
428 if (Args.hasFlag(options::OPT_ffunction_sections,
429 options::OPT_fno_function_sections, UseSeparateSections)) {
430 CmdArgs.push_back("-plugin-opt=-function-sections");
433 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
434 UseSeparateSections)) {
435 CmdArgs.push_back("-plugin-opt=-data-sections");
438 if (Arg *A = getLastProfileSampleUseArg(Args)) {
439 StringRef FName = A->getValue();
440 if (!llvm::sys::fs::exists(FName))
441 ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName;
444 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
447 // Need this flag to turn on new pass manager via Gold plugin.
448 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
449 options::OPT_fno_experimental_new_pass_manager,
450 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
451 CmdArgs.push_back("-plugin-opt=new-pass-manager");
454 // Setup statistics file output.
455 SmallString<128> StatsFile =
456 getStatsFileName(Args, Output, Input, ToolChain.getDriver());
457 if (!StatsFile.empty())
459 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
462 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
463 ArgStringList &CmdArgs) {
464 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
465 options::OPT_fno_rtlib_add_rpath, false))
468 std::string CandidateRPath = TC.getArchSpecificLibPath();
469 if (TC.getVFS().exists(CandidateRPath)) {
470 CmdArgs.push_back("-rpath");
471 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
475 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
476 const ArgList &Args, bool IsOffloadingHost,
478 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
479 options::OPT_fno_openmp, false))
482 switch (TC.getDriver().getOpenMPRuntime(Args)) {
483 case Driver::OMPRT_OMP:
484 CmdArgs.push_back("-lomp");
486 case Driver::OMPRT_GOMP:
487 CmdArgs.push_back("-lgomp");
490 CmdArgs.push_back("-lrt");
492 case Driver::OMPRT_IOMP5:
493 CmdArgs.push_back("-liomp5");
495 case Driver::OMPRT_Unknown:
496 // Already diagnosed.
500 if (IsOffloadingHost)
501 CmdArgs.push_back("-lomptarget");
503 addArchSpecificRPath(TC, Args, CmdArgs);
508 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
509 ArgStringList &CmdArgs, StringRef Sanitizer,
510 bool IsShared, bool IsWhole) {
511 // Wrap any static runtimes that must be forced into executable in
513 if (IsWhole) CmdArgs.push_back("--whole-archive");
514 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
515 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
518 addArchSpecificRPath(TC, Args, CmdArgs);
522 // Tries to use a file with the list of dynamic symbols that need to be exported
523 // from the runtime library. Returns true if the file was found.
524 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
525 ArgStringList &CmdArgs,
526 StringRef Sanitizer) {
527 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
528 // the option, so don't try to pass it.
529 if (TC.getTriple().getOS() == llvm::Triple::Solaris)
531 // Myriad is static linking only. Furthermore, some versions of its
532 // linker have the bug where --export-dynamic overrides -static, so
533 // don't use --export-dynamic on that platform.
534 if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
536 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
537 if (llvm::sys::fs::exists(SanRT + ".syms")) {
538 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
544 static void addSanitizerLibPath(const ToolChain &TC, const ArgList &Args,
545 ArgStringList &CmdArgs, StringRef Name) {
546 for (const auto &LibPath : TC.getLibraryPaths()) {
547 if (!LibPath.empty()) {
548 SmallString<128> P(LibPath);
549 llvm::sys::path::append(P, Name);
550 if (TC.getVFS().exists(P))
551 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
556 void tools::addSanitizerPathLibArgs(const ToolChain &TC, const ArgList &Args,
557 ArgStringList &CmdArgs) {
558 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
559 if (SanArgs.needsAsanRt()) {
560 addSanitizerLibPath(TC, Args, CmdArgs, "asan");
562 if (SanArgs.needsHwasanRt()) {
563 addSanitizerLibPath(TC, Args, CmdArgs, "hwasan");
565 if (SanArgs.needsLsanRt()) {
566 addSanitizerLibPath(TC, Args, CmdArgs, "lsan");
568 if (SanArgs.needsMsanRt()) {
569 addSanitizerLibPath(TC, Args, CmdArgs, "msan");
571 if (SanArgs.needsTsanRt()) {
572 addSanitizerLibPath(TC, Args, CmdArgs, "tsan");
578 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
579 ArgStringList &CmdArgs) {
580 // Force linking against the system libraries sanitizers depends on
581 // (see PR15823 why this is necessary).
582 CmdArgs.push_back("--no-as-needed");
583 // There's no libpthread or librt on RTEMS & Android.
584 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
585 !TC.getTriple().isAndroid()) {
586 CmdArgs.push_back("-lpthread");
587 if (!TC.getTriple().isOSOpenBSD())
588 CmdArgs.push_back("-lrt");
590 CmdArgs.push_back("-lm");
591 // There's no libdl on all OSes.
592 if (!TC.getTriple().isOSFreeBSD() &&
593 !TC.getTriple().isOSNetBSD() &&
594 !TC.getTriple().isOSOpenBSD() &&
595 TC.getTriple().getOS() != llvm::Triple::RTEMS)
596 CmdArgs.push_back("-ldl");
597 // Required for backtrace on some OSes
598 if (TC.getTriple().isOSFreeBSD() ||
599 TC.getTriple().isOSNetBSD())
600 CmdArgs.push_back("-lexecinfo");
604 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
605 SmallVectorImpl<StringRef> &SharedRuntimes,
606 SmallVectorImpl<StringRef> &StaticRuntimes,
607 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
608 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
609 SmallVectorImpl<StringRef> &RequiredSymbols) {
610 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
611 // Collect shared runtimes.
612 if (SanArgs.needsSharedRt()) {
613 if (SanArgs.needsAsanRt()) {
614 SharedRuntimes.push_back("asan");
615 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
616 HelperStaticRuntimes.push_back("asan-preinit");
618 if (SanArgs.needsUbsanRt()) {
619 if (SanArgs.requiresMinimalRuntime())
620 SharedRuntimes.push_back("ubsan_minimal");
622 SharedRuntimes.push_back("ubsan_standalone");
624 if (SanArgs.needsScudoRt()) {
625 if (SanArgs.requiresMinimalRuntime())
626 SharedRuntimes.push_back("scudo_minimal");
628 SharedRuntimes.push_back("scudo");
630 if (SanArgs.needsHwasanRt())
631 SharedRuntimes.push_back("hwasan");
634 // The stats_client library is also statically linked into DSOs.
635 if (SanArgs.needsStatsRt())
636 StaticRuntimes.push_back("stats_client");
638 // Collect static runtimes.
639 if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
640 // Don't link static runtimes into DSOs or if -shared-libasan.
643 if (SanArgs.needsAsanRt()) {
644 StaticRuntimes.push_back("asan");
645 if (SanArgs.linkCXXRuntimes())
646 StaticRuntimes.push_back("asan_cxx");
649 if (SanArgs.needsHwasanRt()) {
650 StaticRuntimes.push_back("hwasan");
651 if (SanArgs.linkCXXRuntimes())
652 StaticRuntimes.push_back("hwasan_cxx");
654 if (SanArgs.needsDfsanRt())
655 StaticRuntimes.push_back("dfsan");
656 if (SanArgs.needsLsanRt())
657 StaticRuntimes.push_back("lsan");
658 if (SanArgs.needsMsanRt()) {
659 StaticRuntimes.push_back("msan");
660 if (SanArgs.linkCXXRuntimes())
661 StaticRuntimes.push_back("msan_cxx");
663 if (SanArgs.needsTsanRt()) {
664 StaticRuntimes.push_back("tsan");
665 if (SanArgs.linkCXXRuntimes())
666 StaticRuntimes.push_back("tsan_cxx");
668 if (SanArgs.needsUbsanRt()) {
669 if (SanArgs.requiresMinimalRuntime()) {
670 StaticRuntimes.push_back("ubsan_minimal");
672 StaticRuntimes.push_back("ubsan_standalone");
673 if (SanArgs.linkCXXRuntimes())
674 StaticRuntimes.push_back("ubsan_standalone_cxx");
677 if (SanArgs.needsSafeStackRt()) {
678 NonWholeStaticRuntimes.push_back("safestack");
679 RequiredSymbols.push_back("__safestack_init");
681 if (SanArgs.needsCfiRt())
682 StaticRuntimes.push_back("cfi");
683 if (SanArgs.needsCfiDiagRt()) {
684 StaticRuntimes.push_back("cfi_diag");
685 if (SanArgs.linkCXXRuntimes())
686 StaticRuntimes.push_back("ubsan_standalone_cxx");
688 if (SanArgs.needsStatsRt()) {
689 NonWholeStaticRuntimes.push_back("stats");
690 RequiredSymbols.push_back("__sanitizer_stats_register");
692 if (SanArgs.needsEsanRt())
693 StaticRuntimes.push_back("esan");
694 if (SanArgs.needsScudoRt()) {
695 if (SanArgs.requiresMinimalRuntime()) {
696 StaticRuntimes.push_back("scudo_minimal");
697 if (SanArgs.linkCXXRuntimes())
698 StaticRuntimes.push_back("scudo_cxx_minimal");
700 StaticRuntimes.push_back("scudo");
701 if (SanArgs.linkCXXRuntimes())
702 StaticRuntimes.push_back("scudo_cxx");
707 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
708 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
709 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
710 ArgStringList &CmdArgs) {
711 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
712 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
713 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
714 NonWholeStaticRuntimes, HelperStaticRuntimes,
717 // Inject libfuzzer dependencies.
718 if (TC.getSanitizerArgs().needsFuzzer()
719 && !Args.hasArg(options::OPT_shared)) {
721 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
722 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
723 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
726 for (auto RT : SharedRuntimes)
727 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
728 for (auto RT : HelperStaticRuntimes)
729 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
730 bool AddExportDynamic = false;
731 for (auto RT : StaticRuntimes) {
732 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
733 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
735 for (auto RT : NonWholeStaticRuntimes) {
736 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
737 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
739 for (auto S : RequiredSymbols) {
740 CmdArgs.push_back("-u");
741 CmdArgs.push_back(Args.MakeArgString(S));
743 // If there is a static runtime with no dynamic list, force all the symbols
744 // to be dynamic to be sure we export sanitizer interface functions.
745 if (AddExportDynamic)
746 CmdArgs.push_back("--export-dynamic");
748 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
749 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
750 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
752 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
755 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
756 if (Args.hasArg(options::OPT_shared))
759 if (TC.getXRayArgs().needsXRayRt()) {
760 CmdArgs.push_back("-whole-archive");
761 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
762 for (const auto &Mode : TC.getXRayArgs().modeList())
763 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode, false));
764 CmdArgs.push_back("-no-whole-archive");
771 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
772 CmdArgs.push_back("--no-as-needed");
773 CmdArgs.push_back("-lpthread");
774 if (!TC.getTriple().isOSOpenBSD())
775 CmdArgs.push_back("-lrt");
776 CmdArgs.push_back("-lm");
778 if (!TC.getTriple().isOSFreeBSD() &&
779 !TC.getTriple().isOSNetBSD() &&
780 !TC.getTriple().isOSOpenBSD())
781 CmdArgs.push_back("-ldl");
784 bool tools::areOptimizationsEnabled(const ArgList &Args) {
785 // Find the last -O arg and see if it is non-zero.
786 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
787 return !A->getOption().matches(options::OPT_O0);
792 const char *tools::SplitDebugName(const ArgList &Args,
793 const InputInfo &Output) {
794 SmallString<128> F(Output.isFilename()
795 ? Output.getFilename()
796 : llvm::sys::path::stem(Output.getBaseInput()));
798 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
799 if (StringRef(A->getValue()) == "single")
800 return Args.MakeArgString(F);
802 llvm::sys::path::replace_extension(F, "dwo");
803 return Args.MakeArgString(F);
806 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
807 const JobAction &JA, const ArgList &Args,
808 const InputInfo &Output, const char *OutFile) {
809 ArgStringList ExtractArgs;
810 ExtractArgs.push_back("--extract-dwo");
812 ArgStringList StripArgs;
813 StripArgs.push_back("--strip-dwo");
815 // Grabbing the output of the earlier compile step.
816 StripArgs.push_back(Output.getFilename());
817 ExtractArgs.push_back(Output.getFilename());
818 ExtractArgs.push_back(OutFile);
821 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
822 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
824 // First extract the dwo sections.
825 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
827 // Then remove them from the original .o file.
828 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
831 // Claim options we don't want to warn if they are unused. We do this for
832 // options that build systems might add but are unused when assembling or only
833 // running the preprocessor for example.
834 void tools::claimNoWarnArgs(const ArgList &Args) {
835 // Don't warn about unused -f(no-)?lto. This can happen when we're
836 // preprocessing, precompiling or assembling.
837 Args.ClaimAllArgs(options::OPT_flto_EQ);
838 Args.ClaimAllArgs(options::OPT_flto);
839 Args.ClaimAllArgs(options::OPT_fno_lto);
842 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
843 auto *ProfileUseArg = Args.getLastArg(
844 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
845 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
846 options::OPT_fno_profile_instr_use);
849 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
850 ProfileUseArg = nullptr;
852 return ProfileUseArg;
855 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
856 auto *ProfileSampleUseArg = Args.getLastArg(
857 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
858 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
859 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
861 if (ProfileSampleUseArg &&
862 (ProfileSampleUseArg->getOption().matches(
863 options::OPT_fno_profile_sample_use) ||
864 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
867 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
868 options::OPT_fauto_profile_EQ);
871 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
872 /// smooshes them together with platform defaults, to decide whether
873 /// this compile should be using PIC mode or not. Returns a tuple of
874 /// (RelocationModel, PICLevel, IsPIE).
875 std::tuple<llvm::Reloc::Model, unsigned, bool>
876 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
877 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
878 const llvm::Triple &Triple = ToolChain.getTriple();
880 bool PIE = ToolChain.isPIEDefault();
881 bool PIC = PIE || ToolChain.isPICDefault();
882 // The Darwin/MachO default to use PIC does not apply when using -static.
883 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
885 bool IsPICLevelTwo = PIC;
888 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
890 // Android-specific defaults for PIC/PIE
891 if (Triple.isAndroid()) {
892 switch (Triple.getArch()) {
893 case llvm::Triple::arm:
894 case llvm::Triple::armeb:
895 case llvm::Triple::thumb:
896 case llvm::Triple::thumbeb:
897 case llvm::Triple::aarch64:
898 case llvm::Triple::mips:
899 case llvm::Triple::mipsel:
900 case llvm::Triple::mips64:
901 case llvm::Triple::mips64el:
902 PIC = true; // "-fpic"
905 case llvm::Triple::x86:
906 case llvm::Triple::x86_64:
907 PIC = true; // "-fPIC"
908 IsPICLevelTwo = true;
916 // OpenBSD-specific defaults for PIE
917 if (Triple.isOSOpenBSD()) {
918 switch (ToolChain.getArch()) {
919 case llvm::Triple::arm:
920 case llvm::Triple::aarch64:
921 case llvm::Triple::mips64:
922 case llvm::Triple::mips64el:
923 case llvm::Triple::x86:
924 case llvm::Triple::x86_64:
925 IsPICLevelTwo = false; // "-fpie"
928 case llvm::Triple::ppc:
929 case llvm::Triple::sparc:
930 case llvm::Triple::sparcel:
931 case llvm::Triple::sparcv9:
932 IsPICLevelTwo = true; // "-fPIE"
940 // AMDGPU-specific defaults for PIC.
941 if (Triple.getArch() == llvm::Triple::amdgcn)
944 // The last argument relating to either PIC or PIE wins, and no
945 // other argument is used. If the last argument is any flavor of the
946 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
947 // option implicitly enables PIC at the same level.
948 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
949 options::OPT_fpic, options::OPT_fno_pic,
950 options::OPT_fPIE, options::OPT_fno_PIE,
951 options::OPT_fpie, options::OPT_fno_pie);
952 if (Triple.isOSWindows() && LastPICArg &&
954 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
955 options::OPT_fPIE, options::OPT_fpie)) {
956 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
957 << LastPICArg->getSpelling() << Triple.str();
958 if (Triple.getArch() == llvm::Triple::x86_64)
959 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
960 return std::make_tuple(llvm::Reloc::Static, 0U, false);
963 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
964 // is forced, then neither PIC nor PIE flags will have no effect.
965 if (!ToolChain.isPICDefaultForced()) {
967 Option O = LastPICArg->getOption();
968 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
969 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
970 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
972 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
974 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
977 if (EffectiveTriple.isPS4CPU()) {
978 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
979 StringRef Model = ModelArg ? ModelArg->getValue() : "";
980 if (Model != "kernel") {
982 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
983 << LastPICArg->getSpelling();
990 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
991 // PIC level would've been set to level 1, force it back to level 2 PIC
993 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
994 IsPICLevelTwo |= ToolChain.isPICDefault();
996 // This kernel flags are a trump-card: they will disable PIC/PIE
997 // generation, independent of the argument order.
999 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1000 !EffectiveTriple.isWatchOS()))
1003 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1004 // This is a very special mode. It trumps the other modes, almost no one
1005 // uses it, and it isn't even valid on any OS but Darwin.
1006 if (!Triple.isOSDarwin())
1007 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1008 << A->getSpelling() << Triple.str();
1010 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1012 // Only a forced PIC mode can cause the actual compile to have PIC defines
1013 // etc., no flags are sufficient. This behavior was selected to closely
1014 // match that of llvm-gcc and Apple GCC before that.
1015 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1017 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1020 bool EmbeddedPISupported;
1021 switch (Triple.getArch()) {
1022 case llvm::Triple::arm:
1023 case llvm::Triple::armeb:
1024 case llvm::Triple::thumb:
1025 case llvm::Triple::thumbeb:
1026 EmbeddedPISupported = true;
1029 EmbeddedPISupported = false;
1033 bool ROPI = false, RWPI = false;
1034 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1035 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1036 if (!EmbeddedPISupported)
1037 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1038 << LastROPIArg->getSpelling() << Triple.str();
1041 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1042 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1043 if (!EmbeddedPISupported)
1044 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1045 << LastRWPIArg->getSpelling() << Triple.str();
1049 // ROPI and RWPI are not compatible with PIC or PIE.
1050 if ((ROPI || RWPI) && (PIC || PIE))
1051 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1053 if (Triple.isMIPS()) {
1056 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1057 // When targeting the N64 ABI, PIC is the default, except in the case
1058 // when the -mno-abicalls option is used. In that case we exit
1059 // at next check regardless of PIC being set below.
1060 if (ABIName == "n64")
1062 // When targettng MIPS with -mno-abicalls, it's always static.
1063 if(Args.hasArg(options::OPT_mno_abicalls))
1064 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1065 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1066 // does not use PIC level 2 for historical reasons.
1067 IsPICLevelTwo = false;
1071 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1073 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1075 RelocM = llvm::Reloc::ROPI_RWPI;
1077 RelocM = llvm::Reloc::ROPI;
1079 RelocM = llvm::Reloc::RWPI;
1081 return std::make_tuple(RelocM, 0U, false);
1084 // `-falign-functions` indicates that the functions should be aligned to a
1085 // 16-byte boundary.
1087 // `-falign-functions=1` is the same as `-fno-align-functions`.
1089 // The scalar `n` in `-falign-functions=n` must be an integral value between
1090 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1091 // the nearest power-of-two.
1093 // If we return `0`, the frontend will default to the backend's preferred
1096 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1097 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1098 // alignment. For unaligned functions, we default to the backend's preferred
1100 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1101 const ArgList &Args) {
1102 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1103 options::OPT_falign_functions_EQ,
1104 options::OPT_fno_align_functions);
1105 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1108 if (A->getOption().matches(options::OPT_falign_functions))
1112 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1113 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1114 << A->getAsString(Args) << A->getValue();
1115 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1118 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1119 ArgStringList &CmdArgs) {
1120 llvm::Reloc::Model RelocationModel;
1123 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1125 if (RelocationModel != llvm::Reloc::Static)
1126 CmdArgs.push_back("-KPIC");
1129 /// Determine whether Objective-C automated reference counting is
1131 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1132 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1135 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1136 ArgStringList &CmdArgs, const ArgList &Args) {
1137 bool isAndroid = Triple.isAndroid();
1138 bool isCygMing = Triple.isOSCygMing();
1139 bool IsIAMCU = Triple.isOSIAMCU();
1140 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1141 Args.hasArg(options::OPT_static);
1143 bool SharedLibgcc = Args.hasArg(options::OPT_shared_libgcc);
1144 bool UnspecifiedLibgcc = !StaticLibgcc && !SharedLibgcc;
1146 // Gcc adds libgcc arguments in various ways:
1148 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
1149 // g++ <none>: -lgcc_s -lgcc
1150 // gcc shared: -lgcc_s -lgcc
1151 // g++ shared: -lgcc_s -lgcc
1152 // gcc static: -lgcc -lgcc_eh
1153 // g++ static: -lgcc -lgcc_eh
1155 // Also, certain targets need additional adjustments.
1157 bool LibGccFirst = (D.CCCIsCC() && UnspecifiedLibgcc) || StaticLibgcc;
1159 CmdArgs.push_back("-lgcc");
1161 bool AsNeeded = D.CCCIsCC() && UnspecifiedLibgcc && !isAndroid && !isCygMing;
1163 CmdArgs.push_back("--as-needed");
1165 if ((UnspecifiedLibgcc || SharedLibgcc) && !isAndroid)
1166 CmdArgs.push_back("-lgcc_s");
1168 else if (StaticLibgcc && !isAndroid && !IsIAMCU)
1169 CmdArgs.push_back("-lgcc_eh");
1172 CmdArgs.push_back("--no-as-needed");
1175 CmdArgs.push_back("-lgcc");
1177 // According to Android ABI, we have to link with libdl if we are
1178 // linking with non-static libgcc.
1180 // NOTE: This fixes a link error on Android MIPS as well. The non-static
1181 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1182 if (isAndroid && !StaticLibgcc)
1183 CmdArgs.push_back("-ldl");
1186 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1187 ArgStringList &CmdArgs, const ArgList &Args) {
1188 // Make use of compiler-rt if --rtlib option is used
1189 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1192 case ToolChain::RLT_CompilerRT:
1193 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1195 case ToolChain::RLT_Libgcc:
1196 // Make sure libgcc is not used under MSVC environment by default
1197 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1198 // Issue error diagnostic if libgcc is explicitly specified
1199 // through command line as --rtlib option argument.
1200 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1201 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1202 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1205 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1210 /// Add OpenMP linker script arguments at the end of the argument list so that
1211 /// the fat binary is built by embedding each of the device images into the
1212 /// host. The linker script also defines a few symbols required by the code
1213 /// generation so that the images can be easily retrieved at runtime by the
1214 /// offloading library. This should be used only in tool chains that support
1216 void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1217 const InputInfo &Output,
1218 const InputInfoList &Inputs,
1219 const ArgList &Args, ArgStringList &CmdArgs,
1220 const JobAction &JA) {
1222 // If this is not an OpenMP host toolchain, we don't need to do anything.
1223 if (!JA.isHostOffloading(Action::OFK_OpenMP))
1226 // Create temporary linker script. Keep it if save-temps is enabled.
1228 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1229 if (C.getDriver().isSaveTempsEnabled()) {
1230 llvm::sys::path::replace_extension(Name, "lk");
1231 LKS = C.getArgs().MakeArgString(Name.c_str());
1233 llvm::sys::path::replace_extension(Name, "");
1234 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1235 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1238 // Add linker script option to the command.
1239 CmdArgs.push_back("-T");
1240 CmdArgs.push_back(LKS);
1242 // Create a buffer to write the contents of the linker script.
1243 std::string LksBuffer;
1244 llvm::raw_string_ostream LksStream(LksBuffer);
1246 // Get the OpenMP offload tool chains so that we can extract the triple
1247 // associated with each device input.
1248 auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1249 assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1250 "No OpenMP toolchains??");
1252 // Track the input file name and device triple in order to build the script,
1253 // inserting binaries in the designated sections.
1254 SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1256 // Add commands to embed target binaries. We ensure that each section and
1257 // image is 16-byte aligned. This is not mandatory, but increases the
1258 // likelihood of data to be aligned with a cache block in several main host
1260 LksStream << "/*\n";
1261 LksStream << " OpenMP Offload Linker Script\n";
1262 LksStream << " *** Automatically generated by Clang ***\n";
1263 LksStream << "*/\n";
1264 LksStream << "TARGET(binary)\n";
1265 auto DTC = OpenMPToolChains.first;
1266 for (auto &II : Inputs) {
1267 const Action *A = II.getAction();
1268 // Is this a device linking action?
1269 if (A && isa<LinkJobAction>(A) &&
1270 A->isDeviceOffloading(Action::OFK_OpenMP)) {
1271 assert(DTC != OpenMPToolChains.second &&
1272 "More device inputs than device toolchains??");
1273 InputBinaryInfo.push_back(std::make_pair(
1274 DTC->second->getTriple().normalize(), II.getFilename()));
1276 LksStream << "INPUT(" << II.getFilename() << ")\n";
1280 assert(DTC == OpenMPToolChains.second &&
1281 "Less device inputs than device toolchains??");
1283 LksStream << "SECTIONS\n";
1286 // Put each target binary into a separate section.
1287 for (const auto &BI : InputBinaryInfo) {
1288 LksStream << " .omp_offloading." << BI.first << " :\n";
1289 LksStream << " ALIGN(0x10)\n";
1290 LksStream << " {\n";
1291 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1293 LksStream << " " << BI.second << "\n";
1294 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1296 LksStream << " }\n";
1299 // Add commands to define host entries begin and end. We use 1-byte subalign
1300 // so that the linker does not add any padding and the elements in this
1301 // section form an array.
1302 LksStream << " .omp_offloading.entries :\n";
1303 LksStream << " ALIGN(0x10)\n";
1304 LksStream << " SUBALIGN(0x01)\n";
1305 LksStream << " {\n";
1306 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1307 LksStream << " *(.omp_offloading.entries)\n";
1308 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1309 LksStream << " }\n";
1311 LksStream << "INSERT BEFORE .data\n";
1314 // Dump the contents of the linker script if the user requested that. We
1315 // support this option to enable testing of behavior with -###.
1316 if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1317 llvm::errs() << LksBuffer;
1319 // If this is a dry run, do not create the linker script file.
1320 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1323 // Open script file and write the contents.
1325 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1328 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1335 /// Add HIP linker script arguments at the end of the argument list so that
1336 /// the fat binary is built by embedding the device images into the host. The
1337 /// linker script also defines a symbol required by the code generation so that
1338 /// the image can be retrieved at runtime. This should be used only in tool
1339 /// chains that support linker scripts.
1340 void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C,
1341 const InputInfo &Output,
1342 const InputInfoList &Inputs, const ArgList &Args,
1343 ArgStringList &CmdArgs, const JobAction &JA,
1346 // If this is not a HIP host toolchain, we don't need to do anything.
1347 if (!JA.isHostOffloading(Action::OFK_HIP))
1350 InputInfoList DeviceInputs;
1351 for (const auto &II : Inputs) {
1352 const Action *A = II.getAction();
1353 // Is this a device linking action?
1354 if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) {
1355 DeviceInputs.push_back(II);
1359 if (DeviceInputs.empty())
1362 // Create temporary linker script. Keep it if save-temps is enabled.
1364 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1365 if (C.getDriver().isSaveTempsEnabled()) {
1366 llvm::sys::path::replace_extension(Name, "lk");
1367 LKS = C.getArgs().MakeArgString(Name.c_str());
1369 llvm::sys::path::replace_extension(Name, "");
1370 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1371 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1374 // Add linker script option to the command.
1375 CmdArgs.push_back("-T");
1376 CmdArgs.push_back(LKS);
1378 // Create a buffer to write the contents of the linker script.
1379 std::string LksBuffer;
1380 llvm::raw_string_ostream LksStream(LksBuffer);
1382 // Get the HIP offload tool chain.
1383 auto *HIPTC = static_cast<const toolchains::CudaToolChain *>(
1384 C.getSingleOffloadToolChain<Action::OFK_HIP>());
1385 assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn &&
1389 // The output file name needs to persist through the compilation, therefore
1390 // it needs to be created through MakeArgString.
1391 std::string BundleFileName = C.getDriver().GetTemporaryPath("BUNDLE", "hipfb");
1392 const char *BundleFile =
1393 C.addTempFile(C.getArgs().MakeArgString(BundleFileName.c_str()));
1394 AMDGCN::constructHIPFatbinCommand(C, JA, BundleFile, DeviceInputs, Args, T);
1396 // Add commands to embed target binaries. We ensure that each section and
1397 // image is 16-byte aligned. This is not mandatory, but increases the
1398 // likelihood of data to be aligned with a cache block in several main host
1400 LksStream << "/*\n";
1401 LksStream << " HIP Offload Linker Script\n";
1402 LksStream << " *** Automatically generated by Clang ***\n";
1403 LksStream << "*/\n";
1404 LksStream << "TARGET(binary)\n";
1405 LksStream << "INPUT(" << BundleFileName << ")\n";
1406 LksStream << "SECTIONS\n";
1408 LksStream << " .hip_fatbin :\n";
1409 LksStream << " ALIGN(0x10)\n";
1410 LksStream << " {\n";
1411 LksStream << " PROVIDE_HIDDEN(__hip_fatbin = .);\n";
1412 LksStream << " " << BundleFileName << "\n";
1413 LksStream << " }\n";
1414 LksStream << " /DISCARD/ :\n";
1415 LksStream << " {\n";
1416 LksStream << " * ( __CLANG_OFFLOAD_BUNDLE__* )\n";
1417 LksStream << " }\n";
1419 LksStream << "INSERT BEFORE .data\n";
1422 // Dump the contents of the linker script if the user requested that. We
1423 // support this option to enable testing of behavior with -###.
1424 if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
1425 llvm::errs() << LksBuffer;
1427 // If this is a dry run, do not create the linker script file.
1428 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1431 // Open script file and write the contents.
1433 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1436 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1443 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1444 const InputInfo &Output,
1445 const InputInfo &Input,
1447 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1451 StringRef SaveStats = A->getValue();
1452 SmallString<128> StatsFile;
1453 if (SaveStats == "obj" && Output.isFilename()) {
1454 StatsFile.assign(Output.getFilename());
1455 llvm::sys::path::remove_filename(StatsFile);
1456 } else if (SaveStats != "cwd") {
1457 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1461 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1462 llvm::sys::path::append(StatsFile, BaseName);
1463 llvm::sys::path::replace_extension(StatsFile, "stats");