clang 19.0.0git
CommonArgs.cpp
Go to the documentation of this file.
1//===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "CommonArgs.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/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"
30#include "clang/Basic/Version.h"
31#include "clang/Config/config.h"
32#include "clang/Driver/Action.h"
34#include "clang/Driver/Driver.h"
37#include "clang/Driver/Job.h"
41#include "clang/Driver/Util.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/TargetParser.h"
68#include <optional>
69
70using namespace clang::driver;
71using namespace clang::driver::tools;
72using namespace clang;
73using namespace llvm::opt;
74
75static bool useFramePointerForTargetByDefault(const llvm::opt::ArgList &Args,
76 const llvm::Triple &Triple) {
77 if (Args.hasArg(clang::driver::options::OPT_pg) &&
78 !Args.hasArg(clang::driver::options::OPT_mfentry))
79 return true;
80
81 if (Triple.isAndroid()) {
82 switch (Triple.getArch()) {
83 case llvm::Triple::aarch64:
84 case llvm::Triple::arm:
85 case llvm::Triple::armeb:
86 case llvm::Triple::thumb:
87 case llvm::Triple::thumbeb:
88 case llvm::Triple::riscv64:
89 return true;
90 default:
91 break;
92 }
93 }
94
95 switch (Triple.getArch()) {
96 case llvm::Triple::xcore:
97 case llvm::Triple::wasm32:
98 case llvm::Triple::wasm64:
99 case llvm::Triple::msp430:
100 // XCore never wants frame pointers, regardless of OS.
101 // WebAssembly never wants frame pointers.
102 return false;
103 case llvm::Triple::ppc:
104 case llvm::Triple::ppcle:
105 case llvm::Triple::ppc64:
106 case llvm::Triple::ppc64le:
107 case llvm::Triple::riscv32:
108 case llvm::Triple::riscv64:
109 case llvm::Triple::sparc:
110 case llvm::Triple::sparcel:
111 case llvm::Triple::sparcv9:
112 case llvm::Triple::amdgcn:
113 case llvm::Triple::r600:
114 case llvm::Triple::csky:
115 case llvm::Triple::loongarch32:
116 case llvm::Triple::loongarch64:
117 case llvm::Triple::m68k:
119 default:
120 break;
121 }
122
123 if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
125 }
126
127 if (Triple.isOSLinux() || Triple.isOSHurd()) {
128 switch (Triple.getArch()) {
129 // Don't use a frame pointer on linux if optimizing for certain targets.
130 case llvm::Triple::arm:
131 case llvm::Triple::armeb:
132 case llvm::Triple::thumb:
133 case llvm::Triple::thumbeb:
134 case llvm::Triple::mips64:
135 case llvm::Triple::mips64el:
136 case llvm::Triple::mips:
137 case llvm::Triple::mipsel:
138 case llvm::Triple::systemz:
139 case llvm::Triple::x86:
140 case llvm::Triple::x86_64:
142 default:
143 return true;
144 }
145 }
146
147 if (Triple.isOSWindows()) {
148 switch (Triple.getArch()) {
149 case llvm::Triple::x86:
151 case llvm::Triple::x86_64:
152 return Triple.isOSBinFormatMachO();
153 case llvm::Triple::arm:
154 case llvm::Triple::thumb:
155 // Windows on ARM builds with FPO disabled to aid fast stack walking
156 return true;
157 default:
158 // All other supported Windows ISAs use xdata unwind information, so frame
159 // pointers are not generally useful.
160 return false;
161 }
162 }
163
164 return true;
165}
166
167static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
168 switch (Triple.getArch()) {
169 default:
170 return false;
171 case llvm::Triple::arm:
172 case llvm::Triple::thumb:
173 // ARM Darwin targets require a frame pointer to be always present to aid
174 // offline debugging via backtraces.
175 return Triple.isOSDarwin();
176 }
177}
178
180getFramePointerKind(const llvm::opt::ArgList &Args,
181 const llvm::Triple &Triple) {
182 // We have 4 states:
183 //
184 // 00) leaf retained, non-leaf retained
185 // 01) leaf retained, non-leaf omitted (this is invalid)
186 // 10) leaf omitted, non-leaf retained
187 // (what -momit-leaf-frame-pointer was designed for)
188 // 11) leaf omitted, non-leaf omitted
189 //
190 // "omit" options taking precedence over "no-omit" options is the only way
191 // to make 3 valid states representable
192 llvm::opt::Arg *A =
193 Args.getLastArg(clang::driver::options::OPT_fomit_frame_pointer,
194 clang::driver::options::OPT_fno_omit_frame_pointer);
195
196 bool OmitFP = A && A->getOption().matches(
197 clang::driver::options::OPT_fomit_frame_pointer);
198 bool NoOmitFP = A && A->getOption().matches(
199 clang::driver::options::OPT_fno_omit_frame_pointer);
200 bool OmitLeafFP =
201 Args.hasFlag(clang::driver::options::OPT_momit_leaf_frame_pointer,
202 clang::driver::options::OPT_mno_omit_leaf_frame_pointer,
203 Triple.isAArch64() || Triple.isPS() || Triple.isVE() ||
204 (Triple.isAndroid() && Triple.isRISCV64()));
205 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
206 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
207 if (OmitLeafFP)
210 }
212}
213
214static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs,
215 const StringRef PluginOptPrefix) {
216 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
217 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
218 "-pass-remarks=" + A->getValue()));
219
220 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
221 CmdArgs.push_back(Args.MakeArgString(
222 Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue()));
223
224 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
225 CmdArgs.push_back(Args.MakeArgString(
226 Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue()));
227}
228
229static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
230 const llvm::Triple &Triple,
231 const InputInfo &Input,
232 const InputInfo &Output,
233 const StringRef PluginOptPrefix) {
234 StringRef Format = "yaml";
235 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
236 Format = A->getValue();
237
239 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
240 if (A)
241 F = A->getValue();
242 else if (Output.isFilename())
243 F = Output.getFilename();
244
245 assert(!F.empty() && "Cannot determine remarks output name.");
246 // Append "opt.ld.<format>" to the end of the file name.
247 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
248 "opt-remarks-filename=" + F +
249 ".opt.ld." + Format));
250
251 if (const Arg *A =
252 Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
253 CmdArgs.push_back(Args.MakeArgString(
254 Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue()));
255
256 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
257 "opt-remarks-format=" + Format.data()));
258}
259
260static void renderRemarksHotnessOptions(const ArgList &Args,
261 ArgStringList &CmdArgs,
262 const StringRef PluginOptPrefix) {
263 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
264 options::OPT_fno_diagnostics_show_hotness, false))
265 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
266 "opt-remarks-with-hotness"));
267
268 if (const Arg *A =
269 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
270 CmdArgs.push_back(
271 Args.MakeArgString(Twine(PluginOptPrefix) +
272 "opt-remarks-hotness-threshold=" + A->getValue()));
273}
274
275static bool shouldIgnoreUnsupportedTargetFeature(const Arg &TargetFeatureArg,
276 llvm::Triple T,
277 StringRef Processor) {
278 // Warn no-cumode for AMDGCN processors not supporing WGP mode.
279 if (!T.isAMDGPU())
280 return false;
281 auto GPUKind = T.isAMDGCN() ? llvm::AMDGPU::parseArchAMDGCN(Processor)
282 : llvm::AMDGPU::parseArchR600(Processor);
283 auto GPUFeatures = T.isAMDGCN() ? llvm::AMDGPU::getArchAttrAMDGCN(GPUKind)
284 : llvm::AMDGPU::getArchAttrR600(GPUKind);
285 if (GPUFeatures & llvm::AMDGPU::FEATURE_WGP)
286 return false;
287 return TargetFeatureArg.getOption().matches(options::OPT_mno_cumode);
288}
289
290void tools::addPathIfExists(const Driver &D, const Twine &Path,
291 ToolChain::path_list &Paths) {
292 if (D.getVFS().exists(Path))
293 Paths.push_back(Path.str());
294}
295
297 const llvm::Triple &Triple,
298 const ArgList &Args,
299 std::vector<StringRef> &Features,
300 OptSpecifier Group) {
301 std::set<StringRef> Warned;
302 for (const Arg *A : Args.filtered(Group)) {
303 StringRef Name = A->getOption().getName();
304 A->claim();
305
306 // Skip over "-m".
307 assert(Name.starts_with("m") && "Invalid feature name.");
308 Name = Name.substr(1);
309
310 auto Proc = getCPUName(D, Args, Triple);
311 if (shouldIgnoreUnsupportedTargetFeature(*A, Triple, Proc)) {
312 if (Warned.count(Name) == 0) {
313 D.getDiags().Report(
314 clang::diag::warn_drv_unsupported_option_for_processor)
315 << A->getAsString(Args) << Proc;
316 Warned.insert(Name);
317 }
318 continue;
319 }
320
321 bool IsNegative = Name.consume_front("no-");
322
323 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
324 }
325}
326
329 // Only add a feature if it hasn't been seen before starting from the end.
330 SmallVector<StringRef> UnifiedFeatures;
331 llvm::DenseSet<StringRef> UsedFeatures;
332 for (StringRef Feature : llvm::reverse(Features)) {
333 if (UsedFeatures.insert(Feature.drop_front()).second)
334 UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature);
335 }
336
337 return UnifiedFeatures;
338}
339
340void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
341 const char *ArgName, const char *EnvVar) {
342 const char *DirList = ::getenv(EnvVar);
343 bool CombinedArg = false;
344
345 if (!DirList)
346 return; // Nothing to do.
347
348 StringRef Name(ArgName);
349 if (Name.equals("-I") || Name.equals("-L") || Name.empty())
350 CombinedArg = true;
351
352 StringRef Dirs(DirList);
353 if (Dirs.empty()) // Empty string should not add '.'.
354 return;
355
356 StringRef::size_type Delim;
357 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
358 if (Delim == 0) { // Leading colon.
359 if (CombinedArg) {
360 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
361 } else {
362 CmdArgs.push_back(ArgName);
363 CmdArgs.push_back(".");
364 }
365 } else {
366 if (CombinedArg) {
367 CmdArgs.push_back(
368 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
369 } else {
370 CmdArgs.push_back(ArgName);
371 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
372 }
373 }
374 Dirs = Dirs.substr(Delim + 1);
375 }
376
377 if (Dirs.empty()) { // Trailing colon.
378 if (CombinedArg) {
379 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
380 } else {
381 CmdArgs.push_back(ArgName);
382 CmdArgs.push_back(".");
383 }
384 } else { // Add the last path.
385 if (CombinedArg) {
386 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
387 } else {
388 CmdArgs.push_back(ArgName);
389 CmdArgs.push_back(Args.MakeArgString(Dirs));
390 }
391 }
392}
393
394void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
395 const ArgList &Args, ArgStringList &CmdArgs,
396 const JobAction &JA) {
397 const Driver &D = TC.getDriver();
398
399 // Add extra linker input arguments which are not treated as inputs
400 // (constructed via -Xarch_).
401 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
402
403 // LIBRARY_PATH are included before user inputs and only supported on native
404 // toolchains.
405 if (!TC.isCrossCompiling())
406 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
407
408 for (const auto &II : Inputs) {
409 // If the current tool chain refers to an OpenMP offloading host, we
410 // should ignore inputs that refer to OpenMP offloading devices -
411 // they will be embedded according to a proper linker script.
412 if (auto *IA = II.getAction())
414 IA->isDeviceOffloading(Action::OFK_OpenMP)))
415 continue;
416
417 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
418 // Don't try to pass LLVM inputs unless we have native support.
419 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
420
421 // Add filenames immediately.
422 if (II.isFilename()) {
423 CmdArgs.push_back(II.getFilename());
424 continue;
425 }
426
427 // In some error cases, the input could be Nothing; skip those.
428 if (II.isNothing())
429 continue;
430
431 // Otherwise, this is a linker input argument.
432 const Arg &A = II.getInputArg();
433
434 // Handle reserved library options.
435 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
436 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
437 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
438 TC.AddCCKextLibArgs(Args, CmdArgs);
439 else
440 A.renderAsInput(Args, CmdArgs);
441 }
442}
443
445 const ToolChain &TC, const llvm::opt::ArgList &Args,
446 llvm::opt::ArgStringList &CmdArgs) {
447 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
448 // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
449 // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
450 // is not translated since ld --compress-debug-sections option requires an
451 // argument.
452 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
453 StringRef V = A->getValue();
454 if (V == "none" || V == "zlib" || V == "zstd")
455 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
456 else
457 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
458 << A->getSpelling() << V;
459 }
460}
461
462void tools::AddTargetFeature(const ArgList &Args,
463 std::vector<StringRef> &Features,
464 OptSpecifier OnOpt, OptSpecifier OffOpt,
465 StringRef FeatureName) {
466 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
467 if (A->getOption().matches(OnOpt))
468 Features.push_back(Args.MakeArgString("+" + FeatureName));
469 else
470 Features.push_back(Args.MakeArgString("-" + FeatureName));
471 }
472}
473
474/// Get the (LLVM) name of the AMDGPU gpu we are targeting.
475static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
476 const ArgList &Args) {
477 Arg *MArch = Args.getLastArg(options::OPT_march_EQ);
478 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
479 auto GPUName = getProcessorFromTargetID(T, A->getValue());
480 return llvm::StringSwitch<std::string>(GPUName)
481 .Cases("rv630", "rv635", "r600")
482 .Cases("rv610", "rv620", "rs780", "rs880")
483 .Case("rv740", "rv770")
484 .Case("palm", "cedar")
485 .Cases("sumo", "sumo2", "sumo")
486 .Case("hemlock", "cypress")
487 .Case("aruba", "cayman")
488 .Default(GPUName.str());
489 }
490 if (MArch)
491 return getProcessorFromTargetID(T, MArch->getValue()).str();
492 return "";
493}
494
495static std::string getLanaiTargetCPU(const ArgList &Args) {
496 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
497 return A->getValue();
498 }
499 return "";
500}
501
502/// Get the (LLVM) name of the WebAssembly cpu we are targeting.
503static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
504 // If we have -mcpu=, use that.
505 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
506 StringRef CPU = A->getValue();
507
508#ifdef __wasm__
509 // Handle "native" by examining the host. "native" isn't meaningful when
510 // cross compiling, so only support this when the host is also WebAssembly.
511 if (CPU == "native")
512 return llvm::sys::getHostCPUName();
513#endif
514
515 return CPU;
516 }
517
518 return "generic";
519}
520
521std::string tools::getCPUName(const Driver &D, const ArgList &Args,
522 const llvm::Triple &T, bool FromAs) {
523 Arg *A;
524
525 switch (T.getArch()) {
526 default:
527 return "";
528
529 case llvm::Triple::aarch64:
530 case llvm::Triple::aarch64_32:
531 case llvm::Triple::aarch64_be:
532 return aarch64::getAArch64TargetCPU(Args, T, A);
533
534 case llvm::Triple::arm:
535 case llvm::Triple::armeb:
536 case llvm::Triple::thumb:
537 case llvm::Triple::thumbeb: {
538 StringRef MArch, MCPU;
539 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
540 return arm::getARMTargetCPU(MCPU, MArch, T);
541 }
542
543 case llvm::Triple::avr:
544 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
545 return A->getValue();
546 return "";
547
548 case llvm::Triple::m68k:
549 return m68k::getM68kTargetCPU(Args);
550
551 case llvm::Triple::mips:
552 case llvm::Triple::mipsel:
553 case llvm::Triple::mips64:
554 case llvm::Triple::mips64el: {
555 StringRef CPUName;
556 StringRef ABIName;
557 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
558 return std::string(CPUName);
559 }
560
561 case llvm::Triple::nvptx:
562 case llvm::Triple::nvptx64:
563 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
564 return A->getValue();
565 return "";
566
567 case llvm::Triple::ppc:
568 case llvm::Triple::ppcle:
569 case llvm::Triple::ppc64:
570 case llvm::Triple::ppc64le:
571 return ppc::getPPCTargetCPU(D, Args, T);
572
573 case llvm::Triple::csky:
574 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
575 return A->getValue();
576 else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
577 return A->getValue();
578 else
579 return "ck810";
580 case llvm::Triple::riscv32:
581 case llvm::Triple::riscv64:
582 return riscv::getRISCVTargetCPU(Args, T);
583
584 case llvm::Triple::bpfel:
585 case llvm::Triple::bpfeb:
586 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
587 return A->getValue();
588 return "";
589
590 case llvm::Triple::sparc:
591 case llvm::Triple::sparcel:
592 case llvm::Triple::sparcv9:
593 return sparc::getSparcTargetCPU(D, Args, T);
594
595 case llvm::Triple::x86:
596 case llvm::Triple::x86_64:
597 return x86::getX86TargetCPU(D, Args, T);
598
599 case llvm::Triple::hexagon:
600 return "hexagon" +
602
603 case llvm::Triple::lanai:
604 return getLanaiTargetCPU(Args);
605
606 case llvm::Triple::systemz:
607 return systemz::getSystemZTargetCPU(Args);
608
609 case llvm::Triple::r600:
610 case llvm::Triple::amdgcn:
611 return getAMDGPUTargetGPU(T, Args);
612
613 case llvm::Triple::wasm32:
614 case llvm::Triple::wasm64:
615 return std::string(getWebAssemblyTargetCPU(Args));
616
617 case llvm::Triple::loongarch32:
618 case llvm::Triple::loongarch64:
620 }
621}
622
624 const llvm::Triple &Triple,
625 const ArgList &Args,
626 std::vector<StringRef> &Features) {
627 handleTargetFeaturesGroup(D, Triple, Args, Features,
628 options::OPT_m_wasm_Features_Group);
629}
630
631void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
632 const ArgList &Args, ArgStringList &CmdArgs,
633 bool ForAS, bool IsAux) {
634 std::vector<StringRef> Features;
635 switch (Triple.getArch()) {
636 default:
637 break;
638 case llvm::Triple::mips:
639 case llvm::Triple::mipsel:
640 case llvm::Triple::mips64:
641 case llvm::Triple::mips64el:
642 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
643 break;
644 case llvm::Triple::arm:
645 case llvm::Triple::armeb:
646 case llvm::Triple::thumb:
647 case llvm::Triple::thumbeb:
648 arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS);
649 break;
650 case llvm::Triple::ppc:
651 case llvm::Triple::ppcle:
652 case llvm::Triple::ppc64:
653 case llvm::Triple::ppc64le:
654 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
655 break;
656 case llvm::Triple::riscv32:
657 case llvm::Triple::riscv64:
658 riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
659 break;
660 case llvm::Triple::systemz:
661 systemz::getSystemZTargetFeatures(D, Args, Features);
662 break;
663 case llvm::Triple::aarch64:
664 case llvm::Triple::aarch64_32:
665 case llvm::Triple::aarch64_be:
666 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS);
667 break;
668 case llvm::Triple::x86:
669 case llvm::Triple::x86_64:
670 x86::getX86TargetFeatures(D, Triple, Args, Features);
671 break;
672 case llvm::Triple::hexagon:
673 hexagon::getHexagonTargetFeatures(D, Triple, Args, Features);
674 break;
675 case llvm::Triple::wasm32:
676 case llvm::Triple::wasm64:
677 getWebAssemblyTargetFeatures(D, Triple, Args, Features);
678 break;
679 case llvm::Triple::sparc:
680 case llvm::Triple::sparcel:
681 case llvm::Triple::sparcv9:
682 sparc::getSparcTargetFeatures(D, Args, Features);
683 break;
684 case llvm::Triple::r600:
685 case llvm::Triple::amdgcn:
686 amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
687 break;
688 case llvm::Triple::nvptx:
689 case llvm::Triple::nvptx64:
690 NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features);
691 break;
692 case llvm::Triple::m68k:
693 m68k::getM68kTargetFeatures(D, Triple, Args, Features);
694 break;
695 case llvm::Triple::msp430:
696 msp430::getMSP430TargetFeatures(D, Args, Features);
697 break;
698 case llvm::Triple::ve:
699 ve::getVETargetFeatures(D, Args, Features);
700 break;
701 case llvm::Triple::csky:
702 csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features);
703 break;
704 case llvm::Triple::loongarch32:
705 case llvm::Triple::loongarch64:
706 loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features);
707 break;
708 }
709
710 for (auto Feature : unifyTargetFeatures(Features)) {
711 CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature");
712 CmdArgs.push_back(Feature.data());
713 }
714}
715
716llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
717 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
718 if (!LtoJobsArg)
719 return {};
720 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
721 D.Diag(diag::err_drv_invalid_int_value)
722 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
723 return LtoJobsArg->getValue();
724}
725
726// PS4/PS5 uses -ffunction-sections and -fdata-sections by default.
727bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
728 return Triple.isPS();
729}
730
732 const llvm::opt::ArgList &Args) {
733 const llvm::Triple &Triple = TC.getEffectiveTriple();
734 Arg *A = Args.getLastArg(options::OPT_mtls_dialect_EQ);
735 if (!A)
736 return Triple.hasDefaultTLSDESC();
737 StringRef V = A->getValue();
738 bool SupportedArgument = false, EnableTLSDESC = false;
739 bool Unsupported = !Triple.isOSBinFormatELF();
740 if (Triple.isRISCV()) {
741 SupportedArgument = V == "desc" || V == "trad";
742 EnableTLSDESC = V == "desc";
743 } else if (Triple.isX86()) {
744 SupportedArgument = V == "gnu" || V == "gnu2";
745 EnableTLSDESC = V == "gnu2";
746 } else {
747 Unsupported = true;
748 }
749 if (Unsupported) {
750 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
751 << A->getSpelling() << Triple.getTriple();
752 } else if (!SupportedArgument) {
753 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument_for_target)
754 << A->getSpelling() << V << Triple.getTriple();
755 }
756 return EnableTLSDESC;
757}
758
759void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
760 ArgStringList &CmdArgs, const InputInfo &Output,
761 const InputInfo &Input, bool IsThinLTO) {
762 const llvm::Triple &Triple = ToolChain.getTriple();
763 const bool IsOSAIX = Triple.isOSAIX();
764 const bool IsAMDGCN = Triple.isAMDGCN();
765 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
766 const Driver &D = ToolChain.getDriver();
767 const bool IsFatLTO = Args.hasArg(options::OPT_ffat_lto_objects);
768 const bool IsUnifiedLTO = Args.hasArg(options::OPT_funified_lto);
769 if (llvm::sys::path::filename(Linker) != "ld.lld" &&
770 llvm::sys::path::stem(Linker) != "ld.lld" && !Triple.isOSOpenBSD()) {
771 // Tell the linker to load the plugin. This has to come before
772 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to
773 // come before any -plugin-opt/-bplugin_opt that -Wl might forward.
774 const char *PluginPrefix = IsOSAIX ? "-bplugin:" : "";
775 const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold";
776
777 if (!IsOSAIX)
778 CmdArgs.push_back("-plugin");
779
780#if defined(_WIN32)
781 const char *Suffix = ".dll";
782#elif defined(__APPLE__)
783 const char *Suffix = ".dylib";
784#else
785 const char *Suffix = ".so";
786#endif
787
788 SmallString<1024> Plugin;
789 llvm::sys::path::native(Twine(D.Dir) +
790 "/../" CLANG_INSTALL_LIBDIR_BASENAME +
791 PluginName + Suffix,
792 Plugin);
793 CmdArgs.push_back(Args.MakeArgString(Twine(PluginPrefix) + Plugin));
794 } else {
795 // Tell LLD to find and use .llvm.lto section in regular relocatable object
796 // files
797 if (IsFatLTO)
798 CmdArgs.push_back("--fat-lto-objects");
799 }
800
801 const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt=";
802 const char *ExtraDash = IsOSAIX ? "-" : "";
803 const char *ParallelismOpt = IsOSAIX ? "-threads=" : "jobs=";
804
805 // Note, this solution is far from perfect, better to encode it into IR
806 // metadata, but this may not be worth it, since it looks like aranges is on
807 // the way out.
808 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
809 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
810 "-generate-arange-section"));
811 }
812
813 // Pass vector library arguments to LTO.
814 Arg *ArgVecLib = Args.getLastArg(options::OPT_fveclib);
815 if (ArgVecLib && ArgVecLib->getNumValues() == 1) {
816 // Map the vector library names from clang front-end to opt front-end. The
817 // values are taken from the TargetLibraryInfo class command line options.
818 std::optional<StringRef> OptVal =
819 llvm::StringSwitch<std::optional<StringRef>>(ArgVecLib->getValue())
820 .Case("Accelerate", "Accelerate")
821 .Case("LIBMVEC", "LIBMVEC-X86")
822 .Case("MASSV", "MASSV")
823 .Case("SVML", "SVML")
824 .Case("SLEEF", "sleefgnuabi")
825 .Case("Darwin_libsystem_m", "Darwin_libsystem_m")
826 .Case("ArmPL", "ArmPL")
827 .Case("none", "none")
828 .Default(std::nullopt);
829
830 if (OptVal)
831 CmdArgs.push_back(Args.MakeArgString(
832 Twine(PluginOptPrefix) + "-vector-library=" + OptVal.value()));
833 }
834
835 // Try to pass driver level flags relevant to LTO code generation down to
836 // the plugin.
837
838 // Handle flags for selecting CPU variants.
839 std::string CPU = getCPUName(D, Args, Triple);
840 if (!CPU.empty())
841 CmdArgs.push_back(
842 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU));
843
844 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
845 // The optimization level matches
846 // CompilerInvocation.cpp:getOptimizationLevel().
847 StringRef OOpt;
848 if (A->getOption().matches(options::OPT_O4) ||
849 A->getOption().matches(options::OPT_Ofast))
850 OOpt = "3";
851 else if (A->getOption().matches(options::OPT_O)) {
852 OOpt = A->getValue();
853 if (OOpt == "g")
854 OOpt = "1";
855 else if (OOpt == "s" || OOpt == "z")
856 OOpt = "2";
857 } else if (A->getOption().matches(options::OPT_O0))
858 OOpt = "0";
859 if (!OOpt.empty()) {
860 CmdArgs.push_back(
861 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt));
862 if (IsAMDGCN)
863 CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt));
864 }
865 }
866
867 if (Args.hasArg(options::OPT_gsplit_dwarf))
868 CmdArgs.push_back(Args.MakeArgString(
869 Twine(PluginOptPrefix) + "dwo_dir=" + Output.getFilename() + "_dwo"));
870
871 if (IsThinLTO && !IsOSAIX)
872 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "thinlto"));
873 else if (IsThinLTO && IsOSAIX)
874 CmdArgs.push_back(Args.MakeArgString(Twine("-bdbg:thinlto")));
875
876 // Matrix intrinsic lowering happens at link time with ThinLTO. Enable
877 // LowerMatrixIntrinsicsPass, which is transitively called by
878 // buildThinLTODefaultPipeline under EnableMatrix.
879 if ((IsThinLTO || IsFatLTO || IsUnifiedLTO) &&
880 Args.hasArg(options::OPT_fenable_matrix))
881 CmdArgs.push_back(
882 Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-matrix"));
883
884 StringRef Parallelism = getLTOParallelism(Args, D);
885 if (!Parallelism.empty())
886 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
887 ParallelismOpt + Parallelism));
888
889 // Pass down GlobalISel options.
890 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
891 options::OPT_fno_global_isel)) {
892 // Parsing -fno-global-isel explicitly gives architectures that enable GISel
893 // by default a chance to disable it.
894 CmdArgs.push_back(Args.MakeArgString(
895 Twine(PluginOptPrefix) + "-global-isel=" +
896 (A->getOption().matches(options::OPT_fglobal_isel) ? "1" : "0")));
897 }
898
899 // If an explicit debugger tuning argument appeared, pass it along.
900 if (Arg *A =
901 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
902 if (A->getOption().matches(options::OPT_glldb))
903 CmdArgs.push_back(
904 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=lldb"));
905 else if (A->getOption().matches(options::OPT_gsce))
906 CmdArgs.push_back(
907 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=sce"));
908 else if (A->getOption().matches(options::OPT_gdbx))
909 CmdArgs.push_back(
910 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=dbx"));
911 else
912 CmdArgs.push_back(
913 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=gdb"));
914 }
915
916 if (IsOSAIX) {
918 CmdArgs.push_back(
919 Args.MakeArgString(Twine(PluginOptPrefix) + "-no-integrated-as=1"));
920
921 // On AIX, clang assumes strict-dwarf is true if any debug option is
922 // specified, unless it is told explicitly not to assume so.
923 Arg *A = Args.getLastArg(options::OPT_g_Group);
924 bool EnableDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
925 !A->getOption().matches(options::OPT_ggdb0);
926 if (EnableDebugInfo && Args.hasFlag(options::OPT_gstrict_dwarf,
927 options::OPT_gno_strict_dwarf, true))
928 CmdArgs.push_back(
929 Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true"));
930
931 for (const Arg *A : Args.filtered_reverse(options::OPT_mabi_EQ)) {
932 StringRef V = A->getValue();
933 if (V == "vec-default")
934 break;
935 if (V == "vec-extabi") {
936 CmdArgs.push_back(
937 Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi"));
938 break;
939 }
940 }
941 }
942
943 bool UseSeparateSections =
945
946 if (Args.hasFlag(options::OPT_ffunction_sections,
947 options::OPT_fno_function_sections, UseSeparateSections))
948 CmdArgs.push_back(
949 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=1"));
950 else if (Args.hasArg(options::OPT_fno_function_sections))
951 CmdArgs.push_back(
952 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=0"));
953
954 bool DataSectionsTurnedOff = false;
955 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
956 UseSeparateSections)) {
957 CmdArgs.push_back(
958 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1"));
959 } else if (Args.hasArg(options::OPT_fno_data_sections)) {
960 DataSectionsTurnedOff = true;
961 CmdArgs.push_back(
962 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=0"));
963 }
964
965 if (Args.hasArg(options::OPT_mxcoff_roptr) ||
966 Args.hasArg(options::OPT_mno_xcoff_roptr)) {
967 bool HasRoptr = Args.hasFlag(options::OPT_mxcoff_roptr,
968 options::OPT_mno_xcoff_roptr, false);
969 StringRef OptStr = HasRoptr ? "-mxcoff-roptr" : "-mno-xcoff-roptr";
970 if (!IsOSAIX)
971 D.Diag(diag::err_drv_unsupported_opt_for_target)
972 << OptStr << Triple.str();
973
974 if (HasRoptr) {
975 // The data sections option is on by default on AIX. We only need to error
976 // out when -fno-data-sections is specified explicitly to turn off data
977 // sections.
978 if (DataSectionsTurnedOff)
979 D.Diag(diag::err_roptr_requires_data_sections);
980
981 CmdArgs.push_back(
982 Args.MakeArgString(Twine(PluginOptPrefix) + "-mxcoff-roptr"));
983 }
984 }
985
986 // Pass an option to enable split machine functions.
987 if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
988 options::OPT_fno_split_machine_functions)) {
989 if (A->getOption().matches(options::OPT_fsplit_machine_functions))
990 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
991 "-split-machine-functions"));
992 }
993
994 if (Arg *A = getLastProfileSampleUseArg(Args)) {
995 StringRef FName = A->getValue();
996 if (!llvm::sys::fs::exists(FName))
997 D.Diag(diag::err_drv_no_such_file) << FName;
998 else
999 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
1000 "sample-profile=" + FName));
1001 }
1002
1003 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) {
1004 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1005 "cs-profile-generate"));
1006 if (CSPGOGenerateArg->getOption().matches(
1007 options::OPT_fcs_profile_generate_EQ)) {
1008 SmallString<128> Path(CSPGOGenerateArg->getValue());
1009 llvm::sys::path::append(Path, "default_%m.profraw");
1010 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1011 "cs-profile-path=" + Path));
1012 } else
1013 CmdArgs.push_back(
1014 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1015 "cs-profile-path=default_%m.profraw"));
1016 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) {
1017 SmallString<128> Path(
1018 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
1019 if (Path.empty() || llvm::sys::fs::is_directory(Path))
1020 llvm::sys::path::append(Path, "default.profdata");
1021 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1022 "cs-profile-path=" + Path));
1023 }
1024
1025 // This controls whether or not we perform JustMyCode instrumentation.
1026 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
1027 if (ToolChain.getEffectiveTriple().isOSBinFormatELF())
1028 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
1029 "-enable-jmc-instrument"));
1030 else
1031 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
1032 }
1033
1034 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
1035 Triple.hasDefaultEmulatedTLS())) {
1036 CmdArgs.push_back(
1037 Args.MakeArgString(Twine(PluginOptPrefix) + "-emulated-tls"));
1038 }
1039 if (isTLSDESCEnabled(ToolChain, Args))
1040 CmdArgs.push_back(
1041 Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-tlsdesc"));
1042
1043 if (Args.hasFlag(options::OPT_fstack_size_section,
1044 options::OPT_fno_stack_size_section, false))
1045 CmdArgs.push_back(
1046 Args.MakeArgString(Twine(PluginOptPrefix) + "-stack-size-section"));
1047
1048 // Setup statistics file output.
1049 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
1050 if (!StatsFile.empty())
1051 CmdArgs.push_back(
1052 Args.MakeArgString(Twine(PluginOptPrefix) + "stats-file=" + StatsFile));
1053
1054 // Setup crash diagnostics dir.
1055 if (Arg *A = Args.getLastArg(options::OPT_fcrash_diagnostics_dir))
1056 CmdArgs.push_back(Args.MakeArgString(
1057 Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue()));
1058
1059 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix);
1060
1061 // Handle remark diagnostics on screen options: '-Rpass-*'.
1062 renderRpassOptions(Args, CmdArgs, PluginOptPrefix);
1063
1064 // Handle serialized remarks options: '-fsave-optimization-record'
1065 // and '-foptimization-record-*'.
1066 if (willEmitRemarks(Args))
1067 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
1068 Output, PluginOptPrefix);
1069
1070 // Handle remarks hotness/threshold related options.
1071 renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix);
1072
1074 /*IsLTO=*/true, PluginOptPrefix);
1075}
1076
1077/// Adds the '-lcgpu' and '-lmgpu' libraries to the compilation to include the
1078/// LLVM C library for GPUs.
1079static void addOpenMPDeviceLibC(const Compilation &C, const ArgList &Args,
1080 ArgStringList &CmdArgs) {
1081 if (Args.hasArg(options::OPT_nogpulib) || Args.hasArg(options::OPT_nolibc))
1082 return;
1083
1084 // Check the resource directory for the LLVM libc GPU declarations. If it's
1085 // found we can assume that LLVM was built with support for the GPU libc.
1086 SmallString<256> LibCDecls(C.getDriver().ResourceDir);
1087 llvm::sys::path::append(LibCDecls, "include", "llvm_libc_wrappers",
1088 "llvm-libc-decls");
1089 bool HasLibC = llvm::sys::fs::exists(LibCDecls) &&
1090 llvm::sys::fs::is_directory(LibCDecls);
1091 if (!Args.hasFlag(options::OPT_gpulibc, options::OPT_nogpulibc, HasLibC))
1092 return;
1093
1095 auto TCRange = C.getOffloadToolChains(Action::OFK_OpenMP);
1096 for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
1097 ToolChains.push_back(TI->second);
1098
1099 if (llvm::any_of(ToolChains, [](const ToolChain *TC) {
1100 return TC->getTriple().isAMDGPU();
1101 })) {
1102 CmdArgs.push_back("-lcgpu-amdgpu");
1103 CmdArgs.push_back("-lmgpu-amdgpu");
1104 }
1105 if (llvm::any_of(ToolChains, [](const ToolChain *TC) {
1106 return TC->getTriple().isNVPTX();
1107 })) {
1108 CmdArgs.push_back("-lcgpu-nvptx");
1109 CmdArgs.push_back("-lmgpu-nvptx");
1110 }
1111}
1112
1114 const ArgList &Args,
1115 ArgStringList &CmdArgs) {
1116 // Default to clang lib / lib64 folder, i.e. the same location as device
1117 // runtime.
1118 SmallString<256> DefaultLibPath =
1119 llvm::sys::path::parent_path(TC.getDriver().Dir);
1120 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
1121 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
1122}
1123
1124void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
1125 ArgStringList &CmdArgs) {
1126 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
1127 options::OPT_fno_rtlib_add_rpath, false))
1128 return;
1129
1131 if (const auto CandidateRPath = TC.getStdlibPath())
1132 CandidateRPaths.emplace_back(*CandidateRPath);
1133
1134 for (const auto &CandidateRPath : CandidateRPaths) {
1135 if (TC.getVFS().exists(CandidateRPath)) {
1136 CmdArgs.push_back("-rpath");
1137 CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
1138 }
1139 }
1140}
1141
1142bool tools::addOpenMPRuntime(const Compilation &C, ArgStringList &CmdArgs,
1143 const ToolChain &TC, const ArgList &Args,
1144 bool ForceStaticHostRuntime, bool IsOffloadingHost,
1145 bool GompNeedsRT) {
1146 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
1147 options::OPT_fno_openmp, false))
1148 return false;
1149
1151
1152 if (RTKind == Driver::OMPRT_Unknown)
1153 // Already diagnosed.
1154 return false;
1155
1156 if (ForceStaticHostRuntime)
1157 CmdArgs.push_back("-Bstatic");
1158
1159 switch (RTKind) {
1160 case Driver::OMPRT_OMP:
1161 CmdArgs.push_back("-lomp");
1162 break;
1163 case Driver::OMPRT_GOMP:
1164 CmdArgs.push_back("-lgomp");
1165 break;
1167 CmdArgs.push_back("-liomp5");
1168 break;
1170 break;
1171 }
1172
1173 if (ForceStaticHostRuntime)
1174 CmdArgs.push_back("-Bdynamic");
1175
1176 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
1177 CmdArgs.push_back("-lrt");
1178
1179 if (IsOffloadingHost)
1180 CmdArgs.push_back("-lomptarget");
1181
1182 if (IsOffloadingHost && !Args.hasArg(options::OPT_nogpulib))
1183 CmdArgs.push_back("-lomptarget.devicertl");
1184
1185 if (IsOffloadingHost)
1186 addOpenMPDeviceLibC(C, Args, CmdArgs);
1187
1188 addArchSpecificRPath(TC, Args, CmdArgs);
1189 addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
1190
1191 return true;
1192}
1193
1194/// Determines if --whole-archive is active in the list of arguments.
1195static bool isWholeArchivePresent(const ArgList &Args) {
1196 bool WholeArchiveActive = false;
1197 for (auto *Arg : Args.filtered(options::OPT_Wl_COMMA)) {
1198 if (Arg) {
1199 for (StringRef ArgValue : Arg->getValues()) {
1200 if (ArgValue == "--whole-archive")
1201 WholeArchiveActive = true;
1202 if (ArgValue == "--no-whole-archive")
1203 WholeArchiveActive = false;
1204 }
1205 }
1206 }
1207
1208 return WholeArchiveActive;
1209}
1210
1211/// Determine if driver is invoked to create a shared object library (-static)
1212static bool isSharedLinkage(const ArgList &Args) {
1213 return Args.hasArg(options::OPT_shared);
1214}
1215
1216/// Determine if driver is invoked to create a static object library (-shared)
1217static bool isStaticLinkage(const ArgList &Args) {
1218 return Args.hasArg(options::OPT_static);
1219}
1220
1221/// Add Fortran runtime libs for MSVC
1222static void addFortranRuntimeLibsMSVC(const ArgList &Args,
1223 llvm::opt::ArgStringList &CmdArgs) {
1224 unsigned RTOptionID = options::OPT__SLASH_MT;
1225 if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
1226 RTOptionID = llvm::StringSwitch<unsigned>(rtl->getValue())
1227 .Case("static", options::OPT__SLASH_MT)
1228 .Case("static_dbg", options::OPT__SLASH_MTd)
1229 .Case("dll", options::OPT__SLASH_MD)
1230 .Case("dll_dbg", options::OPT__SLASH_MDd)
1231 .Default(options::OPT__SLASH_MT);
1232 }
1233 switch (RTOptionID) {
1234 case options::OPT__SLASH_MT:
1235 CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.static.lib");
1236 break;
1237 case options::OPT__SLASH_MTd:
1238 CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.static_dbg.lib");
1239 break;
1240 case options::OPT__SLASH_MD:
1241 CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.dynamic.lib");
1242 break;
1243 case options::OPT__SLASH_MDd:
1244 CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.dynamic_dbg.lib");
1245 break;
1246 }
1247}
1248
1249// Add FortranMain runtime lib
1250static void addFortranMain(const ToolChain &TC, const ArgList &Args,
1251 llvm::opt::ArgStringList &CmdArgs) {
1252 // 0. Shared-library linkage
1253 // If we are attempting to link a library, we should not add
1254 // -lFortran_main.a to the link line, as the `main` symbol is not
1255 // required for a library and should also be provided by one of
1256 // the translation units of the code that this shared library
1257 // will be linked against eventually.
1258 if (isSharedLinkage(Args) || isStaticLinkage(Args)) {
1259 return;
1260 }
1261
1262 // 1. MSVC
1263 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1264 addFortranRuntimeLibsMSVC(Args, CmdArgs);
1265 return;
1266 }
1267
1268 // 2. GNU and similar
1269 const Driver &D = TC.getDriver();
1270 const char *FortranMainLinkFlag = "-lFortran_main";
1271
1272 // Warn if the user added `-lFortran_main` - this library is an implementation
1273 // detail of Flang and should be handled automaticaly by the driver.
1274 for (const char *arg : CmdArgs) {
1275 if (strncmp(arg, FortranMainLinkFlag, strlen(FortranMainLinkFlag)) == 0)
1276 D.Diag(diag::warn_drv_deprecated_custom)
1277 << FortranMainLinkFlag
1278 << "see the Flang driver documentation for correct usage";
1279 }
1280
1281 // The --whole-archive option needs to be part of the link line to make
1282 // sure that the main() function from Fortran_main.a is pulled in by the
1283 // linker. However, it shouldn't be used if it's already active.
1284 // TODO: Find an equivalent of `--whole-archive` for Darwin and AIX.
1285 if (!isWholeArchivePresent(Args) && !TC.getTriple().isMacOSX() &&
1286 !TC.getTriple().isOSAIX()) {
1287 CmdArgs.push_back("--whole-archive");
1288 CmdArgs.push_back(FortranMainLinkFlag);
1289 CmdArgs.push_back("--no-whole-archive");
1290 return;
1291 }
1292
1293 CmdArgs.push_back(FortranMainLinkFlag);
1294}
1295
1296/// Add Fortran runtime libs
1297void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args,
1298 llvm::opt::ArgStringList &CmdArgs) {
1299 // 1. Link FortranMain
1300 // FortranMain depends on FortranRuntime, so needs to be listed first. If
1301 // -fno-fortran-main has been passed, skip linking Fortran_main.a
1302 if (!Args.hasArg(options::OPT_no_fortran_main))
1303 addFortranMain(TC, Args, CmdArgs);
1304
1305 // 2. Link FortranRuntime and FortranDecimal
1306 // These are handled earlier on Windows by telling the frontend driver to
1307 // add the correct libraries to link against as dependents in the object
1308 // file.
1309 if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1310 StringRef F128LibName = TC.getDriver().getFlangF128MathLibrary();
1311 F128LibName.consume_front_insensitive("lib");
1312 if (!F128LibName.empty()) {
1313 bool AsNeeded = !TC.getTriple().isOSAIX();
1314 CmdArgs.push_back("-lFortranFloat128Math");
1315 if (AsNeeded)
1316 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true);
1317 CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
1318 if (AsNeeded)
1319 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
1320 }
1321 CmdArgs.push_back("-lFortranRuntime");
1322 CmdArgs.push_back("-lFortranDecimal");
1323 }
1324}
1325
1327 const llvm::opt::ArgList &Args,
1328 ArgStringList &CmdArgs) {
1329 // Default to the <driver-path>/../lib directory. This works fine on the
1330 // platforms that we have tested so far. We will probably have to re-fine
1331 // this in the future. In particular, on some platforms, we may need to use
1332 // lib64 instead of lib.
1333 SmallString<256> DefaultLibPath =
1334 llvm::sys::path::parent_path(TC.getDriver().Dir);
1335 llvm::sys::path::append(DefaultLibPath, "lib");
1336 if (TC.getTriple().isKnownWindowsMSVCEnvironment())
1337 CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
1338 else
1339 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
1340}
1341
1342static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
1343 ArgStringList &CmdArgs, StringRef Sanitizer,
1344 bool IsShared, bool IsWhole) {
1345 // Wrap any static runtimes that must be forced into executable in
1346 // whole-archive.
1347 if (IsWhole) CmdArgs.push_back("--whole-archive");
1348 CmdArgs.push_back(TC.getCompilerRTArgString(
1349 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
1350 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
1351
1352 if (IsShared) {
1353 addArchSpecificRPath(TC, Args, CmdArgs);
1354 }
1355}
1356
1357// Tries to use a file with the list of dynamic symbols that need to be exported
1358// from the runtime library. Returns true if the file was found.
1359static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
1360 ArgStringList &CmdArgs,
1361 StringRef Sanitizer) {
1362 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1363
1364 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
1365 // the option, so don't try to pass it.
1366 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd)
1367 return true;
1368 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
1369 if (llvm::sys::fs::exists(SanRT + ".syms")) {
1370 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
1371 return true;
1372 }
1373 return false;
1374}
1375
1377 const llvm::opt::ArgList &Args,
1378 llvm::opt::ArgStringList &CmdArgs,
1379 bool as_needed) {
1380 assert(!TC.getTriple().isOSAIX() &&
1381 "AIX linker does not support any form of --as-needed option yet.");
1382 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1383
1384 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
1385 // for the native forms -z ignore/-z record, they are missing in Illumos,
1386 // so always use the native form.
1387 // GNU ld doesn't support -z ignore/-z record, so don't use them even on
1388 // Solaris.
1389 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) {
1390 CmdArgs.push_back("-z");
1391 CmdArgs.push_back(as_needed ? "ignore" : "record");
1392 } else {
1393 CmdArgs.push_back(as_needed ? "--as-needed" : "--no-as-needed");
1394 }
1395}
1396
1398 const llvm::opt::ArgList &Args,
1399 ArgStringList &CmdArgs) {
1400 // Force linking against the system libraries sanitizers depends on
1401 // (see PR15823 why this is necessary).
1402 addAsNeededOption(TC, Args, CmdArgs, false);
1403 // There's no libpthread or librt on RTEMS & Android.
1404 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
1405 !TC.getTriple().isAndroid() && !TC.getTriple().isOHOSFamily()) {
1406 CmdArgs.push_back("-lpthread");
1407 if (!TC.getTriple().isOSOpenBSD())
1408 CmdArgs.push_back("-lrt");
1409 }
1410 CmdArgs.push_back("-lm");
1411 // There's no libdl on all OSes.
1412 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
1413 !TC.getTriple().isOSOpenBSD() &&
1414 TC.getTriple().getOS() != llvm::Triple::RTEMS)
1415 CmdArgs.push_back("-ldl");
1416 // Required for backtrace on some OSes
1417 if (TC.getTriple().isOSFreeBSD() ||
1418 TC.getTriple().isOSNetBSD() ||
1419 TC.getTriple().isOSOpenBSD())
1420 CmdArgs.push_back("-lexecinfo");
1421 // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
1422 // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
1423 // requirement.
1424 if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
1425 !TC.getTriple().isMusl())
1426 CmdArgs.push_back("-lresolv");
1427}
1428
1429static void
1430collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1431 SmallVectorImpl<StringRef> &SharedRuntimes,
1432 SmallVectorImpl<StringRef> &StaticRuntimes,
1433 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
1434 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
1435 SmallVectorImpl<StringRef> &RequiredSymbols) {
1436 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1437 // Collect shared runtimes.
1438 if (SanArgs.needsSharedRt()) {
1439 if (SanArgs.needsAsanRt()) {
1440 SharedRuntimes.push_back("asan");
1441 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1442 HelperStaticRuntimes.push_back("asan-preinit");
1443 }
1444 if (SanArgs.needsMemProfRt()) {
1445 SharedRuntimes.push_back("memprof");
1446 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1447 HelperStaticRuntimes.push_back("memprof-preinit");
1448 }
1449 if (SanArgs.needsUbsanRt()) {
1450 if (SanArgs.requiresMinimalRuntime())
1451 SharedRuntimes.push_back("ubsan_minimal");
1452 else
1453 SharedRuntimes.push_back("ubsan_standalone");
1454 }
1455 if (SanArgs.needsScudoRt()) {
1456 SharedRuntimes.push_back("scudo_standalone");
1457 }
1458 if (SanArgs.needsTsanRt())
1459 SharedRuntimes.push_back("tsan");
1460 if (SanArgs.needsHwasanRt()) {
1461 if (SanArgs.needsHwasanAliasesRt())
1462 SharedRuntimes.push_back("hwasan_aliases");
1463 else
1464 SharedRuntimes.push_back("hwasan");
1465 if (!Args.hasArg(options::OPT_shared))
1466 HelperStaticRuntimes.push_back("hwasan-preinit");
1467 }
1468 }
1469
1470 // The stats_client library is also statically linked into DSOs.
1471 if (SanArgs.needsStatsRt())
1472 StaticRuntimes.push_back("stats_client");
1473
1474 // Always link the static runtime regardless of DSO or executable.
1475 if (SanArgs.needsAsanRt())
1476 HelperStaticRuntimes.push_back("asan_static");
1477
1478 // Collect static runtimes.
1479 if (Args.hasArg(options::OPT_shared)) {
1480 // Don't link static runtimes into DSOs.
1481 return;
1482 }
1483
1484 // Each static runtime that has a DSO counterpart above is excluded below,
1485 // but runtimes that exist only as static are not affected by needsSharedRt.
1486
1487 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt()) {
1488 StaticRuntimes.push_back("asan");
1489 if (SanArgs.linkCXXRuntimes())
1490 StaticRuntimes.push_back("asan_cxx");
1491 }
1492
1493 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt()) {
1494 StaticRuntimes.push_back("memprof");
1495 if (SanArgs.linkCXXRuntimes())
1496 StaticRuntimes.push_back("memprof_cxx");
1497 }
1498
1499 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt()) {
1500 if (SanArgs.needsHwasanAliasesRt()) {
1501 StaticRuntimes.push_back("hwasan_aliases");
1502 if (SanArgs.linkCXXRuntimes())
1503 StaticRuntimes.push_back("hwasan_aliases_cxx");
1504 } else {
1505 StaticRuntimes.push_back("hwasan");
1506 if (SanArgs.linkCXXRuntimes())
1507 StaticRuntimes.push_back("hwasan_cxx");
1508 }
1509 }
1510 if (SanArgs.needsDfsanRt())
1511 StaticRuntimes.push_back("dfsan");
1512 if (SanArgs.needsLsanRt())
1513 StaticRuntimes.push_back("lsan");
1514 if (SanArgs.needsMsanRt()) {
1515 StaticRuntimes.push_back("msan");
1516 if (SanArgs.linkCXXRuntimes())
1517 StaticRuntimes.push_back("msan_cxx");
1518 }
1519 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) {
1520 StaticRuntimes.push_back("tsan");
1521 if (SanArgs.linkCXXRuntimes())
1522 StaticRuntimes.push_back("tsan_cxx");
1523 }
1524 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt()) {
1525 if (SanArgs.requiresMinimalRuntime()) {
1526 StaticRuntimes.push_back("ubsan_minimal");
1527 } else {
1528 StaticRuntimes.push_back("ubsan_standalone");
1529 if (SanArgs.linkCXXRuntimes())
1530 StaticRuntimes.push_back("ubsan_standalone_cxx");
1531 }
1532 }
1533 if (SanArgs.needsSafeStackRt()) {
1534 NonWholeStaticRuntimes.push_back("safestack");
1535 RequiredSymbols.push_back("__safestack_init");
1536 }
1537 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt())) {
1538 if (SanArgs.needsCfiRt())
1539 StaticRuntimes.push_back("cfi");
1540 if (SanArgs.needsCfiDiagRt()) {
1541 StaticRuntimes.push_back("cfi_diag");
1542 if (SanArgs.linkCXXRuntimes())
1543 StaticRuntimes.push_back("ubsan_standalone_cxx");
1544 }
1545 }
1546 if (SanArgs.needsStatsRt()) {
1547 NonWholeStaticRuntimes.push_back("stats");
1548 RequiredSymbols.push_back("__sanitizer_stats_register");
1549 }
1550 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt()) {
1551 StaticRuntimes.push_back("scudo_standalone");
1552 if (SanArgs.linkCXXRuntimes())
1553 StaticRuntimes.push_back("scudo_standalone_cxx");
1554 }
1555}
1556
1557// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
1558// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
1559bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1560 ArgStringList &CmdArgs) {
1561 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1562 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
1563 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
1564 if (SanArgs.linkRuntimes()) {
1565 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1566 NonWholeStaticRuntimes, HelperStaticRuntimes,
1567 RequiredSymbols);
1568 }
1569
1570 // Inject libfuzzer dependencies.
1571 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1572 !Args.hasArg(options::OPT_shared)) {
1573
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");
1586 }
1587 }
1588
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);
1597 }
1598 for (auto RT : NonWholeStaticRuntimes) {
1599 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1600 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1601 }
1602 for (auto S : RequiredSymbols) {
1603 CmdArgs.push_back("-u");
1604 CmdArgs.push_back(Args.MakeArgString(S));
1605 }
1606 // If there is a static runtime with no dynamic list, force all the symbols
1607 // to be dynamic to be sure we export sanitizer interface functions.
1608 if (AddExportDynamic)
1609 CmdArgs.push_back("--export-dynamic");
1610
1611 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1612 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1613
1614 if (SanArgs.hasMemTag()) {
1615 if (!TC.getTriple().isAndroid()) {
1616 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1617 << "-fsanitize=memtag*" << TC.getTriple().str();
1618 }
1619 CmdArgs.push_back(
1620 Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1621 if (SanArgs.hasMemtagHeap())
1622 CmdArgs.push_back("--android-memtag-heap");
1623 if (SanArgs.hasMemtagStack())
1624 CmdArgs.push_back("--android-memtag-stack");
1625 }
1626
1627 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1628}
1629
1630bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1631 if (Args.hasArg(options::OPT_shared))
1632 return false;
1633
1634 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;
1641 }
1642
1643 return false;
1644}
1645
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");
1654
1655 if (!TC.getTriple().isOSFreeBSD() &&
1656 !TC.getTriple().isOSNetBSD() &&
1657 !TC.getTriple().isOSOpenBSD())
1658 CmdArgs.push_back("-ldl");
1659}
1660
1661bool 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;
1667}
1668
1669const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1670 const InputInfo &Input,
1671 const InputInfo &Output) {
1672 auto AddPostfix = [JA](auto &F) {
1674 F += (Twine("_") + JA.getOffloadingArch()).str();
1675 F += ".dwo";
1676 };
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());
1680
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);
1693 }
1694 }
1695
1696 T += llvm::sys::path::stem(Input.getBaseInput());
1697 AddPostfix(T);
1698 return Args.MakeArgString(T);
1699}
1700
1701void 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");
1706
1707 ArgStringList StripArgs;
1708 StripArgs.push_back("--strip-dwo");
1709
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);
1714
1715 const char *Exec =
1716 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1717 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1718
1719 // First extract the dwo sections.
1720 C.addCommand(std::make_unique<Command>(JA, T,
1722 Exec, ExtractArgs, II, Output));
1723
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));
1727}
1728
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.
1732void 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);
1738}
1739
1740Arg *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;
1747
1748 return CSPGOGenerateArg;
1749}
1750
1751Arg *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);
1756
1757 if (ProfileUseArg &&
1758 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1759 ProfileUseArg = nullptr;
1760
1761 return ProfileUseArg;
1762}
1763
1764Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1765 auto *ProfileSampleUseArg = Args.getLastArg(
1766 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1767 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1768 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1769
1770 if (ProfileSampleUseArg &&
1771 (ProfileSampleUseArg->getOption().matches(
1772 options::OPT_fno_profile_sample_use) ||
1773 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1774 return nullptr;
1775
1776 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1777 options::OPT_fauto_profile_EQ);
1778}
1779
1780const char *tools::RelocationModelName(llvm::Reloc::Model Model) {
1781 switch (Model) {
1782 case llvm::Reloc::Static:
1783 return "static";
1784 case llvm::Reloc::PIC_:
1785 return "pic";
1786 case llvm::Reloc::DynamicNoPIC:
1787 return "dynamic-no-pic";
1788 case llvm::Reloc::ROPI:
1789 return "ropi";
1790 case llvm::Reloc::RWPI:
1791 return "rwpi";
1792 case llvm::Reloc::ROPI_RWPI:
1793 return "ropi-rwpi";
1794 }
1795 llvm_unreachable("Unknown Reloc::Model kind");
1796}
1797
1798/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
1799/// smooshes them together with platform defaults, to decide whether
1800/// this compile should be using PIC mode or not. Returns a tuple of
1801/// (RelocationModel, PICLevel, IsPIE).
1802std::tuple<llvm::Reloc::Model, unsigned, bool>
1803tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1804 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1805 const llvm::Triple &Triple = ToolChain.getTriple();
1806
1807 bool PIE = ToolChain.isPIEDefault(Args);
1808 bool PIC = PIE || ToolChain.isPICDefault();
1809 // The Darwin/MachO default to use PIC does not apply when using -static.
1810 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1811 PIE = PIC = false;
1812 bool IsPICLevelTwo = PIC;
1813
1814 bool KernelOrKext =
1815 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1816
1817 // Android-specific defaults for PIC/PIE
1818 if (Triple.isAndroid()) {
1819 switch (Triple.getArch()) {
1820 case llvm::Triple::arm:
1821 case llvm::Triple::armeb:
1822 case llvm::Triple::thumb:
1823 case llvm::Triple::thumbeb:
1824 case llvm::Triple::aarch64:
1825 case llvm::Triple::mips:
1826 case llvm::Triple::mipsel:
1827 case llvm::Triple::mips64:
1828 case llvm::Triple::mips64el:
1829 PIC = true; // "-fpic"
1830 break;
1831
1832 case llvm::Triple::x86:
1833 case llvm::Triple::x86_64:
1834 PIC = true; // "-fPIC"
1835 IsPICLevelTwo = true;
1836 break;
1837
1838 default:
1839 break;
1840 }
1841 }
1842
1843 // OHOS-specific defaults for PIC/PIE
1844 if (Triple.isOHOSFamily() && Triple.getArch() == llvm::Triple::aarch64)
1845 PIC = true;
1846
1847 // OpenBSD-specific defaults for PIE
1848 if (Triple.isOSOpenBSD()) {
1849 switch (ToolChain.getArch()) {
1850 case llvm::Triple::arm:
1851 case llvm::Triple::aarch64:
1852 case llvm::Triple::mips64:
1853 case llvm::Triple::mips64el:
1854 case llvm::Triple::x86:
1855 case llvm::Triple::x86_64:
1856 IsPICLevelTwo = false; // "-fpie"
1857 break;
1858
1859 case llvm::Triple::ppc:
1860 case llvm::Triple::sparcv9:
1861 IsPICLevelTwo = true; // "-fPIE"
1862 break;
1863
1864 default:
1865 break;
1866 }
1867 }
1868
1869 // The last argument relating to either PIC or PIE wins, and no
1870 // other argument is used. If the last argument is any flavor of the
1871 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1872 // option implicitly enables PIC at the same level.
1873 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1874 options::OPT_fpic, options::OPT_fno_pic,
1875 options::OPT_fPIE, options::OPT_fno_PIE,
1876 options::OPT_fpie, options::OPT_fno_pie);
1877 if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1878 LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1879 options::OPT_fPIE, options::OPT_fpie)) {
1880 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1881 << LastPICArg->getSpelling() << Triple.str();
1882 if (Triple.getArch() == llvm::Triple::x86_64)
1883 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1884 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1885 }
1886
1887 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1888 // is forced, then neither PIC nor PIE flags will have no effect.
1890 if (LastPICArg) {
1891 Option O = LastPICArg->getOption();
1892 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1893 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1894 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1895 PIC =
1896 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1897 IsPICLevelTwo =
1898 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1899 } else {
1900 PIE = PIC = false;
1901 if (EffectiveTriple.isPS()) {
1902 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1903 StringRef Model = ModelArg ? ModelArg->getValue() : "";
1904 if (Model != "kernel") {
1905 PIC = true;
1906 ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1907 << LastPICArg->getSpelling()
1908 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1909 }
1910 }
1911 }
1912 }
1913 }
1914
1915 // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1916 // the PIC level would've been set to level 1, force it back to level 2 PIC
1917 // instead.
1918 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1919 IsPICLevelTwo |= ToolChain.isPICDefault();
1920
1921 // This kernel flags are a trump-card: they will disable PIC/PIE
1922 // generation, independent of the argument order.
1923 if (KernelOrKext &&
1924 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1925 !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1926 PIC = PIE = false;
1927
1928 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1929 // This is a very special mode. It trumps the other modes, almost no one
1930 // uses it, and it isn't even valid on any OS but Darwin.
1931 if (!Triple.isOSDarwin())
1932 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1933 << A->getSpelling() << Triple.str();
1934
1935 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1936
1937 // Only a forced PIC mode can cause the actual compile to have PIC defines
1938 // etc., no flags are sufficient. This behavior was selected to closely
1939 // match that of llvm-gcc and Apple GCC before that.
1941
1942 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1943 }
1944
1945 bool EmbeddedPISupported;
1946 switch (Triple.getArch()) {
1947 case llvm::Triple::arm:
1948 case llvm::Triple::armeb:
1949 case llvm::Triple::thumb:
1950 case llvm::Triple::thumbeb:
1951 EmbeddedPISupported = true;
1952 break;
1953 default:
1954 EmbeddedPISupported = false;
1955 break;
1956 }
1957
1958 bool ROPI = false, RWPI = false;
1959 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1960 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1961 if (!EmbeddedPISupported)
1962 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1963 << LastROPIArg->getSpelling() << Triple.str();
1964 ROPI = true;
1965 }
1966 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1967 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1968 if (!EmbeddedPISupported)
1969 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1970 << LastRWPIArg->getSpelling() << Triple.str();
1971 RWPI = true;
1972 }
1973
1974 // ROPI and RWPI are not compatible with PIC or PIE.
1975 if ((ROPI || RWPI) && (PIC || PIE))
1976 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1977
1978 if (Triple.isMIPS()) {
1979 StringRef CPUName;
1980 StringRef ABIName;
1981 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1982 // When targeting the N64 ABI, PIC is the default, except in the case
1983 // when the -mno-abicalls option is used. In that case we exit
1984 // at next check regardless of PIC being set below.
1985 if (ABIName == "n64")
1986 PIC = true;
1987 // When targettng MIPS with -mno-abicalls, it's always static.
1988 if(Args.hasArg(options::OPT_mno_abicalls))
1989 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1990 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1991 // does not use PIC level 2 for historical reasons.
1992 IsPICLevelTwo = false;
1993 }
1994
1995 if (PIC)
1996 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1997
1998 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1999 if (ROPI && RWPI)
2000 RelocM = llvm::Reloc::ROPI_RWPI;
2001 else if (ROPI)
2002 RelocM = llvm::Reloc::ROPI;
2003 else if (RWPI)
2004 RelocM = llvm::Reloc::RWPI;
2005
2006 return std::make_tuple(RelocM, 0U, false);
2007}
2008
2009// `-falign-functions` indicates that the functions should be aligned to a
2010// 16-byte boundary.
2011//
2012// `-falign-functions=1` is the same as `-fno-align-functions`.
2013//
2014// The scalar `n` in `-falign-functions=n` must be an integral value between
2015// [0, 65536]. If the value is not a power-of-two, it will be rounded up to
2016// the nearest power-of-two.
2017//
2018// If we return `0`, the frontend will default to the backend's preferred
2019// alignment.
2020//
2021// NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
2022// to mean `-falign-functions=16`. GCC defaults to the backend's preferred
2023// alignment. For unaligned functions, we default to the backend's preferred
2024// alignment.
2025unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
2026 const ArgList &Args) {
2027 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
2028 options::OPT_falign_functions_EQ,
2029 options::OPT_fno_align_functions);
2030 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
2031 return 0;
2032
2033 if (A->getOption().matches(options::OPT_falign_functions))
2034 return 0;
2035
2036 unsigned Value = 0;
2037 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
2038 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
2039 << A->getAsString(Args) << A->getValue();
2040 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
2041}
2042
2044 ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) {
2045 switch (DebugInfoKind) {
2046 case llvm::codegenoptions::DebugDirectivesOnly:
2047 CmdArgs.push_back("-debug-info-kind=line-directives-only");
2048 break;
2049 case llvm::codegenoptions::DebugLineTablesOnly:
2050 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2051 break;
2052 case llvm::codegenoptions::DebugInfoConstructor:
2053 CmdArgs.push_back("-debug-info-kind=constructor");
2054 break;
2055 case llvm::codegenoptions::LimitedDebugInfo:
2056 CmdArgs.push_back("-debug-info-kind=limited");
2057 break;
2058 case llvm::codegenoptions::FullDebugInfo:
2059 CmdArgs.push_back("-debug-info-kind=standalone");
2060 break;
2061 case llvm::codegenoptions::UnusedTypeInfo:
2062 CmdArgs.push_back("-debug-info-kind=unused-types");
2063 break;
2064 default:
2065 break;
2066 }
2067}
2068
2069// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2070// to the corresponding DebugInfoKind.
2071llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) {
2072 assert(A.getOption().matches(options::OPT_gN_Group) &&
2073 "Not a -g option that specifies a debug-info level");
2074 if (A.getOption().matches(options::OPT_g0) ||
2075 A.getOption().matches(options::OPT_ggdb0))
2076 return llvm::codegenoptions::NoDebugInfo;
2077 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2078 A.getOption().matches(options::OPT_ggdb1))
2079 return llvm::codegenoptions::DebugLineTablesOnly;
2080 if (A.getOption().matches(options::OPT_gline_directives_only))
2081 return llvm::codegenoptions::DebugDirectivesOnly;
2082 return llvm::codegenoptions::DebugInfoConstructor;
2083}
2084
2085static unsigned ParseDebugDefaultVersion(const ToolChain &TC,
2086 const ArgList &Args) {
2087 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
2088
2089 if (!A)
2090 return 0;
2091
2092 unsigned Value = 0;
2093 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
2094 Value < 2)
2095 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
2096 << A->getAsString(Args) << A->getValue();
2097 return Value;
2098}
2099
2100unsigned tools::DwarfVersionNum(StringRef ArgValue) {
2101 return llvm::StringSwitch<unsigned>(ArgValue)
2102 .Case("-gdwarf-2", 2)
2103 .Case("-gdwarf-3", 3)
2104 .Case("-gdwarf-4", 4)
2105 .Case("-gdwarf-5", 5)
2106 .Default(0);
2107}
2108
2109const Arg *tools::getDwarfNArg(const ArgList &Args) {
2110 return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2111 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
2112 options::OPT_gdwarf);
2113}
2114
2116 const llvm::opt::ArgList &Args) {
2117 unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args);
2118 if (const Arg *GDwarfN = getDwarfNArg(Args))
2119 if (int N = DwarfVersionNum(GDwarfN->getSpelling())) {
2120 DwarfVersion = N;
2121 if (DwarfVersion == 5 && TC.getTriple().isOSAIX())
2122 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
2123 << GDwarfN->getSpelling() << TC.getTriple().str();
2124 }
2125 if (DwarfVersion == 0) {
2126 DwarfVersion = TC.GetDefaultDwarfVersion();
2127 assert(DwarfVersion && "toolchain default DWARF version must be nonzero");
2128 }
2129 return DwarfVersion;
2130}
2131
2132void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
2133 ArgStringList &CmdArgs) {
2134 llvm::Reloc::Model RelocationModel;
2135 unsigned PICLevel;
2136 bool IsPIE;
2137 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
2138
2139 if (RelocationModel != llvm::Reloc::Static)
2140 CmdArgs.push_back("-KPIC");
2141}
2142
2143/// Determine whether Objective-C automated reference counting is
2144/// enabled.
2145bool tools::isObjCAutoRefCount(const ArgList &Args) {
2146 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
2147}
2148
2150
2151static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
2152 const ArgList &Args) {
2153 if (Args.hasArg(options::OPT_static_libgcc) ||
2154 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
2155 // The Android NDK only provides libunwind.a, not libunwind.so.
2156 TC.getTriple().isAndroid())
2158 if (Args.hasArg(options::OPT_shared_libgcc))
2161}
2162
2163// Gcc adds libgcc arguments in various ways:
2164//
2165// gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
2166// g++ <none>: -lgcc_s -lgcc
2167// gcc shared: -lgcc_s -lgcc
2168// g++ shared: -lgcc_s -lgcc
2169// gcc static: -lgcc -lgcc_eh
2170// g++ static: -lgcc -lgcc_eh
2171// gcc static-pie: -lgcc -lgcc_eh
2172// g++ static-pie: -lgcc -lgcc_eh
2173//
2174// Also, certain targets need additional adjustments.
2175
2176static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
2177 ArgStringList &CmdArgs, const ArgList &Args) {
2179 // By default OHOS binaries are linked statically to libunwind.
2180 if (TC.getTriple().isOHOSFamily() && UNW == ToolChain::UNW_CompilerRT) {
2181 CmdArgs.push_back("-l:libunwind.a");
2182 return;
2183 }
2184
2185 // Targets that don't use unwind libraries.
2186 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
2187 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
2188 TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
2189 return;
2190
2191 LibGccType LGT = getLibGccType(TC, D, Args);
2192 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
2193 (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
2194 !TC.getTriple().isAndroid() &&
2195 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
2196 if (AsNeeded)
2197 addAsNeededOption(TC, Args, CmdArgs, true);
2198
2199 switch (UNW) {
2201 return;
2202 case ToolChain::UNW_Libgcc: {
2203 if (LGT == LibGccType::StaticLibGcc)
2204 CmdArgs.push_back("-lgcc_eh");
2205 else
2206 CmdArgs.push_back("-lgcc_s");
2207 break;
2208 }
2210 if (TC.getTriple().isOSAIX()) {
2211 // AIX only has libunwind as a shared library. So do not pass
2212 // anything in if -static is specified.
2213 if (LGT != LibGccType::StaticLibGcc)
2214 CmdArgs.push_back("-lunwind");
2215 } else if (LGT == LibGccType::StaticLibGcc) {
2216 CmdArgs.push_back("-l:libunwind.a");
2217 } else if (LGT == LibGccType::SharedLibGcc) {
2218 if (TC.getTriple().isOSCygMing())
2219 CmdArgs.push_back("-l:libunwind.dll.a");
2220 else
2221 CmdArgs.push_back("-l:libunwind.so");
2222 } else {
2223 // Let the linker choose between libunwind.so and libunwind.a
2224 // depending on what's available, and depending on the -static flag
2225 CmdArgs.push_back("-lunwind");
2226 }
2227 break;
2228 }
2229
2230 if (AsNeeded)
2231 addAsNeededOption(TC, Args, CmdArgs, false);
2232}
2233
2234static void AddLibgcc(const ToolChain &TC, const Driver &D,
2235 ArgStringList &CmdArgs, const ArgList &Args) {
2236 LibGccType LGT = getLibGccType(TC, D, Args);
2237 if (LGT == LibGccType::StaticLibGcc ||
2238 (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
2239 CmdArgs.push_back("-lgcc");
2240 AddUnwindLibrary(TC, D, CmdArgs, Args);
2241 if (LGT == LibGccType::SharedLibGcc ||
2243 CmdArgs.push_back("-lgcc");
2244}
2245
2246void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
2247 ArgStringList &CmdArgs, const ArgList &Args) {
2248 // Make use of compiler-rt if --rtlib option is used
2250
2251 switch (RLT) {
2253 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2254 AddUnwindLibrary(TC, D, CmdArgs, Args);
2255 break;
2257 // Make sure libgcc is not used under MSVC environment by default
2258 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
2259 // Issue error diagnostic if libgcc is explicitly specified
2260 // through command line as --rtlib option argument.
2261 Arg *A = Args.getLastArg(options::OPT_rtlib_EQ);
2262 if (A && A->getValue() != StringRef("platform")) {
2263 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
2264 << A->getValue() << "MSVC";
2265 }
2266 } else
2267 AddLibgcc(TC, D, CmdArgs, Args);
2268 break;
2269 }
2270
2271 // On Android, the unwinder uses dl_iterate_phdr (or one of
2272 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
2273 // statically-linked executables, these functions come from libc.a instead.
2274 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
2275 !Args.hasArg(options::OPT_static_pie))
2276 CmdArgs.push_back("-ldl");
2277}
2278
2279SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
2280 const InputInfo &Output,
2281 const InputInfo &Input,
2282 const Driver &D) {
2283 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
2284 if (!A && !D.CCPrintInternalStats)
2285 return {};
2286
2287 SmallString<128> StatsFile;
2288 if (A) {
2289 StringRef SaveStats = A->getValue();
2290 if (SaveStats == "obj" && Output.isFilename()) {
2291 StatsFile.assign(Output.getFilename());
2292 llvm::sys::path::remove_filename(StatsFile);
2293 } else if (SaveStats != "cwd") {
2294 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
2295 return {};
2296 }
2297
2298 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
2299 llvm::sys::path::append(StatsFile, BaseName);
2300 llvm::sys::path::replace_extension(StatsFile, "stats");
2301 } else {
2302 assert(D.CCPrintInternalStats);
2303 StatsFile.assign(D.CCPrintInternalStatReportFilename.empty()
2304 ? "-"
2306 }
2307 return StatsFile;
2308}
2309
2310void tools::addMultilibFlag(bool Enabled, const StringRef Flag,
2311 Multilib::flags_list &Flags) {
2312 assert(Flag.front() == '-');
2313 if (Enabled) {
2314 Flags.push_back(Flag.str());
2315 } else {
2316 Flags.push_back(("!" + Flag.substr(1)).str());
2317 }
2318}
2319
2320void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
2321 ArgStringList &CmdArgs, bool IsLTO,
2322 const StringRef PluginOptPrefix) {
2323 auto addArg = [&, IsLTO](const Twine &Arg) {
2324 if (IsLTO) {
2325 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2326 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2327 } else {
2328 CmdArgs.push_back("-mllvm");
2329 CmdArgs.push_back(Args.MakeArgString(Arg));
2330 }
2331 };
2332
2333 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
2334 addArg(Twine("-x86-branches-within-32B-boundaries"));
2335 }
2336 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
2337 StringRef Value = A->getValue();
2338 unsigned Boundary;
2339 if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
2340 !llvm::isPowerOf2_64(Boundary)) {
2341 D.Diag(diag::err_drv_invalid_argument_to_option)
2342 << Value << A->getOption().getName();
2343 } else {
2344 addArg("-x86-align-branch-boundary=" + Twine(Boundary));
2345 }
2346 }
2347 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
2348 std::string AlignBranch;
2349 for (StringRef T : A->getValues()) {
2350 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
2351 T != "ret" && T != "indirect")
2352 D.Diag(diag::err_drv_invalid_malign_branch_EQ)
2353 << T << "fused, jcc, jmp, call, ret, indirect";
2354 if (!AlignBranch.empty())
2355 AlignBranch += '+';
2356 AlignBranch += T;
2357 }
2358 addArg("-x86-align-branch=" + Twine(AlignBranch));
2359 }
2360 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
2361 StringRef Value = A->getValue();
2362 unsigned PrefixSize;
2363 if (Value.getAsInteger(10, PrefixSize)) {
2364 D.Diag(diag::err_drv_invalid_argument_to_option)
2365 << Value << A->getOption().getName();
2366 } else {
2367 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
2368 }
2369 }
2370}
2371
2372/// SDLSearch: Search for Static Device Library
2373/// The search for SDL bitcode files is consistent with how static host
2374/// libraries are discovered. That is, the -l option triggers a search for
2375/// files in a set of directories called the LINKPATH. The host library search
2376/// procedure looks for a specific filename in the LINKPATH. The filename for
2377/// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
2378/// ordered-set of filenames that are searched. We call this ordered-set of
2379/// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
2380/// architecture specific, or generic across all architectures, a naming
2381/// convention and search order is used where the file name embeds the
2382/// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
2383/// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
2384/// device-independent SDLs. To reduce congestion in host library directories,
2385/// the search first looks for files in the “libdevice” subdirectory. SDLs that
2386/// are bc files begin with the prefix “lib”.
2387///
2388/// Machine-code SDLs can also be managed as an archive (*.a file). The
2389/// convention has been to use the prefix “lib”. To avoid confusion with host
2390/// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
2391///
2392static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
2393 llvm::opt::ArgStringList &CC1Args,
2394 const SmallVectorImpl<std::string> &LibraryPaths,
2395 StringRef Lib, StringRef Arch, StringRef Target,
2396 bool isBitCodeSDL) {
2398
2399 std::string LibDeviceLoc = "/libdevice";
2400 std::string LibBcPrefix = "/libbc-";
2401 std::string LibPrefix = "/lib";
2402
2403 if (isBitCodeSDL) {
2404 // SEARCH-ORDER for Bitcode SDLs:
2405 // libdevice/libbc-<libname>-<arch-name>-<device-type>.a
2406 // libbc-<libname>-<arch-name>-<device-type>.a
2407 // libdevice/libbc-<libname>-<arch-name>.a
2408 // libbc-<libname>-<arch-name>.a
2409 // libdevice/libbc-<libname>.a
2410 // libbc-<libname>.a
2411 // libdevice/lib<libname>-<arch-name>-<device-type>.bc
2412 // lib<libname>-<arch-name>-<device-type>.bc
2413 // libdevice/lib<libname>-<arch-name>.bc
2414 // lib<libname>-<arch-name>.bc
2415 // libdevice/lib<libname>.bc
2416 // lib<libname>.bc
2417
2418 for (StringRef Base : {LibBcPrefix, LibPrefix}) {
2419 const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
2420
2421 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2422 Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
2423 SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
2424 SDLs.push_back(Twine(Base + Suffix + Ext).str());
2425 }
2426 }
2427 } else {
2428 // SEARCH-ORDER for Machine-code SDLs:
2429 // libdevice/lib<libname>-<arch-name>-<device-type>.a
2430 // lib<libname>-<arch-name>-<device-type>.a
2431 // libdevice/lib<libname>-<arch-name>.a
2432 // lib<libname>-<arch-name>.a
2433
2434 const auto *Ext = ".a";
2435
2436 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2437 Twine(Lib + "-" + Arch).str()}) {
2438 SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
2439 SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
2440 }
2441 }
2442
2443 // The CUDA toolchain does not use a global device llvm-link before the LLVM
2444 // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
2445 // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
2446 // will link libraries after clang compilation while the LLVM IR is still in
2447 // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
2448 // This is a clang -cc1 option that is generated by the clang driver. The
2449 // option value must a full path to an existing file.
2450 bool FoundSDL = false;
2451 for (auto LPath : LibraryPaths) {
2452 for (auto SDL : SDLs) {
2453 auto FullName = Twine(LPath + SDL).str();
2454 if (llvm::sys::fs::exists(FullName)) {
2455 CC1Args.push_back(DriverArgs.MakeArgString(FullName));
2456 FoundSDL = true;
2457 break;
2458 }
2459 }
2460 if (FoundSDL)
2461 break;
2462 }
2463 return FoundSDL;
2464}
2465
2466/// Search if a user provided archive file lib<libname>.a exists in any of
2467/// the library paths. If so, add a new command to clang-offload-bundler to
2468/// unbundle this archive and create a temporary device specific archive. Name
2469/// of this SDL is passed to the llvm-link tool.
2471 Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
2472 const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
2473 llvm::opt::ArgStringList &CC1Args,
2474 const SmallVectorImpl<std::string> &LibraryPaths, StringRef Lib,
2475 StringRef Arch, StringRef Target, bool isBitCodeSDL) {
2476
2477 // We don't support bitcode archive bundles for nvptx
2478 if (isBitCodeSDL && Arch.contains("nvptx"))
2479 return;
2480
2481 bool FoundAOB = false;
2482 std::string ArchiveOfBundles;
2483
2484 llvm::Triple Triple(D.getTargetTriple());
2485 bool IsMSVC = Triple.isWindowsMSVCEnvironment();
2486 auto Ext = IsMSVC ? ".lib" : ".a";
2487 if (!Lib.starts_with(":") && !Lib.starts_with("-l")) {
2488 if (llvm::sys::fs::exists(Lib)) {
2489 ArchiveOfBundles = Lib;
2490 FoundAOB = true;
2491 }
2492 } else {
2493 Lib.consume_front("-l");
2494 for (auto LPath : LibraryPaths) {
2495 ArchiveOfBundles.clear();
2496 auto LibFile = (Lib.starts_with(":") ? Lib.drop_front()
2497 : IsMSVC ? Lib + Ext
2498 : "lib" + Lib + Ext)
2499 .str();
2500 for (auto Prefix : {"/libdevice/", "/"}) {
2501 auto AOB = Twine(LPath + Prefix + LibFile).str();
2502 if (llvm::sys::fs::exists(AOB)) {
2503 ArchiveOfBundles = AOB;
2504 FoundAOB = true;
2505 break;
2506 }
2507 }
2508 if (FoundAOB)
2509 break;
2510 }
2511 }
2512
2513 if (!FoundAOB)
2514 return;
2515
2516 llvm::file_magic Magic;
2517 auto EC = llvm::identify_magic(ArchiveOfBundles, Magic);
2518 if (EC || Magic != llvm::file_magic::archive)
2519 return;
2520
2521 StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
2522 std::string OutputLib =
2523 D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" +
2524 Arch + "-" + Target)
2525 .str(),
2526 "a");
2527
2528 C.addTempFile(C.getArgs().MakeArgString(OutputLib));
2529
2530 ArgStringList CmdArgs;
2531 SmallString<128> DeviceTriple;
2533 DeviceTriple += '-';
2534 std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
2535 DeviceTriple += NormalizedTriple;
2536 if (!Target.empty()) {
2537 DeviceTriple += '-';
2538 DeviceTriple += Target;
2539 }
2540
2541 std::string UnbundleArg("-unbundle");
2542 std::string TypeArg("-type=a");
2543 std::string InputArg("-input=" + ArchiveOfBundles);
2544 std::string OffloadArg("-targets=" + std::string(DeviceTriple));
2545 std::string OutputArg("-output=" + OutputLib);
2546
2547 const char *UBProgram = DriverArgs.MakeArgString(
2548 T.getToolChain().GetProgramPath("clang-offload-bundler"));
2549
2550 ArgStringList UBArgs;
2551 UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
2552 UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
2553 UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
2554 UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
2555 UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
2556
2557 // Add this flag to not exit from clang-offload-bundler if no compatible
2558 // code object is found in heterogenous archive library.
2559 std::string AdditionalArgs("-allow-missing-bundles");
2560 UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
2561
2562 // Add this flag to treat hip and hipv4 offload kinds as compatible with
2563 // openmp offload kind while extracting code objects from a heterogenous
2564 // archive library. Vice versa is also considered compatible.
2565 std::string HipCompatibleArgs("-hip-openmp-compatible");
2566 UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
2567
2568 C.addCommand(std::make_unique<Command>(
2569 JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
2570 InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
2571
2572 CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
2573
2574 return;
2575}
2576
2577// Wrapper function used by driver for adding SDLs during link phase.
2579 const JobAction &JA,
2580 const InputInfoList &Inputs,
2581 const llvm::opt::ArgList &DriverArgs,
2582 llvm::opt::ArgStringList &CC1Args,
2583 StringRef Arch, StringRef Target,
2584 bool isBitCodeSDL) {
2585 AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
2586 Arch, Target, isBitCodeSDL);
2587}
2588
2589// User defined Static Device Libraries(SDLs) can be passed to clang for
2590// offloading GPU compilers. Like static host libraries, the use of a SDL is
2591// specified with the -l command line option. The primary difference between
2592// host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
2593// and SEARCH-ORDER for Machine-code SDLs for the naming convention).
2594// SDLs are of following types:
2595//
2596// * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
2597// For NVPTX, these libraries are post-clang linked following each
2598// compilation. For AMDGPU, these libraries are linked one time
2599// during the application link phase.
2600//
2601// * Machine-code SDLs: They are archive files. For AMDGPU, the process for
2602// machine code SDLs is still in development. But they will be linked
2603// by the LLVM tool lld.
2604//
2605// * Bundled objects that contain both host and device codes: Bundled objects
2606// may also contain library code compiled from source. For NVPTX, the
2607// bundle contains cubin. For AMDGPU, the bundle contains bitcode.
2608//
2609// For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
2610// inclusion of specific SDLs such as math libraries and the OpenMP device
2611// library libomptarget.
2613 const JobAction *JA,
2614 const InputInfoList *Inputs, const Driver &D,
2615 const llvm::opt::ArgList &DriverArgs,
2616 llvm::opt::ArgStringList &CC1Args,
2617 StringRef Arch, StringRef Target,
2618 bool isBitCodeSDL) {
2619
2620 SmallVector<std::string, 8> LibraryPaths;
2621 // Add search directories from LIBRARY_PATH env variable
2622 std::optional<std::string> LibPath =
2623 llvm::sys::Process::GetEnv("LIBRARY_PATH");
2624 if (LibPath) {
2626 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2627 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2628 for (StringRef Path : Frags)
2629 LibraryPaths.emplace_back(Path.trim());
2630 }
2631
2632 // Add directories from user-specified -L options
2633 for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
2634 LibraryPaths.emplace_back(Search_Dir);
2635
2636 // Add path to lib-debug folders
2637 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2638 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
2639 LibraryPaths.emplace_back(DefaultLibPath.c_str());
2640
2641 // Build list of Static Device Libraries SDLs specified by -l option
2642 llvm::SmallSet<std::string, 16> SDLNames;
2643 static const StringRef HostOnlyArchives[] = {
2644 "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
2645 for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
2646 if (!llvm::is_contained(HostOnlyArchives, SDLName)) {
2647 SDLNames.insert(std::string("-l") + SDLName);
2648 }
2649 }
2650
2651 for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) {
2652 auto FileName = StringRef(Input);
2653 // Clang treats any unknown file types as archives and passes them to the
2654 // linker. Files with extension 'lib' are classified as TY_Object by clang
2655 // but they are usually archives. It is OK if the file is not really an
2656 // archive since GetSDLFromOffloadArchive will check the magic of the file
2657 // and only unbundle it if it is really an archive.
2658 const StringRef LibFileExt = ".lib";
2659 if (!llvm::sys::path::has_extension(FileName) ||
2661 llvm::sys::path::extension(FileName).drop_front()) ==
2663 llvm::sys::path::extension(FileName) == LibFileExt)
2664 SDLNames.insert(Input);
2665 }
2666
2667 // The search stops as soon as an SDL file is found. The driver then provides
2668 // the full filename of the SDL to the llvm-link command. If no SDL is found
2669 // after searching each LINKPATH with SEARCH-ORDER, it is possible that an
2670 // archive file lib<libname>.a exists and may contain bundled object files.
2671 for (auto SDLName : SDLNames) {
2672 // This is the only call to SDLSearch
2673 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
2674 isBitCodeSDL)) {
2675 GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
2676 LibraryPaths, SDLName, Arch, Target,
2677 isBitCodeSDL);
2678 }
2679 }
2680}
2681
2682static llvm::opt::Arg *
2683getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
2684 return Args.getLastArg(options::OPT_mcode_object_version_EQ);
2685}
2686
2688 const llvm::opt::ArgList &Args) {
2689 const unsigned MinCodeObjVer = 4;
2690 const unsigned MaxCodeObjVer = 6;
2691
2692 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2693 if (CodeObjArg->getOption().getID() ==
2694 options::OPT_mcode_object_version_EQ) {
2695 unsigned CodeObjVer = MaxCodeObjVer;
2696 auto Remnant =
2697 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2698 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
2699 D.Diag(diag::err_drv_invalid_int_value)
2700 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
2701
2702 // COV6 is only supported by LLVM at the time of writing this, and it's
2703 // expected to take some time before all ROCm components fully
2704 // support it. In the meantime, make sure users are aware of this.
2705 if (CodeObjVer == 6)
2706 D.Diag(diag::warn_drv_amdgpu_cov6);
2707 }
2708 }
2709}
2710
2712 const llvm::opt::ArgList &Args) {
2713 unsigned CodeObjVer = 4; // default
2714 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args))
2715 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2716 return CodeObjVer;
2717}
2718
2720 const Driver &D, const llvm::opt::ArgList &Args) {
2721 return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2722}
2723
2725 const llvm::opt::ArgList &Args,
2726 llvm::opt::ArgStringList &CmdArgs,
2727 const llvm::Triple &Triple, bool IsLTO,
2728 const StringRef PluginOptPrefix) {
2729 auto addArg = [&, IsLTO](const Twine &Arg) {
2730 if (IsLTO) {
2731 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2732 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2733 } else {
2734 CmdArgs.push_back("-mllvm");
2735 CmdArgs.push_back(Args.MakeArgString(Arg));
2736 }
2737 };
2738
2739 if (Arg *A = Args.getLastArg(options::OPT_moutline,
2740 options::OPT_mno_outline)) {
2741 if (A->getOption().matches(options::OPT_moutline)) {
2742 // We only support -moutline in AArch64 and ARM targets right now. If
2743 // we're not compiling for these, emit a warning and ignore the flag.
2744 // Otherwise, add the proper mllvm flags.
2745 if (!(Triple.isARM() || Triple.isThumb() || Triple.isAArch64())) {
2746 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2747 } else {
2748 addArg(Twine("-enable-machine-outliner"));
2749 }
2750 } else {
2751 // Disable all outlining behaviour.
2752 addArg(Twine("-enable-machine-outliner=never"));
2753 }
2754 }
2755}
2756
2758 const llvm::opt::ArgList &DriverArgs,
2759 llvm::opt::ArgStringList &CC1Args,
2760 StringRef BitcodeSuffix,
2761 const llvm::Triple &Triple,
2762 const ToolChain &HostTC) {
2763 SmallVector<StringRef, 8> LibraryPaths;
2764
2765 // Add user defined library paths from LIBRARY_PATH.
2766 std::optional<std::string> LibPath =
2767 llvm::sys::Process::GetEnv("LIBRARY_PATH");
2768 if (LibPath) {
2770 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2771 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2772 for (StringRef Path : Frags)
2773 LibraryPaths.emplace_back(Path.trim());
2774 }
2775
2776 // Check all of the standard library search paths used by the compiler.
2777 for (const auto &LibPath : HostTC.getFilePaths())
2778 LibraryPaths.emplace_back(LibPath);
2779
2780 OptSpecifier LibomptargetBCPathOpt =
2781 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2782 : options::OPT_libomptarget_nvptx_bc_path_EQ;
2783
2784 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2785 std::string LibOmpTargetName =
2786 ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2787
2788 // First check whether user specifies bc library
2789 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2790 SmallString<128> LibOmpTargetFile(A->getValue());
2791 if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2792 llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2793 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2794 }
2795
2796 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2797 CC1Args.push_back("-mlink-builtin-bitcode");
2798 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2799 } else {
2800 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2801 << LibOmpTargetFile;
2802 }
2803 } else {
2804 bool FoundBCLibrary = false;
2805
2806 for (StringRef LibraryPath : LibraryPaths) {
2807 SmallString<128> LibOmpTargetFile(LibraryPath);
2808 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2809 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2810 CC1Args.push_back("-mlink-builtin-bitcode");
2811 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2812 FoundBCLibrary = true;
2813 break;
2814 }
2815 }
2816
2817 if (!FoundBCLibrary)
2818 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2819 << LibOmpTargetName << ArchPrefix;
2820 }
2821}
2823 const llvm::opt::ArgList &Args,
2824 llvm::opt::ArgStringList &CmdArgs) {
2825 if ((C.getActiveOffloadKinds() & Action::OFK_HIP) &&
2826 !Args.hasArg(options::OPT_nostdlib) &&
2827 !Args.hasArg(options::OPT_no_hip_rt) && !Args.hasArg(options::OPT_r)) {
2828 TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2829 } else {
2830 // Claim "no HIP libraries" arguments if any
2831 for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) {
2832 Arg->claim();
2833 }
2834 }
2835}
2836
2838 const llvm::opt::ArgList &Args,
2839 llvm::opt::ArgStringList &CmdArgs,
2840 const llvm::Triple &Triple) {
2841 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
2842 options::OPT_mno_outline_atomics)) {
2843 // Option -moutline-atomics supported for AArch64 target only.
2844 if (!Triple.isAArch64()) {
2845 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
2846 << Triple.getArchName() << A->getOption().getName();
2847 } else {
2848 if (A->getOption().matches(options::OPT_moutline_atomics)) {
2849 CmdArgs.push_back("-target-feature");
2850 CmdArgs.push_back("+outline-atomics");
2851 } else {
2852 CmdArgs.push_back("-target-feature");
2853 CmdArgs.push_back("-outline-atomics");
2854 }
2855 }
2856 } else if (Triple.isAArch64() && TC.IsAArch64OutlineAtomicsDefault(Args)) {
2857 CmdArgs.push_back("-target-feature");
2858 CmdArgs.push_back("+outline-atomics");
2859 }
2860}
2861
2862void tools::addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs,
2863 llvm::opt::ArgStringList &CmdArgs) {
2864 if (TCArgs.hasFlag(options::OPT_offload_compress,
2865 options::OPT_no_offload_compress, false))
2866 CmdArgs.push_back("-compress");
2867 if (TCArgs.hasArg(options::OPT_v))
2868 CmdArgs.push_back("-verbose");
2869 if (auto *Arg = TCArgs.getLastArg(options::OPT_offload_compression_level_EQ))
2870 CmdArgs.push_back(
2871 TCArgs.MakeArgString(Twine("-compression-level=") + Arg->getValue()));
2872}
#define V(N, I)
Definition: ASTContext.h:3273
static unsigned ParseDebugDefaultVersion(const ToolChain &TC, const ArgList &Args)
static void getWebAssemblyTargetFeatures(const Driver &D, const llvm::Triple &Triple, const ArgList &Args, std::vector< StringRef > &Features)
Definition: CommonArgs.cpp:623
LibGccType
static bool isWholeArchivePresent(const ArgList &Args)
Determines if –whole-archive is active in the list of arguments.
static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, StringRef Sanitizer)
static void addOpenMPDeviceLibC(const Compilation &C, const ArgList &Args, ArgStringList &CmdArgs)
Adds the '-lcgpu' and '-lmgpu' libraries to the compilation to include the LLVM C library for GPUs.
static llvm::opt::Arg * getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args)
static void collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, SmallVectorImpl< StringRef > &SharedRuntimes, SmallVectorImpl< StringRef > &StaticRuntimes, SmallVectorImpl< StringRef > &NonWholeStaticRuntimes, SmallVectorImpl< StringRef > &HelperStaticRuntimes, SmallVectorImpl< StringRef > &RequiredSymbols)
static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, StringRef Sanitizer, bool IsShared, bool IsWhole)
static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, ArgStringList &CmdArgs, const ArgList &Args)
static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const SmallVectorImpl< std::string > &LibraryPaths, StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL)
SDLSearch: Search for Static Device Library The search for SDL bitcode files is consistent with how s...
static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs, const StringRef PluginOptPrefix)
Definition: CommonArgs.cpp:214
static void addFortranMain(const ToolChain &TC, const ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
static StringRef getWebAssemblyTargetCPU(const ArgList &Args)
Get the (LLVM) name of the WebAssembly cpu we are targeting.
Definition: CommonArgs.cpp:503
static bool isStaticLinkage(const ArgList &Args)
Determine if driver is invoked to create a static object library (-shared)
static void renderRemarksHotnessOptions(const ArgList &Args, ArgStringList &CmdArgs, const StringRef PluginOptPrefix)
Definition: CommonArgs.cpp:260
static void GetSDLFromOffloadArchive(Compilation &C, const Driver &D, const Tool &T, const JobAction &JA, const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const SmallVectorImpl< std::string > &LibraryPaths, StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL)
Search if a user provided archive file lib<libname>.a exists in any of the library paths.
static std::string getLanaiTargetCPU(const ArgList &Args)
Definition: CommonArgs.cpp:495
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const StringRef PluginOptPrefix)
Definition: CommonArgs.cpp:229
static bool useFramePointerForTargetByDefault(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: CommonArgs.cpp:75
static void AddLibgcc(const ToolChain &TC, const Driver &D, ArgStringList &CmdArgs, const ArgList &Args)
static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, const ArgList &Args)
clang::CodeGenOptions::FramePointerKind getFramePointerKind(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: CommonArgs.cpp:180
static bool isSharedLinkage(const ArgList &Args)
Determine if driver is invoked to create a shared object library (-static)
static std::string getAMDGPUTargetGPU(const llvm::Triple &T, const ArgList &Args)
Get the (LLVM) name of the AMDGPU gpu we are targeting.
Definition: CommonArgs.cpp:475
static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple)
Definition: CommonArgs.cpp:167
static void addFortranRuntimeLibsMSVC(const ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Add Fortran runtime libs for MSVC.
static bool shouldIgnoreUnsupportedTargetFeature(const Arg &TargetFeatureArg, llvm::Triple T, StringRef Processor)
Definition: CommonArgs.cpp:275
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:48
Defines types useful for describing an Objective-C runtime.
Defines version macros and version-related utility functions for Clang.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
const char * getOffloadingArch() const
Definition: Action.h:211
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition: Action.cpp:156
OffloadKind getOffloadingDeviceKind() const
Definition: Action.h:210
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition: Action.h:218
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:77
std::string CCPrintInternalStatReportFilename
The file to log CC_PRINT_INTERNAL_STAT_FILE output to, if enabled.
Definition: Driver.h:195
DiagnosticsEngine & getDiags() const
Definition: Driver.h:401
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition: Driver.cpp:735
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:144
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition: Driver.h:274
StringRef getFlangF128MathLibrary() const
Definition: Driver.h:445
llvm::vfs::FileSystem & getVFS() const
Definition: Driver.h:403
std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const
GetTemporaryPath - Return the pathname of a temporary file to use as part of compilation; the file wi...
Definition: Driver.cpp:6258
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:155
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition: Driver.h:140
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition: Driver.h:130
@ OMPRT_Unknown
An unknown OpenMP runtime.
Definition: Driver.h:126
@ OMPRT_GOMP
The GNU OpenMP runtime.
Definition: Driver.h:135
std::string getTargetTriple() const
Definition: Driver.h:420
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition: Driver.h:213
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getBaseInput() const
Definition: InputInfo.h:78
const char * getFilename() const
Definition: InputInfo.h:83
bool isFilename() const
Definition: InputInfo.h:75
std::vector< std::string > flags_list
Definition: Multilib.h:34
bool requiresMinimalRuntime() const
Definition: SanitizerArgs.h:99
const std::string & getMemtagMode() const
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:92
virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCCKextLibArgs - Add the system specific linker arguments to use for kernel extensions (Darwin-spec...
Definition: ToolChain.cpp:1303
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
Definition: ToolChain.cpp:145
virtual void AddHIPRuntimeLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Add the system specific linker arguments to use for the given HIP runtime library type.
Definition: ToolChain.h:776
std::optional< std::string > getStdlibPath() const
Definition: ToolChain.cpp:808
virtual unsigned GetDefaultDwarfVersion() const
Definition: ToolChain.h:583
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:1081
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:704
path_list & getFilePaths()
Definition: ToolChain.h:294
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:268
const Driver & getDriver() const
Definition: ToolChain.h:252
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:141
const XRayArgs & getXRayArgs() const
Definition: ToolChain.cpp:306
virtual bool isPIEDefault(const llvm::opt::ArgList &Args) const =0
Test whether this toolchain defaults to PIE.
virtual bool isPICDefaultForced() const =0
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition: ToolChain.h:282
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChain.cpp:1277
const llvm::Triple & getTriple() const
Definition: ToolChain.h:254
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: ToolChain.cpp:959
virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:1107
std::string GetLinkerPath(bool *LinkerIsLLD=nullptr) const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name.
Definition: ToolChain.cpp:868
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:673
std::string GetProgramPath(const char *Name) const
Definition: ToolChain.cpp:864
std::string getTripleString() const
Definition: ToolChain.h:277
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const
Definition: ToolChain.cpp:300
virtual bool IsAArch64OutlineAtomicsDefault(const llvm::opt::ArgList &Args) const
Test whether this toolchain supports outline atomics by default.
Definition: ToolChain.h:547
virtual path_list getArchSpecificLibPaths() const
Definition: ToolChain.cpp:814
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
Definition: ToolChain.cpp:963
virtual bool isPICDefault() const =0
Test whether this toolchain defaults to PIC.
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
bool needsXRayRt() const
Definition: XRayArgs.h:37
llvm::ArrayRef< std::string > modeList() const
Definition: XRayArgs.h:38
static StringRef GetTargetCPUVersion(const llvm::opt::ArgList &Args)
Definition: Hexagon.cpp:794
void getNVPTXTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features)
Definition: Cuda.cpp:671
void getAArch64TargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features, bool ForAS)
std::string getAArch64TargetCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, llvm::opt::Arg *&A)
void getAMDGPUTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features)
Definition: AMDGPU.cpp:643
void getARMArchCPUFromArgs(const llvm::opt::ArgList &Args, llvm::StringRef &Arch, llvm::StringRef &CPU, bool FromAs=false)
std::string getARMTargetCPU(StringRef CPU, llvm::StringRef Arch, const llvm::Triple &Triple)
llvm::ARM::FPUKind getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features, bool ForAS, bool ForMultilib=false)
void getCSKYTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, std::vector< llvm::StringRef > &Features)
void getHexagonTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features)
std::string getLoongArchTargetCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: LoongArch.cpp:224
void getLoongArchTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
void getM68kTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
std::string getM68kTargetCPU(const llvm::opt::ArgList &Args)
void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features)
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
void getMSP430TargetFeatures(const Driver &D, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
std::string getPPCTargetCPU(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T)
void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
std::string getRISCVTargetCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: RISCV.cpp:339
void getRISCVTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
bool isLinkerGnuLd(const ToolChain &TC, const llvm::opt::ArgList &Args)
void getSparcTargetFeatures(const Driver &D, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
std::string getSparcTargetCPU(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
void getSystemZTargetFeatures(const Driver &D, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
std::string getSystemZTargetCPU(const llvm::opt::ArgList &Args)
void getVETargetFeatures(const Driver &D, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
std::string getX86TargetCPU(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
void AddStaticDeviceLibs(Compilation *C, const Tool *T, const JobAction *JA, const InputInfoList *Inputs, const Driver &D, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CmdArgs, StringRef Arch, StringRef Target, bool isBitCodeSDL)
void addX86AlignBranchArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsLTO, const StringRef PluginOptPrefix="")
void addMachineOutlinerArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple, bool IsLTO, const StringRef PluginOptPrefix="")
unsigned ParseFunctionAlignment(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, llvm::opt::ArgStringList &CmdArgs)
void handleTargetFeaturesGroup(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features, llvm::opt::OptSpecifier Group)
Iterate Args and convert -mxxx to +xxx and -mno-xxx to -xxx and append it to Features.
SmallVector< StringRef > unifyTargetFeatures(ArrayRef< StringRef > Features)
If there are multiple +xxx or -xxx features, keep the last one.
Definition: CommonArgs.cpp:328
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
void addOpenMPDeviceRTL(const Driver &D, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, StringRef BitcodeSuffix, const llvm::Triple &Triple, const ToolChain &HostTC)
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
void addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
void checkAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
void getTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForAS, bool IsAux=false)
void AddStaticDeviceLibsLinking(Compilation &C, const Tool &T, const JobAction &JA, const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CmdArgs, StringRef Arch, StringRef Target, bool isBitCodeSDL)
void addAsNeededOption(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool as_needed)
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
void addHIPRuntimeLibArgs(const ToolChain &TC, Compilation &C, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addMultilibFlag(bool Enabled, const StringRef Flag, Multilib::flags_list &Flags)
Flag must be a flag accepted by the driver.
bool isUseSeparateSections(const llvm::Triple &Triple)
Definition: CommonArgs.cpp:727
void linkXRayRuntimeDeps(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Output, const char *OutFile)
void linkSanitizerRuntimeDeps(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
bool addSanitizerRuntimes(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
bool areOptimizationsEnabled(const llvm::opt::ArgList &Args)
void addOpenMPRuntimeLibraryPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
bool addXRayRuntime(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void AddAssemblerKPIC(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
bool haveAMDGPUCodeObjectVersionArgument(const Driver &D, const llvm::opt::ArgList &Args)
bool isTLSDESCEnabled(const ToolChain &TC, const llvm::opt::ArgList &Args)
Definition: CommonArgs.cpp:731
void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
void addPathIfExists(const Driver &D, const Twine &Path, ToolChain::path_list &Paths)
Definition: CommonArgs.cpp:290
llvm::codegenoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A)
llvm::opt::Arg * getLastCSProfileGenerateArg(const llvm::opt::ArgList &Args)
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
void addFortranRuntimeLibraryPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds the path for the Fortran runtime libraries to CmdArgs.
llvm::StringRef getLTOParallelism(const llvm::opt::ArgList &Args, const Driver &D)
void addLinkerCompressDebugSectionsOption(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Definition: CommonArgs.cpp:444
void addLTOOptions(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const InputInfo &Output, const InputInfo &Input, bool IsThinLTO)
bool addOpenMPRuntime(const Compilation &C, llvm::opt::ArgStringList &CmdArgs, const ToolChain &TC, const llvm::opt::ArgList &Args, bool ForceStaticHostRuntime=false, bool IsOffloadingHost=false, bool GompNeedsRT=false)
Returns true, if an OpenMP runtime has been added.
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
unsigned DwarfVersionNum(StringRef ArgValue)
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
unsigned getDwarfVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
const llvm::opt::Arg * getDwarfNArg(const llvm::opt::ArgList &Args)
void AddTargetFeature(const llvm::opt::ArgList &Args, std::vector< StringRef > &Features, llvm::opt::OptSpecifier OnOpt, llvm::opt::OptSpecifier OffOpt, StringRef FeatureName)
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
void addArchSpecificRPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
void addFortranRuntimeLibs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds Fortran runtime libraries to CmdArgs.
const char * RelocationModelName(llvm::Reloc::Model Model)
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition: Types.cpp:255
ID lookupTypeForExtension(llvm::StringRef Ext)
lookupTypeForExtension - Lookup the type to use for the file extension Ext.
Definition: Types.cpp:298
bool willEmitRemarks(const llvm::opt::ArgList &Args)
The JSON file list parser is used to communicate input to InstallAPI.
llvm::StringRef getProcessorFromTargetID(const llvm::Triple &T, llvm::StringRef OffloadArch)
Get processor name from target ID.
Definition: TargetID.cpp:54
const FunctionProtoType * T
static constexpr ResponseFileSupport AtFileCurCP()
Definition: Job.h:92