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"
18 #include "InputInfo.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/ObjCRuntime.h"
22 #include "clang/Basic/Version.h"
23 #include "clang/Basic/VirtualFileSystem.h"
24 #include "clang/Config/config.h"
25 #include "clang/Driver/Action.h"
26 #include "clang/Driver/Compilation.h"
27 #include "clang/Driver/Driver.h"
28 #include "clang/Driver/DriverDiagnostic.h"
29 #include "clang/Driver/Job.h"
30 #include "clang/Driver/Options.h"
31 #include "clang/Driver/SanitizerArgs.h"
32 #include "clang/Driver/ToolChain.h"
33 #include "clang/Driver/Util.h"
34 #include "clang/Driver/XRayArgs.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/Option/Arg.h"
41 #include "llvm/Option/ArgList.h"
42 #include "llvm/Option/Option.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/Compression.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/Process.h"
51 #include "llvm/Support/Program.h"
52 #include "llvm/Support/ScopedPrinter.h"
53 #include "llvm/Support/TargetParser.h"
54 #include "llvm/Support/YAMLParser.h"
56 using namespace clang::driver;
57 using namespace clang::driver::tools;
58 using namespace clang;
59 using namespace llvm::opt;
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());
67 void tools::handleTargetFeaturesGroup(const ArgList &Args,
68 std::vector<StringRef> &Features,
70 for (const Arg *A : Args.filtered(Group)) {
71 StringRef Name = A->getOption().getName();
75 assert(Name.startswith("m") && "Invalid feature name.");
76 Name = Name.substr(1);
78 bool IsNegative = Name.startswith("no-");
80 Name = Name.substr(3);
81 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
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;
91 return; // Nothing to do.
93 StringRef Name(ArgName);
94 if (Name.equals("-I") || Name.equals("-L"))
97 StringRef Dirs(DirList);
98 if (Dirs.empty()) // Empty string should not add '.'.
101 StringRef::size_type Delim;
102 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
103 if (Delim == 0) { // Leading colon.
105 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
107 CmdArgs.push_back(ArgName);
108 CmdArgs.push_back(".");
113 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
115 CmdArgs.push_back(ArgName);
116 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
119 Dirs = Dirs.substr(Delim + 1);
122 if (Dirs.empty()) { // Trailing colon.
124 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
126 CmdArgs.push_back(ArgName);
127 CmdArgs.push_back(".");
129 } else { // Add the last path.
131 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
133 CmdArgs.push_back(ArgName);
134 CmdArgs.push_back(Args.MakeArgString(Dirs));
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();
144 // Add extra linker input arguments which are not treated as inputs
145 // (constructed via -Xarch_).
146 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
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)))
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();
163 // Add filenames immediately.
164 if (II.isFilename()) {
165 CmdArgs.push_back(II.getFilename());
169 // Otherwise, this is a linker input argument.
170 const Arg &A = II.getInputArg();
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.
180 A.render(Args, CmdArgs);
182 A.renderAsInput(Args, CmdArgs);
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");
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));
201 Features.push_back(Args.MakeArgString("-" + FeatureName));
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")
222 static std::string getNios2TargetCPU(const ArgList &Args) {
223 Arg *A = Args.getLastArg(options::OPT_mcpu_EQ);
225 A = Args.getLastArg(options::OPT_march_EQ);
230 const char *name = A->getValue();
231 return llvm::StringSwitch<const char *>(name)
232 .Case("r1", "nios2r1")
233 .Case("r2", "nios2r2")
237 static std::string getLanaiTargetCPU(const ArgList &Args) {
238 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
239 return A->getValue();
244 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
245 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
246 // If we have -mcpu=, use that.
247 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
248 StringRef CPU = A->getValue();
251 // Handle "native" by examining the host. "native" isn't meaningful when
252 // cross compiling, so only support this when the host is also WebAssembly.
254 return llvm::sys::getHostCPUName();
263 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
267 switch (T.getArch()) {
271 case llvm::Triple::aarch64:
272 case llvm::Triple::aarch64_be:
273 return aarch64::getAArch64TargetCPU(Args, A);
275 case llvm::Triple::arm:
276 case llvm::Triple::armeb:
277 case llvm::Triple::thumb:
278 case llvm::Triple::thumbeb: {
279 StringRef MArch, MCPU;
280 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
281 return arm::getARMTargetCPU(MCPU, MArch, T);
284 case llvm::Triple::avr:
285 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
286 return A->getValue();
289 case llvm::Triple::nios2: {
290 return getNios2TargetCPU(Args);
293 case llvm::Triple::mips:
294 case llvm::Triple::mipsel:
295 case llvm::Triple::mips64:
296 case llvm::Triple::mips64el: {
299 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
303 case llvm::Triple::nvptx:
304 case llvm::Triple::nvptx64:
305 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
306 return A->getValue();
309 case llvm::Triple::ppc:
310 case llvm::Triple::ppc64:
311 case llvm::Triple::ppc64le: {
312 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
313 // LLVM may default to generating code for the native CPU,
314 // but, like gcc, we default to a more generic option for
315 // each architecture. (except on Darwin)
316 if (TargetCPUName.empty() && !T.isOSDarwin()) {
317 if (T.getArch() == llvm::Triple::ppc64)
318 TargetCPUName = "ppc64";
319 else if (T.getArch() == llvm::Triple::ppc64le)
320 TargetCPUName = "ppc64le";
322 TargetCPUName = "ppc";
324 return TargetCPUName;
327 case llvm::Triple::bpfel:
328 case llvm::Triple::bpfeb:
329 case llvm::Triple::sparc:
330 case llvm::Triple::sparcel:
331 case llvm::Triple::sparcv9:
332 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
333 return A->getValue();
336 case llvm::Triple::x86:
337 case llvm::Triple::x86_64:
338 return x86::getX86TargetCPU(Args, T);
340 case llvm::Triple::hexagon:
342 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
344 case llvm::Triple::lanai:
345 return getLanaiTargetCPU(Args);
347 case llvm::Triple::systemz:
348 return systemz::getSystemZTargetCPU(Args);
350 case llvm::Triple::r600:
351 case llvm::Triple::amdgcn:
352 return getR600TargetGPU(Args);
354 case llvm::Triple::wasm32:
355 case llvm::Triple::wasm64:
356 return getWebAssemblyTargetCPU(Args);
360 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
361 unsigned Parallelism = 0;
362 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
364 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
365 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
366 << LtoJobsArg->getValue();
370 // CloudABI uses -ffunction-sections and -fdata-sections by default.
371 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
372 return Triple.getOS() == llvm::Triple::CloudABI;
375 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
376 ArgStringList &CmdArgs, const InputInfo &Output,
377 const InputInfo &Input, bool IsThinLTO) {
378 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
379 // as gold requires -plugin to come before any -plugin-opt that -Wl might
381 CmdArgs.push_back("-plugin");
384 const char *Suffix = ".dll";
385 #elif defined(__APPLE__)
386 const char *Suffix = ".dylib";
388 const char *Suffix = ".so";
391 SmallString<1024> Plugin;
392 llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
393 "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
396 CmdArgs.push_back(Args.MakeArgString(Plugin));
398 // Try to pass driver level flags relevant to LTO code generation down to
401 // Handle flags for selecting CPU variants.
402 std::string CPU = getCPUName(Args, ToolChain.getTriple());
404 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
406 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
408 if (A->getOption().matches(options::OPT_O4) ||
409 A->getOption().matches(options::OPT_Ofast))
411 else if (A->getOption().matches(options::OPT_O))
412 OOpt = A->getValue();
413 else if (A->getOption().matches(options::OPT_O0))
416 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
419 if (Args.hasArg(options::OPT_gsplit_dwarf)) {
421 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
422 Output.getFilename() + "_dwo"));
426 CmdArgs.push_back("-plugin-opt=thinlto");
428 if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver()))
430 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
432 // If an explicit debugger tuning argument appeared, pass it along.
433 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
434 options::OPT_ggdbN_Group)) {
435 if (A->getOption().matches(options::OPT_glldb))
436 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
437 else if (A->getOption().matches(options::OPT_gsce))
438 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
440 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
443 bool UseSeparateSections =
444 isUseSeparateSections(ToolChain.getEffectiveTriple());
446 if (Args.hasFlag(options::OPT_ffunction_sections,
447 options::OPT_fno_function_sections, UseSeparateSections)) {
448 CmdArgs.push_back("-plugin-opt=-function-sections");
451 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
452 UseSeparateSections)) {
453 CmdArgs.push_back("-plugin-opt=-data-sections");
456 if (Arg *A = getLastProfileSampleUseArg(Args)) {
457 StringRef FName = A->getValue();
458 if (!llvm::sys::fs::exists(FName))
459 ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName;
462 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
465 // Need this flag to turn on new pass manager via Gold plugin.
466 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
467 options::OPT_fno_experimental_new_pass_manager,
468 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
469 CmdArgs.push_back("-plugin-opt=new-pass-manager");
472 // Setup statistics file output.
473 SmallString<128> StatsFile =
474 getStatsFileName(Args, Output, Input, ToolChain.getDriver());
475 if (!StatsFile.empty())
477 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
480 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
481 ArgStringList &CmdArgs) {
482 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
483 options::OPT_fno_rtlib_add_rpath, false))
486 std::string CandidateRPath = TC.getArchSpecificLibPath();
487 if (TC.getVFS().exists(CandidateRPath)) {
488 CmdArgs.push_back("-rpath");
489 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
493 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
494 const ArgList &Args, bool IsOffloadingHost,
496 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
497 options::OPT_fno_openmp, false))
500 switch (TC.getDriver().getOpenMPRuntime(Args)) {
501 case Driver::OMPRT_OMP:
502 CmdArgs.push_back("-lomp");
504 case Driver::OMPRT_GOMP:
505 CmdArgs.push_back("-lgomp");
508 CmdArgs.push_back("-lrt");
510 case Driver::OMPRT_IOMP5:
511 CmdArgs.push_back("-liomp5");
513 case Driver::OMPRT_Unknown:
514 // Already diagnosed.
518 if (IsOffloadingHost)
519 CmdArgs.push_back("-lomptarget");
521 addArchSpecificRPath(TC, Args, CmdArgs);
526 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
527 ArgStringList &CmdArgs, StringRef Sanitizer,
528 bool IsShared, bool IsWhole) {
529 // Wrap any static runtimes that must be forced into executable in
531 if (IsWhole) CmdArgs.push_back("--whole-archive");
532 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
533 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
536 addArchSpecificRPath(TC, Args, CmdArgs);
540 // Tries to use a file with the list of dynamic symbols that need to be exported
541 // from the runtime library. Returns true if the file was found.
542 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
543 ArgStringList &CmdArgs,
544 StringRef Sanitizer) {
545 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
546 // the option, so don't try to pass it.
547 if (TC.getTriple().getOS() == llvm::Triple::Solaris)
549 // Myriad is static linking only. Furthermore, some versions of its
550 // linker have the bug where --export-dynamic overrides -static, so
551 // don't use --export-dynamic on that platform.
552 if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
554 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
555 if (llvm::sys::fs::exists(SanRT + ".syms")) {
556 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
562 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
563 ArgStringList &CmdArgs) {
564 // Force linking against the system libraries sanitizers depends on
565 // (see PR15823 why this is necessary).
566 CmdArgs.push_back("--no-as-needed");
567 // There's no libpthread or librt on RTEMS & Android.
568 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
569 !TC.getTriple().isAndroid()) {
570 CmdArgs.push_back("-lpthread");
571 if (TC.getTriple().getOS() != llvm::Triple::OpenBSD)
572 CmdArgs.push_back("-lrt");
574 CmdArgs.push_back("-lm");
575 // There's no libdl on all OSes.
576 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
577 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
578 TC.getTriple().getOS() != llvm::Triple::OpenBSD &&
579 TC.getTriple().getOS() != llvm::Triple::RTEMS)
580 CmdArgs.push_back("-ldl");
581 // Required for backtrace on some OSes
582 if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
583 TC.getTriple().getOS() == llvm::Triple::FreeBSD)
584 CmdArgs.push_back("-lexecinfo");
588 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
589 SmallVectorImpl<StringRef> &SharedRuntimes,
590 SmallVectorImpl<StringRef> &StaticRuntimes,
591 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
592 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
593 SmallVectorImpl<StringRef> &RequiredSymbols) {
594 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
595 // Collect shared runtimes.
596 if (SanArgs.needsSharedRt()) {
597 if (SanArgs.needsAsanRt()) {
598 SharedRuntimes.push_back("asan");
599 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
600 HelperStaticRuntimes.push_back("asan-preinit");
602 if (SanArgs.needsUbsanRt()) {
603 if (SanArgs.requiresMinimalRuntime())
604 SharedRuntimes.push_back("ubsan_minimal");
606 SharedRuntimes.push_back("ubsan_standalone");
608 if (SanArgs.needsScudoRt()) {
609 if (SanArgs.requiresMinimalRuntime())
610 SharedRuntimes.push_back("scudo_minimal");
612 SharedRuntimes.push_back("scudo");
614 if (SanArgs.needsHwasanRt())
615 SharedRuntimes.push_back("hwasan");
618 // The stats_client library is also statically linked into DSOs.
619 if (SanArgs.needsStatsRt())
620 StaticRuntimes.push_back("stats_client");
622 // Collect static runtimes.
623 if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
624 // Don't link static runtimes into DSOs or if -shared-libasan.
627 if (SanArgs.needsAsanRt()) {
628 StaticRuntimes.push_back("asan");
629 if (SanArgs.linkCXXRuntimes())
630 StaticRuntimes.push_back("asan_cxx");
633 if (SanArgs.needsHwasanRt()) {
634 StaticRuntimes.push_back("hwasan");
635 if (SanArgs.linkCXXRuntimes())
636 StaticRuntimes.push_back("hwasan_cxx");
638 if (SanArgs.needsDfsanRt())
639 StaticRuntimes.push_back("dfsan");
640 if (SanArgs.needsLsanRt())
641 StaticRuntimes.push_back("lsan");
642 if (SanArgs.needsMsanRt()) {
643 StaticRuntimes.push_back("msan");
644 if (SanArgs.linkCXXRuntimes())
645 StaticRuntimes.push_back("msan_cxx");
647 if (SanArgs.needsTsanRt()) {
648 StaticRuntimes.push_back("tsan");
649 if (SanArgs.linkCXXRuntimes())
650 StaticRuntimes.push_back("tsan_cxx");
652 if (SanArgs.needsUbsanRt()) {
653 if (SanArgs.requiresMinimalRuntime()) {
654 StaticRuntimes.push_back("ubsan_minimal");
656 StaticRuntimes.push_back("ubsan_standalone");
657 if (SanArgs.linkCXXRuntimes())
658 StaticRuntimes.push_back("ubsan_standalone_cxx");
661 if (SanArgs.needsSafeStackRt()) {
662 NonWholeStaticRuntimes.push_back("safestack");
663 RequiredSymbols.push_back("__safestack_init");
665 if (SanArgs.needsCfiRt())
666 StaticRuntimes.push_back("cfi");
667 if (SanArgs.needsCfiDiagRt()) {
668 StaticRuntimes.push_back("cfi_diag");
669 if (SanArgs.linkCXXRuntimes())
670 StaticRuntimes.push_back("ubsan_standalone_cxx");
672 if (SanArgs.needsStatsRt()) {
673 NonWholeStaticRuntimes.push_back("stats");
674 RequiredSymbols.push_back("__sanitizer_stats_register");
676 if (SanArgs.needsEsanRt())
677 StaticRuntimes.push_back("esan");
678 if (SanArgs.needsScudoRt()) {
679 if (SanArgs.requiresMinimalRuntime()) {
680 StaticRuntimes.push_back("scudo_minimal");
681 if (SanArgs.linkCXXRuntimes())
682 StaticRuntimes.push_back("scudo_cxx_minimal");
684 StaticRuntimes.push_back("scudo");
685 if (SanArgs.linkCXXRuntimes())
686 StaticRuntimes.push_back("scudo_cxx");
691 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
692 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
693 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
694 ArgStringList &CmdArgs) {
695 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
696 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
697 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
698 NonWholeStaticRuntimes, HelperStaticRuntimes,
701 // Inject libfuzzer dependencies.
702 if (TC.getSanitizerArgs().needsFuzzer()
703 && !Args.hasArg(options::OPT_shared)) {
705 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
706 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
707 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
710 for (auto RT : SharedRuntimes)
711 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
712 for (auto RT : HelperStaticRuntimes)
713 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
714 bool AddExportDynamic = false;
715 for (auto RT : StaticRuntimes) {
716 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
717 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
719 for (auto RT : NonWholeStaticRuntimes) {
720 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
721 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
723 for (auto S : RequiredSymbols) {
724 CmdArgs.push_back("-u");
725 CmdArgs.push_back(Args.MakeArgString(S));
727 // If there is a static runtime with no dynamic list, force all the symbols
728 // to be dynamic to be sure we export sanitizer interface functions.
729 if (AddExportDynamic)
730 CmdArgs.push_back("--export-dynamic");
732 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
733 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
734 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
736 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
739 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
740 if (Args.hasArg(options::OPT_shared))
743 if (TC.getXRayArgs().needsXRayRt()) {
744 CmdArgs.push_back("-whole-archive");
745 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
746 for (const auto &Mode : TC.getXRayArgs().modeList())
747 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode, false));
748 CmdArgs.push_back("-no-whole-archive");
755 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
756 CmdArgs.push_back("--no-as-needed");
757 CmdArgs.push_back("-lpthread");
758 if (TC.getTriple().getOS() != llvm::Triple::OpenBSD)
759 CmdArgs.push_back("-lrt");
760 CmdArgs.push_back("-lm");
762 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
763 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
764 TC.getTriple().getOS() != llvm::Triple::OpenBSD)
765 CmdArgs.push_back("-ldl");
768 bool tools::areOptimizationsEnabled(const ArgList &Args) {
769 // Find the last -O arg and see if it is non-zero.
770 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
771 return !A->getOption().matches(options::OPT_O0);
776 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
777 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
778 if (FinalOutput && Args.hasArg(options::OPT_c)) {
779 SmallString<128> T(FinalOutput->getValue());
780 llvm::sys::path::replace_extension(T, "dwo");
781 return Args.MakeArgString(T);
783 // Use the compilation dir.
785 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
786 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
787 llvm::sys::path::replace_extension(F, "dwo");
789 return Args.MakeArgString(F);
793 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
794 const JobAction &JA, const ArgList &Args,
795 const InputInfo &Output, const char *OutFile) {
796 ArgStringList ExtractArgs;
797 ExtractArgs.push_back("--extract-dwo");
799 ArgStringList StripArgs;
800 StripArgs.push_back("--strip-dwo");
802 // Grabbing the output of the earlier compile step.
803 StripArgs.push_back(Output.getFilename());
804 ExtractArgs.push_back(Output.getFilename());
805 ExtractArgs.push_back(OutFile);
808 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
809 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
811 // First extract the dwo sections.
812 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
814 // Then remove them from the original .o file.
815 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
818 // Claim options we don't want to warn if they are unused. We do this for
819 // options that build systems might add but are unused when assembling or only
820 // running the preprocessor for example.
821 void tools::claimNoWarnArgs(const ArgList &Args) {
822 // Don't warn about unused -f(no-)?lto. This can happen when we're
823 // preprocessing, precompiling or assembling.
824 Args.ClaimAllArgs(options::OPT_flto_EQ);
825 Args.ClaimAllArgs(options::OPT_flto);
826 Args.ClaimAllArgs(options::OPT_fno_lto);
829 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
830 auto *ProfileUseArg = Args.getLastArg(
831 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
832 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
833 options::OPT_fno_profile_instr_use);
836 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
837 ProfileUseArg = nullptr;
839 return ProfileUseArg;
842 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
843 auto *ProfileSampleUseArg = Args.getLastArg(
844 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
845 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
846 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
848 if (ProfileSampleUseArg &&
849 (ProfileSampleUseArg->getOption().matches(
850 options::OPT_fno_profile_sample_use) ||
851 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
854 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
855 options::OPT_fauto_profile_EQ);
858 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
859 /// smooshes them together with platform defaults, to decide whether
860 /// this compile should be using PIC mode or not. Returns a tuple of
861 /// (RelocationModel, PICLevel, IsPIE).
862 std::tuple<llvm::Reloc::Model, unsigned, bool>
863 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
864 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
865 const llvm::Triple &Triple = ToolChain.getTriple();
867 bool PIE = ToolChain.isPIEDefault();
868 bool PIC = PIE || ToolChain.isPICDefault();
869 // The Darwin/MachO default to use PIC does not apply when using -static.
870 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
872 bool IsPICLevelTwo = PIC;
875 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
877 // Android-specific defaults for PIC/PIE
878 if (Triple.isAndroid()) {
879 switch (Triple.getArch()) {
880 case llvm::Triple::arm:
881 case llvm::Triple::armeb:
882 case llvm::Triple::thumb:
883 case llvm::Triple::thumbeb:
884 case llvm::Triple::aarch64:
885 case llvm::Triple::mips:
886 case llvm::Triple::mipsel:
887 case llvm::Triple::mips64:
888 case llvm::Triple::mips64el:
889 PIC = true; // "-fpic"
892 case llvm::Triple::x86:
893 case llvm::Triple::x86_64:
894 PIC = true; // "-fPIC"
895 IsPICLevelTwo = true;
903 // OpenBSD-specific defaults for PIE
904 if (Triple.getOS() == llvm::Triple::OpenBSD) {
905 switch (ToolChain.getArch()) {
906 case llvm::Triple::arm:
907 case llvm::Triple::aarch64:
908 case llvm::Triple::mips64:
909 case llvm::Triple::mips64el:
910 case llvm::Triple::x86:
911 case llvm::Triple::x86_64:
912 IsPICLevelTwo = false; // "-fpie"
915 case llvm::Triple::ppc:
916 case llvm::Triple::sparc:
917 case llvm::Triple::sparcel:
918 case llvm::Triple::sparcv9:
919 IsPICLevelTwo = true; // "-fPIE"
927 // AMDGPU-specific defaults for PIC.
928 if (Triple.getArch() == llvm::Triple::amdgcn)
931 // The last argument relating to either PIC or PIE wins, and no
932 // other argument is used. If the last argument is any flavor of the
933 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
934 // option implicitly enables PIC at the same level.
935 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
936 options::OPT_fpic, options::OPT_fno_pic,
937 options::OPT_fPIE, options::OPT_fno_PIE,
938 options::OPT_fpie, options::OPT_fno_pie);
939 if (Triple.isOSWindows() && LastPICArg &&
941 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
942 options::OPT_fPIE, options::OPT_fpie)) {
943 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
944 << LastPICArg->getSpelling() << Triple.str();
945 if (Triple.getArch() == llvm::Triple::x86_64)
946 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
947 return std::make_tuple(llvm::Reloc::Static, 0U, false);
950 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
951 // is forced, then neither PIC nor PIE flags will have no effect.
952 if (!ToolChain.isPICDefaultForced()) {
954 Option O = LastPICArg->getOption();
955 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
956 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
957 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
959 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
961 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
964 if (EffectiveTriple.isPS4CPU()) {
965 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
966 StringRef Model = ModelArg ? ModelArg->getValue() : "";
967 if (Model != "kernel") {
969 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
970 << LastPICArg->getSpelling();
977 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
978 // PIC level would've been set to level 1, force it back to level 2 PIC
980 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
981 IsPICLevelTwo |= ToolChain.isPICDefault();
983 // This kernel flags are a trump-card: they will disable PIC/PIE
984 // generation, independent of the argument order.
986 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
987 !EffectiveTriple.isWatchOS()))
990 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
991 // This is a very special mode. It trumps the other modes, almost no one
992 // uses it, and it isn't even valid on any OS but Darwin.
993 if (!Triple.isOSDarwin())
994 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
995 << A->getSpelling() << Triple.str();
997 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
999 // Only a forced PIC mode can cause the actual compile to have PIC defines
1000 // etc., no flags are sufficient. This behavior was selected to closely
1001 // match that of llvm-gcc and Apple GCC before that.
1002 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1004 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1007 bool EmbeddedPISupported;
1008 switch (Triple.getArch()) {
1009 case llvm::Triple::arm:
1010 case llvm::Triple::armeb:
1011 case llvm::Triple::thumb:
1012 case llvm::Triple::thumbeb:
1013 EmbeddedPISupported = true;
1016 EmbeddedPISupported = false;
1020 bool ROPI = false, RWPI = false;
1021 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1022 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1023 if (!EmbeddedPISupported)
1024 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1025 << LastROPIArg->getSpelling() << Triple.str();
1028 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1029 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1030 if (!EmbeddedPISupported)
1031 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1032 << LastRWPIArg->getSpelling() << Triple.str();
1036 // ROPI and RWPI are not compatible with PIC or PIE.
1037 if ((ROPI || RWPI) && (PIC || PIE))
1038 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1040 if (Triple.isMIPS()) {
1043 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1044 // When targeting the N64 ABI, PIC is the default, except in the case
1045 // when the -mno-abicalls option is used. In that case we exit
1046 // at next check regardless of PIC being set below.
1047 if (ABIName == "n64")
1049 // When targettng MIPS with -mno-abicalls, it's always static.
1050 if(Args.hasArg(options::OPT_mno_abicalls))
1051 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1052 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1053 // does not use PIC level 2 for historical reasons.
1054 IsPICLevelTwo = false;
1058 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1060 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1062 RelocM = llvm::Reloc::ROPI_RWPI;
1064 RelocM = llvm::Reloc::ROPI;
1066 RelocM = llvm::Reloc::RWPI;
1068 return std::make_tuple(RelocM, 0U, false);
1071 // `-falign-functions` indicates that the functions should be aligned to a
1072 // 16-byte boundary.
1074 // `-falign-functions=1` is the same as `-fno-align-functions`.
1076 // The scalar `n` in `-falign-functions=n` must be an integral value between
1077 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1078 // the nearest power-of-two.
1080 // If we return `0`, the frontend will default to the backend's preferred
1083 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1084 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1085 // alignment. For unaligned functions, we default to the backend's preferred
1087 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1088 const ArgList &Args) {
1089 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1090 options::OPT_falign_functions_EQ,
1091 options::OPT_fno_align_functions);
1092 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1095 if (A->getOption().matches(options::OPT_falign_functions))
1099 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1100 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1101 << A->getAsString(Args) << A->getValue();
1102 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1105 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1106 ArgStringList &CmdArgs) {
1107 llvm::Reloc::Model RelocationModel;
1110 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1112 if (RelocationModel != llvm::Reloc::Static)
1113 CmdArgs.push_back("-KPIC");
1116 /// Determine whether Objective-C automated reference counting is
1118 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1119 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1122 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1123 ArgStringList &CmdArgs, const ArgList &Args) {
1124 bool isAndroid = Triple.isAndroid();
1125 bool isCygMing = Triple.isOSCygMing();
1126 bool IsIAMCU = Triple.isOSIAMCU();
1127 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1128 Args.hasArg(options::OPT_static);
1130 CmdArgs.push_back("-lgcc");
1132 if (StaticLibgcc || isAndroid) {
1134 CmdArgs.push_back("-lgcc");
1136 if (!D.CCCIsCXX() && !isCygMing)
1137 CmdArgs.push_back("--as-needed");
1138 CmdArgs.push_back("-lgcc_s");
1139 if (!D.CCCIsCXX() && !isCygMing)
1140 CmdArgs.push_back("--no-as-needed");
1143 if (StaticLibgcc && !isAndroid && !IsIAMCU)
1144 CmdArgs.push_back("-lgcc_eh");
1145 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
1146 CmdArgs.push_back("-lgcc");
1148 // According to Android ABI, we have to link with libdl if we are
1149 // linking with non-static libgcc.
1151 // NOTE: This fixes a link error on Android MIPS as well. The non-static
1152 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1153 if (isAndroid && !StaticLibgcc)
1154 CmdArgs.push_back("-ldl");
1157 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1158 ArgStringList &CmdArgs, const ArgList &Args) {
1159 // Make use of compiler-rt if --rtlib option is used
1160 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1163 case ToolChain::RLT_CompilerRT:
1164 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1166 case ToolChain::RLT_Libgcc:
1167 // Make sure libgcc is not used under MSVC environment by default
1168 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1169 // Issue error diagnostic if libgcc is explicitly specified
1170 // through command line as --rtlib option argument.
1171 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1172 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1173 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1176 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1181 /// Add OpenMP linker script arguments at the end of the argument list so that
1182 /// the fat binary is built by embedding each of the device images into the
1183 /// host. The linker script also defines a few symbols required by the code
1184 /// generation so that the images can be easily retrieved at runtime by the
1185 /// offloading library. This should be used only in tool chains that support
1187 void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1188 const InputInfo &Output,
1189 const InputInfoList &Inputs,
1190 const ArgList &Args, ArgStringList &CmdArgs,
1191 const JobAction &JA) {
1193 // If this is not an OpenMP host toolchain, we don't need to do anything.
1194 if (!JA.isHostOffloading(Action::OFK_OpenMP))
1197 // Create temporary linker script. Keep it if save-temps is enabled.
1199 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1200 if (C.getDriver().isSaveTempsEnabled()) {
1201 llvm::sys::path::replace_extension(Name, "lk");
1202 LKS = C.getArgs().MakeArgString(Name.c_str());
1204 llvm::sys::path::replace_extension(Name, "");
1205 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1206 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1209 // Add linker script option to the command.
1210 CmdArgs.push_back("-T");
1211 CmdArgs.push_back(LKS);
1213 // Create a buffer to write the contents of the linker script.
1214 std::string LksBuffer;
1215 llvm::raw_string_ostream LksStream(LksBuffer);
1217 // Get the OpenMP offload tool chains so that we can extract the triple
1218 // associated with each device input.
1219 auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1220 assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1221 "No OpenMP toolchains??");
1223 // Track the input file name and device triple in order to build the script,
1224 // inserting binaries in the designated sections.
1225 SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1227 // Add commands to embed target binaries. We ensure that each section and
1228 // image is 16-byte aligned. This is not mandatory, but increases the
1229 // likelihood of data to be aligned with a cache block in several main host
1231 LksStream << "/*\n";
1232 LksStream << " OpenMP Offload Linker Script\n";
1233 LksStream << " *** Automatically generated by Clang ***\n";
1234 LksStream << "*/\n";
1235 LksStream << "TARGET(binary)\n";
1236 auto DTC = OpenMPToolChains.first;
1237 for (auto &II : Inputs) {
1238 const Action *A = II.getAction();
1239 // Is this a device linking action?
1240 if (A && isa<LinkJobAction>(A) &&
1241 A->isDeviceOffloading(Action::OFK_OpenMP)) {
1242 assert(DTC != OpenMPToolChains.second &&
1243 "More device inputs than device toolchains??");
1244 InputBinaryInfo.push_back(std::make_pair(
1245 DTC->second->getTriple().normalize(), II.getFilename()));
1247 LksStream << "INPUT(" << II.getFilename() << ")\n";
1251 assert(DTC == OpenMPToolChains.second &&
1252 "Less device inputs than device toolchains??");
1254 LksStream << "SECTIONS\n";
1257 // Put each target binary into a separate section.
1258 for (const auto &BI : InputBinaryInfo) {
1259 LksStream << " .omp_offloading." << BI.first << " :\n";
1260 LksStream << " ALIGN(0x10)\n";
1261 LksStream << " {\n";
1262 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1264 LksStream << " " << BI.second << "\n";
1265 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1267 LksStream << " }\n";
1270 // Add commands to define host entries begin and end. We use 1-byte subalign
1271 // so that the linker does not add any padding and the elements in this
1272 // section form an array.
1273 LksStream << " .omp_offloading.entries :\n";
1274 LksStream << " ALIGN(0x10)\n";
1275 LksStream << " SUBALIGN(0x01)\n";
1276 LksStream << " {\n";
1277 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1278 LksStream << " *(.omp_offloading.entries)\n";
1279 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1280 LksStream << " }\n";
1282 LksStream << "INSERT BEFORE .data\n";
1285 // Dump the contents of the linker script if the user requested that. We
1286 // support this option to enable testing of behavior with -###.
1287 if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1288 llvm::errs() << LksBuffer;
1290 // If this is a dry run, do not create the linker script file.
1291 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1294 // Open script file and write the contents.
1296 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1299 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1306 /// Add HIP linker script arguments at the end of the argument list so that
1307 /// the fat binary is built by embedding the device images into the host. The
1308 /// linker script also defines a symbol required by the code generation so that
1309 /// the image can be retrieved at runtime. This should be used only in tool
1310 /// chains that support linker scripts.
1311 void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C,
1312 const InputInfo &Output,
1313 const InputInfoList &Inputs, const ArgList &Args,
1314 ArgStringList &CmdArgs, const JobAction &JA,
1317 // If this is not a HIP host toolchain, we don't need to do anything.
1318 if (!JA.isHostOffloading(Action::OFK_HIP))
1321 // Create temporary linker script. Keep it if save-temps is enabled.
1323 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1324 if (C.getDriver().isSaveTempsEnabled()) {
1325 llvm::sys::path::replace_extension(Name, "lk");
1326 LKS = C.getArgs().MakeArgString(Name.c_str());
1328 llvm::sys::path::replace_extension(Name, "");
1329 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1330 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1333 // Add linker script option to the command.
1334 CmdArgs.push_back("-T");
1335 CmdArgs.push_back(LKS);
1337 // Create a buffer to write the contents of the linker script.
1338 std::string LksBuffer;
1339 llvm::raw_string_ostream LksStream(LksBuffer);
1341 // Get the HIP offload tool chain.
1342 auto *HIPTC = static_cast<const toolchains::CudaToolChain *>(
1343 C.getSingleOffloadToolChain<Action::OFK_HIP>());
1344 assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn &&
1348 // Construct clang-offload-bundler command to bundle object files for
1349 // for different GPU archs.
1350 ArgStringList BundlerArgs;
1351 BundlerArgs.push_back(Args.MakeArgString("-type=o"));
1353 // ToDo: Remove the dummy host binary entry which is required by
1354 // clang-offload-bundler.
1355 std::string BundlerTargetArg = "-targets=host-x86_64-unknown-linux";
1356 std::string BundlerInputArg = "-inputs=/dev/null";
1358 for (const auto &II : Inputs) {
1359 const Action *A = II.getAction();
1360 // Is this a device linking action?
1361 if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) {
1362 BundlerTargetArg = BundlerTargetArg + ",hip-amdgcn-amd-amdhsa-" +
1363 StringRef(A->getOffloadingArch()).str();
1364 BundlerInputArg = BundlerInputArg + "," + II.getFilename();
1367 BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
1368 BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
1370 std::string BundleFileName = C.getDriver().GetTemporaryPath("BUNDLE", "o");
1371 const char *BundleFile =
1372 C.addTempFile(C.getArgs().MakeArgString(BundleFileName.c_str()));
1373 auto BundlerOutputArg =
1374 Args.MakeArgString(std::string("-outputs=").append(BundleFile));
1375 BundlerArgs.push_back(BundlerOutputArg);
1377 SmallString<128> BundlerPath(C.getDriver().Dir);
1378 llvm::sys::path::append(BundlerPath, "clang-offload-bundler");
1379 const char *Bundler = Args.MakeArgString(BundlerPath);
1380 C.addCommand(llvm::make_unique<Command>(JA, T, Bundler, BundlerArgs, Inputs));
1382 // Add commands to embed target binaries. We ensure that each section and
1383 // image is 16-byte aligned. This is not mandatory, but increases the
1384 // likelihood of data to be aligned with a cache block in several main host
1386 LksStream << "/*\n";
1387 LksStream << " HIP Offload Linker Script\n";
1388 LksStream << " *** Automatically generated by Clang ***\n";
1389 LksStream << "*/\n";
1390 LksStream << "TARGET(binary)\n";
1391 LksStream << "INPUT(" << BundleFileName << ")\n";
1392 LksStream << "SECTIONS\n";
1394 LksStream << " .hip_fatbin :\n";
1395 LksStream << " ALIGN(0x10)\n";
1396 LksStream << " {\n";
1397 LksStream << " PROVIDE_HIDDEN(__hip_fatbin = .);\n";
1398 LksStream << " " << BundleFileName << "\n";
1399 LksStream << " }\n";
1401 LksStream << "INSERT BEFORE .data\n";
1404 // Dump the contents of the linker script if the user requested that. We
1405 // support this option to enable testing of behavior with -###.
1406 if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
1407 llvm::errs() << LksBuffer;
1409 // If this is a dry run, do not create the linker script file.
1410 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1413 // Open script file and write the contents.
1415 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1418 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1425 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1426 const InputInfo &Output,
1427 const InputInfo &Input,
1429 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1433 StringRef SaveStats = A->getValue();
1434 SmallString<128> StatsFile;
1435 if (SaveStats == "obj" && Output.isFilename()) {
1436 StatsFile.assign(Output.getFilename());
1437 llvm::sys::path::remove_filename(StatsFile);
1438 } else if (SaveStats != "cwd") {
1439 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1443 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1444 llvm::sys::path::append(StatsFile, BaseName);
1445 llvm::sys::path::replace_extension(StatsFile, "stats");