[flang][cuda] Do not register global constants (#118582)
[llvm-project.git] / clang / lib / Driver / ToolChains / CommonArgs.cpp
blob8d977149e62485a6097be40fa7b1c9ad4cdc074f
1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "CommonArgs.h"
10 #include "Arch/AArch64.h"
11 #include "Arch/ARM.h"
12 #include "Arch/CSKY.h"
13 #include "Arch/LoongArch.h"
14 #include "Arch/M68k.h"
15 #include "Arch/Mips.h"
16 #include "Arch/PPC.h"
17 #include "Arch/RISCV.h"
18 #include "Arch/Sparc.h"
19 #include "Arch/SystemZ.h"
20 #include "Arch/VE.h"
21 #include "Arch/X86.h"
22 #include "HIPAMD.h"
23 #include "Hexagon.h"
24 #include "MSP430.h"
25 #include "Solaris.h"
26 #include "clang/Basic/CharInfo.h"
27 #include "clang/Basic/CodeGenOptions.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/ObjCRuntime.h"
30 #include "clang/Basic/Version.h"
31 #include "clang/Config/config.h"
32 #include "clang/Driver/Action.h"
33 #include "clang/Driver/Compilation.h"
34 #include "clang/Driver/Driver.h"
35 #include "clang/Driver/DriverDiagnostic.h"
36 #include "clang/Driver/InputInfo.h"
37 #include "clang/Driver/Job.h"
38 #include "clang/Driver/Options.h"
39 #include "clang/Driver/SanitizerArgs.h"
40 #include "clang/Driver/ToolChain.h"
41 #include "clang/Driver/Util.h"
42 #include "clang/Driver/XRayArgs.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/StringSwitch.h"
48 #include "llvm/ADT/Twine.h"
49 #include "llvm/BinaryFormat/Magic.h"
50 #include "llvm/Config/llvm-config.h"
51 #include "llvm/Option/Arg.h"
52 #include "llvm/Option/ArgList.h"
53 #include "llvm/Option/Option.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Compression.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/FileSystem.h"
59 #include "llvm/Support/Path.h"
60 #include "llvm/Support/Process.h"
61 #include "llvm/Support/Program.h"
62 #include "llvm/Support/ScopedPrinter.h"
63 #include "llvm/Support/Threading.h"
64 #include "llvm/Support/VirtualFileSystem.h"
65 #include "llvm/Support/YAMLParser.h"
66 #include "llvm/TargetParser/Host.h"
67 #include "llvm/TargetParser/PPCTargetParser.h"
68 #include "llvm/TargetParser/TargetParser.h"
69 #include <optional>
71 using namespace clang::driver;
72 using namespace clang::driver::tools;
73 using namespace clang;
74 using namespace llvm::opt;
76 static bool useFramePointerForTargetByDefault(const llvm::opt::ArgList &Args,
77 const llvm::Triple &Triple) {
78 if (Args.hasArg(clang::driver::options::OPT_pg) &&
79 !Args.hasArg(clang::driver::options::OPT_mfentry))
80 return true;
82 if (Triple.isAndroid())
83 return true;
85 switch (Triple.getArch()) {
86 case llvm::Triple::xcore:
87 case llvm::Triple::wasm32:
88 case llvm::Triple::wasm64:
89 case llvm::Triple::msp430:
90 // XCore never wants frame pointers, regardless of OS.
91 // WebAssembly never wants frame pointers.
92 return false;
93 case llvm::Triple::ppc:
94 case llvm::Triple::ppcle:
95 case llvm::Triple::ppc64:
96 case llvm::Triple::ppc64le:
97 case llvm::Triple::riscv32:
98 case llvm::Triple::riscv64:
99 case llvm::Triple::sparc:
100 case llvm::Triple::sparcel:
101 case llvm::Triple::sparcv9:
102 case llvm::Triple::amdgcn:
103 case llvm::Triple::r600:
104 case llvm::Triple::csky:
105 case llvm::Triple::loongarch32:
106 case llvm::Triple::loongarch64:
107 case llvm::Triple::m68k:
108 return !clang::driver::tools::areOptimizationsEnabled(Args);
109 default:
110 break;
113 if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
114 return !clang::driver::tools::areOptimizationsEnabled(Args);
117 if (Triple.isOSLinux() || Triple.isOSHurd()) {
118 switch (Triple.getArch()) {
119 // Don't use a frame pointer on linux if optimizing for certain targets.
120 case llvm::Triple::arm:
121 case llvm::Triple::armeb:
122 case llvm::Triple::thumb:
123 case llvm::Triple::thumbeb:
124 case llvm::Triple::mips64:
125 case llvm::Triple::mips64el:
126 case llvm::Triple::mips:
127 case llvm::Triple::mipsel:
128 case llvm::Triple::systemz:
129 case llvm::Triple::x86:
130 case llvm::Triple::x86_64:
131 return !clang::driver::tools::areOptimizationsEnabled(Args);
132 default:
133 return true;
137 if (Triple.isOSWindows()) {
138 switch (Triple.getArch()) {
139 case llvm::Triple::x86:
140 return !clang::driver::tools::areOptimizationsEnabled(Args);
141 case llvm::Triple::x86_64:
142 return Triple.isOSBinFormatMachO();
143 case llvm::Triple::arm:
144 case llvm::Triple::thumb:
145 // Windows on ARM builds with FPO disabled to aid fast stack walking
146 return true;
147 default:
148 // All other supported Windows ISAs use xdata unwind information, so frame
149 // pointers are not generally useful.
150 return false;
154 return true;
157 static bool useLeafFramePointerForTargetByDefault(const llvm::Triple &Triple) {
158 if (Triple.isAArch64() || Triple.isPS() || Triple.isVE() ||
159 (Triple.isAndroid() && !Triple.isARM()))
160 return false;
162 return true;
165 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
166 switch (Triple.getArch()) {
167 default:
168 return false;
169 case llvm::Triple::arm:
170 case llvm::Triple::thumb:
171 // ARM Darwin targets require a frame pointer to be always present to aid
172 // offline debugging via backtraces.
173 return Triple.isOSDarwin();
177 // True if a target-specific option requires the frame chain to be preserved,
178 // even if new frame records are not created.
179 static bool mustMaintainValidFrameChain(const llvm::opt::ArgList &Args,
180 const llvm::Triple &Triple) {
181 if (Triple.isARM() || Triple.isThumb()) {
182 // For 32-bit Arm, the -mframe-chain=aapcs and -mframe-chain=aapcs+leaf
183 // options require the frame pointer register to be reserved (or point to a
184 // new AAPCS-compilant frame record), even with -fno-omit-frame-pointer.
185 if (Arg *A = Args.getLastArg(options::OPT_mframe_chain)) {
186 StringRef V = A->getValue();
187 return V != "none";
189 return false;
191 return false;
194 // True if a target-specific option causes -fno-omit-frame-pointer to also
195 // cause frame records to be created in leaf functions.
196 static bool framePointerImpliesLeafFramePointer(const llvm::opt::ArgList &Args,
197 const llvm::Triple &Triple) {
198 if (Triple.isARM() || Triple.isThumb()) {
199 // For 32-bit Arm, the -mframe-chain=aapcs+leaf option causes the
200 // -fno-omit-frame-pointer optiion to imply -mno-omit-leaf-frame-pointer,
201 // but does not by itself imply either option.
202 if (Arg *A = Args.getLastArg(options::OPT_mframe_chain)) {
203 StringRef V = A->getValue();
204 return V == "aapcs+leaf";
206 return false;
208 return false;
211 clang::CodeGenOptions::FramePointerKind
212 getFramePointerKind(const llvm::opt::ArgList &Args,
213 const llvm::Triple &Triple) {
214 // There are three things to consider here:
215 // * Should a frame record be created for non-leaf functions?
216 // * Should a frame record be created for leaf functions?
217 // * Is the frame pointer register reserved, i.e. must it always point to
218 // either a new, valid frame record or be un-modified?
220 // Not all combinations of these are valid:
221 // * It's not useful to have leaf frame records without non-leaf ones.
222 // * It's not useful to have frame records without reserving the frame
223 // pointer.
225 // | Non-leaf | Leaf | Reserved |
226 // | N | N | N | FramePointerKind::None
227 // | N | N | Y | FramePointerKind::Reserved
228 // | N | Y | N | Invalid
229 // | N | Y | Y | Invalid
230 // | Y | N | N | Invalid
231 // | Y | N | Y | FramePointerKind::NonLeaf
232 // | Y | Y | N | Invalid
233 // | Y | Y | Y | FramePointerKind::All
235 // The FramePointerKind::Reserved case is currently only reachable for Arm,
236 // which has the -mframe-chain= option which can (in combination with
237 // -fno-omit-frame-pointer) specify that the frame chain must be valid,
238 // without requiring new frame records to be created.
240 bool DefaultFP = useFramePointerForTargetByDefault(Args, Triple);
241 bool EnableFP =
242 mustUseNonLeafFramePointerForTarget(Triple) ||
243 Args.hasFlag(clang::driver::options::OPT_fno_omit_frame_pointer,
244 clang::driver::options::OPT_fomit_frame_pointer, DefaultFP);
246 bool DefaultLeafFP =
247 useLeafFramePointerForTargetByDefault(Triple) ||
248 (EnableFP && framePointerImpliesLeafFramePointer(Args, Triple));
249 bool EnableLeafFP = Args.hasFlag(
250 clang::driver::options::OPT_mno_omit_leaf_frame_pointer,
251 clang::driver::options::OPT_momit_leaf_frame_pointer, DefaultLeafFP);
253 bool FPRegReserved = EnableFP || mustMaintainValidFrameChain(Args, Triple);
255 if (EnableFP) {
256 if (EnableLeafFP)
257 return clang::CodeGenOptions::FramePointerKind::All;
258 return clang::CodeGenOptions::FramePointerKind::NonLeaf;
260 if (FPRegReserved)
261 return clang::CodeGenOptions::FramePointerKind::Reserved;
262 return clang::CodeGenOptions::FramePointerKind::None;
265 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs,
266 const StringRef PluginOptPrefix) {
267 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
268 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
269 "-pass-remarks=" + A->getValue()));
271 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
272 CmdArgs.push_back(Args.MakeArgString(
273 Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue()));
275 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
276 CmdArgs.push_back(Args.MakeArgString(
277 Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue()));
280 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
281 const llvm::Triple &Triple,
282 const InputInfo &Input,
283 const InputInfo &Output,
284 const StringRef PluginOptPrefix) {
285 StringRef Format = "yaml";
286 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
287 Format = A->getValue();
289 SmallString<128> F;
290 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
291 if (A)
292 F = A->getValue();
293 else if (Output.isFilename())
294 F = Output.getFilename();
296 assert(!F.empty() && "Cannot determine remarks output name.");
297 // Append "opt.ld.<format>" to the end of the file name.
298 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
299 "opt-remarks-filename=" + F +
300 ".opt.ld." + Format));
302 if (const Arg *A =
303 Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
304 CmdArgs.push_back(Args.MakeArgString(
305 Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue()));
307 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
308 "opt-remarks-format=" + Format.data()));
311 static void renderRemarksHotnessOptions(const ArgList &Args,
312 ArgStringList &CmdArgs,
313 const StringRef PluginOptPrefix) {
314 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
315 options::OPT_fno_diagnostics_show_hotness, false))
316 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
317 "opt-remarks-with-hotness"));
319 if (const Arg *A =
320 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
321 CmdArgs.push_back(
322 Args.MakeArgString(Twine(PluginOptPrefix) +
323 "opt-remarks-hotness-threshold=" + A->getValue()));
326 static bool shouldIgnoreUnsupportedTargetFeature(const Arg &TargetFeatureArg,
327 llvm::Triple T,
328 StringRef Processor) {
329 // Warn no-cumode for AMDGCN processors not supporing WGP mode.
330 if (!T.isAMDGPU())
331 return false;
332 auto GPUKind = T.isAMDGCN() ? llvm::AMDGPU::parseArchAMDGCN(Processor)
333 : llvm::AMDGPU::parseArchR600(Processor);
334 auto GPUFeatures = T.isAMDGCN() ? llvm::AMDGPU::getArchAttrAMDGCN(GPUKind)
335 : llvm::AMDGPU::getArchAttrR600(GPUKind);
336 if (GPUFeatures & llvm::AMDGPU::FEATURE_WGP)
337 return false;
338 return TargetFeatureArg.getOption().matches(options::OPT_mno_cumode);
341 void tools::addPathIfExists(const Driver &D, const Twine &Path,
342 ToolChain::path_list &Paths) {
343 if (D.getVFS().exists(Path))
344 Paths.push_back(Path.str());
347 void tools::handleTargetFeaturesGroup(const Driver &D,
348 const llvm::Triple &Triple,
349 const ArgList &Args,
350 std::vector<StringRef> &Features,
351 OptSpecifier Group) {
352 std::set<StringRef> Warned;
353 for (const Arg *A : Args.filtered(Group)) {
354 StringRef Name = A->getOption().getName();
355 A->claim();
357 // Skip over "-m".
358 assert(Name.starts_with("m") && "Invalid feature name.");
359 Name = Name.substr(1);
361 auto Proc = getCPUName(D, Args, Triple);
362 if (shouldIgnoreUnsupportedTargetFeature(*A, Triple, Proc)) {
363 if (Warned.count(Name) == 0) {
364 D.getDiags().Report(
365 clang::diag::warn_drv_unsupported_option_for_processor)
366 << A->getAsString(Args) << Proc;
367 Warned.insert(Name);
369 continue;
372 bool IsNegative = Name.consume_front("no-");
374 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
378 SmallVector<StringRef>
379 tools::unifyTargetFeatures(ArrayRef<StringRef> Features) {
380 // Only add a feature if it hasn't been seen before starting from the end.
381 SmallVector<StringRef> UnifiedFeatures;
382 llvm::DenseSet<StringRef> UsedFeatures;
383 for (StringRef Feature : llvm::reverse(Features)) {
384 if (UsedFeatures.insert(Feature.drop_front()).second)
385 UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature);
388 return UnifiedFeatures;
391 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
392 const char *ArgName, const char *EnvVar) {
393 const char *DirList = ::getenv(EnvVar);
394 bool CombinedArg = false;
396 if (!DirList)
397 return; // Nothing to do.
399 StringRef Name(ArgName);
400 if (Name == "-I" || Name == "-L" || Name.empty())
401 CombinedArg = true;
403 StringRef Dirs(DirList);
404 if (Dirs.empty()) // Empty string should not add '.'.
405 return;
407 StringRef::size_type Delim;
408 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
409 if (Delim == 0) { // Leading colon.
410 if (CombinedArg) {
411 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
412 } else {
413 CmdArgs.push_back(ArgName);
414 CmdArgs.push_back(".");
416 } else {
417 if (CombinedArg) {
418 CmdArgs.push_back(
419 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
420 } else {
421 CmdArgs.push_back(ArgName);
422 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
425 Dirs = Dirs.substr(Delim + 1);
428 if (Dirs.empty()) { // Trailing colon.
429 if (CombinedArg) {
430 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
431 } else {
432 CmdArgs.push_back(ArgName);
433 CmdArgs.push_back(".");
435 } else { // Add the last path.
436 if (CombinedArg) {
437 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
438 } else {
439 CmdArgs.push_back(ArgName);
440 CmdArgs.push_back(Args.MakeArgString(Dirs));
445 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
446 const ArgList &Args, ArgStringList &CmdArgs,
447 const JobAction &JA) {
448 const Driver &D = TC.getDriver();
450 // Add extra linker input arguments which are not treated as inputs
451 // (constructed via -Xarch_).
452 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
454 // LIBRARY_PATH are included before user inputs and only supported on native
455 // toolchains.
456 if (!TC.isCrossCompiling())
457 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
459 for (const auto &II : Inputs) {
460 // If the current tool chain refers to an OpenMP offloading host, we
461 // should ignore inputs that refer to OpenMP offloading devices -
462 // they will be embedded according to a proper linker script.
463 if (auto *IA = II.getAction())
464 if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
465 IA->isDeviceOffloading(Action::OFK_OpenMP)))
466 continue;
468 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
469 // Don't try to pass LLVM inputs unless we have native support.
470 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
472 // Add filenames immediately.
473 if (II.isFilename()) {
474 CmdArgs.push_back(II.getFilename());
475 continue;
478 // In some error cases, the input could be Nothing; skip those.
479 if (II.isNothing())
480 continue;
482 // Otherwise, this is a linker input argument.
483 const Arg &A = II.getInputArg();
485 // Handle reserved library options.
486 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
487 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
488 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
489 TC.AddCCKextLibArgs(Args, CmdArgs);
490 else
491 A.renderAsInput(Args, CmdArgs);
495 void tools::addLinkerCompressDebugSectionsOption(
496 const ToolChain &TC, const llvm::opt::ArgList &Args,
497 llvm::opt::ArgStringList &CmdArgs) {
498 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
499 // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
500 // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
501 // is not translated since ld --compress-debug-sections option requires an
502 // argument.
503 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
504 StringRef V = A->getValue();
505 if (V == "none" || V == "zlib" || V == "zstd")
506 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
507 else
508 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
509 << A->getSpelling() << V;
513 void tools::AddTargetFeature(const ArgList &Args,
514 std::vector<StringRef> &Features,
515 OptSpecifier OnOpt, OptSpecifier OffOpt,
516 StringRef FeatureName) {
517 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
518 if (A->getOption().matches(OnOpt))
519 Features.push_back(Args.MakeArgString("+" + FeatureName));
520 else
521 Features.push_back(Args.MakeArgString("-" + FeatureName));
525 /// Get the (LLVM) name of the AMDGPU gpu we are targeting.
526 static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
527 const ArgList &Args) {
528 Arg *MArch = Args.getLastArg(options::OPT_march_EQ);
529 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
530 auto GPUName = getProcessorFromTargetID(T, A->getValue());
531 return llvm::StringSwitch<std::string>(GPUName)
532 .Cases("rv630", "rv635", "r600")
533 .Cases("rv610", "rv620", "rs780", "rs880")
534 .Case("rv740", "rv770")
535 .Case("palm", "cedar")
536 .Cases("sumo", "sumo2", "sumo")
537 .Case("hemlock", "cypress")
538 .Case("aruba", "cayman")
539 .Default(GPUName.str());
541 if (MArch)
542 return getProcessorFromTargetID(T, MArch->getValue()).str();
543 return "";
546 static std::string getLanaiTargetCPU(const ArgList &Args) {
547 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
548 return A->getValue();
550 return "";
553 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
554 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
555 // If we have -mcpu=, use that.
556 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
557 StringRef CPU = A->getValue();
559 #ifdef __wasm__
560 // Handle "native" by examining the host. "native" isn't meaningful when
561 // cross compiling, so only support this when the host is also WebAssembly.
562 if (CPU == "native")
563 return llvm::sys::getHostCPUName();
564 #endif
566 return CPU;
569 return "generic";
572 std::string tools::getCPUName(const Driver &D, const ArgList &Args,
573 const llvm::Triple &T, bool FromAs) {
574 Arg *A;
576 switch (T.getArch()) {
577 default:
578 return "";
580 case llvm::Triple::aarch64:
581 case llvm::Triple::aarch64_32:
582 case llvm::Triple::aarch64_be:
583 return aarch64::getAArch64TargetCPU(Args, T, A);
585 case llvm::Triple::arm:
586 case llvm::Triple::armeb:
587 case llvm::Triple::thumb:
588 case llvm::Triple::thumbeb: {
589 StringRef MArch, MCPU;
590 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
591 return arm::getARMTargetCPU(MCPU, MArch, T);
594 case llvm::Triple::avr:
595 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
596 return A->getValue();
597 return "";
599 case llvm::Triple::m68k:
600 return m68k::getM68kTargetCPU(Args);
602 case llvm::Triple::mips:
603 case llvm::Triple::mipsel:
604 case llvm::Triple::mips64:
605 case llvm::Triple::mips64el: {
606 StringRef CPUName;
607 StringRef ABIName;
608 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
609 return std::string(CPUName);
612 case llvm::Triple::nvptx:
613 case llvm::Triple::nvptx64:
614 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
615 return A->getValue();
616 return "";
618 case llvm::Triple::ppc:
619 case llvm::Triple::ppcle:
620 case llvm::Triple::ppc64:
621 case llvm::Triple::ppc64le:
622 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ))
623 return std::string(
624 llvm::PPC::getNormalizedPPCTargetCPU(T, A->getValue()));
625 return std::string(llvm::PPC::getNormalizedPPCTargetCPU(T));
627 case llvm::Triple::csky:
628 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
629 return A->getValue();
630 else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
631 return A->getValue();
632 else
633 return "ck810";
634 case llvm::Triple::riscv32:
635 case llvm::Triple::riscv64:
636 return riscv::getRISCVTargetCPU(Args, T);
638 case llvm::Triple::bpfel:
639 case llvm::Triple::bpfeb:
640 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
641 return A->getValue();
642 return "";
644 case llvm::Triple::sparc:
645 case llvm::Triple::sparcel:
646 case llvm::Triple::sparcv9:
647 return sparc::getSparcTargetCPU(D, Args, T);
649 case llvm::Triple::x86:
650 case llvm::Triple::x86_64:
651 return x86::getX86TargetCPU(D, Args, T);
653 case llvm::Triple::hexagon:
654 return "hexagon" +
655 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
657 case llvm::Triple::lanai:
658 return getLanaiTargetCPU(Args);
660 case llvm::Triple::systemz:
661 return systemz::getSystemZTargetCPU(Args, T);
663 case llvm::Triple::r600:
664 case llvm::Triple::amdgcn:
665 return getAMDGPUTargetGPU(T, Args);
667 case llvm::Triple::wasm32:
668 case llvm::Triple::wasm64:
669 return std::string(getWebAssemblyTargetCPU(Args));
671 case llvm::Triple::loongarch32:
672 case llvm::Triple::loongarch64:
673 return loongarch::getLoongArchTargetCPU(Args, T);
677 static void getWebAssemblyTargetFeatures(const Driver &D,
678 const llvm::Triple &Triple,
679 const ArgList &Args,
680 std::vector<StringRef> &Features) {
681 handleTargetFeaturesGroup(D, Triple, Args, Features,
682 options::OPT_m_wasm_Features_Group);
685 void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
686 const ArgList &Args, ArgStringList &CmdArgs,
687 bool ForAS, bool IsAux) {
688 std::vector<StringRef> Features;
689 switch (Triple.getArch()) {
690 default:
691 break;
692 case llvm::Triple::mips:
693 case llvm::Triple::mipsel:
694 case llvm::Triple::mips64:
695 case llvm::Triple::mips64el:
696 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
697 break;
698 case llvm::Triple::arm:
699 case llvm::Triple::armeb:
700 case llvm::Triple::thumb:
701 case llvm::Triple::thumbeb:
702 arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS);
703 break;
704 case llvm::Triple::ppc:
705 case llvm::Triple::ppcle:
706 case llvm::Triple::ppc64:
707 case llvm::Triple::ppc64le:
708 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
709 break;
710 case llvm::Triple::riscv32:
711 case llvm::Triple::riscv64:
712 riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
713 break;
714 case llvm::Triple::systemz:
715 systemz::getSystemZTargetFeatures(D, Args, Features);
716 break;
717 case llvm::Triple::aarch64:
718 case llvm::Triple::aarch64_32:
719 case llvm::Triple::aarch64_be:
720 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS);
721 break;
722 case llvm::Triple::x86:
723 case llvm::Triple::x86_64:
724 x86::getX86TargetFeatures(D, Triple, Args, Features);
725 break;
726 case llvm::Triple::hexagon:
727 hexagon::getHexagonTargetFeatures(D, Triple, Args, Features);
728 break;
729 case llvm::Triple::wasm32:
730 case llvm::Triple::wasm64:
731 getWebAssemblyTargetFeatures(D, Triple, Args, Features);
732 break;
733 case llvm::Triple::sparc:
734 case llvm::Triple::sparcel:
735 case llvm::Triple::sparcv9:
736 sparc::getSparcTargetFeatures(D, Args, Features);
737 break;
738 case llvm::Triple::r600:
739 case llvm::Triple::amdgcn:
740 amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
741 break;
742 case llvm::Triple::nvptx:
743 case llvm::Triple::nvptx64:
744 NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features);
745 break;
746 case llvm::Triple::m68k:
747 m68k::getM68kTargetFeatures(D, Triple, Args, Features);
748 break;
749 case llvm::Triple::msp430:
750 msp430::getMSP430TargetFeatures(D, Args, Features);
751 break;
752 case llvm::Triple::ve:
753 ve::getVETargetFeatures(D, Args, Features);
754 break;
755 case llvm::Triple::csky:
756 csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features);
757 break;
758 case llvm::Triple::loongarch32:
759 case llvm::Triple::loongarch64:
760 loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features);
761 break;
764 for (auto Feature : unifyTargetFeatures(Features)) {
765 CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature");
766 CmdArgs.push_back(Feature.data());
770 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
771 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
772 if (!LtoJobsArg)
773 return {};
774 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
775 D.Diag(diag::err_drv_invalid_int_value)
776 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
777 return LtoJobsArg->getValue();
780 // PS4/PS5 uses -ffunction-sections and -fdata-sections by default.
781 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
782 return Triple.isPS();
785 bool tools::isTLSDESCEnabled(const ToolChain &TC,
786 const llvm::opt::ArgList &Args) {
787 const llvm::Triple &Triple = TC.getEffectiveTriple();
788 Arg *A = Args.getLastArg(options::OPT_mtls_dialect_EQ);
789 if (!A)
790 return Triple.hasDefaultTLSDESC();
791 StringRef V = A->getValue();
792 bool SupportedArgument = false, EnableTLSDESC = false;
793 bool Unsupported = !Triple.isOSBinFormatELF();
794 if (Triple.isLoongArch() || Triple.isRISCV()) {
795 SupportedArgument = V == "desc" || V == "trad";
796 EnableTLSDESC = V == "desc";
797 } else if (Triple.isX86()) {
798 SupportedArgument = V == "gnu" || V == "gnu2";
799 EnableTLSDESC = V == "gnu2";
800 } else {
801 Unsupported = true;
803 if (Unsupported) {
804 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
805 << A->getSpelling() << Triple.getTriple();
806 } else if (!SupportedArgument) {
807 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument_for_target)
808 << A->getSpelling() << V << Triple.getTriple();
810 return EnableTLSDESC;
813 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
814 ArgStringList &CmdArgs, const InputInfo &Output,
815 const InputInfo &Input, bool IsThinLTO) {
816 const llvm::Triple &Triple = ToolChain.getTriple();
817 const bool IsOSAIX = Triple.isOSAIX();
818 const bool IsAMDGCN = Triple.isAMDGCN();
819 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
820 const Driver &D = ToolChain.getDriver();
821 const bool IsFatLTO = Args.hasArg(options::OPT_ffat_lto_objects);
822 const bool IsUnifiedLTO = Args.hasArg(options::OPT_funified_lto);
823 if (llvm::sys::path::filename(Linker) != "ld.lld" &&
824 llvm::sys::path::stem(Linker) != "ld.lld" && !Triple.isOSOpenBSD()) {
825 // Tell the linker to load the plugin. This has to come before
826 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to
827 // come before any -plugin-opt/-bplugin_opt that -Wl might forward.
828 const char *PluginPrefix = IsOSAIX ? "-bplugin:" : "";
829 const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold";
831 if (!IsOSAIX)
832 CmdArgs.push_back("-plugin");
834 #if defined(_WIN32)
835 const char *Suffix = ".dll";
836 #elif defined(__APPLE__)
837 const char *Suffix = ".dylib";
838 #else
839 const char *Suffix = ".so";
840 #endif
842 SmallString<1024> Plugin;
843 llvm::sys::path::native(Twine(D.Dir) +
844 "/../" CLANG_INSTALL_LIBDIR_BASENAME +
845 PluginName + Suffix,
846 Plugin);
847 CmdArgs.push_back(Args.MakeArgString(Twine(PluginPrefix) + Plugin));
848 } else {
849 // Tell LLD to find and use .llvm.lto section in regular relocatable object
850 // files
851 if (IsFatLTO)
852 CmdArgs.push_back("--fat-lto-objects");
855 const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt=";
856 const char *ExtraDash = IsOSAIX ? "-" : "";
857 const char *ParallelismOpt = IsOSAIX ? "-threads=" : "jobs=";
859 // Note, this solution is far from perfect, better to encode it into IR
860 // metadata, but this may not be worth it, since it looks like aranges is on
861 // the way out.
862 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
863 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
864 "-generate-arange-section"));
867 // Pass vector library arguments to LTO.
868 Arg *ArgVecLib = Args.getLastArg(options::OPT_fveclib);
869 if (ArgVecLib && ArgVecLib->getNumValues() == 1) {
870 // Map the vector library names from clang front-end to opt front-end. The
871 // values are taken from the TargetLibraryInfo class command line options.
872 std::optional<StringRef> OptVal =
873 llvm::StringSwitch<std::optional<StringRef>>(ArgVecLib->getValue())
874 .Case("Accelerate", "Accelerate")
875 .Case("LIBMVEC", "LIBMVEC-X86")
876 .Case("MASSV", "MASSV")
877 .Case("SVML", "SVML")
878 .Case("SLEEF", "sleefgnuabi")
879 .Case("Darwin_libsystem_m", "Darwin_libsystem_m")
880 .Case("ArmPL", "ArmPL")
881 .Case("none", "none")
882 .Default(std::nullopt);
884 if (OptVal)
885 CmdArgs.push_back(Args.MakeArgString(
886 Twine(PluginOptPrefix) + "-vector-library=" + OptVal.value()));
889 // Try to pass driver level flags relevant to LTO code generation down to
890 // the plugin.
892 // Handle flags for selecting CPU variants.
893 std::string CPU = getCPUName(D, Args, Triple);
894 if (!CPU.empty())
895 CmdArgs.push_back(
896 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU));
898 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
899 // The optimization level matches
900 // CompilerInvocation.cpp:getOptimizationLevel().
901 StringRef OOpt;
902 if (A->getOption().matches(options::OPT_O4) ||
903 A->getOption().matches(options::OPT_Ofast))
904 OOpt = "3";
905 else if (A->getOption().matches(options::OPT_O)) {
906 OOpt = A->getValue();
907 if (OOpt == "g")
908 OOpt = "1";
909 else if (OOpt == "s" || OOpt == "z")
910 OOpt = "2";
911 } else if (A->getOption().matches(options::OPT_O0))
912 OOpt = "0";
913 if (!OOpt.empty()) {
914 CmdArgs.push_back(
915 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt));
916 if (IsAMDGCN)
917 CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt));
921 if (Args.hasArg(options::OPT_gsplit_dwarf))
922 CmdArgs.push_back(Args.MakeArgString(
923 Twine(PluginOptPrefix) + "dwo_dir=" + Output.getFilename() + "_dwo"));
925 if (IsThinLTO && !IsOSAIX)
926 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "thinlto"));
927 else if (IsThinLTO && IsOSAIX)
928 CmdArgs.push_back(Args.MakeArgString(Twine("-bdbg:thinlto")));
930 // Matrix intrinsic lowering happens at link time with ThinLTO. Enable
931 // LowerMatrixIntrinsicsPass, which is transitively called by
932 // buildThinLTODefaultPipeline under EnableMatrix.
933 if ((IsThinLTO || IsFatLTO || IsUnifiedLTO) &&
934 Args.hasArg(options::OPT_fenable_matrix))
935 CmdArgs.push_back(
936 Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-matrix"));
938 StringRef Parallelism = getLTOParallelism(Args, D);
939 if (!Parallelism.empty())
940 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
941 ParallelismOpt + Parallelism));
943 // Pass down GlobalISel options.
944 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
945 options::OPT_fno_global_isel)) {
946 // Parsing -fno-global-isel explicitly gives architectures that enable GISel
947 // by default a chance to disable it.
948 CmdArgs.push_back(Args.MakeArgString(
949 Twine(PluginOptPrefix) + "-global-isel=" +
950 (A->getOption().matches(options::OPT_fglobal_isel) ? "1" : "0")));
953 // If an explicit debugger tuning argument appeared, pass it along.
954 if (Arg *A =
955 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
956 if (A->getOption().matches(options::OPT_glldb))
957 CmdArgs.push_back(
958 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=lldb"));
959 else if (A->getOption().matches(options::OPT_gsce))
960 CmdArgs.push_back(
961 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=sce"));
962 else if (A->getOption().matches(options::OPT_gdbx))
963 CmdArgs.push_back(
964 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=dbx"));
965 else
966 CmdArgs.push_back(
967 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=gdb"));
970 if (IsOSAIX) {
971 if (!ToolChain.useIntegratedAs())
972 CmdArgs.push_back(
973 Args.MakeArgString(Twine(PluginOptPrefix) + "-no-integrated-as=1"));
975 // On AIX, clang assumes strict-dwarf is true if any debug option is
976 // specified, unless it is told explicitly not to assume so.
977 Arg *A = Args.getLastArg(options::OPT_g_Group);
978 bool EnableDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
979 !A->getOption().matches(options::OPT_ggdb0);
980 if (EnableDebugInfo && Args.hasFlag(options::OPT_gstrict_dwarf,
981 options::OPT_gno_strict_dwarf, true))
982 CmdArgs.push_back(
983 Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true"));
985 for (const Arg *A : Args.filtered_reverse(options::OPT_mabi_EQ)) {
986 StringRef V = A->getValue();
987 if (V == "vec-default")
988 break;
989 if (V == "vec-extabi") {
990 CmdArgs.push_back(
991 Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi"));
992 break;
997 bool UseSeparateSections =
998 isUseSeparateSections(ToolChain.getEffectiveTriple());
1000 if (Args.hasFlag(options::OPT_ffunction_sections,
1001 options::OPT_fno_function_sections, UseSeparateSections))
1002 CmdArgs.push_back(
1003 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=1"));
1004 else if (Args.hasArg(options::OPT_fno_function_sections))
1005 CmdArgs.push_back(
1006 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=0"));
1008 bool DataSectionsTurnedOff = false;
1009 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
1010 UseSeparateSections)) {
1011 CmdArgs.push_back(
1012 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1"));
1013 } else if (Args.hasArg(options::OPT_fno_data_sections)) {
1014 DataSectionsTurnedOff = true;
1015 CmdArgs.push_back(
1016 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=0"));
1019 if (Args.hasArg(options::OPT_mxcoff_roptr) ||
1020 Args.hasArg(options::OPT_mno_xcoff_roptr)) {
1021 bool HasRoptr = Args.hasFlag(options::OPT_mxcoff_roptr,
1022 options::OPT_mno_xcoff_roptr, false);
1023 StringRef OptStr = HasRoptr ? "-mxcoff-roptr" : "-mno-xcoff-roptr";
1024 if (!IsOSAIX)
1025 D.Diag(diag::err_drv_unsupported_opt_for_target)
1026 << OptStr << Triple.str();
1028 if (HasRoptr) {
1029 // The data sections option is on by default on AIX. We only need to error
1030 // out when -fno-data-sections is specified explicitly to turn off data
1031 // sections.
1032 if (DataSectionsTurnedOff)
1033 D.Diag(diag::err_roptr_requires_data_sections);
1035 CmdArgs.push_back(
1036 Args.MakeArgString(Twine(PluginOptPrefix) + "-mxcoff-roptr"));
1040 // Pass an option to enable split machine functions.
1041 if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
1042 options::OPT_fno_split_machine_functions)) {
1043 if (A->getOption().matches(options::OPT_fsplit_machine_functions))
1044 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
1045 "-split-machine-functions"));
1048 if (Arg *A = getLastProfileSampleUseArg(Args)) {
1049 StringRef FName = A->getValue();
1050 if (!llvm::sys::fs::exists(FName))
1051 D.Diag(diag::err_drv_no_such_file) << FName;
1052 else
1053 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
1054 "sample-profile=" + FName));
1057 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) {
1058 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1059 "cs-profile-generate"));
1060 if (CSPGOGenerateArg->getOption().matches(
1061 options::OPT_fcs_profile_generate_EQ)) {
1062 SmallString<128> Path(CSPGOGenerateArg->getValue());
1063 llvm::sys::path::append(Path, "default_%m.profraw");
1064 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1065 "cs-profile-path=" + Path));
1066 } else
1067 CmdArgs.push_back(
1068 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1069 "cs-profile-path=default_%m.profraw"));
1070 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) {
1071 SmallString<128> Path(
1072 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
1073 if (Path.empty() || llvm::sys::fs::is_directory(Path))
1074 llvm::sys::path::append(Path, "default.profdata");
1075 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1076 "cs-profile-path=" + Path));
1079 // This controls whether or not we perform JustMyCode instrumentation.
1080 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
1081 if (ToolChain.getEffectiveTriple().isOSBinFormatELF())
1082 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
1083 "-enable-jmc-instrument"));
1084 else
1085 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
1088 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
1089 Triple.hasDefaultEmulatedTLS())) {
1090 CmdArgs.push_back(
1091 Args.MakeArgString(Twine(PluginOptPrefix) + "-emulated-tls"));
1093 if (isTLSDESCEnabled(ToolChain, Args))
1094 CmdArgs.push_back(
1095 Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-tlsdesc"));
1097 if (Args.hasFlag(options::OPT_fstack_size_section,
1098 options::OPT_fno_stack_size_section, false))
1099 CmdArgs.push_back(
1100 Args.MakeArgString(Twine(PluginOptPrefix) + "-stack-size-section"));
1102 // Setup statistics file output.
1103 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
1104 if (!StatsFile.empty())
1105 CmdArgs.push_back(
1106 Args.MakeArgString(Twine(PluginOptPrefix) + "stats-file=" + StatsFile));
1108 // Setup crash diagnostics dir.
1109 if (Arg *A = Args.getLastArg(options::OPT_fcrash_diagnostics_dir))
1110 CmdArgs.push_back(Args.MakeArgString(
1111 Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue()));
1113 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix);
1115 // Handle remark diagnostics on screen options: '-Rpass-*'.
1116 renderRpassOptions(Args, CmdArgs, PluginOptPrefix);
1118 // Handle serialized remarks options: '-fsave-optimization-record'
1119 // and '-foptimization-record-*'.
1120 if (willEmitRemarks(Args))
1121 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
1122 Output, PluginOptPrefix);
1124 // Handle remarks hotness/threshold related options.
1125 renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix);
1127 addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(),
1128 /*IsLTO=*/true, PluginOptPrefix);
1130 bool IsELF = Triple.isOSBinFormatELF();
1131 bool Crel = false;
1132 bool ImplicitMapSyms = false;
1133 for (const Arg *A : Args.filtered(options::OPT_Wa_COMMA)) {
1134 for (StringRef V : A->getValues()) {
1135 auto Equal = V.split('=');
1136 auto checkArg = [&](bool ValidTarget,
1137 std::initializer_list<const char *> Set) {
1138 if (!ValidTarget) {
1139 D.Diag(diag::err_drv_unsupported_opt_for_target)
1140 << (Twine("-Wa,") + Equal.first + "=").str()
1141 << Triple.getTriple();
1142 } else if (!llvm::is_contained(Set, Equal.second)) {
1143 D.Diag(diag::err_drv_unsupported_option_argument)
1144 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
1147 if (Equal.first == "-mmapsyms") {
1148 ImplicitMapSyms = Equal.second == "implicit";
1149 checkArg(IsELF && Triple.isAArch64(), {"default", "implicit"});
1150 } else if (V == "--crel")
1151 Crel = true;
1152 else if (V == "--no-crel")
1153 Crel = false;
1154 else
1155 continue;
1156 A->claim();
1159 if (Crel) {
1160 if (IsELF && !Triple.isMIPS()) {
1161 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "-crel"));
1162 } else {
1163 D.Diag(diag::err_drv_unsupported_opt_for_target)
1164 << "-Wa,--crel" << D.getTargetTriple();
1167 if (ImplicitMapSyms)
1168 CmdArgs.push_back(
1169 Args.MakeArgString(Twine(PluginOptPrefix) + "-implicit-mapsyms"));
1172 void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC,
1173 const ArgList &Args,
1174 ArgStringList &CmdArgs) {
1175 // Default to clang lib / lib64 folder, i.e. the same location as device
1176 // runtime.
1177 SmallString<256> DefaultLibPath =
1178 llvm::sys::path::parent_path(TC.getDriver().Dir);
1179 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
1180 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
1183 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
1184 ArgStringList &CmdArgs) {
1185 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
1186 options::OPT_fno_rtlib_add_rpath, false))
1187 return;
1189 SmallVector<std::string> CandidateRPaths(TC.getArchSpecificLibPaths());
1190 if (const auto CandidateRPath = TC.getStdlibPath())
1191 CandidateRPaths.emplace_back(*CandidateRPath);
1193 for (const auto &CandidateRPath : CandidateRPaths) {
1194 if (TC.getVFS().exists(CandidateRPath)) {
1195 CmdArgs.push_back("-rpath");
1196 CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
1201 bool tools::addOpenMPRuntime(const Compilation &C, ArgStringList &CmdArgs,
1202 const ToolChain &TC, const ArgList &Args,
1203 bool ForceStaticHostRuntime, bool IsOffloadingHost,
1204 bool GompNeedsRT) {
1205 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
1206 options::OPT_fno_openmp, false)) {
1207 // We need libomptarget (liboffload) if it's the choosen offloading runtime.
1208 if (Args.hasFlag(options::OPT_foffload_via_llvm,
1209 options::OPT_fno_offload_via_llvm, false))
1210 CmdArgs.push_back("-lomptarget");
1211 return false;
1214 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
1216 if (RTKind == Driver::OMPRT_Unknown)
1217 // Already diagnosed.
1218 return false;
1220 if (ForceStaticHostRuntime)
1221 CmdArgs.push_back("-Bstatic");
1223 switch (RTKind) {
1224 case Driver::OMPRT_OMP:
1225 CmdArgs.push_back("-lomp");
1226 break;
1227 case Driver::OMPRT_GOMP:
1228 CmdArgs.push_back("-lgomp");
1229 break;
1230 case Driver::OMPRT_IOMP5:
1231 CmdArgs.push_back("-liomp5");
1232 break;
1233 case Driver::OMPRT_Unknown:
1234 break;
1237 if (ForceStaticHostRuntime)
1238 CmdArgs.push_back("-Bdynamic");
1240 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
1241 CmdArgs.push_back("-lrt");
1243 if (IsOffloadingHost)
1244 CmdArgs.push_back("-lomptarget");
1246 if (IsOffloadingHost && !Args.hasArg(options::OPT_nogpulib))
1247 CmdArgs.push_back("-lomptarget.devicertl");
1249 addArchSpecificRPath(TC, Args, CmdArgs);
1251 addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
1253 return true;
1256 void tools::addOpenMPHostOffloadingArgs(const Compilation &C,
1257 const JobAction &JA,
1258 const llvm::opt::ArgList &Args,
1259 llvm::opt::ArgStringList &CmdArgs) {
1260 if (!JA.isHostOffloading(Action::OFK_OpenMP))
1261 return;
1263 // For all the host OpenMP offloading compile jobs we need to pass the targets
1264 // information using -fopenmp-targets= option.
1265 constexpr llvm::StringLiteral Targets("-fopenmp-targets=");
1267 SmallVector<std::string> Triples;
1268 auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
1269 std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
1270 [](auto TC) { return TC.second->getTripleString(); });
1271 CmdArgs.push_back(
1272 Args.MakeArgString(Twine(Targets) + llvm::join(Triples, ",")));
1275 /// Add Fortran runtime libs
1276 void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args,
1277 llvm::opt::ArgStringList &CmdArgs) {
1278 // Link FortranRuntime and FortranDecimal
1279 // These are handled earlier on Windows by telling the frontend driver to
1280 // add the correct libraries to link against as dependents in the object
1281 // file.
1282 if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1283 StringRef F128LibName = TC.getDriver().getFlangF128MathLibrary();
1284 F128LibName.consume_front_insensitive("lib");
1285 if (!F128LibName.empty()) {
1286 bool AsNeeded = !TC.getTriple().isOSAIX();
1287 CmdArgs.push_back("-lFortranFloat128Math");
1288 if (AsNeeded)
1289 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true);
1290 CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
1291 if (AsNeeded)
1292 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
1294 CmdArgs.push_back("-lFortranRuntime");
1295 CmdArgs.push_back("-lFortranDecimal");
1296 addArchSpecificRPath(TC, Args, CmdArgs);
1299 // libomp needs libatomic for atomic operations if using libgcc
1300 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
1301 options::OPT_fno_openmp, false)) {
1302 Driver::OpenMPRuntimeKind OMPRuntime =
1303 TC.getDriver().getOpenMPRuntime(Args);
1304 ToolChain::RuntimeLibType RuntimeLib = TC.GetRuntimeLibType(Args);
1305 if (OMPRuntime == Driver::OMPRT_OMP && RuntimeLib == ToolChain::RLT_Libgcc)
1306 CmdArgs.push_back("-latomic");
1310 void tools::addFortranRuntimeLibraryPath(const ToolChain &TC,
1311 const llvm::opt::ArgList &Args,
1312 ArgStringList &CmdArgs) {
1313 // Default to the <driver-path>/../lib directory. This works fine on the
1314 // platforms that we have tested so far. We will probably have to re-fine
1315 // this in the future. In particular, on some platforms, we may need to use
1316 // lib64 instead of lib.
1317 SmallString<256> DefaultLibPath =
1318 llvm::sys::path::parent_path(TC.getDriver().Dir);
1319 llvm::sys::path::append(DefaultLibPath, "lib");
1320 if (TC.getTriple().isKnownWindowsMSVCEnvironment())
1321 CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
1322 else
1323 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
1326 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
1327 ArgStringList &CmdArgs, StringRef Sanitizer,
1328 bool IsShared, bool IsWhole) {
1329 // Wrap any static runtimes that must be forced into executable in
1330 // whole-archive.
1331 if (IsWhole) CmdArgs.push_back("--whole-archive");
1332 CmdArgs.push_back(TC.getCompilerRTArgString(
1333 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
1334 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
1336 if (IsShared) {
1337 addArchSpecificRPath(TC, Args, CmdArgs);
1341 // Tries to use a file with the list of dynamic symbols that need to be exported
1342 // from the runtime library. Returns true if the file was found.
1343 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
1344 ArgStringList &CmdArgs,
1345 StringRef Sanitizer) {
1346 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1348 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
1349 // the option, so don't try to pass it.
1350 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd)
1351 return true;
1352 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
1353 if (llvm::sys::fs::exists(SanRT + ".syms")) {
1354 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
1355 return true;
1357 return false;
1360 void tools::addAsNeededOption(const ToolChain &TC,
1361 const llvm::opt::ArgList &Args,
1362 llvm::opt::ArgStringList &CmdArgs,
1363 bool as_needed) {
1364 assert(!TC.getTriple().isOSAIX() &&
1365 "AIX linker does not support any form of --as-needed option yet.");
1366 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1368 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
1369 // for the native forms -z ignore/-z record, they are missing in Illumos,
1370 // so always use the native form.
1371 // GNU ld doesn't support -z ignore/-z record, so don't use them even on
1372 // Solaris.
1373 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) {
1374 CmdArgs.push_back("-z");
1375 CmdArgs.push_back(as_needed ? "ignore" : "record");
1376 } else {
1377 CmdArgs.push_back(as_needed ? "--as-needed" : "--no-as-needed");
1381 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
1382 const llvm::opt::ArgList &Args,
1383 ArgStringList &CmdArgs) {
1384 // Force linking against the system libraries sanitizers depends on
1385 // (see PR15823 why this is necessary).
1386 addAsNeededOption(TC, Args, CmdArgs, false);
1387 // There's no libpthread or librt on RTEMS & Android.
1388 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
1389 !TC.getTriple().isAndroid() && !TC.getTriple().isOHOSFamily()) {
1390 CmdArgs.push_back("-lpthread");
1391 if (!TC.getTriple().isOSOpenBSD())
1392 CmdArgs.push_back("-lrt");
1394 CmdArgs.push_back("-lm");
1395 // There's no libdl on all OSes.
1396 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
1397 !TC.getTriple().isOSOpenBSD() &&
1398 TC.getTriple().getOS() != llvm::Triple::RTEMS)
1399 CmdArgs.push_back("-ldl");
1400 // Required for backtrace on some OSes
1401 if (TC.getTriple().isOSFreeBSD() ||
1402 TC.getTriple().isOSNetBSD() ||
1403 TC.getTriple().isOSOpenBSD())
1404 CmdArgs.push_back("-lexecinfo");
1405 // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
1406 // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
1407 // requirement.
1408 if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
1409 !TC.getTriple().isMusl())
1410 CmdArgs.push_back("-lresolv");
1413 static void
1414 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1415 SmallVectorImpl<StringRef> &SharedRuntimes,
1416 SmallVectorImpl<StringRef> &StaticRuntimes,
1417 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
1418 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
1419 SmallVectorImpl<StringRef> &RequiredSymbols) {
1420 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1421 // Collect shared runtimes.
1422 if (SanArgs.needsSharedRt()) {
1423 if (SanArgs.needsAsanRt()) {
1424 SharedRuntimes.push_back("asan");
1425 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1426 HelperStaticRuntimes.push_back("asan-preinit");
1428 if (SanArgs.needsMemProfRt()) {
1429 SharedRuntimes.push_back("memprof");
1430 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1431 HelperStaticRuntimes.push_back("memprof-preinit");
1433 if (SanArgs.needsNsanRt())
1434 SharedRuntimes.push_back("nsan");
1435 if (SanArgs.needsUbsanRt()) {
1436 if (SanArgs.requiresMinimalRuntime())
1437 SharedRuntimes.push_back("ubsan_minimal");
1438 else
1439 SharedRuntimes.push_back("ubsan_standalone");
1441 if (SanArgs.needsScudoRt()) {
1442 SharedRuntimes.push_back("scudo_standalone");
1444 if (SanArgs.needsTsanRt())
1445 SharedRuntimes.push_back("tsan");
1446 if (SanArgs.needsHwasanRt()) {
1447 if (SanArgs.needsHwasanAliasesRt())
1448 SharedRuntimes.push_back("hwasan_aliases");
1449 else
1450 SharedRuntimes.push_back("hwasan");
1451 if (!Args.hasArg(options::OPT_shared))
1452 HelperStaticRuntimes.push_back("hwasan-preinit");
1454 if (SanArgs.needsRtsanRt() && SanArgs.linkRuntimes())
1455 SharedRuntimes.push_back("rtsan");
1458 // The stats_client library is also statically linked into DSOs.
1459 if (SanArgs.needsStatsRt())
1460 StaticRuntimes.push_back("stats_client");
1462 // Always link the static runtime regardless of DSO or executable.
1463 if (SanArgs.needsAsanRt())
1464 HelperStaticRuntimes.push_back("asan_static");
1466 // Collect static runtimes.
1467 if (Args.hasArg(options::OPT_shared)) {
1468 // Don't link static runtimes into DSOs.
1469 return;
1472 // Each static runtime that has a DSO counterpart above is excluded below,
1473 // but runtimes that exist only as static are not affected by needsSharedRt.
1475 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt()) {
1476 StaticRuntimes.push_back("asan");
1477 if (SanArgs.linkCXXRuntimes())
1478 StaticRuntimes.push_back("asan_cxx");
1481 if (!SanArgs.needsSharedRt() && SanArgs.needsRtsanRt() &&
1482 SanArgs.linkRuntimes())
1483 StaticRuntimes.push_back("rtsan");
1485 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt()) {
1486 StaticRuntimes.push_back("memprof");
1487 if (SanArgs.linkCXXRuntimes())
1488 StaticRuntimes.push_back("memprof_cxx");
1491 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt()) {
1492 if (SanArgs.needsHwasanAliasesRt()) {
1493 StaticRuntimes.push_back("hwasan_aliases");
1494 if (SanArgs.linkCXXRuntimes())
1495 StaticRuntimes.push_back("hwasan_aliases_cxx");
1496 } else {
1497 StaticRuntimes.push_back("hwasan");
1498 if (SanArgs.linkCXXRuntimes())
1499 StaticRuntimes.push_back("hwasan_cxx");
1502 if (SanArgs.needsDfsanRt())
1503 StaticRuntimes.push_back("dfsan");
1504 if (SanArgs.needsLsanRt())
1505 StaticRuntimes.push_back("lsan");
1506 if (SanArgs.needsMsanRt()) {
1507 StaticRuntimes.push_back("msan");
1508 if (SanArgs.linkCXXRuntimes())
1509 StaticRuntimes.push_back("msan_cxx");
1511 if (!SanArgs.needsSharedRt() && SanArgs.needsNsanRt())
1512 StaticRuntimes.push_back("nsan");
1513 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) {
1514 StaticRuntimes.push_back("tsan");
1515 if (SanArgs.linkCXXRuntimes())
1516 StaticRuntimes.push_back("tsan_cxx");
1518 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt()) {
1519 if (SanArgs.requiresMinimalRuntime()) {
1520 StaticRuntimes.push_back("ubsan_minimal");
1521 } else {
1522 StaticRuntimes.push_back("ubsan_standalone");
1523 if (SanArgs.linkCXXRuntimes())
1524 StaticRuntimes.push_back("ubsan_standalone_cxx");
1527 if (SanArgs.needsSafeStackRt()) {
1528 NonWholeStaticRuntimes.push_back("safestack");
1529 RequiredSymbols.push_back("__safestack_init");
1531 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt())) {
1532 if (SanArgs.needsCfiRt())
1533 StaticRuntimes.push_back("cfi");
1534 if (SanArgs.needsCfiDiagRt()) {
1535 StaticRuntimes.push_back("cfi_diag");
1536 if (SanArgs.linkCXXRuntimes())
1537 StaticRuntimes.push_back("ubsan_standalone_cxx");
1540 if (SanArgs.needsStatsRt()) {
1541 NonWholeStaticRuntimes.push_back("stats");
1542 RequiredSymbols.push_back("__sanitizer_stats_register");
1544 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt()) {
1545 StaticRuntimes.push_back("scudo_standalone");
1546 if (SanArgs.linkCXXRuntimes())
1547 StaticRuntimes.push_back("scudo_standalone_cxx");
1551 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
1552 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
1553 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1554 ArgStringList &CmdArgs) {
1555 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1556 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
1557 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
1558 if (SanArgs.linkRuntimes()) {
1559 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1560 NonWholeStaticRuntimes, HelperStaticRuntimes,
1561 RequiredSymbols);
1564 // -u options must be added before the runtime libs that resolve them.
1565 for (auto S : RequiredSymbols) {
1566 CmdArgs.push_back("-u");
1567 CmdArgs.push_back(Args.MakeArgString(S));
1570 // Inject libfuzzer dependencies.
1571 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1572 !Args.hasArg(options::OPT_shared)) {
1574 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
1575 if (SanArgs.needsFuzzerInterceptors())
1576 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
1577 true);
1578 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
1579 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
1580 !Args.hasArg(options::OPT_static);
1581 if (OnlyLibstdcxxStatic)
1582 CmdArgs.push_back("-Bstatic");
1583 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1584 if (OnlyLibstdcxxStatic)
1585 CmdArgs.push_back("-Bdynamic");
1589 for (auto RT : SharedRuntimes)
1590 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
1591 for (auto RT : HelperStaticRuntimes)
1592 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1593 bool AddExportDynamic = false;
1594 for (auto RT : StaticRuntimes) {
1595 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1596 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1598 for (auto RT : NonWholeStaticRuntimes) {
1599 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1600 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1602 // If there is a static runtime with no dynamic list, force all the symbols
1603 // to be dynamic to be sure we export sanitizer interface functions.
1604 if (AddExportDynamic)
1605 CmdArgs.push_back("--export-dynamic");
1607 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1608 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1610 if (SanArgs.hasMemTag()) {
1611 if (!TC.getTriple().isAndroid()) {
1612 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1613 << "-fsanitize=memtag*" << TC.getTriple().str();
1615 CmdArgs.push_back(
1616 Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1617 if (SanArgs.hasMemtagHeap())
1618 CmdArgs.push_back("--android-memtag-heap");
1619 if (SanArgs.hasMemtagStack())
1620 CmdArgs.push_back("--android-memtag-stack");
1623 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1626 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1627 if (Args.hasArg(options::OPT_shared)) {
1628 if (TC.getXRayArgs().needsXRayDSORt()) {
1629 CmdArgs.push_back("--whole-archive");
1630 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray-dso"));
1631 CmdArgs.push_back("--no-whole-archive");
1632 return true;
1634 } else if (TC.getXRayArgs().needsXRayRt()) {
1635 CmdArgs.push_back("--whole-archive");
1636 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
1637 for (const auto &Mode : TC.getXRayArgs().modeList())
1638 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
1639 CmdArgs.push_back("--no-whole-archive");
1640 return true;
1643 return false;
1646 void tools::linkXRayRuntimeDeps(const ToolChain &TC,
1647 const llvm::opt::ArgList &Args,
1648 ArgStringList &CmdArgs) {
1649 addAsNeededOption(TC, Args, CmdArgs, false);
1650 CmdArgs.push_back("-lpthread");
1651 if (!TC.getTriple().isOSOpenBSD())
1652 CmdArgs.push_back("-lrt");
1653 CmdArgs.push_back("-lm");
1655 if (!TC.getTriple().isOSFreeBSD() &&
1656 !TC.getTriple().isOSNetBSD() &&
1657 !TC.getTriple().isOSOpenBSD())
1658 CmdArgs.push_back("-ldl");
1661 bool tools::areOptimizationsEnabled(const ArgList &Args) {
1662 // Find the last -O arg and see if it is non-zero.
1663 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1664 return !A->getOption().matches(options::OPT_O0);
1665 // Defaults to -O0.
1666 return false;
1669 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1670 const InputInfo &Input,
1671 const InputInfo &Output) {
1672 auto AddPostfix = [JA](auto &F) {
1673 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1674 F += (Twine("_") + JA.getOffloadingArch()).str();
1675 F += ".dwo";
1677 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1678 if (StringRef(A->getValue()) == "single" && Output.isFilename())
1679 return Args.MakeArgString(Output.getFilename());
1681 SmallString<128> T;
1682 if (const Arg *A = Args.getLastArg(options::OPT_dumpdir)) {
1683 T = A->getValue();
1684 } else {
1685 Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o);
1686 if (FinalOutput && Args.hasArg(options::OPT_c)) {
1687 T = FinalOutput->getValue();
1688 llvm::sys::path::remove_filename(T);
1689 llvm::sys::path::append(T,
1690 llvm::sys::path::stem(FinalOutput->getValue()));
1691 AddPostfix(T);
1692 return Args.MakeArgString(T);
1696 T += llvm::sys::path::stem(Input.getBaseInput());
1697 AddPostfix(T);
1698 return Args.MakeArgString(T);
1701 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1702 const JobAction &JA, const ArgList &Args,
1703 const InputInfo &Output, const char *OutFile) {
1704 ArgStringList ExtractArgs;
1705 ExtractArgs.push_back("--extract-dwo");
1707 ArgStringList StripArgs;
1708 StripArgs.push_back("--strip-dwo");
1710 // Grabbing the output of the earlier compile step.
1711 StripArgs.push_back(Output.getFilename());
1712 ExtractArgs.push_back(Output.getFilename());
1713 ExtractArgs.push_back(OutFile);
1715 const char *Exec =
1716 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1717 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1719 // First extract the dwo sections.
1720 C.addCommand(std::make_unique<Command>(JA, T,
1721 ResponseFileSupport::AtFileCurCP(),
1722 Exec, ExtractArgs, II, Output));
1724 // Then remove them from the original .o file.
1725 C.addCommand(std::make_unique<Command>(
1726 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1729 // Claim options we don't want to warn if they are unused. We do this for
1730 // options that build systems might add but are unused when assembling or only
1731 // running the preprocessor for example.
1732 void tools::claimNoWarnArgs(const ArgList &Args) {
1733 // Don't warn about unused -f(no-)?lto. This can happen when we're
1734 // preprocessing, precompiling or assembling.
1735 Args.ClaimAllArgs(options::OPT_flto_EQ);
1736 Args.ClaimAllArgs(options::OPT_flto);
1737 Args.ClaimAllArgs(options::OPT_fno_lto);
1740 Arg *tools::getLastCSProfileGenerateArg(const ArgList &Args) {
1741 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
1742 options::OPT_fcs_profile_generate_EQ,
1743 options::OPT_fno_profile_generate);
1744 if (CSPGOGenerateArg &&
1745 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
1746 CSPGOGenerateArg = nullptr;
1748 return CSPGOGenerateArg;
1751 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1752 auto *ProfileUseArg = Args.getLastArg(
1753 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1754 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1755 options::OPT_fno_profile_instr_use);
1757 if (ProfileUseArg &&
1758 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1759 ProfileUseArg = nullptr;
1761 return ProfileUseArg;
1764 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1765 auto *ProfileSampleUseArg = Args.getLastArg(
1766 options::OPT_fprofile_sample_use_EQ, options::OPT_fno_profile_sample_use);
1768 if (ProfileSampleUseArg && (ProfileSampleUseArg->getOption().matches(
1769 options::OPT_fno_profile_sample_use)))
1770 return nullptr;
1772 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ);
1775 const char *tools::RelocationModelName(llvm::Reloc::Model Model) {
1776 switch (Model) {
1777 case llvm::Reloc::Static:
1778 return "static";
1779 case llvm::Reloc::PIC_:
1780 return "pic";
1781 case llvm::Reloc::DynamicNoPIC:
1782 return "dynamic-no-pic";
1783 case llvm::Reloc::ROPI:
1784 return "ropi";
1785 case llvm::Reloc::RWPI:
1786 return "rwpi";
1787 case llvm::Reloc::ROPI_RWPI:
1788 return "ropi-rwpi";
1790 llvm_unreachable("Unknown Reloc::Model kind");
1793 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
1794 /// smooshes them together with platform defaults, to decide whether
1795 /// this compile should be using PIC mode or not. Returns a tuple of
1796 /// (RelocationModel, PICLevel, IsPIE).
1797 std::tuple<llvm::Reloc::Model, unsigned, bool>
1798 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1799 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1800 const llvm::Triple &Triple = ToolChain.getTriple();
1802 bool PIE = ToolChain.isPIEDefault(Args);
1803 bool PIC = PIE || ToolChain.isPICDefault();
1804 // The Darwin/MachO default to use PIC does not apply when using -static.
1805 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1806 PIE = PIC = false;
1807 bool IsPICLevelTwo = PIC;
1809 bool KernelOrKext =
1810 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1812 // Android-specific defaults for PIC/PIE
1813 if (Triple.isAndroid()) {
1814 switch (Triple.getArch()) {
1815 case llvm::Triple::arm:
1816 case llvm::Triple::armeb:
1817 case llvm::Triple::thumb:
1818 case llvm::Triple::thumbeb:
1819 case llvm::Triple::aarch64:
1820 case llvm::Triple::mips:
1821 case llvm::Triple::mipsel:
1822 case llvm::Triple::mips64:
1823 case llvm::Triple::mips64el:
1824 PIC = true; // "-fpic"
1825 break;
1827 case llvm::Triple::x86:
1828 case llvm::Triple::x86_64:
1829 PIC = true; // "-fPIC"
1830 IsPICLevelTwo = true;
1831 break;
1833 default:
1834 break;
1838 // OHOS-specific defaults for PIC/PIE
1839 if (Triple.isOHOSFamily() && Triple.getArch() == llvm::Triple::aarch64)
1840 PIC = true;
1842 // OpenBSD-specific defaults for PIE
1843 if (Triple.isOSOpenBSD()) {
1844 switch (ToolChain.getArch()) {
1845 case llvm::Triple::arm:
1846 case llvm::Triple::aarch64:
1847 case llvm::Triple::mips64:
1848 case llvm::Triple::mips64el:
1849 case llvm::Triple::x86:
1850 case llvm::Triple::x86_64:
1851 IsPICLevelTwo = false; // "-fpie"
1852 break;
1854 case llvm::Triple::ppc:
1855 case llvm::Triple::sparcv9:
1856 IsPICLevelTwo = true; // "-fPIE"
1857 break;
1859 default:
1860 break;
1864 // The last argument relating to either PIC or PIE wins, and no
1865 // other argument is used. If the last argument is any flavor of the
1866 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1867 // option implicitly enables PIC at the same level.
1868 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1869 options::OPT_fpic, options::OPT_fno_pic,
1870 options::OPT_fPIE, options::OPT_fno_PIE,
1871 options::OPT_fpie, options::OPT_fno_pie);
1872 if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1873 LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1874 options::OPT_fPIE, options::OPT_fpie)) {
1875 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1876 << LastPICArg->getSpelling() << Triple.str();
1877 if (Triple.getArch() == llvm::Triple::x86_64)
1878 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1879 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1882 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1883 // is forced, then neither PIC nor PIE flags will have no effect.
1884 if (!ToolChain.isPICDefaultForced()) {
1885 if (LastPICArg) {
1886 Option O = LastPICArg->getOption();
1887 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1888 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1889 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1890 PIC =
1891 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1892 IsPICLevelTwo =
1893 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1894 } else {
1895 PIE = PIC = false;
1896 if (EffectiveTriple.isPS()) {
1897 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1898 StringRef Model = ModelArg ? ModelArg->getValue() : "";
1899 if (Model != "kernel") {
1900 PIC = true;
1901 ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1902 << LastPICArg->getSpelling()
1903 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1910 // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1911 // the PIC level would've been set to level 1, force it back to level 2 PIC
1912 // instead.
1913 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1914 IsPICLevelTwo |= ToolChain.isPICDefault();
1916 // This kernel flags are a trump-card: they will disable PIC/PIE
1917 // generation, independent of the argument order.
1918 if (KernelOrKext &&
1919 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1920 !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1921 PIC = PIE = false;
1923 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1924 // This is a very special mode. It trumps the other modes, almost no one
1925 // uses it, and it isn't even valid on any OS but Darwin.
1926 if (!Triple.isOSDarwin())
1927 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1928 << A->getSpelling() << Triple.str();
1930 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1932 // Only a forced PIC mode can cause the actual compile to have PIC defines
1933 // etc., no flags are sufficient. This behavior was selected to closely
1934 // match that of llvm-gcc and Apple GCC before that.
1935 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1937 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1940 bool EmbeddedPISupported;
1941 switch (Triple.getArch()) {
1942 case llvm::Triple::arm:
1943 case llvm::Triple::armeb:
1944 case llvm::Triple::thumb:
1945 case llvm::Triple::thumbeb:
1946 EmbeddedPISupported = true;
1947 break;
1948 default:
1949 EmbeddedPISupported = false;
1950 break;
1953 bool ROPI = false, RWPI = false;
1954 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1955 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1956 if (!EmbeddedPISupported)
1957 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1958 << LastROPIArg->getSpelling() << Triple.str();
1959 ROPI = true;
1961 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1962 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1963 if (!EmbeddedPISupported)
1964 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1965 << LastRWPIArg->getSpelling() << Triple.str();
1966 RWPI = true;
1969 // ROPI and RWPI are not compatible with PIC or PIE.
1970 if ((ROPI || RWPI) && (PIC || PIE))
1971 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1973 if (Triple.isMIPS()) {
1974 StringRef CPUName;
1975 StringRef ABIName;
1976 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1977 // When targeting the N64 ABI, PIC is the default, except in the case
1978 // when the -mno-abicalls option is used. In that case we exit
1979 // at next check regardless of PIC being set below.
1980 if (ABIName == "n64")
1981 PIC = true;
1982 // When targettng MIPS with -mno-abicalls, it's always static.
1983 if(Args.hasArg(options::OPT_mno_abicalls))
1984 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1985 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1986 // does not use PIC level 2 for historical reasons.
1987 IsPICLevelTwo = false;
1990 if (PIC)
1991 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1993 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1994 if (ROPI && RWPI)
1995 RelocM = llvm::Reloc::ROPI_RWPI;
1996 else if (ROPI)
1997 RelocM = llvm::Reloc::ROPI;
1998 else if (RWPI)
1999 RelocM = llvm::Reloc::RWPI;
2001 return std::make_tuple(RelocM, 0U, false);
2004 // `-falign-functions` indicates that the functions should be aligned to the
2005 // backend's preferred alignment.
2007 // `-falign-functions=1` is the same as `-fno-align-functions`.
2009 // The scalar `n` in `-falign-functions=n` must be an integral value between
2010 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
2011 // the nearest power-of-two.
2013 // If we return `0`, the frontend will default to the backend's preferred
2014 // alignment.
2016 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
2017 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
2018 // alignment. For unaligned functions, we default to the backend's preferred
2019 // alignment.
2020 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
2021 const ArgList &Args) {
2022 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
2023 options::OPT_falign_functions_EQ,
2024 options::OPT_fno_align_functions);
2025 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
2026 return 0;
2028 if (A->getOption().matches(options::OPT_falign_functions))
2029 return 0;
2031 unsigned Value = 0;
2032 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
2033 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
2034 << A->getAsString(Args) << A->getValue();
2035 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
2038 void tools::addDebugInfoKind(
2039 ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) {
2040 switch (DebugInfoKind) {
2041 case llvm::codegenoptions::DebugDirectivesOnly:
2042 CmdArgs.push_back("-debug-info-kind=line-directives-only");
2043 break;
2044 case llvm::codegenoptions::DebugLineTablesOnly:
2045 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2046 break;
2047 case llvm::codegenoptions::DebugInfoConstructor:
2048 CmdArgs.push_back("-debug-info-kind=constructor");
2049 break;
2050 case llvm::codegenoptions::LimitedDebugInfo:
2051 CmdArgs.push_back("-debug-info-kind=limited");
2052 break;
2053 case llvm::codegenoptions::FullDebugInfo:
2054 CmdArgs.push_back("-debug-info-kind=standalone");
2055 break;
2056 case llvm::codegenoptions::UnusedTypeInfo:
2057 CmdArgs.push_back("-debug-info-kind=unused-types");
2058 break;
2059 default:
2060 break;
2064 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2065 // to the corresponding DebugInfoKind.
2066 llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) {
2067 assert(A.getOption().matches(options::OPT_gN_Group) &&
2068 "Not a -g option that specifies a debug-info level");
2069 if (A.getOption().matches(options::OPT_g0) ||
2070 A.getOption().matches(options::OPT_ggdb0))
2071 return llvm::codegenoptions::NoDebugInfo;
2072 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2073 A.getOption().matches(options::OPT_ggdb1))
2074 return llvm::codegenoptions::DebugLineTablesOnly;
2075 if (A.getOption().matches(options::OPT_gline_directives_only))
2076 return llvm::codegenoptions::DebugDirectivesOnly;
2077 return llvm::codegenoptions::DebugInfoConstructor;
2080 static unsigned ParseDebugDefaultVersion(const ToolChain &TC,
2081 const ArgList &Args) {
2082 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
2084 if (!A)
2085 return 0;
2087 unsigned Value = 0;
2088 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
2089 Value < 2)
2090 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
2091 << A->getAsString(Args) << A->getValue();
2092 return Value;
2095 unsigned tools::DwarfVersionNum(StringRef ArgValue) {
2096 return llvm::StringSwitch<unsigned>(ArgValue)
2097 .Case("-gdwarf-2", 2)
2098 .Case("-gdwarf-3", 3)
2099 .Case("-gdwarf-4", 4)
2100 .Case("-gdwarf-5", 5)
2101 .Default(0);
2104 const Arg *tools::getDwarfNArg(const ArgList &Args) {
2105 return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2106 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
2107 options::OPT_gdwarf);
2110 unsigned tools::getDwarfVersion(const ToolChain &TC,
2111 const llvm::opt::ArgList &Args) {
2112 unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args);
2113 if (const Arg *GDwarfN = getDwarfNArg(Args))
2114 if (int N = DwarfVersionNum(GDwarfN->getSpelling())) {
2115 DwarfVersion = N;
2116 if (DwarfVersion == 5 && TC.getTriple().isOSAIX())
2117 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
2118 << GDwarfN->getSpelling() << TC.getTriple().str();
2120 if (DwarfVersion == 0) {
2121 DwarfVersion = TC.GetDefaultDwarfVersion();
2122 assert(DwarfVersion && "toolchain default DWARF version must be nonzero");
2124 return DwarfVersion;
2127 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
2128 ArgStringList &CmdArgs) {
2129 llvm::Reloc::Model RelocationModel;
2130 unsigned PICLevel;
2131 bool IsPIE;
2132 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
2134 if (RelocationModel != llvm::Reloc::Static)
2135 CmdArgs.push_back("-KPIC");
2138 /// Determine whether Objective-C automated reference counting is
2139 /// enabled.
2140 bool tools::isObjCAutoRefCount(const ArgList &Args) {
2141 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
2144 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
2146 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
2147 const ArgList &Args) {
2148 if (Args.hasArg(options::OPT_static_libgcc) ||
2149 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
2150 // The Android NDK only provides libunwind.a, not libunwind.so.
2151 TC.getTriple().isAndroid())
2152 return LibGccType::StaticLibGcc;
2153 if (Args.hasArg(options::OPT_shared_libgcc))
2154 return LibGccType::SharedLibGcc;
2155 return LibGccType::UnspecifiedLibGcc;
2158 // Gcc adds libgcc arguments in various ways:
2160 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
2161 // g++ <none>: -lgcc_s -lgcc
2162 // gcc shared: -lgcc_s -lgcc
2163 // g++ shared: -lgcc_s -lgcc
2164 // gcc static: -lgcc -lgcc_eh
2165 // g++ static: -lgcc -lgcc_eh
2166 // gcc static-pie: -lgcc -lgcc_eh
2167 // g++ static-pie: -lgcc -lgcc_eh
2169 // Also, certain targets need additional adjustments.
2171 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
2172 ArgStringList &CmdArgs, const ArgList &Args) {
2173 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
2174 // By default OHOS binaries are linked statically to libunwind.
2175 if (TC.getTriple().isOHOSFamily() && UNW == ToolChain::UNW_CompilerRT) {
2176 CmdArgs.push_back("-l:libunwind.a");
2177 return;
2180 // Targets that don't use unwind libraries.
2181 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
2182 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
2183 TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
2184 return;
2186 LibGccType LGT = getLibGccType(TC, D, Args);
2187 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
2188 (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
2189 !TC.getTriple().isAndroid() &&
2190 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
2191 if (AsNeeded)
2192 addAsNeededOption(TC, Args, CmdArgs, true);
2194 switch (UNW) {
2195 case ToolChain::UNW_None:
2196 return;
2197 case ToolChain::UNW_Libgcc: {
2198 if (LGT == LibGccType::StaticLibGcc)
2199 CmdArgs.push_back("-lgcc_eh");
2200 else
2201 CmdArgs.push_back("-lgcc_s");
2202 break;
2204 case ToolChain::UNW_CompilerRT:
2205 if (TC.getTriple().isOSAIX()) {
2206 // AIX only has libunwind as a shared library. So do not pass
2207 // anything in if -static is specified.
2208 if (LGT != LibGccType::StaticLibGcc)
2209 CmdArgs.push_back("-lunwind");
2210 } else if (LGT == LibGccType::StaticLibGcc) {
2211 CmdArgs.push_back("-l:libunwind.a");
2212 } else if (LGT == LibGccType::SharedLibGcc) {
2213 if (TC.getTriple().isOSCygMing())
2214 CmdArgs.push_back("-l:libunwind.dll.a");
2215 else
2216 CmdArgs.push_back("-l:libunwind.so");
2217 } else {
2218 // Let the linker choose between libunwind.so and libunwind.a
2219 // depending on what's available, and depending on the -static flag
2220 CmdArgs.push_back("-lunwind");
2222 break;
2225 if (AsNeeded)
2226 addAsNeededOption(TC, Args, CmdArgs, false);
2229 static void AddLibgcc(const ToolChain &TC, const Driver &D,
2230 ArgStringList &CmdArgs, const ArgList &Args) {
2231 LibGccType LGT = getLibGccType(TC, D, Args);
2232 if (LGT == LibGccType::StaticLibGcc ||
2233 (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
2234 CmdArgs.push_back("-lgcc");
2235 AddUnwindLibrary(TC, D, CmdArgs, Args);
2236 if (LGT == LibGccType::SharedLibGcc ||
2237 (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
2238 CmdArgs.push_back("-lgcc");
2241 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
2242 ArgStringList &CmdArgs, const ArgList &Args) {
2243 // Make use of compiler-rt if --rtlib option is used
2244 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
2246 switch (RLT) {
2247 case ToolChain::RLT_CompilerRT:
2248 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2249 AddUnwindLibrary(TC, D, CmdArgs, Args);
2250 break;
2251 case ToolChain::RLT_Libgcc:
2252 // Make sure libgcc is not used under MSVC environment by default
2253 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
2254 // Issue error diagnostic if libgcc is explicitly specified
2255 // through command line as --rtlib option argument.
2256 Arg *A = Args.getLastArg(options::OPT_rtlib_EQ);
2257 if (A && A->getValue() != StringRef("platform")) {
2258 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
2259 << A->getValue() << "MSVC";
2261 } else
2262 AddLibgcc(TC, D, CmdArgs, Args);
2263 break;
2266 // On Android, the unwinder uses dl_iterate_phdr (or one of
2267 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
2268 // statically-linked executables, these functions come from libc.a instead.
2269 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
2270 !Args.hasArg(options::OPT_static_pie))
2271 CmdArgs.push_back("-ldl");
2274 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
2275 const InputInfo &Output,
2276 const InputInfo &Input,
2277 const Driver &D) {
2278 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
2279 if (!A && !D.CCPrintInternalStats)
2280 return {};
2282 SmallString<128> StatsFile;
2283 if (A) {
2284 StringRef SaveStats = A->getValue();
2285 if (SaveStats == "obj" && Output.isFilename()) {
2286 StatsFile.assign(Output.getFilename());
2287 llvm::sys::path::remove_filename(StatsFile);
2288 } else if (SaveStats != "cwd") {
2289 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
2290 return {};
2293 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
2294 llvm::sys::path::append(StatsFile, BaseName);
2295 llvm::sys::path::replace_extension(StatsFile, "stats");
2296 } else {
2297 assert(D.CCPrintInternalStats);
2298 StatsFile.assign(D.CCPrintInternalStatReportFilename.empty()
2299 ? "-"
2300 : D.CCPrintInternalStatReportFilename);
2302 return StatsFile;
2305 void tools::addMultilibFlag(bool Enabled, const StringRef Flag,
2306 Multilib::flags_list &Flags) {
2307 assert(Flag.front() == '-');
2308 if (Enabled) {
2309 Flags.push_back(Flag.str());
2310 } else {
2311 Flags.push_back(("!" + Flag.substr(1)).str());
2315 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
2316 ArgStringList &CmdArgs, bool IsLTO,
2317 const StringRef PluginOptPrefix) {
2318 auto addArg = [&, IsLTO](const Twine &Arg) {
2319 if (IsLTO) {
2320 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2321 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2322 } else {
2323 CmdArgs.push_back("-mllvm");
2324 CmdArgs.push_back(Args.MakeArgString(Arg));
2328 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
2329 addArg(Twine("-x86-branches-within-32B-boundaries"));
2331 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
2332 StringRef Value = A->getValue();
2333 unsigned Boundary;
2334 if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
2335 !llvm::isPowerOf2_64(Boundary)) {
2336 D.Diag(diag::err_drv_invalid_argument_to_option)
2337 << Value << A->getOption().getName();
2338 } else {
2339 addArg("-x86-align-branch-boundary=" + Twine(Boundary));
2342 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
2343 std::string AlignBranch;
2344 for (StringRef T : A->getValues()) {
2345 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
2346 T != "ret" && T != "indirect")
2347 D.Diag(diag::err_drv_invalid_malign_branch_EQ)
2348 << T << "fused, jcc, jmp, call, ret, indirect";
2349 if (!AlignBranch.empty())
2350 AlignBranch += '+';
2351 AlignBranch += T;
2353 addArg("-x86-align-branch=" + Twine(AlignBranch));
2355 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
2356 StringRef Value = A->getValue();
2357 unsigned PrefixSize;
2358 if (Value.getAsInteger(10, PrefixSize)) {
2359 D.Diag(diag::err_drv_invalid_argument_to_option)
2360 << Value << A->getOption().getName();
2361 } else {
2362 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
2367 /// SDLSearch: Search for Static Device Library
2368 /// The search for SDL bitcode files is consistent with how static host
2369 /// libraries are discovered. That is, the -l option triggers a search for
2370 /// files in a set of directories called the LINKPATH. The host library search
2371 /// procedure looks for a specific filename in the LINKPATH. The filename for
2372 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
2373 /// ordered-set of filenames that are searched. We call this ordered-set of
2374 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
2375 /// architecture specific, or generic across all architectures, a naming
2376 /// convention and search order is used where the file name embeds the
2377 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
2378 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
2379 /// device-independent SDLs. To reduce congestion in host library directories,
2380 /// the search first looks for files in the “libdevice” subdirectory. SDLs that
2381 /// are bc files begin with the prefix “lib”.
2383 /// Machine-code SDLs can also be managed as an archive (*.a file). The
2384 /// convention has been to use the prefix “lib”. To avoid confusion with host
2385 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
2387 static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
2388 llvm::opt::ArgStringList &CC1Args,
2389 const SmallVectorImpl<std::string> &LibraryPaths,
2390 StringRef Lib, StringRef Arch, StringRef Target,
2391 bool isBitCodeSDL) {
2392 SmallVector<std::string, 12> SDLs;
2394 std::string LibDeviceLoc = "/libdevice";
2395 std::string LibBcPrefix = "/libbc-";
2396 std::string LibPrefix = "/lib";
2398 if (isBitCodeSDL) {
2399 // SEARCH-ORDER for Bitcode SDLs:
2400 // libdevice/libbc-<libname>-<arch-name>-<device-type>.a
2401 // libbc-<libname>-<arch-name>-<device-type>.a
2402 // libdevice/libbc-<libname>-<arch-name>.a
2403 // libbc-<libname>-<arch-name>.a
2404 // libdevice/libbc-<libname>.a
2405 // libbc-<libname>.a
2406 // libdevice/lib<libname>-<arch-name>-<device-type>.bc
2407 // lib<libname>-<arch-name>-<device-type>.bc
2408 // libdevice/lib<libname>-<arch-name>.bc
2409 // lib<libname>-<arch-name>.bc
2410 // libdevice/lib<libname>.bc
2411 // lib<libname>.bc
2413 for (StringRef Base : {LibBcPrefix, LibPrefix}) {
2414 const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
2416 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2417 Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
2418 SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
2419 SDLs.push_back(Twine(Base + Suffix + Ext).str());
2422 } else {
2423 // SEARCH-ORDER for Machine-code SDLs:
2424 // libdevice/lib<libname>-<arch-name>-<device-type>.a
2425 // lib<libname>-<arch-name>-<device-type>.a
2426 // libdevice/lib<libname>-<arch-name>.a
2427 // lib<libname>-<arch-name>.a
2429 const auto *Ext = ".a";
2431 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2432 Twine(Lib + "-" + Arch).str()}) {
2433 SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
2434 SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
2438 // The CUDA toolchain does not use a global device llvm-link before the LLVM
2439 // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
2440 // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
2441 // will link libraries after clang compilation while the LLVM IR is still in
2442 // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
2443 // This is a clang -cc1 option that is generated by the clang driver. The
2444 // option value must a full path to an existing file.
2445 bool FoundSDL = false;
2446 for (auto LPath : LibraryPaths) {
2447 for (auto SDL : SDLs) {
2448 auto FullName = Twine(LPath + SDL).str();
2449 if (llvm::sys::fs::exists(FullName)) {
2450 CC1Args.push_back(DriverArgs.MakeArgString(FullName));
2451 FoundSDL = true;
2452 break;
2455 if (FoundSDL)
2456 break;
2458 return FoundSDL;
2461 /// Search if a user provided archive file lib<libname>.a exists in any of
2462 /// the library paths. If so, add a new command to clang-offload-bundler to
2463 /// unbundle this archive and create a temporary device specific archive. Name
2464 /// of this SDL is passed to the llvm-link tool.
2465 static void GetSDLFromOffloadArchive(
2466 Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
2467 const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
2468 llvm::opt::ArgStringList &CC1Args,
2469 const SmallVectorImpl<std::string> &LibraryPaths, StringRef Lib,
2470 StringRef Arch, StringRef Target, bool isBitCodeSDL) {
2472 // We don't support bitcode archive bundles for nvptx
2473 if (isBitCodeSDL && Arch.contains("nvptx"))
2474 return;
2476 bool FoundAOB = false;
2477 std::string ArchiveOfBundles;
2479 llvm::Triple Triple(D.getTargetTriple());
2480 bool IsMSVC = Triple.isWindowsMSVCEnvironment();
2481 auto Ext = IsMSVC ? ".lib" : ".a";
2482 if (!Lib.starts_with(":") && !Lib.starts_with("-l")) {
2483 if (llvm::sys::fs::exists(Lib)) {
2484 ArchiveOfBundles = Lib;
2485 FoundAOB = true;
2487 } else {
2488 Lib.consume_front("-l");
2489 for (auto LPath : LibraryPaths) {
2490 ArchiveOfBundles.clear();
2491 auto LibFile = (Lib.starts_with(":") ? Lib.drop_front()
2492 : IsMSVC ? Lib + Ext
2493 : "lib" + Lib + Ext)
2494 .str();
2495 for (auto Prefix : {"/libdevice/", "/"}) {
2496 auto AOB = Twine(LPath + Prefix + LibFile).str();
2497 if (llvm::sys::fs::exists(AOB)) {
2498 ArchiveOfBundles = AOB;
2499 FoundAOB = true;
2500 break;
2503 if (FoundAOB)
2504 break;
2508 if (!FoundAOB)
2509 return;
2511 llvm::file_magic Magic;
2512 auto EC = llvm::identify_magic(ArchiveOfBundles, Magic);
2513 if (EC || Magic != llvm::file_magic::archive)
2514 return;
2516 StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
2517 std::string OutputLib =
2518 D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" +
2519 Arch + "-" + Target)
2520 .str(),
2521 "a");
2523 C.addTempFile(C.getArgs().MakeArgString(OutputLib));
2525 ArgStringList CmdArgs;
2526 SmallString<128> DeviceTriple;
2527 DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind());
2528 DeviceTriple += '-';
2529 std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
2530 DeviceTriple += NormalizedTriple;
2531 if (!Target.empty()) {
2532 DeviceTriple += '-';
2533 DeviceTriple += Target;
2536 std::string UnbundleArg("-unbundle");
2537 std::string TypeArg("-type=a");
2538 std::string InputArg("-input=" + ArchiveOfBundles);
2539 std::string OffloadArg("-targets=" + std::string(DeviceTriple));
2540 std::string OutputArg("-output=" + OutputLib);
2542 const char *UBProgram = DriverArgs.MakeArgString(
2543 T.getToolChain().GetProgramPath("clang-offload-bundler"));
2545 ArgStringList UBArgs;
2546 UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
2547 UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
2548 UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
2549 UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
2550 UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
2552 // Add this flag to not exit from clang-offload-bundler if no compatible
2553 // code object is found in heterogenous archive library.
2554 std::string AdditionalArgs("-allow-missing-bundles");
2555 UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
2557 // Add this flag to treat hip and hipv4 offload kinds as compatible with
2558 // openmp offload kind while extracting code objects from a heterogenous
2559 // archive library. Vice versa is also considered compatible.
2560 std::string HipCompatibleArgs("-hip-openmp-compatible");
2561 UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
2563 C.addCommand(std::make_unique<Command>(
2564 JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
2565 InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
2567 CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
2569 return;
2572 // Wrapper function used by driver for adding SDLs during link phase.
2573 void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T,
2574 const JobAction &JA,
2575 const InputInfoList &Inputs,
2576 const llvm::opt::ArgList &DriverArgs,
2577 llvm::opt::ArgStringList &CC1Args,
2578 StringRef Arch, StringRef Target,
2579 bool isBitCodeSDL) {
2580 AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
2581 Arch, Target, isBitCodeSDL);
2584 // User defined Static Device Libraries(SDLs) can be passed to clang for
2585 // offloading GPU compilers. Like static host libraries, the use of a SDL is
2586 // specified with the -l command line option. The primary difference between
2587 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
2588 // and SEARCH-ORDER for Machine-code SDLs for the naming convention).
2589 // SDLs are of following types:
2591 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
2592 // For NVPTX, these libraries are post-clang linked following each
2593 // compilation. For AMDGPU, these libraries are linked one time
2594 // during the application link phase.
2596 // * Machine-code SDLs: They are archive files. For AMDGPU, the process for
2597 // machine code SDLs is still in development. But they will be linked
2598 // by the LLVM tool lld.
2600 // * Bundled objects that contain both host and device codes: Bundled objects
2601 // may also contain library code compiled from source. For NVPTX, the
2602 // bundle contains cubin. For AMDGPU, the bundle contains bitcode.
2604 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
2605 // inclusion of specific SDLs such as math libraries and the OpenMP device
2606 // library libomptarget.
2607 void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T,
2608 const JobAction *JA,
2609 const InputInfoList *Inputs, const Driver &D,
2610 const llvm::opt::ArgList &DriverArgs,
2611 llvm::opt::ArgStringList &CC1Args,
2612 StringRef Arch, StringRef Target,
2613 bool isBitCodeSDL) {
2615 SmallVector<std::string, 8> LibraryPaths;
2616 // Add search directories from LIBRARY_PATH env variable
2617 std::optional<std::string> LibPath =
2618 llvm::sys::Process::GetEnv("LIBRARY_PATH");
2619 if (LibPath) {
2620 SmallVector<StringRef, 8> Frags;
2621 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2622 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2623 for (StringRef Path : Frags)
2624 LibraryPaths.emplace_back(Path.trim());
2627 // Add directories from user-specified -L options
2628 for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
2629 LibraryPaths.emplace_back(Search_Dir);
2631 // Add path to lib-debug folders
2632 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2633 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
2634 LibraryPaths.emplace_back(DefaultLibPath.c_str());
2636 // Build list of Static Device Libraries SDLs specified by -l option
2637 llvm::SmallSet<std::string, 16> SDLNames;
2638 static const StringRef HostOnlyArchives[] = {
2639 "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
2640 for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
2641 if (!llvm::is_contained(HostOnlyArchives, SDLName)) {
2642 SDLNames.insert(std::string("-l") + SDLName);
2646 for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) {
2647 auto FileName = StringRef(Input);
2648 // Clang treats any unknown file types as archives and passes them to the
2649 // linker. Files with extension 'lib' are classified as TY_Object by clang
2650 // but they are usually archives. It is OK if the file is not really an
2651 // archive since GetSDLFromOffloadArchive will check the magic of the file
2652 // and only unbundle it if it is really an archive.
2653 const StringRef LibFileExt = ".lib";
2654 if (!llvm::sys::path::has_extension(FileName) ||
2655 types::lookupTypeForExtension(
2656 llvm::sys::path::extension(FileName).drop_front()) ==
2657 types::TY_INVALID ||
2658 llvm::sys::path::extension(FileName) == LibFileExt)
2659 SDLNames.insert(Input);
2662 // The search stops as soon as an SDL file is found. The driver then provides
2663 // the full filename of the SDL to the llvm-link command. If no SDL is found
2664 // after searching each LINKPATH with SEARCH-ORDER, it is possible that an
2665 // archive file lib<libname>.a exists and may contain bundled object files.
2666 for (auto SDLName : SDLNames) {
2667 // This is the only call to SDLSearch
2668 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
2669 isBitCodeSDL)) {
2670 GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
2671 LibraryPaths, SDLName, Arch, Target,
2672 isBitCodeSDL);
2677 static llvm::opt::Arg *
2678 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
2679 return Args.getLastArg(options::OPT_mcode_object_version_EQ);
2682 void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
2683 const llvm::opt::ArgList &Args) {
2684 const unsigned MinCodeObjVer = 4;
2685 const unsigned MaxCodeObjVer = 6;
2687 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2688 if (CodeObjArg->getOption().getID() ==
2689 options::OPT_mcode_object_version_EQ) {
2690 unsigned CodeObjVer = MaxCodeObjVer;
2691 auto Remnant =
2692 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2693 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
2694 D.Diag(diag::err_drv_invalid_int_value)
2695 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
2697 // COV6 is only supported by LLVM at the time of writing this, and it's
2698 // expected to take some time before all ROCm components fully
2699 // support it. In the meantime, make sure users are aware of this.
2700 if (CodeObjVer == 6)
2701 D.Diag(diag::warn_drv_amdgpu_cov6);
2706 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
2707 const llvm::opt::ArgList &Args) {
2708 unsigned CodeObjVer = 5; // default
2709 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args))
2710 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2711 return CodeObjVer;
2714 bool tools::haveAMDGPUCodeObjectVersionArgument(
2715 const Driver &D, const llvm::opt::ArgList &Args) {
2716 return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2719 void tools::addMachineOutlinerArgs(const Driver &D,
2720 const llvm::opt::ArgList &Args,
2721 llvm::opt::ArgStringList &CmdArgs,
2722 const llvm::Triple &Triple, bool IsLTO,
2723 const StringRef PluginOptPrefix) {
2724 auto addArg = [&, IsLTO](const Twine &Arg) {
2725 if (IsLTO) {
2726 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2727 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2728 } else {
2729 CmdArgs.push_back("-mllvm");
2730 CmdArgs.push_back(Args.MakeArgString(Arg));
2734 if (Arg *A = Args.getLastArg(options::OPT_moutline,
2735 options::OPT_mno_outline)) {
2736 if (A->getOption().matches(options::OPT_moutline)) {
2737 // We only support -moutline in AArch64 and ARM targets right now. If
2738 // we're not compiling for these, emit a warning and ignore the flag.
2739 // Otherwise, add the proper mllvm flags.
2740 if (!(Triple.isARM() || Triple.isThumb() || Triple.isAArch64())) {
2741 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2742 } else {
2743 addArg(Twine("-enable-machine-outliner"));
2745 } else {
2746 // Disable all outlining behaviour.
2747 addArg(Twine("-enable-machine-outliner=never"));
2751 auto *CodeGenDataGenArg =
2752 Args.getLastArg(options::OPT_fcodegen_data_generate_EQ);
2753 auto *CodeGenDataUseArg = Args.getLastArg(options::OPT_fcodegen_data_use_EQ);
2755 // We only allow one of them to be specified.
2756 if (CodeGenDataGenArg && CodeGenDataUseArg)
2757 D.Diag(diag::err_drv_argument_not_allowed_with)
2758 << CodeGenDataGenArg->getAsString(Args)
2759 << CodeGenDataUseArg->getAsString(Args);
2761 // For codegen data gen, the output file is passed to the linker
2762 // while a boolean flag is passed to the LLVM backend.
2763 if (CodeGenDataGenArg)
2764 addArg(Twine("-codegen-data-generate"));
2766 // For codegen data use, the input file is passed to the LLVM backend.
2767 if (CodeGenDataUseArg)
2768 addArg(Twine("-codegen-data-use-path=") + CodeGenDataUseArg->getValue());
2771 void tools::addOpenMPDeviceRTL(const Driver &D,
2772 const llvm::opt::ArgList &DriverArgs,
2773 llvm::opt::ArgStringList &CC1Args,
2774 StringRef BitcodeSuffix,
2775 const llvm::Triple &Triple,
2776 const ToolChain &HostTC) {
2777 SmallVector<StringRef, 8> LibraryPaths;
2779 // Add user defined library paths from LIBRARY_PATH.
2780 std::optional<std::string> LibPath =
2781 llvm::sys::Process::GetEnv("LIBRARY_PATH");
2782 if (LibPath) {
2783 SmallVector<StringRef, 8> Frags;
2784 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2785 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2786 for (StringRef Path : Frags)
2787 LibraryPaths.emplace_back(Path.trim());
2790 // Check all of the standard library search paths used by the compiler.
2791 for (const auto &LibPath : HostTC.getFilePaths())
2792 LibraryPaths.emplace_back(LibPath);
2794 OptSpecifier LibomptargetBCPathOpt =
2795 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2796 : options::OPT_libomptarget_nvptx_bc_path_EQ;
2798 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2799 std::string LibOmpTargetName =
2800 ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2802 // First check whether user specifies bc library
2803 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2804 SmallString<128> LibOmpTargetFile(A->getValue());
2805 if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2806 llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2807 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2810 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2811 CC1Args.push_back("-mlink-builtin-bitcode");
2812 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2813 } else {
2814 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2815 << LibOmpTargetFile;
2817 } else {
2818 bool FoundBCLibrary = false;
2820 for (StringRef LibraryPath : LibraryPaths) {
2821 SmallString<128> LibOmpTargetFile(LibraryPath);
2822 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2823 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2824 CC1Args.push_back("-mlink-builtin-bitcode");
2825 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2826 FoundBCLibrary = true;
2827 break;
2831 if (!FoundBCLibrary)
2832 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2833 << LibOmpTargetName << ArchPrefix;
2836 void tools::addHIPRuntimeLibArgs(const ToolChain &TC, Compilation &C,
2837 const llvm::opt::ArgList &Args,
2838 llvm::opt::ArgStringList &CmdArgs) {
2839 if ((C.getActiveOffloadKinds() & Action::OFK_HIP) &&
2840 !Args.hasArg(options::OPT_nostdlib) &&
2841 !Args.hasArg(options::OPT_no_hip_rt) && !Args.hasArg(options::OPT_r)) {
2842 TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2843 } else {
2844 // Claim "no HIP libraries" arguments if any
2845 for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) {
2846 Arg->claim();
2851 void tools::addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC,
2852 const llvm::opt::ArgList &Args,
2853 llvm::opt::ArgStringList &CmdArgs,
2854 const llvm::Triple &Triple) {
2855 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
2856 options::OPT_mno_outline_atomics)) {
2857 // Option -moutline-atomics supported for AArch64 target only.
2858 if (!Triple.isAArch64()) {
2859 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
2860 << Triple.getArchName() << A->getOption().getName();
2861 } else {
2862 if (A->getOption().matches(options::OPT_moutline_atomics)) {
2863 CmdArgs.push_back("-target-feature");
2864 CmdArgs.push_back("+outline-atomics");
2865 } else {
2866 CmdArgs.push_back("-target-feature");
2867 CmdArgs.push_back("-outline-atomics");
2870 } else if (Triple.isAArch64() && TC.IsAArch64OutlineAtomicsDefault(Args)) {
2871 CmdArgs.push_back("-target-feature");
2872 CmdArgs.push_back("+outline-atomics");
2876 void tools::addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs,
2877 llvm::opt::ArgStringList &CmdArgs) {
2878 if (TCArgs.hasFlag(options::OPT_offload_compress,
2879 options::OPT_no_offload_compress, false))
2880 CmdArgs.push_back("-compress");
2881 if (TCArgs.hasArg(options::OPT_v))
2882 CmdArgs.push_back("-verbose");
2883 if (auto *Arg = TCArgs.getLastArg(options::OPT_offload_compression_level_EQ))
2884 CmdArgs.push_back(
2885 TCArgs.MakeArgString(Twine("-compression-level=") + Arg->getValue()));
2888 void tools::addMCModel(const Driver &D, const llvm::opt::ArgList &Args,
2889 const llvm::Triple &Triple,
2890 const llvm::Reloc::Model &RelocationModel,
2891 llvm::opt::ArgStringList &CmdArgs) {
2892 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2893 StringRef CM = A->getValue();
2894 bool Ok = false;
2895 if (Triple.isOSAIX() && CM == "medium")
2896 CM = "large";
2897 if (Triple.isAArch64(64)) {
2898 Ok = CM == "tiny" || CM == "small" || CM == "large";
2899 if (CM == "large" && !Triple.isOSBinFormatMachO() &&
2900 RelocationModel != llvm::Reloc::Static)
2901 D.Diag(diag::err_drv_argument_only_allowed_with)
2902 << A->getAsString(Args) << "-fno-pic";
2903 } else if (Triple.isLoongArch()) {
2904 if (CM == "extreme" &&
2905 Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false))
2906 D.Diag(diag::err_drv_argument_not_allowed_with)
2907 << A->getAsString(Args) << "-fplt";
2908 Ok = CM == "normal" || CM == "medium" || CM == "extreme";
2909 // Convert to LLVM recognizable names.
2910 if (Ok)
2911 CM = llvm::StringSwitch<StringRef>(CM)
2912 .Case("normal", "small")
2913 .Case("extreme", "large")
2914 .Default(CM);
2915 } else if (Triple.isPPC64() || Triple.isOSAIX()) {
2916 Ok = CM == "small" || CM == "medium" || CM == "large";
2917 } else if (Triple.isRISCV()) {
2918 // Large code model is disallowed to be used with PIC code model.
2919 if (CM == "large" && RelocationModel != llvm::Reloc::Static)
2920 D.Diag(diag::err_drv_argument_not_allowed_with)
2921 << A->getAsString(Args) << "-fpic";
2922 if (CM == "medlow")
2923 CM = "small";
2924 else if (CM == "medany")
2925 CM = "medium";
2926 Ok = CM == "small" || CM == "medium" ||
2927 (CM == "large" && Triple.isRISCV64());
2928 } else if (Triple.getArch() == llvm::Triple::x86_64) {
2929 Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"},
2930 CM);
2931 } else if (Triple.isNVPTX() || Triple.isAMDGPU() || Triple.isSPIRV()) {
2932 // NVPTX/AMDGPU/SPIRV does not care about the code model and will accept
2933 // whatever works for the host.
2934 Ok = true;
2935 } else if (Triple.isSPARC64()) {
2936 if (CM == "medlow")
2937 CM = "small";
2938 else if (CM == "medmid")
2939 CM = "medium";
2940 else if (CM == "medany")
2941 CM = "large";
2942 Ok = CM == "small" || CM == "medium" || CM == "large";
2944 if (Ok) {
2945 CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM));
2946 } else {
2947 D.Diag(diag::err_drv_unsupported_option_argument_for_target)
2948 << A->getSpelling() << CM << Triple.getTriple();
2952 if (Triple.getArch() == llvm::Triple::x86_64) {
2953 bool IsMediumCM = false;
2954 bool IsLargeCM = false;
2955 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2956 IsMediumCM = StringRef(A->getValue()) == "medium";
2957 IsLargeCM = StringRef(A->getValue()) == "large";
2959 if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) {
2960 if (!IsMediumCM && !IsLargeCM) {
2961 D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model)
2962 << A->getOption().getRenderName();
2963 } else {
2964 A->render(Args, CmdArgs);
2966 } else if (IsMediumCM) {
2967 CmdArgs.push_back("-mlarge-data-threshold=65536");
2968 } else if (IsLargeCM) {
2969 CmdArgs.push_back("-mlarge-data-threshold=0");
2974 void tools::handleColorDiagnosticsArgs(const Driver &D, const ArgList &Args,
2975 ArgStringList &CmdArgs) {
2976 // Color diagnostics are parsed by the driver directly from argv and later
2977 // re-parsed to construct this job; claim any possible color diagnostic here
2978 // to avoid warn_drv_unused_argument and diagnose bad
2979 // OPT_fdiagnostics_color_EQ values.
2980 Args.getLastArg(options::OPT_fcolor_diagnostics,
2981 options::OPT_fno_color_diagnostics);
2982 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
2983 StringRef Value(A->getValue());
2984 if (Value != "always" && Value != "never" && Value != "auto")
2985 D.Diag(diag::err_drv_invalid_argument_to_option)
2986 << Value << A->getOption().getName();
2989 if (D.getDiags().getDiagnosticOptions().ShowColors)
2990 CmdArgs.push_back("-fcolor-diagnostics");
2993 void tools::escapeSpacesAndBackslashes(const char *Arg,
2994 llvm::SmallVectorImpl<char> &Res) {
2995 for (; *Arg; ++Arg) {
2996 switch (*Arg) {
2997 default:
2998 break;
2999 case ' ':
3000 case '\\':
3001 Res.push_back('\\');
3002 break;
3004 Res.push_back(*Arg);
3008 const char *tools::renderEscapedCommandLine(const ToolChain &TC,
3009 const llvm::opt::ArgList &Args) {
3010 const Driver &D = TC.getDriver();
3011 const char *Exec = D.getClangProgramPath();
3013 llvm::opt::ArgStringList OriginalArgs;
3014 for (const auto &Arg : Args)
3015 Arg->render(Args, OriginalArgs);
3017 llvm::SmallString<256> Flags;
3018 escapeSpacesAndBackslashes(Exec, Flags);
3019 for (const char *OriginalArg : OriginalArgs) {
3020 llvm::SmallString<128> EscapedArg;
3021 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
3022 Flags += " ";
3023 Flags += EscapedArg;
3026 return Args.MakeArgString(Flags);
3029 bool tools::shouldRecordCommandLine(const ToolChain &TC,
3030 const llvm::opt::ArgList &Args,
3031 bool &FRecordCommandLine,
3032 bool &GRecordCommandLine) {
3033 const Driver &D = TC.getDriver();
3034 const llvm::Triple &Triple = TC.getEffectiveTriple();
3035 const std::string &TripleStr = Triple.getTriple();
3037 FRecordCommandLine =
3038 Args.hasFlag(options::OPT_frecord_command_line,
3039 options::OPT_fno_record_command_line, false);
3040 GRecordCommandLine =
3041 Args.hasFlag(options::OPT_grecord_command_line,
3042 options::OPT_gno_record_command_line, false);
3043 if (FRecordCommandLine && !Triple.isOSBinFormatELF() &&
3044 !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
3045 D.Diag(diag::err_drv_unsupported_opt_for_target)
3046 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
3047 << TripleStr;
3049 return FRecordCommandLine || TC.UseDwarfDebugFlags() || GRecordCommandLine;
3052 void tools::renderCommonIntegerOverflowOptions(const ArgList &Args,
3053 ArgStringList &CmdArgs) {
3054 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3055 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3056 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3057 if (A->getOption().matches(options::OPT_fwrapv))
3058 CmdArgs.push_back("-fwrapv");
3059 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3060 options::OPT_fno_strict_overflow)) {
3061 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3062 CmdArgs.push_back("-fwrapv");