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/M68k.h"
13 #include "Arch/Mips.h"
14 #include "Arch/PPC.h"
15 #include "Arch/Sparc.h"
16 #include "Arch/SystemZ.h"
17 #include "Arch/VE.h"
18 #include "Arch/X86.h"
19 #include "HIPAMD.h"
20 #include "Hexagon.h"
21 #include "clang/Basic/CharInfo.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/ObjCRuntime.h"
24 #include "clang/Basic/Version.h"
25 #include "clang/Config/config.h"
26 #include "clang/Driver/Action.h"
27 #include "clang/Driver/Compilation.h"
28 #include "clang/Driver/Driver.h"
29 #include "clang/Driver/DriverDiagnostic.h"
30 #include "clang/Driver/InputInfo.h"
31 #include "clang/Driver/Job.h"
32 #include "clang/Driver/Options.h"
33 #include "clang/Driver/SanitizerArgs.h"
34 #include "clang/Driver/ToolChain.h"
35 #include "clang/Driver/Util.h"
36 #include "clang/Driver/XRayArgs.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/ADT/Twine.h"
43 #include "llvm/Config/llvm-config.h"
44 #include "llvm/Option/Arg.h"
45 #include "llvm/Option/ArgList.h"
46 #include "llvm/Option/Option.h"
47 #include "llvm/Support/CodeGen.h"
48 #include "llvm/Support/Compression.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/FileSystem.h"
52 #include "llvm/Support/Host.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/Process.h"
55 #include "llvm/Support/Program.h"
56 #include "llvm/Support/ScopedPrinter.h"
57 #include "llvm/Support/TargetParser.h"
58 #include "llvm/Support/Threading.h"
59 #include "llvm/Support/VirtualFileSystem.h"
60 #include "llvm/Support/YAMLParser.h"
61 
62 using namespace clang::driver;
63 using namespace clang::driver::tools;
64 using namespace clang;
65 using namespace llvm::opt;
66 
67 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
68   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
69     CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") +
70                                          A->getValue()));
71 
72   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
73     CmdArgs.push_back(Args.MakeArgString(
74         Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue()));
75 
76   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
77     CmdArgs.push_back(Args.MakeArgString(
78         Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue()));
79 }
80 
81 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
82                                  const llvm::Triple &Triple,
83                                  const InputInfo &Input,
84                                  const InputInfo &Output) {
85   StringRef Format = "yaml";
86   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
87     Format = A->getValue();
88 
89   SmallString<128> F;
90   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
91   if (A)
92     F = A->getValue();
93   else if (Output.isFilename())
94     F = Output.getFilename();
95 
96   assert(!F.empty() && "Cannot determine remarks output name.");
97   // Append "opt.ld.<format>" to the end of the file name.
98   CmdArgs.push_back(
99       Args.MakeArgString(Twine("--plugin-opt=opt-remarks-filename=") + F +
100                          Twine(".opt.ld.") + Format));
101 
102   if (const Arg *A =
103           Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
104     CmdArgs.push_back(Args.MakeArgString(
105         Twine("--plugin-opt=opt-remarks-passes=") + A->getValue()));
106 
107   CmdArgs.push_back(Args.MakeArgString(
108       Twine("--plugin-opt=opt-remarks-format=") + Format.data()));
109 }
110 
111 static void renderRemarksHotnessOptions(const ArgList &Args,
112                                         ArgStringList &CmdArgs) {
113   if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
114                    options::OPT_fno_diagnostics_show_hotness, false))
115     CmdArgs.push_back("--plugin-opt=opt-remarks-with-hotness");
116 
117   if (const Arg *A =
118           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
119     CmdArgs.push_back(Args.MakeArgString(
120         Twine("--plugin-opt=opt-remarks-hotness-threshold=") + A->getValue()));
121 }
122 
123 void tools::addPathIfExists(const Driver &D, const Twine &Path,
124                             ToolChain::path_list &Paths) {
125   if (D.getVFS().exists(Path))
126     Paths.push_back(Path.str());
127 }
128 
129 void tools::handleTargetFeaturesGroup(const ArgList &Args,
130                                       std::vector<StringRef> &Features,
131                                       OptSpecifier Group) {
132   for (const Arg *A : Args.filtered(Group)) {
133     StringRef Name = A->getOption().getName();
134     A->claim();
135 
136     // Skip over "-m".
137     assert(Name.startswith("m") && "Invalid feature name.");
138     Name = Name.substr(1);
139 
140     bool IsNegative = Name.startswith("no-");
141     if (IsNegative)
142       Name = Name.substr(3);
143     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
144   }
145 }
146 
147 SmallVector<StringRef>
148 tools::unifyTargetFeatures(ArrayRef<StringRef> Features) {
149   // Only add a feature if it hasn't been seen before starting from the end.
150   SmallVector<StringRef> UnifiedFeatures;
151   llvm::DenseSet<StringRef> UsedFeatures;
152   for (StringRef Feature : llvm::reverse(Features)) {
153     if (UsedFeatures.insert(Feature.drop_front()).second)
154       UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature);
155   }
156 
157   return UnifiedFeatures;
158 }
159 
160 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
161                              const char *ArgName, const char *EnvVar) {
162   const char *DirList = ::getenv(EnvVar);
163   bool CombinedArg = false;
164 
165   if (!DirList)
166     return; // Nothing to do.
167 
168   StringRef Name(ArgName);
169   if (Name.equals("-I") || Name.equals("-L") || Name.empty())
170     CombinedArg = true;
171 
172   StringRef Dirs(DirList);
173   if (Dirs.empty()) // Empty string should not add '.'.
174     return;
175 
176   StringRef::size_type Delim;
177   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
178     if (Delim == 0) { // Leading colon.
179       if (CombinedArg) {
180         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
181       } else {
182         CmdArgs.push_back(ArgName);
183         CmdArgs.push_back(".");
184       }
185     } else {
186       if (CombinedArg) {
187         CmdArgs.push_back(
188             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
189       } else {
190         CmdArgs.push_back(ArgName);
191         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
192       }
193     }
194     Dirs = Dirs.substr(Delim + 1);
195   }
196 
197   if (Dirs.empty()) { // Trailing colon.
198     if (CombinedArg) {
199       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
200     } else {
201       CmdArgs.push_back(ArgName);
202       CmdArgs.push_back(".");
203     }
204   } else { // Add the last path.
205     if (CombinedArg) {
206       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
207     } else {
208       CmdArgs.push_back(ArgName);
209       CmdArgs.push_back(Args.MakeArgString(Dirs));
210     }
211   }
212 }
213 
214 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
215                             const ArgList &Args, ArgStringList &CmdArgs,
216                             const JobAction &JA) {
217   const Driver &D = TC.getDriver();
218 
219   // Add extra linker input arguments which are not treated as inputs
220   // (constructed via -Xarch_).
221   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
222 
223   // LIBRARY_PATH are included before user inputs and only supported on native
224   // toolchains.
225   if (!TC.isCrossCompiling())
226     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
227 
228   for (const auto &II : Inputs) {
229     // If the current tool chain refers to an OpenMP offloading host, we
230     // should ignore inputs that refer to OpenMP offloading devices -
231     // they will be embedded according to a proper linker script.
232     if (auto *IA = II.getAction())
233       if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
234            IA->isDeviceOffloading(Action::OFK_OpenMP)))
235         continue;
236 
237     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
238       // Don't try to pass LLVM inputs unless we have native support.
239       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
240 
241     // Add filenames immediately.
242     if (II.isFilename()) {
243       CmdArgs.push_back(II.getFilename());
244       continue;
245     }
246 
247     // In some error cases, the input could be Nothing; skip those.
248     if (II.isNothing())
249       continue;
250 
251     // Otherwise, this is a linker input argument.
252     const Arg &A = II.getInputArg();
253 
254     // Handle reserved library options.
255     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
256       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
257     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
258       TC.AddCCKextLibArgs(Args, CmdArgs);
259     else if (A.getOption().matches(options::OPT_z)) {
260       // Pass -z prefix for gcc linker compatibility.
261       A.claim();
262       A.render(Args, CmdArgs);
263     } else if (A.getOption().matches(options::OPT_b)) {
264       const llvm::Triple &T = TC.getTriple();
265       if (!T.isOSAIX()) {
266         TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
267             << A.getSpelling() << T.str();
268       }
269       // Pass -b prefix for AIX linker.
270       A.claim();
271       A.render(Args, CmdArgs);
272     } else {
273       A.renderAsInput(Args, CmdArgs);
274     }
275   }
276 }
277 
278 void tools::addLinkerCompressDebugSectionsOption(
279     const ToolChain &TC, const llvm::opt::ArgList &Args,
280     llvm::opt::ArgStringList &CmdArgs) {
281   // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
282   // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
283   // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
284   // is not translated since ld --compress-debug-sections option requires an
285   // argument.
286   if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
287     StringRef V = A->getValue();
288     if (V == "none" || V == "zlib")
289       CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
290     else
291       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
292           << A->getOption().getName() << V;
293   }
294 }
295 
296 void tools::AddTargetFeature(const ArgList &Args,
297                              std::vector<StringRef> &Features,
298                              OptSpecifier OnOpt, OptSpecifier OffOpt,
299                              StringRef FeatureName) {
300   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
301     if (A->getOption().matches(OnOpt))
302       Features.push_back(Args.MakeArgString("+" + FeatureName));
303     else
304       Features.push_back(Args.MakeArgString("-" + FeatureName));
305   }
306 }
307 
308 /// Get the (LLVM) name of the AMDGPU gpu we are targeting.
309 static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
310                                       const ArgList &Args) {
311   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
312     auto GPUName = getProcessorFromTargetID(T, A->getValue());
313     return llvm::StringSwitch<std::string>(GPUName)
314         .Cases("rv630", "rv635", "r600")
315         .Cases("rv610", "rv620", "rs780", "rs880")
316         .Case("rv740", "rv770")
317         .Case("palm", "cedar")
318         .Cases("sumo", "sumo2", "sumo")
319         .Case("hemlock", "cypress")
320         .Case("aruba", "cayman")
321         .Default(GPUName.str());
322   }
323   return "";
324 }
325 
326 static std::string getLanaiTargetCPU(const ArgList &Args) {
327   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
328     return A->getValue();
329   }
330   return "";
331 }
332 
333 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
334 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
335   // If we have -mcpu=, use that.
336   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
337     StringRef CPU = A->getValue();
338 
339 #ifdef __wasm__
340     // Handle "native" by examining the host. "native" isn't meaningful when
341     // cross compiling, so only support this when the host is also WebAssembly.
342     if (CPU == "native")
343       return llvm::sys::getHostCPUName();
344 #endif
345 
346     return CPU;
347   }
348 
349   return "generic";
350 }
351 
352 std::string tools::getCPUName(const Driver &D, const ArgList &Args,
353                               const llvm::Triple &T, bool FromAs) {
354   Arg *A;
355 
356   switch (T.getArch()) {
357   default:
358     return "";
359 
360   case llvm::Triple::aarch64:
361   case llvm::Triple::aarch64_32:
362   case llvm::Triple::aarch64_be:
363     return aarch64::getAArch64TargetCPU(Args, T, A);
364 
365   case llvm::Triple::arm:
366   case llvm::Triple::armeb:
367   case llvm::Triple::thumb:
368   case llvm::Triple::thumbeb: {
369     StringRef MArch, MCPU;
370     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
371     return arm::getARMTargetCPU(MCPU, MArch, T);
372   }
373 
374   case llvm::Triple::avr:
375     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
376       return A->getValue();
377     return "";
378 
379   case llvm::Triple::m68k:
380     return m68k::getM68kTargetCPU(Args);
381 
382   case llvm::Triple::mips:
383   case llvm::Triple::mipsel:
384   case llvm::Triple::mips64:
385   case llvm::Triple::mips64el: {
386     StringRef CPUName;
387     StringRef ABIName;
388     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
389     return std::string(CPUName);
390   }
391 
392   case llvm::Triple::nvptx:
393   case llvm::Triple::nvptx64:
394     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
395       return A->getValue();
396     return "";
397 
398   case llvm::Triple::ppc:
399   case llvm::Triple::ppcle:
400   case llvm::Triple::ppc64:
401   case llvm::Triple::ppc64le: {
402     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
403     // LLVM may default to generating code for the native CPU,
404     // but, like gcc, we default to a more generic option for
405     // each architecture. (except on AIX)
406     if (!TargetCPUName.empty())
407       return TargetCPUName;
408 
409     if (T.isOSAIX())
410       TargetCPUName = "pwr7";
411     else if (T.getArch() == llvm::Triple::ppc64le)
412       TargetCPUName = "ppc64le";
413     else if (T.getArch() == llvm::Triple::ppc64)
414       TargetCPUName = "ppc64";
415     else
416       TargetCPUName = "ppc";
417 
418     return TargetCPUName;
419   }
420   case llvm::Triple::csky:
421     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
422       return A->getValue();
423     else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
424       return A->getValue();
425     else
426       return "ck810";
427   case llvm::Triple::riscv32:
428   case llvm::Triple::riscv64:
429     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
430       return A->getValue();
431     return "";
432 
433   case llvm::Triple::bpfel:
434   case llvm::Triple::bpfeb:
435     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
436       return A->getValue();
437     return "";
438 
439   case llvm::Triple::sparc:
440   case llvm::Triple::sparcel:
441   case llvm::Triple::sparcv9:
442     return sparc::getSparcTargetCPU(D, Args, T);
443 
444   case llvm::Triple::x86:
445   case llvm::Triple::x86_64:
446     return x86::getX86TargetCPU(D, Args, T);
447 
448   case llvm::Triple::hexagon:
449     return "hexagon" +
450            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
451 
452   case llvm::Triple::lanai:
453     return getLanaiTargetCPU(Args);
454 
455   case llvm::Triple::systemz:
456     return systemz::getSystemZTargetCPU(Args);
457 
458   case llvm::Triple::r600:
459   case llvm::Triple::amdgcn:
460     return getAMDGPUTargetGPU(T, Args);
461 
462   case llvm::Triple::wasm32:
463   case llvm::Triple::wasm64:
464     return std::string(getWebAssemblyTargetCPU(Args));
465   }
466 }
467 
468 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
469   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
470   if (!LtoJobsArg)
471     return {};
472   if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
473     D.Diag(diag::err_drv_invalid_int_value)
474         << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
475   return LtoJobsArg->getValue();
476 }
477 
478 // CloudABI and PS4/PS5 use -ffunction-sections and -fdata-sections by default.
479 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
480   return Triple.getOS() == llvm::Triple::CloudABI || Triple.isPS();
481 }
482 
483 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
484                           ArgStringList &CmdArgs, const InputInfo &Output,
485                           const InputInfo &Input, bool IsThinLTO) {
486   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
487   const Driver &D = ToolChain.getDriver();
488   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
489       llvm::sys::path::stem(Linker) != "ld.lld") {
490     // Tell the linker to load the plugin. This has to come before
491     // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
492     // that -Wl might forward.
493     CmdArgs.push_back("-plugin");
494 
495 #if defined(_WIN32)
496     const char *Suffix = ".dll";
497 #elif defined(__APPLE__)
498     const char *Suffix = ".dylib";
499 #else
500     const char *Suffix = ".so";
501 #endif
502 
503     SmallString<1024> Plugin;
504     llvm::sys::path::native(
505         Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix,
506         Plugin);
507     CmdArgs.push_back(Args.MakeArgString(Plugin));
508   }
509 
510   // Try to pass driver level flags relevant to LTO code generation down to
511   // the plugin.
512 
513   // Handle flags for selecting CPU variants.
514   std::string CPU = getCPUName(D, Args, ToolChain.getTriple());
515   if (!CPU.empty())
516     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
517 
518   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
519     // The optimization level matches
520     // CompilerInvocation.cpp:getOptimizationLevel().
521     StringRef OOpt;
522     if (A->getOption().matches(options::OPT_O4) ||
523         A->getOption().matches(options::OPT_Ofast))
524       OOpt = "3";
525     else if (A->getOption().matches(options::OPT_O)) {
526       OOpt = A->getValue();
527       if (OOpt == "g")
528         OOpt = "1";
529       else if (OOpt == "s" || OOpt == "z")
530         OOpt = "2";
531     } else if (A->getOption().matches(options::OPT_O0))
532       OOpt = "0";
533     if (!OOpt.empty())
534       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
535   }
536 
537   if (Args.hasArg(options::OPT_gsplit_dwarf)) {
538     CmdArgs.push_back(
539         Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
540             Output.getFilename() + "_dwo"));
541   }
542 
543   if (IsThinLTO)
544     CmdArgs.push_back("-plugin-opt=thinlto");
545 
546   StringRef Parallelism = getLTOParallelism(Args, D);
547   if (!Parallelism.empty())
548     CmdArgs.push_back(
549         Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
550 
551   if (!CLANG_ENABLE_OPAQUE_POINTERS_INTERNAL)
552     CmdArgs.push_back(Args.MakeArgString("-plugin-opt=no-opaque-pointers"));
553 
554   // If an explicit debugger tuning argument appeared, pass it along.
555   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
556                                options::OPT_ggdbN_Group)) {
557     if (A->getOption().matches(options::OPT_glldb))
558       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
559     else if (A->getOption().matches(options::OPT_gsce))
560       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
561     else if (A->getOption().matches(options::OPT_gdbx))
562       CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx");
563     else
564       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
565   }
566 
567   bool UseSeparateSections =
568       isUseSeparateSections(ToolChain.getEffectiveTriple());
569 
570   if (Args.hasFlag(options::OPT_ffunction_sections,
571                    options::OPT_fno_function_sections, UseSeparateSections)) {
572     CmdArgs.push_back("-plugin-opt=-function-sections");
573   }
574 
575   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
576                    UseSeparateSections)) {
577     CmdArgs.push_back("-plugin-opt=-data-sections");
578   }
579 
580   // Pass an option to enable split machine functions.
581   if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
582                                 options::OPT_fno_split_machine_functions)) {
583     if (A->getOption().matches(options::OPT_fsplit_machine_functions))
584       CmdArgs.push_back("-plugin-opt=-split-machine-functions");
585   }
586 
587   if (Arg *A = getLastProfileSampleUseArg(Args)) {
588     StringRef FName = A->getValue();
589     if (!llvm::sys::fs::exists(FName))
590       D.Diag(diag::err_drv_no_such_file) << FName;
591     else
592       CmdArgs.push_back(
593           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
594   }
595 
596   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
597                                            options::OPT_fcs_profile_generate_EQ,
598                                            options::OPT_fno_profile_generate);
599   if (CSPGOGenerateArg &&
600       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
601     CSPGOGenerateArg = nullptr;
602 
603   auto *ProfileUseArg = getLastProfileUseArg(Args);
604 
605   if (CSPGOGenerateArg) {
606     CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
607     if (CSPGOGenerateArg->getOption().matches(
608             options::OPT_fcs_profile_generate_EQ)) {
609       SmallString<128> Path(CSPGOGenerateArg->getValue());
610       llvm::sys::path::append(Path, "default_%m.profraw");
611       CmdArgs.push_back(
612           Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
613     } else
614       CmdArgs.push_back(
615           Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
616   } else if (ProfileUseArg) {
617     SmallString<128> Path(
618         ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
619     if (Path.empty() || llvm::sys::fs::is_directory(Path))
620       llvm::sys::path::append(Path, "default.profdata");
621     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
622                                          Path));
623   }
624 
625   // Setup statistics file output.
626   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
627   if (!StatsFile.empty())
628     CmdArgs.push_back(
629         Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
630 
631   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true);
632 
633   // Handle remark diagnostics on screen options: '-Rpass-*'.
634   renderRpassOptions(Args, CmdArgs);
635 
636   // Handle serialized remarks options: '-fsave-optimization-record'
637   // and '-foptimization-record-*'.
638   if (willEmitRemarks(Args))
639     renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
640                          Output);
641 
642   // Handle remarks hotness/threshold related options.
643   renderRemarksHotnessOptions(Args, CmdArgs);
644 
645   addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(),
646                          /*IsLTO=*/true);
647 }
648 
649 void tools::addOpenMPRuntimeSpecificRPath(const ToolChain &TC,
650                                           const ArgList &Args,
651                                           ArgStringList &CmdArgs) {
652 
653   if (Args.hasFlag(options::OPT_fopenmp_implicit_rpath,
654                    options::OPT_fno_openmp_implicit_rpath, true)) {
655     // Default to clang lib / lib64 folder, i.e. the same location as device
656     // runtime
657     SmallString<256> DefaultLibPath =
658         llvm::sys::path::parent_path(TC.getDriver().Dir);
659     llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
660     CmdArgs.push_back("-rpath");
661     CmdArgs.push_back(Args.MakeArgString(DefaultLibPath));
662   }
663 }
664 
665 void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC,
666                                         const ArgList &Args,
667                                         ArgStringList &CmdArgs) {
668   // Default to clang lib / lib64 folder, i.e. the same location as device
669   // runtime.
670   SmallString<256> DefaultLibPath =
671       llvm::sys::path::parent_path(TC.getDriver().Dir);
672   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
673   CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
674 }
675 
676 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
677                                  ArgStringList &CmdArgs) {
678   // Enable -frtlib-add-rpath by default for the case of VE.
679   const bool IsVE = TC.getTriple().isVE();
680   bool DefaultValue = IsVE;
681   if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
682                     options::OPT_fno_rtlib_add_rpath, DefaultValue))
683     return;
684 
685   std::string CandidateRPath = TC.getArchSpecificLibPath();
686   if (TC.getVFS().exists(CandidateRPath)) {
687     CmdArgs.push_back("-rpath");
688     CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
689   }
690 }
691 
692 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
693                              const ArgList &Args, bool ForceStaticHostRuntime,
694                              bool IsOffloadingHost, bool GompNeedsRT) {
695   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
696                     options::OPT_fno_openmp, false))
697     return false;
698 
699   Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
700 
701   if (RTKind == Driver::OMPRT_Unknown)
702     // Already diagnosed.
703     return false;
704 
705   if (ForceStaticHostRuntime)
706     CmdArgs.push_back("-Bstatic");
707 
708   switch (RTKind) {
709   case Driver::OMPRT_OMP:
710     CmdArgs.push_back("-lomp");
711     break;
712   case Driver::OMPRT_GOMP:
713     CmdArgs.push_back("-lgomp");
714     break;
715   case Driver::OMPRT_IOMP5:
716     CmdArgs.push_back("-liomp5");
717     break;
718   case Driver::OMPRT_Unknown:
719     break;
720   }
721 
722   if (ForceStaticHostRuntime)
723     CmdArgs.push_back("-Bdynamic");
724 
725   if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
726       CmdArgs.push_back("-lrt");
727 
728   if (IsOffloadingHost)
729     CmdArgs.push_back("-lomptarget");
730 
731   if (IsOffloadingHost && TC.getDriver().isUsingLTO(/* IsOffload */ true) &&
732       !Args.hasArg(options::OPT_nogpulib))
733     CmdArgs.push_back("-lomptarget.devicertl");
734 
735   addArchSpecificRPath(TC, Args, CmdArgs);
736 
737   if (RTKind == Driver::OMPRT_OMP)
738     addOpenMPRuntimeSpecificRPath(TC, Args, CmdArgs);
739   addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
740 
741   return true;
742 }
743 
744 void tools::addFortranRuntimeLibs(const ToolChain &TC,
745                                   llvm::opt::ArgStringList &CmdArgs) {
746   if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
747     CmdArgs.push_back("Fortran_main.lib");
748     CmdArgs.push_back("FortranRuntime.lib");
749     CmdArgs.push_back("FortranDecimal.lib");
750   } else {
751     CmdArgs.push_back("-lFortran_main");
752     CmdArgs.push_back("-lFortranRuntime");
753     CmdArgs.push_back("-lFortranDecimal");
754   }
755 }
756 
757 void tools::addFortranRuntimeLibraryPath(const ToolChain &TC,
758                                          const llvm::opt::ArgList &Args,
759                                          ArgStringList &CmdArgs) {
760   // NOTE: Generating executables by Flang is considered an "experimental"
761   // feature and hence this is guarded with a command line option.
762   // TODO: Make this work unconditionally once Flang is mature enough.
763   if (!Args.hasArg(options::OPT_flang_experimental_exec))
764     return;
765 
766   // Default to the <driver-path>/../lib directory. This works fine on the
767   // platforms that we have tested so far. We will probably have to re-fine
768   // this in the future. In particular, on some platforms, we may need to use
769   // lib64 instead of lib.
770   SmallString<256> DefaultLibPath =
771       llvm::sys::path::parent_path(TC.getDriver().Dir);
772   llvm::sys::path::append(DefaultLibPath, "lib");
773   if (TC.getTriple().isKnownWindowsMSVCEnvironment())
774     CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
775   else
776     CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
777 }
778 
779 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
780                                 ArgStringList &CmdArgs, StringRef Sanitizer,
781                                 bool IsShared, bool IsWhole) {
782   // Wrap any static runtimes that must be forced into executable in
783   // whole-archive.
784   if (IsWhole) CmdArgs.push_back("--whole-archive");
785   CmdArgs.push_back(TC.getCompilerRTArgString(
786       Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
787   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
788 
789   if (IsShared) {
790     addArchSpecificRPath(TC, Args, CmdArgs);
791   }
792 }
793 
794 // Tries to use a file with the list of dynamic symbols that need to be exported
795 // from the runtime library. Returns true if the file was found.
796 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
797                                     ArgStringList &CmdArgs,
798                                     StringRef Sanitizer) {
799   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
800   // the option, so don't try to pass it.
801   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
802     return true;
803   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
804   if (llvm::sys::fs::exists(SanRT + ".syms")) {
805     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
806     return true;
807   }
808   return false;
809 }
810 
811 const char *tools::getAsNeededOption(const ToolChain &TC, bool as_needed) {
812   assert(!TC.getTriple().isOSAIX() &&
813          "AIX linker does not support any form of --as-needed option yet.");
814 
815   // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
816   // for the native forms -z ignore/-z record, they are missing in Illumos,
817   // so always use the native form.
818   if (TC.getTriple().isOSSolaris())
819     return as_needed ? "-zignore" : "-zrecord";
820   else
821     return as_needed ? "--as-needed" : "--no-as-needed";
822 }
823 
824 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
825                                      ArgStringList &CmdArgs) {
826   // Force linking against the system libraries sanitizers depends on
827   // (see PR15823 why this is necessary).
828   CmdArgs.push_back(getAsNeededOption(TC, false));
829   // There's no libpthread or librt on RTEMS & Android.
830   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
831       !TC.getTriple().isAndroid()) {
832     CmdArgs.push_back("-lpthread");
833     if (!TC.getTriple().isOSOpenBSD())
834       CmdArgs.push_back("-lrt");
835   }
836   CmdArgs.push_back("-lm");
837   // There's no libdl on all OSes.
838   if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
839       !TC.getTriple().isOSOpenBSD() &&
840       TC.getTriple().getOS() != llvm::Triple::RTEMS)
841     CmdArgs.push_back("-ldl");
842   // Required for backtrace on some OSes
843   if (TC.getTriple().isOSFreeBSD() ||
844       TC.getTriple().isOSNetBSD() ||
845       TC.getTriple().isOSOpenBSD())
846     CmdArgs.push_back("-lexecinfo");
847   // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
848   // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
849   // requirement.
850   if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
851       !TC.getTriple().isMusl())
852     CmdArgs.push_back("-lresolv");
853 }
854 
855 static void
856 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
857                          SmallVectorImpl<StringRef> &SharedRuntimes,
858                          SmallVectorImpl<StringRef> &StaticRuntimes,
859                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
860                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
861                          SmallVectorImpl<StringRef> &RequiredSymbols) {
862   const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
863   // Collect shared runtimes.
864   if (SanArgs.needsSharedRt()) {
865     if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
866       SharedRuntimes.push_back("asan");
867       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
868         HelperStaticRuntimes.push_back("asan-preinit");
869     }
870     if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
871       SharedRuntimes.push_back("memprof");
872       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
873         HelperStaticRuntimes.push_back("memprof-preinit");
874     }
875     if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
876       if (SanArgs.requiresMinimalRuntime())
877         SharedRuntimes.push_back("ubsan_minimal");
878       else
879         SharedRuntimes.push_back("ubsan_standalone");
880     }
881     if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
882       if (SanArgs.requiresMinimalRuntime())
883         SharedRuntimes.push_back("scudo_minimal");
884       else
885         SharedRuntimes.push_back("scudo");
886     }
887     if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
888       SharedRuntimes.push_back("tsan");
889     if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
890       if (SanArgs.needsHwasanAliasesRt())
891         SharedRuntimes.push_back("hwasan_aliases");
892       else
893         SharedRuntimes.push_back("hwasan");
894       if (!Args.hasArg(options::OPT_shared))
895         HelperStaticRuntimes.push_back("hwasan-preinit");
896     }
897   }
898 
899   // The stats_client library is also statically linked into DSOs.
900   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
901     StaticRuntimes.push_back("stats_client");
902 
903   // Always link the static runtime regardless of DSO or executable.
904   if (SanArgs.needsAsanRt())
905     HelperStaticRuntimes.push_back("asan_static");
906 
907   // Collect static runtimes.
908   if (Args.hasArg(options::OPT_shared)) {
909     // Don't link static runtimes into DSOs.
910     return;
911   }
912 
913   // Each static runtime that has a DSO counterpart above is excluded below,
914   // but runtimes that exist only as static are not affected by needsSharedRt.
915 
916   if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
917     StaticRuntimes.push_back("asan");
918     if (SanArgs.linkCXXRuntimes())
919       StaticRuntimes.push_back("asan_cxx");
920   }
921 
922   if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
923       SanArgs.linkRuntimes()) {
924     StaticRuntimes.push_back("memprof");
925     if (SanArgs.linkCXXRuntimes())
926       StaticRuntimes.push_back("memprof_cxx");
927   }
928 
929   if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
930     if (SanArgs.needsHwasanAliasesRt()) {
931       StaticRuntimes.push_back("hwasan_aliases");
932       if (SanArgs.linkCXXRuntimes())
933         StaticRuntimes.push_back("hwasan_aliases_cxx");
934     } else {
935       StaticRuntimes.push_back("hwasan");
936       if (SanArgs.linkCXXRuntimes())
937         StaticRuntimes.push_back("hwasan_cxx");
938     }
939   }
940   if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
941     StaticRuntimes.push_back("dfsan");
942   if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
943     StaticRuntimes.push_back("lsan");
944   if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
945     StaticRuntimes.push_back("msan");
946     if (SanArgs.linkCXXRuntimes())
947       StaticRuntimes.push_back("msan_cxx");
948   }
949   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
950       SanArgs.linkRuntimes()) {
951     StaticRuntimes.push_back("tsan");
952     if (SanArgs.linkCXXRuntimes())
953       StaticRuntimes.push_back("tsan_cxx");
954   }
955   if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
956     if (SanArgs.requiresMinimalRuntime()) {
957       StaticRuntimes.push_back("ubsan_minimal");
958     } else {
959       StaticRuntimes.push_back("ubsan_standalone");
960       if (SanArgs.linkCXXRuntimes())
961         StaticRuntimes.push_back("ubsan_standalone_cxx");
962     }
963   }
964   if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
965     NonWholeStaticRuntimes.push_back("safestack");
966     RequiredSymbols.push_back("__safestack_init");
967   }
968   if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
969     if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
970       StaticRuntimes.push_back("cfi");
971     if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
972       StaticRuntimes.push_back("cfi_diag");
973       if (SanArgs.linkCXXRuntimes())
974         StaticRuntimes.push_back("ubsan_standalone_cxx");
975     }
976   }
977   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
978     NonWholeStaticRuntimes.push_back("stats");
979     RequiredSymbols.push_back("__sanitizer_stats_register");
980   }
981   if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
982     if (SanArgs.requiresMinimalRuntime()) {
983       StaticRuntimes.push_back("scudo_minimal");
984       if (SanArgs.linkCXXRuntimes())
985         StaticRuntimes.push_back("scudo_cxx_minimal");
986     } else {
987       StaticRuntimes.push_back("scudo");
988       if (SanArgs.linkCXXRuntimes())
989         StaticRuntimes.push_back("scudo_cxx");
990     }
991   }
992 }
993 
994 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
995 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
996 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
997                                  ArgStringList &CmdArgs) {
998   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
999       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
1000   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1001                            NonWholeStaticRuntimes, HelperStaticRuntimes,
1002                            RequiredSymbols);
1003 
1004   const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1005   // Inject libfuzzer dependencies.
1006   if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1007       !Args.hasArg(options::OPT_shared)) {
1008 
1009     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
1010     if (SanArgs.needsFuzzerInterceptors())
1011       addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
1012                           true);
1013     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
1014       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
1015                                  !Args.hasArg(options::OPT_static);
1016       if (OnlyLibstdcxxStatic)
1017         CmdArgs.push_back("-Bstatic");
1018       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1019       if (OnlyLibstdcxxStatic)
1020         CmdArgs.push_back("-Bdynamic");
1021     }
1022   }
1023 
1024   for (auto RT : SharedRuntimes)
1025     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
1026   for (auto RT : HelperStaticRuntimes)
1027     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1028   bool AddExportDynamic = false;
1029   for (auto RT : StaticRuntimes) {
1030     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1031     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1032   }
1033   for (auto RT : NonWholeStaticRuntimes) {
1034     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1035     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1036   }
1037   for (auto S : RequiredSymbols) {
1038     CmdArgs.push_back("-u");
1039     CmdArgs.push_back(Args.MakeArgString(S));
1040   }
1041   // If there is a static runtime with no dynamic list, force all the symbols
1042   // to be dynamic to be sure we export sanitizer interface functions.
1043   if (AddExportDynamic)
1044     CmdArgs.push_back("--export-dynamic");
1045 
1046   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1047     CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1048 
1049   if (SanArgs.hasMemTag()) {
1050     if (!TC.getTriple().isAndroid()) {
1051       TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1052           << "-fsanitize=memtag*" << TC.getTriple().str();
1053     }
1054     CmdArgs.push_back(
1055         Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1056     if (SanArgs.hasMemtagHeap())
1057       CmdArgs.push_back("--android-memtag-heap");
1058     if (SanArgs.hasMemtagStack())
1059       CmdArgs.push_back("--android-memtag-stack");
1060   }
1061 
1062   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1063 }
1064 
1065 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1066   if (Args.hasArg(options::OPT_shared))
1067     return false;
1068 
1069   if (TC.getXRayArgs().needsXRayRt()) {
1070     CmdArgs.push_back("-whole-archive");
1071     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
1072     for (const auto &Mode : TC.getXRayArgs().modeList())
1073       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
1074     CmdArgs.push_back("-no-whole-archive");
1075     return true;
1076   }
1077 
1078   return false;
1079 }
1080 
1081 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
1082   CmdArgs.push_back(getAsNeededOption(TC, false));
1083   CmdArgs.push_back("-lpthread");
1084   if (!TC.getTriple().isOSOpenBSD())
1085     CmdArgs.push_back("-lrt");
1086   CmdArgs.push_back("-lm");
1087 
1088   if (!TC.getTriple().isOSFreeBSD() &&
1089       !TC.getTriple().isOSNetBSD() &&
1090       !TC.getTriple().isOSOpenBSD())
1091     CmdArgs.push_back("-ldl");
1092 }
1093 
1094 bool tools::areOptimizationsEnabled(const ArgList &Args) {
1095   // Find the last -O arg and see if it is non-zero.
1096   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1097     return !A->getOption().matches(options::OPT_O0);
1098   // Defaults to -O0.
1099   return false;
1100 }
1101 
1102 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1103                                   const InputInfo &Input,
1104                                   const InputInfo &Output) {
1105   auto AddPostfix = [JA](auto &F) {
1106     if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1107       F += (Twine("_") + JA.getOffloadingArch()).str();
1108     F += ".dwo";
1109   };
1110   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1111     if (StringRef(A->getValue()) == "single")
1112       return Args.MakeArgString(Output.getFilename());
1113 
1114   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1115   if (FinalOutput && Args.hasArg(options::OPT_c)) {
1116     SmallString<128> T(FinalOutput->getValue());
1117     llvm::sys::path::remove_filename(T);
1118     llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1119     AddPostfix(T);
1120     return Args.MakeArgString(T);
1121   } else {
1122     // Use the compilation dir.
1123     Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
1124                              options::OPT_fdebug_compilation_dir_EQ);
1125     SmallString<128> T(A ? A->getValue() : "");
1126     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1127     AddPostfix(F);
1128     T += F;
1129     return Args.MakeArgString(T);
1130   }
1131 }
1132 
1133 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1134                            const JobAction &JA, const ArgList &Args,
1135                            const InputInfo &Output, const char *OutFile) {
1136   ArgStringList ExtractArgs;
1137   ExtractArgs.push_back("--extract-dwo");
1138 
1139   ArgStringList StripArgs;
1140   StripArgs.push_back("--strip-dwo");
1141 
1142   // Grabbing the output of the earlier compile step.
1143   StripArgs.push_back(Output.getFilename());
1144   ExtractArgs.push_back(Output.getFilename());
1145   ExtractArgs.push_back(OutFile);
1146 
1147   const char *Exec =
1148       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1149   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1150 
1151   // First extract the dwo sections.
1152   C.addCommand(std::make_unique<Command>(JA, T,
1153                                          ResponseFileSupport::AtFileCurCP(),
1154                                          Exec, ExtractArgs, II, Output));
1155 
1156   // Then remove them from the original .o file.
1157   C.addCommand(std::make_unique<Command>(
1158       JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1159 }
1160 
1161 // Claim options we don't want to warn if they are unused. We do this for
1162 // options that build systems might add but are unused when assembling or only
1163 // running the preprocessor for example.
1164 void tools::claimNoWarnArgs(const ArgList &Args) {
1165   // Don't warn about unused -f(no-)?lto.  This can happen when we're
1166   // preprocessing, precompiling or assembling.
1167   Args.ClaimAllArgs(options::OPT_flto_EQ);
1168   Args.ClaimAllArgs(options::OPT_flto);
1169   Args.ClaimAllArgs(options::OPT_fno_lto);
1170 }
1171 
1172 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1173   auto *ProfileUseArg = Args.getLastArg(
1174       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1175       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1176       options::OPT_fno_profile_instr_use);
1177 
1178   if (ProfileUseArg &&
1179       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1180     ProfileUseArg = nullptr;
1181 
1182   return ProfileUseArg;
1183 }
1184 
1185 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1186   auto *ProfileSampleUseArg = Args.getLastArg(
1187       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1188       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1189       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1190 
1191   if (ProfileSampleUseArg &&
1192       (ProfileSampleUseArg->getOption().matches(
1193            options::OPT_fno_profile_sample_use) ||
1194        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1195     return nullptr;
1196 
1197   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1198                          options::OPT_fauto_profile_EQ);
1199 }
1200 
1201 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
1202 /// smooshes them together with platform defaults, to decide whether
1203 /// this compile should be using PIC mode or not. Returns a tuple of
1204 /// (RelocationModel, PICLevel, IsPIE).
1205 std::tuple<llvm::Reloc::Model, unsigned, bool>
1206 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1207   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1208   const llvm::Triple &Triple = ToolChain.getTriple();
1209 
1210   bool PIE = ToolChain.isPIEDefault(Args);
1211   bool PIC = PIE || ToolChain.isPICDefault();
1212   // The Darwin/MachO default to use PIC does not apply when using -static.
1213   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1214     PIE = PIC = false;
1215   bool IsPICLevelTwo = PIC;
1216 
1217   bool KernelOrKext =
1218       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1219 
1220   // Android-specific defaults for PIC/PIE
1221   if (Triple.isAndroid()) {
1222     switch (Triple.getArch()) {
1223     case llvm::Triple::arm:
1224     case llvm::Triple::armeb:
1225     case llvm::Triple::thumb:
1226     case llvm::Triple::thumbeb:
1227     case llvm::Triple::aarch64:
1228     case llvm::Triple::mips:
1229     case llvm::Triple::mipsel:
1230     case llvm::Triple::mips64:
1231     case llvm::Triple::mips64el:
1232       PIC = true; // "-fpic"
1233       break;
1234 
1235     case llvm::Triple::x86:
1236     case llvm::Triple::x86_64:
1237       PIC = true; // "-fPIC"
1238       IsPICLevelTwo = true;
1239       break;
1240 
1241     default:
1242       break;
1243     }
1244   }
1245 
1246   // OpenBSD-specific defaults for PIE
1247   if (Triple.isOSOpenBSD()) {
1248     switch (ToolChain.getArch()) {
1249     case llvm::Triple::arm:
1250     case llvm::Triple::aarch64:
1251     case llvm::Triple::mips64:
1252     case llvm::Triple::mips64el:
1253     case llvm::Triple::x86:
1254     case llvm::Triple::x86_64:
1255       IsPICLevelTwo = false; // "-fpie"
1256       break;
1257 
1258     case llvm::Triple::ppc:
1259     case llvm::Triple::sparcv9:
1260       IsPICLevelTwo = true; // "-fPIE"
1261       break;
1262 
1263     default:
1264       break;
1265     }
1266   }
1267 
1268   // AMDGPU-specific defaults for PIC.
1269   if (Triple.getArch() == llvm::Triple::amdgcn)
1270     PIC = true;
1271 
1272   // The last argument relating to either PIC or PIE wins, and no
1273   // other argument is used. If the last argument is any flavor of the
1274   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1275   // option implicitly enables PIC at the same level.
1276   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1277                                     options::OPT_fpic, options::OPT_fno_pic,
1278                                     options::OPT_fPIE, options::OPT_fno_PIE,
1279                                     options::OPT_fpie, options::OPT_fno_pie);
1280   if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1281       LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1282                                     options::OPT_fPIE, options::OPT_fpie)) {
1283     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1284         << LastPICArg->getSpelling() << Triple.str();
1285     if (Triple.getArch() == llvm::Triple::x86_64)
1286       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1287     return std::make_tuple(llvm::Reloc::Static, 0U, false);
1288   }
1289 
1290   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1291   // is forced, then neither PIC nor PIE flags will have no effect.
1292   if (!ToolChain.isPICDefaultForced()) {
1293     if (LastPICArg) {
1294       Option O = LastPICArg->getOption();
1295       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1296           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1297         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1298         PIC =
1299             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1300         IsPICLevelTwo =
1301             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1302       } else {
1303         PIE = PIC = false;
1304         if (EffectiveTriple.isPS()) {
1305           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1306           StringRef Model = ModelArg ? ModelArg->getValue() : "";
1307           if (Model != "kernel") {
1308             PIC = true;
1309             ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1310                 << LastPICArg->getSpelling()
1311                 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1312           }
1313         }
1314       }
1315     }
1316   }
1317 
1318   // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1319   // the PIC level would've been set to level 1, force it back to level 2 PIC
1320   // instead.
1321   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1322     IsPICLevelTwo |= ToolChain.isPICDefault();
1323 
1324   // This kernel flags are a trump-card: they will disable PIC/PIE
1325   // generation, independent of the argument order.
1326   if (KernelOrKext &&
1327       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1328        !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1329     PIC = PIE = false;
1330 
1331   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1332     // This is a very special mode. It trumps the other modes, almost no one
1333     // uses it, and it isn't even valid on any OS but Darwin.
1334     if (!Triple.isOSDarwin())
1335       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1336           << A->getSpelling() << Triple.str();
1337 
1338     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1339 
1340     // Only a forced PIC mode can cause the actual compile to have PIC defines
1341     // etc., no flags are sufficient. This behavior was selected to closely
1342     // match that of llvm-gcc and Apple GCC before that.
1343     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1344 
1345     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1346   }
1347 
1348   bool EmbeddedPISupported;
1349   switch (Triple.getArch()) {
1350     case llvm::Triple::arm:
1351     case llvm::Triple::armeb:
1352     case llvm::Triple::thumb:
1353     case llvm::Triple::thumbeb:
1354       EmbeddedPISupported = true;
1355       break;
1356     default:
1357       EmbeddedPISupported = false;
1358       break;
1359   }
1360 
1361   bool ROPI = false, RWPI = false;
1362   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1363   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1364     if (!EmbeddedPISupported)
1365       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1366           << LastROPIArg->getSpelling() << Triple.str();
1367     ROPI = true;
1368   }
1369   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1370   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1371     if (!EmbeddedPISupported)
1372       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1373           << LastRWPIArg->getSpelling() << Triple.str();
1374     RWPI = true;
1375   }
1376 
1377   // ROPI and RWPI are not compatible with PIC or PIE.
1378   if ((ROPI || RWPI) && (PIC || PIE))
1379     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1380 
1381   if (Triple.isMIPS()) {
1382     StringRef CPUName;
1383     StringRef ABIName;
1384     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1385     // When targeting the N64 ABI, PIC is the default, except in the case
1386     // when the -mno-abicalls option is used. In that case we exit
1387     // at next check regardless of PIC being set below.
1388     if (ABIName == "n64")
1389       PIC = true;
1390     // When targettng MIPS with -mno-abicalls, it's always static.
1391     if(Args.hasArg(options::OPT_mno_abicalls))
1392       return std::make_tuple(llvm::Reloc::Static, 0U, false);
1393     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1394     // does not use PIC level 2 for historical reasons.
1395     IsPICLevelTwo = false;
1396   }
1397 
1398   if (PIC)
1399     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1400 
1401   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1402   if (ROPI && RWPI)
1403     RelocM = llvm::Reloc::ROPI_RWPI;
1404   else if (ROPI)
1405     RelocM = llvm::Reloc::ROPI;
1406   else if (RWPI)
1407     RelocM = llvm::Reloc::RWPI;
1408 
1409   return std::make_tuple(RelocM, 0U, false);
1410 }
1411 
1412 // `-falign-functions` indicates that the functions should be aligned to a
1413 // 16-byte boundary.
1414 //
1415 // `-falign-functions=1` is the same as `-fno-align-functions`.
1416 //
1417 // The scalar `n` in `-falign-functions=n` must be an integral value between
1418 // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1419 // the nearest power-of-two.
1420 //
1421 // If we return `0`, the frontend will default to the backend's preferred
1422 // alignment.
1423 //
1424 // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1425 // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1426 // alignment.  For unaligned functions, we default to the backend's preferred
1427 // alignment.
1428 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1429                                        const ArgList &Args) {
1430   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1431                                  options::OPT_falign_functions_EQ,
1432                                  options::OPT_fno_align_functions);
1433   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1434     return 0;
1435 
1436   if (A->getOption().matches(options::OPT_falign_functions))
1437     return 0;
1438 
1439   unsigned Value = 0;
1440   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1441     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1442         << A->getAsString(Args) << A->getValue();
1443   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1444 }
1445 
1446 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1447                                          const ArgList &Args) {
1448   const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1449 
1450   if (!A)
1451     return 0;
1452 
1453   unsigned Value = 0;
1454   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1455       Value < 2)
1456     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1457         << A->getAsString(Args) << A->getValue();
1458   return Value;
1459 }
1460 
1461 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1462                              ArgStringList &CmdArgs) {
1463   llvm::Reloc::Model RelocationModel;
1464   unsigned PICLevel;
1465   bool IsPIE;
1466   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1467 
1468   if (RelocationModel != llvm::Reloc::Static)
1469     CmdArgs.push_back("-KPIC");
1470 }
1471 
1472 /// Determine whether Objective-C automated reference counting is
1473 /// enabled.
1474 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1475   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1476 }
1477 
1478 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1479 
1480 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
1481                                 const ArgList &Args) {
1482   if (Args.hasArg(options::OPT_static_libgcc) ||
1483       Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
1484       // The Android NDK only provides libunwind.a, not libunwind.so.
1485       TC.getTriple().isAndroid())
1486     return LibGccType::StaticLibGcc;
1487   if (Args.hasArg(options::OPT_shared_libgcc))
1488     return LibGccType::SharedLibGcc;
1489   return LibGccType::UnspecifiedLibGcc;
1490 }
1491 
1492 // Gcc adds libgcc arguments in various ways:
1493 //
1494 // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
1495 // g++ <none>:                       -lgcc_s               -lgcc
1496 // gcc shared:                       -lgcc_s               -lgcc
1497 // g++ shared:                       -lgcc_s               -lgcc
1498 // gcc static:     -lgcc             -lgcc_eh
1499 // g++ static:     -lgcc             -lgcc_eh
1500 // gcc static-pie: -lgcc             -lgcc_eh
1501 // g++ static-pie: -lgcc             -lgcc_eh
1502 //
1503 // Also, certain targets need additional adjustments.
1504 
1505 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1506                              ArgStringList &CmdArgs, const ArgList &Args) {
1507   ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1508   // Targets that don't use unwind libraries.
1509   if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
1510       TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
1511       UNW == ToolChain::UNW_None)
1512     return;
1513 
1514   LibGccType LGT = getLibGccType(TC, D, Args);
1515   bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1516                   (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
1517                   !TC.getTriple().isAndroid() &&
1518                   !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
1519   if (AsNeeded)
1520     CmdArgs.push_back(getAsNeededOption(TC, true));
1521 
1522   switch (UNW) {
1523   case ToolChain::UNW_None:
1524     return;
1525   case ToolChain::UNW_Libgcc: {
1526     if (LGT == LibGccType::StaticLibGcc)
1527       CmdArgs.push_back("-lgcc_eh");
1528     else
1529       CmdArgs.push_back("-lgcc_s");
1530     break;
1531   }
1532   case ToolChain::UNW_CompilerRT:
1533     if (TC.getTriple().isOSAIX()) {
1534       // AIX only has libunwind as a shared library. So do not pass
1535       // anything in if -static is specified.
1536       if (LGT != LibGccType::StaticLibGcc)
1537         CmdArgs.push_back("-lunwind");
1538     } else if (LGT == LibGccType::StaticLibGcc) {
1539       CmdArgs.push_back("-l:libunwind.a");
1540     } else if (LGT == LibGccType::SharedLibGcc) {
1541       if (TC.getTriple().isOSCygMing())
1542         CmdArgs.push_back("-l:libunwind.dll.a");
1543       else
1544         CmdArgs.push_back("-l:libunwind.so");
1545     } else {
1546       // Let the linker choose between libunwind.so and libunwind.a
1547       // depending on what's available, and depending on the -static flag
1548       CmdArgs.push_back("-lunwind");
1549     }
1550     break;
1551   }
1552 
1553   if (AsNeeded)
1554     CmdArgs.push_back(getAsNeededOption(TC, false));
1555 }
1556 
1557 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1558                       ArgStringList &CmdArgs, const ArgList &Args) {
1559   LibGccType LGT = getLibGccType(TC, D, Args);
1560   if (LGT == LibGccType::StaticLibGcc ||
1561       (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
1562     CmdArgs.push_back("-lgcc");
1563   AddUnwindLibrary(TC, D, CmdArgs, Args);
1564   if (LGT == LibGccType::SharedLibGcc ||
1565       (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
1566     CmdArgs.push_back("-lgcc");
1567 }
1568 
1569 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1570                            ArgStringList &CmdArgs, const ArgList &Args) {
1571   // Make use of compiler-rt if --rtlib option is used
1572   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1573 
1574   switch (RLT) {
1575   case ToolChain::RLT_CompilerRT:
1576     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1577     AddUnwindLibrary(TC, D, CmdArgs, Args);
1578     break;
1579   case ToolChain::RLT_Libgcc:
1580     // Make sure libgcc is not used under MSVC environment by default
1581     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1582       // Issue error diagnostic if libgcc is explicitly specified
1583       // through command line as --rtlib option argument.
1584       if (Args.hasArg(options::OPT_rtlib_EQ)) {
1585         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1586             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1587       }
1588     } else
1589       AddLibgcc(TC, D, CmdArgs, Args);
1590     break;
1591   }
1592 
1593   // On Android, the unwinder uses dl_iterate_phdr (or one of
1594   // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
1595   // statically-linked executables, these functions come from libc.a instead.
1596   if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
1597       !Args.hasArg(options::OPT_static_pie))
1598     CmdArgs.push_back("-ldl");
1599 }
1600 
1601 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1602                                          const InputInfo &Output,
1603                                          const InputInfo &Input,
1604                                          const Driver &D) {
1605   const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1606   if (!A)
1607     return {};
1608 
1609   StringRef SaveStats = A->getValue();
1610   SmallString<128> StatsFile;
1611   if (SaveStats == "obj" && Output.isFilename()) {
1612     StatsFile.assign(Output.getFilename());
1613     llvm::sys::path::remove_filename(StatsFile);
1614   } else if (SaveStats != "cwd") {
1615     D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1616     return {};
1617   }
1618 
1619   StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1620   llvm::sys::path::append(StatsFile, BaseName);
1621   llvm::sys::path::replace_extension(StatsFile, "stats");
1622   return StatsFile;
1623 }
1624 
1625 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1626                             Multilib::flags_list &Flags) {
1627   Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1628 }
1629 
1630 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1631                                   ArgStringList &CmdArgs, bool IsLTO) {
1632   auto addArg = [&, IsLTO](const Twine &Arg) {
1633     if (IsLTO) {
1634       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1635     } else {
1636       CmdArgs.push_back("-mllvm");
1637       CmdArgs.push_back(Args.MakeArgString(Arg));
1638     }
1639   };
1640 
1641   if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1642     addArg(Twine("-x86-branches-within-32B-boundaries"));
1643   }
1644   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1645     StringRef Value = A->getValue();
1646     unsigned Boundary;
1647     if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1648         !llvm::isPowerOf2_64(Boundary)) {
1649       D.Diag(diag::err_drv_invalid_argument_to_option)
1650           << Value << A->getOption().getName();
1651     } else {
1652       addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1653     }
1654   }
1655   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1656     std::string AlignBranch;
1657     for (StringRef T : A->getValues()) {
1658       if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1659           T != "ret" && T != "indirect")
1660         D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1661             << T << "fused, jcc, jmp, call, ret, indirect";
1662       if (!AlignBranch.empty())
1663         AlignBranch += '+';
1664       AlignBranch += T;
1665     }
1666     addArg("-x86-align-branch=" + Twine(AlignBranch));
1667   }
1668   if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1669     StringRef Value = A->getValue();
1670     unsigned PrefixSize;
1671     if (Value.getAsInteger(10, PrefixSize)) {
1672       D.Diag(diag::err_drv_invalid_argument_to_option)
1673           << Value << A->getOption().getName();
1674     } else {
1675       addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1676     }
1677   }
1678 }
1679 
1680 /// SDLSearch: Search for Static Device Library
1681 /// The search for SDL bitcode files is consistent with how static host
1682 /// libraries are discovered. That is, the -l option triggers a search for
1683 /// files in a set of directories called the LINKPATH. The host library search
1684 /// procedure looks for a specific filename in the LINKPATH.  The filename for
1685 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
1686 /// ordered-set of filenames that are searched. We call this ordered-set of
1687 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
1688 /// architecture specific, or generic across all architectures, a naming
1689 /// convention and search order is used where the file name embeds the
1690 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
1691 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
1692 /// device-independent SDLs. To reduce congestion in host library directories,
1693 /// the search first looks for files in the “libdevice” subdirectory. SDLs that
1694 /// are bc files begin with the prefix “lib”.
1695 ///
1696 /// Machine-code SDLs can also be managed as an archive (*.a file). The
1697 /// convention has been to use the prefix “lib”. To avoid confusion with host
1698 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
1699 ///
1700 bool tools::SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
1701                       llvm::opt::ArgStringList &CC1Args,
1702                       SmallVector<std::string, 8> LibraryPaths, std::string Lib,
1703                       StringRef Arch, StringRef Target, bool isBitCodeSDL,
1704                       bool postClangLink) {
1705   SmallVector<std::string, 12> SDLs;
1706 
1707   std::string LibDeviceLoc = "/libdevice";
1708   std::string LibBcPrefix = "/libbc-";
1709   std::string LibPrefix = "/lib";
1710 
1711   if (isBitCodeSDL) {
1712     // SEARCH-ORDER for Bitcode SDLs:
1713     //       libdevice/libbc-<libname>-<arch-name>-<device-type>.a
1714     //       libbc-<libname>-<arch-name>-<device-type>.a
1715     //       libdevice/libbc-<libname>-<arch-name>.a
1716     //       libbc-<libname>-<arch-name>.a
1717     //       libdevice/libbc-<libname>.a
1718     //       libbc-<libname>.a
1719     //       libdevice/lib<libname>-<arch-name>-<device-type>.bc
1720     //       lib<libname>-<arch-name>-<device-type>.bc
1721     //       libdevice/lib<libname>-<arch-name>.bc
1722     //       lib<libname>-<arch-name>.bc
1723     //       libdevice/lib<libname>.bc
1724     //       lib<libname>.bc
1725 
1726     for (StringRef Base : {LibBcPrefix, LibPrefix}) {
1727       const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
1728 
1729       for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1730                           Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
1731         SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
1732         SDLs.push_back(Twine(Base + Suffix + Ext).str());
1733       }
1734     }
1735   } else {
1736     // SEARCH-ORDER for Machine-code SDLs:
1737     //    libdevice/lib<libname>-<arch-name>-<device-type>.a
1738     //    lib<libname>-<arch-name>-<device-type>.a
1739     //    libdevice/lib<libname>-<arch-name>.a
1740     //    lib<libname>-<arch-name>.a
1741 
1742     const auto *Ext = ".a";
1743 
1744     for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1745                         Twine(Lib + "-" + Arch).str()}) {
1746       SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
1747       SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
1748     }
1749   }
1750 
1751   // The CUDA toolchain does not use a global device llvm-link before the LLVM
1752   // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
1753   // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
1754   // will link libraries after clang compilation while the LLVM IR is still in
1755   // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
1756   // This is a clang -cc1 option that is generated by the clang driver. The
1757   // option value must a full path to an existing file.
1758   bool FoundSDL = false;
1759   for (auto LPath : LibraryPaths) {
1760     for (auto SDL : SDLs) {
1761       auto FullName = Twine(LPath + SDL).str();
1762       if (llvm::sys::fs::exists(FullName)) {
1763         if (postClangLink)
1764           CC1Args.push_back("-mlink-builtin-bitcode");
1765         CC1Args.push_back(DriverArgs.MakeArgString(FullName));
1766         FoundSDL = true;
1767         break;
1768       }
1769     }
1770     if (FoundSDL)
1771       break;
1772   }
1773   return FoundSDL;
1774 }
1775 
1776 /// Search if a user provided archive file lib<libname>.a exists in any of
1777 /// the library paths. If so, add a new command to clang-offload-bundler to
1778 /// unbundle this archive and create a temporary device specific archive. Name
1779 /// of this SDL is passed to the llvm-link (for amdgcn) or to the
1780 /// clang-nvlink-wrapper (for nvptx) commands by the driver.
1781 bool tools::GetSDLFromOffloadArchive(
1782     Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
1783     const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
1784     llvm::opt::ArgStringList &CC1Args, SmallVector<std::string, 8> LibraryPaths,
1785     StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
1786     bool postClangLink) {
1787 
1788   // We don't support bitcode archive bundles for nvptx
1789   if (isBitCodeSDL && Arch.contains("nvptx"))
1790     return false;
1791 
1792   bool FoundAOB = false;
1793   SmallVector<std::string, 2> AOBFileNames;
1794   std::string ArchiveOfBundles;
1795   for (auto LPath : LibraryPaths) {
1796     ArchiveOfBundles.clear();
1797 
1798     llvm::Triple Triple(D.getTargetTriple());
1799     bool IsMSVC = Triple.isWindowsMSVCEnvironment();
1800     for (auto Prefix : {"/libdevice/", "/"}) {
1801       if (IsMSVC)
1802         AOBFileNames.push_back(Twine(LPath + Prefix + Lib + ".lib").str());
1803       AOBFileNames.push_back(Twine(LPath + Prefix + "lib" + Lib + ".a").str());
1804     }
1805 
1806     for (auto AOB : AOBFileNames) {
1807       if (llvm::sys::fs::exists(AOB)) {
1808         ArchiveOfBundles = AOB;
1809         FoundAOB = true;
1810         break;
1811       }
1812     }
1813 
1814     if (!FoundAOB)
1815       continue;
1816 
1817     StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
1818     std::string OutputLib = D.GetTemporaryPath(
1819         Twine(Prefix + Lib + "-" + Arch + "-" + Target).str(), "a");
1820 
1821     C.addTempFile(C.getArgs().MakeArgString(OutputLib));
1822 
1823     ArgStringList CmdArgs;
1824     SmallString<128> DeviceTriple;
1825     DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind());
1826     DeviceTriple += '-';
1827     std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
1828     DeviceTriple += NormalizedTriple;
1829     if (!Target.empty()) {
1830       DeviceTriple += '-';
1831       DeviceTriple += Target;
1832     }
1833 
1834     std::string UnbundleArg("-unbundle");
1835     std::string TypeArg("-type=a");
1836     std::string InputArg("-input=" + ArchiveOfBundles);
1837     std::string OffloadArg("-targets=" + std::string(DeviceTriple));
1838     std::string OutputArg("-output=" + OutputLib);
1839 
1840     const char *UBProgram = DriverArgs.MakeArgString(
1841         T.getToolChain().GetProgramPath("clang-offload-bundler"));
1842 
1843     ArgStringList UBArgs;
1844     UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
1845     UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
1846     UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
1847     UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
1848     UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
1849 
1850     // Add this flag to not exit from clang-offload-bundler if no compatible
1851     // code object is found in heterogenous archive library.
1852     std::string AdditionalArgs("-allow-missing-bundles");
1853     UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
1854 
1855     // Add this flag to treat hip and hipv4 offload kinds as compatible with
1856     // openmp offload kind while extracting code objects from a heterogenous
1857     // archive library. Vice versa is also considered compatible.
1858     std::string HipCompatibleArgs("-hip-openmp-compatible");
1859     UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
1860 
1861     C.addCommand(std::make_unique<Command>(
1862         JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
1863         InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
1864     if (postClangLink)
1865       CC1Args.push_back("-mlink-builtin-bitcode");
1866 
1867     CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
1868     break;
1869   }
1870 
1871   return FoundAOB;
1872 }
1873 
1874 // Wrapper function used by driver for adding SDLs during link phase.
1875 void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T,
1876                                 const JobAction &JA,
1877                                 const InputInfoList &Inputs,
1878                                 const llvm::opt::ArgList &DriverArgs,
1879                                 llvm::opt::ArgStringList &CC1Args,
1880                                 StringRef Arch, StringRef Target,
1881                                 bool isBitCodeSDL, bool postClangLink) {
1882   AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
1883                       Arch, Target, isBitCodeSDL, postClangLink);
1884 }
1885 
1886 // Wrapper function used for post clang linking of bitcode SDLS for nvptx by
1887 // the CUDA toolchain.
1888 void tools::AddStaticDeviceLibsPostLinking(const Driver &D,
1889                                 const llvm::opt::ArgList &DriverArgs,
1890                                 llvm::opt::ArgStringList &CC1Args,
1891                                 StringRef Arch, StringRef Target,
1892                                 bool isBitCodeSDL, bool postClangLink) {
1893   AddStaticDeviceLibs(nullptr, nullptr, nullptr, nullptr, D, DriverArgs,
1894                       CC1Args, Arch, Target, isBitCodeSDL, postClangLink);
1895 }
1896 
1897 // User defined Static Device Libraries(SDLs) can be passed to clang for
1898 // offloading GPU compilers. Like static host libraries, the use of a SDL is
1899 // specified with the -l command line option. The primary difference between
1900 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
1901 // and SEARCH-ORDER for Machine-code SDLs for the naming convention).
1902 // SDLs are of following types:
1903 //
1904 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
1905 //           For NVPTX, these libraries are post-clang linked following each
1906 //           compilation. For AMDGPU, these libraries are linked one time
1907 //           during the application link phase.
1908 //
1909 // * Machine-code SDLs: They are archive files. For NVPTX, the archive members
1910 //           contain cubin for Nvidia GPUs and are linked one time during the
1911 //           link phase by the CUDA SDK linker called nvlink.	For AMDGPU, the
1912 //           process for machine code SDLs is still in development. But they
1913 //           will be linked by the LLVM tool lld.
1914 //
1915 // * Bundled objects that contain both host and device codes: Bundled objects
1916 //           may also contain library code compiled from source. For NVPTX, the
1917 //           bundle contains cubin. For AMDGPU, the bundle contains bitcode.
1918 //
1919 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
1920 // inclusion of specific SDLs such as math libraries and the OpenMP device
1921 // library libomptarget.
1922 void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T,
1923                                 const JobAction *JA,
1924                                 const InputInfoList *Inputs, const Driver &D,
1925                                 const llvm::opt::ArgList &DriverArgs,
1926                                 llvm::opt::ArgStringList &CC1Args,
1927                                 StringRef Arch, StringRef Target,
1928                                 bool isBitCodeSDL, bool postClangLink) {
1929 
1930   SmallVector<std::string, 8> LibraryPaths;
1931   // Add search directories from LIBRARY_PATH env variable
1932   llvm::Optional<std::string> LibPath =
1933       llvm::sys::Process::GetEnv("LIBRARY_PATH");
1934   if (LibPath) {
1935     SmallVector<StringRef, 8> Frags;
1936     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
1937     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
1938     for (StringRef Path : Frags)
1939       LibraryPaths.emplace_back(Path.trim());
1940   }
1941 
1942   // Add directories from user-specified -L options
1943   for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
1944     LibraryPaths.emplace_back(Search_Dir);
1945 
1946   // Add path to lib-debug folders
1947   SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
1948   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
1949   LibraryPaths.emplace_back(DefaultLibPath.c_str());
1950 
1951   // Build list of Static Device Libraries SDLs specified by -l option
1952   llvm::SmallSet<std::string, 16> SDLNames;
1953   static const StringRef HostOnlyArchives[] = {
1954       "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
1955   for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
1956     if (!HostOnlyArchives->contains(SDLName)) {
1957       SDLNames.insert(SDLName);
1958     }
1959   }
1960 
1961   // The search stops as soon as an SDL file is found. The driver then provides
1962   // the full filename of the SDL to the llvm-link or clang-nvlink-wrapper
1963   // command. If no SDL is found after searching each LINKPATH with
1964   // SEARCH-ORDER, it is possible that an archive file lib<libname>.a exists
1965   // and may contain bundled object files.
1966   for (auto SDLName : SDLNames) {
1967     // This is the only call to SDLSearch
1968     if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
1969                    isBitCodeSDL, postClangLink)) {
1970       GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
1971                                LibraryPaths, SDLName, Arch, Target,
1972                                isBitCodeSDL, postClangLink);
1973     }
1974   }
1975 }
1976 
1977 static llvm::opt::Arg *
1978 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
1979   // The last of -mcode-object-v3, -mno-code-object-v3 and
1980   // -mcode-object-version=<version> wins.
1981   return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
1982                          options::OPT_mno_code_object_v3_legacy,
1983                          options::OPT_mcode_object_version_EQ);
1984 }
1985 
1986 void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
1987                                          const llvm::opt::ArgList &Args) {
1988   const unsigned MinCodeObjVer = 2;
1989   const unsigned MaxCodeObjVer = 5;
1990 
1991   // Emit warnings for legacy options even if they are overridden.
1992   if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
1993     D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
1994                                           << "-mcode-object-version=2";
1995 
1996   if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
1997     D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
1998                                           << "-mcode-object-version=3";
1999 
2000   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2001     if (CodeObjArg->getOption().getID() ==
2002         options::OPT_mcode_object_version_EQ) {
2003       unsigned CodeObjVer = MaxCodeObjVer;
2004       auto Remnant =
2005           StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2006       if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
2007         D.Diag(diag::err_drv_invalid_int_value)
2008             << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
2009     }
2010   }
2011 }
2012 
2013 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
2014                                            const llvm::opt::ArgList &Args) {
2015   unsigned CodeObjVer = 4; // default
2016   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2017     if (CodeObjArg->getOption().getID() ==
2018         options::OPT_mno_code_object_v3_legacy) {
2019       CodeObjVer = 2;
2020     } else if (CodeObjArg->getOption().getID() ==
2021                options::OPT_mcode_object_v3_legacy) {
2022       CodeObjVer = 3;
2023     } else {
2024       StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2025     }
2026   }
2027   return CodeObjVer;
2028 }
2029 
2030 bool tools::haveAMDGPUCodeObjectVersionArgument(
2031     const Driver &D, const llvm::opt::ArgList &Args) {
2032   return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2033 }
2034 
2035 void tools::addMachineOutlinerArgs(const Driver &D,
2036                                    const llvm::opt::ArgList &Args,
2037                                    llvm::opt::ArgStringList &CmdArgs,
2038                                    const llvm::Triple &Triple, bool IsLTO) {
2039   auto addArg = [&, IsLTO](const Twine &Arg) {
2040     if (IsLTO) {
2041       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
2042     } else {
2043       CmdArgs.push_back("-mllvm");
2044       CmdArgs.push_back(Args.MakeArgString(Arg));
2045     }
2046   };
2047 
2048   if (Arg *A = Args.getLastArg(options::OPT_moutline,
2049                                options::OPT_mno_outline)) {
2050     if (A->getOption().matches(options::OPT_moutline)) {
2051       // We only support -moutline in AArch64 and ARM targets right now. If
2052       // we're not compiling for these, emit a warning and ignore the flag.
2053       // Otherwise, add the proper mllvm flags.
2054       if (!(Triple.isARM() || Triple.isThumb() ||
2055             Triple.getArch() == llvm::Triple::aarch64 ||
2056             Triple.getArch() == llvm::Triple::aarch64_32)) {
2057         D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2058       } else {
2059         addArg(Twine("-enable-machine-outliner"));
2060       }
2061     } else {
2062       // Disable all outlining behaviour.
2063       addArg(Twine("-enable-machine-outliner=never"));
2064     }
2065   }
2066 }
2067 
2068 void tools::addOpenMPDeviceRTL(const Driver &D,
2069                                const llvm::opt::ArgList &DriverArgs,
2070                                llvm::opt::ArgStringList &CC1Args,
2071                                StringRef BitcodeSuffix,
2072                                const llvm::Triple &Triple) {
2073   SmallVector<StringRef, 8> LibraryPaths;
2074 
2075   // Add path to clang lib / lib64 folder.
2076   SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2077   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
2078   LibraryPaths.emplace_back(DefaultLibPath.c_str());
2079 
2080   // Add user defined library paths from LIBRARY_PATH.
2081   llvm::Optional<std::string> LibPath =
2082       llvm::sys::Process::GetEnv("LIBRARY_PATH");
2083   if (LibPath) {
2084     SmallVector<StringRef, 8> Frags;
2085     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2086     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2087     for (StringRef Path : Frags)
2088       LibraryPaths.emplace_back(Path.trim());
2089   }
2090 
2091   OptSpecifier LibomptargetBCPathOpt =
2092       Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2093                         : options::OPT_libomptarget_nvptx_bc_path_EQ;
2094 
2095   StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2096   std::string LibOmpTargetName =
2097       ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2098 
2099   // First check whether user specifies bc library
2100   if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2101     SmallString<128> LibOmpTargetFile(A->getValue());
2102     if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2103         llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2104       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2105     }
2106 
2107     if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2108       CC1Args.push_back("-mlink-builtin-bitcode");
2109       CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2110     } else {
2111       D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2112           << LibOmpTargetFile;
2113     }
2114   } else {
2115     bool FoundBCLibrary = false;
2116 
2117     for (StringRef LibraryPath : LibraryPaths) {
2118       SmallString<128> LibOmpTargetFile(LibraryPath);
2119       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2120       if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2121         CC1Args.push_back("-mlink-builtin-bitcode");
2122         CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2123         FoundBCLibrary = true;
2124         break;
2125       }
2126     }
2127 
2128     if (!FoundBCLibrary)
2129       D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2130           << LibOmpTargetName << ArchPrefix;
2131   }
2132 }
2133 void tools::addHIPRuntimeLibArgs(const ToolChain &TC,
2134                                  const llvm::opt::ArgList &Args,
2135                                  llvm::opt::ArgStringList &CmdArgs) {
2136   if (Args.hasArg(options::OPT_hip_link) &&
2137       !Args.hasArg(options::OPT_nostdlib) &&
2138       !Args.hasArg(options::OPT_no_hip_rt)) {
2139     TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2140   } else {
2141     // Claim "no HIP libraries" arguments if any
2142     for (auto Arg : Args.filtered(options::OPT_no_hip_rt)) {
2143       Arg->claim();
2144     }
2145   }
2146 }
2147