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