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(llvm::opt::ArgStringList &CmdArgs) {
743   CmdArgs.push_back("-lFortran_main");
744   CmdArgs.push_back("-lFortranRuntime");
745   CmdArgs.push_back("-lFortranDecimal");
746 }
747 
748 void tools::addFortranRuntimeLibraryPath(const ToolChain &TC,
749                                          const llvm::opt::ArgList &Args,
750                                          ArgStringList &CmdArgs) {
751   // Default to the <driver-path>/../lib directory. This works fine on the
752   // platforms that we have tested so far. We will probably have to re-fine
753   // this in the future. In particular, on some platforms, we may need to use
754   // lib64 instead of lib.
755   SmallString<256> DefaultLibPath =
756       llvm::sys::path::parent_path(TC.getDriver().Dir);
757   llvm::sys::path::append(DefaultLibPath, "lib");
758   CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
759 }
760 
761 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
762                                 ArgStringList &CmdArgs, StringRef Sanitizer,
763                                 bool IsShared, bool IsWhole) {
764   // Wrap any static runtimes that must be forced into executable in
765   // whole-archive.
766   if (IsWhole) CmdArgs.push_back("--whole-archive");
767   CmdArgs.push_back(TC.getCompilerRTArgString(
768       Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
769   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
770 
771   if (IsShared) {
772     addArchSpecificRPath(TC, Args, CmdArgs);
773   }
774 }
775 
776 // Tries to use a file with the list of dynamic symbols that need to be exported
777 // from the runtime library. Returns true if the file was found.
778 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
779                                     ArgStringList &CmdArgs,
780                                     StringRef Sanitizer) {
781   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
782   // the option, so don't try to pass it.
783   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
784     return true;
785   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
786   if (llvm::sys::fs::exists(SanRT + ".syms")) {
787     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
788     return true;
789   }
790   return false;
791 }
792 
793 const char *tools::getAsNeededOption(const ToolChain &TC, bool as_needed) {
794   assert(!TC.getTriple().isOSAIX() &&
795          "AIX linker does not support any form of --as-needed option yet.");
796 
797   // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
798   // for the native forms -z ignore/-z record, they are missing in Illumos,
799   // so always use the native form.
800   if (TC.getTriple().isOSSolaris())
801     return as_needed ? "-zignore" : "-zrecord";
802   else
803     return as_needed ? "--as-needed" : "--no-as-needed";
804 }
805 
806 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
807                                      ArgStringList &CmdArgs) {
808   // Force linking against the system libraries sanitizers depends on
809   // (see PR15823 why this is necessary).
810   CmdArgs.push_back(getAsNeededOption(TC, false));
811   // There's no libpthread or librt on RTEMS & Android.
812   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
813       !TC.getTriple().isAndroid()) {
814     CmdArgs.push_back("-lpthread");
815     if (!TC.getTriple().isOSOpenBSD())
816       CmdArgs.push_back("-lrt");
817   }
818   CmdArgs.push_back("-lm");
819   // There's no libdl on all OSes.
820   if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
821       !TC.getTriple().isOSOpenBSD() &&
822       TC.getTriple().getOS() != llvm::Triple::RTEMS)
823     CmdArgs.push_back("-ldl");
824   // Required for backtrace on some OSes
825   if (TC.getTriple().isOSFreeBSD() ||
826       TC.getTriple().isOSNetBSD() ||
827       TC.getTriple().isOSOpenBSD())
828     CmdArgs.push_back("-lexecinfo");
829   // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
830   // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
831   // requirement.
832   if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
833       !TC.getTriple().isMusl())
834     CmdArgs.push_back("-lresolv");
835 }
836 
837 static void
838 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
839                          SmallVectorImpl<StringRef> &SharedRuntimes,
840                          SmallVectorImpl<StringRef> &StaticRuntimes,
841                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
842                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
843                          SmallVectorImpl<StringRef> &RequiredSymbols) {
844   const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
845   // Collect shared runtimes.
846   if (SanArgs.needsSharedRt()) {
847     if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
848       SharedRuntimes.push_back("asan");
849       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
850         HelperStaticRuntimes.push_back("asan-preinit");
851     }
852     if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
853       SharedRuntimes.push_back("memprof");
854       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
855         HelperStaticRuntimes.push_back("memprof-preinit");
856     }
857     if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
858       if (SanArgs.requiresMinimalRuntime())
859         SharedRuntimes.push_back("ubsan_minimal");
860       else
861         SharedRuntimes.push_back("ubsan_standalone");
862     }
863     if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
864       if (SanArgs.requiresMinimalRuntime())
865         SharedRuntimes.push_back("scudo_minimal");
866       else
867         SharedRuntimes.push_back("scudo");
868     }
869     if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
870       SharedRuntimes.push_back("tsan");
871     if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
872       if (SanArgs.needsHwasanAliasesRt())
873         SharedRuntimes.push_back("hwasan_aliases");
874       else
875         SharedRuntimes.push_back("hwasan");
876       if (!Args.hasArg(options::OPT_shared))
877         HelperStaticRuntimes.push_back("hwasan-preinit");
878     }
879   }
880 
881   // The stats_client library is also statically linked into DSOs.
882   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
883     StaticRuntimes.push_back("stats_client");
884 
885   // Always link the static runtime regardless of DSO or executable.
886   if (SanArgs.needsAsanRt())
887     HelperStaticRuntimes.push_back("asan_static");
888 
889   // Collect static runtimes.
890   if (Args.hasArg(options::OPT_shared)) {
891     // Don't link static runtimes into DSOs.
892     return;
893   }
894 
895   // Each static runtime that has a DSO counterpart above is excluded below,
896   // but runtimes that exist only as static are not affected by needsSharedRt.
897 
898   if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
899     StaticRuntimes.push_back("asan");
900     if (SanArgs.linkCXXRuntimes())
901       StaticRuntimes.push_back("asan_cxx");
902   }
903 
904   if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
905       SanArgs.linkRuntimes()) {
906     StaticRuntimes.push_back("memprof");
907     if (SanArgs.linkCXXRuntimes())
908       StaticRuntimes.push_back("memprof_cxx");
909   }
910 
911   if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
912     if (SanArgs.needsHwasanAliasesRt()) {
913       StaticRuntimes.push_back("hwasan_aliases");
914       if (SanArgs.linkCXXRuntimes())
915         StaticRuntimes.push_back("hwasan_aliases_cxx");
916     } else {
917       StaticRuntimes.push_back("hwasan");
918       if (SanArgs.linkCXXRuntimes())
919         StaticRuntimes.push_back("hwasan_cxx");
920     }
921   }
922   if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
923     StaticRuntimes.push_back("dfsan");
924   if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
925     StaticRuntimes.push_back("lsan");
926   if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
927     StaticRuntimes.push_back("msan");
928     if (SanArgs.linkCXXRuntimes())
929       StaticRuntimes.push_back("msan_cxx");
930   }
931   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
932       SanArgs.linkRuntimes()) {
933     StaticRuntimes.push_back("tsan");
934     if (SanArgs.linkCXXRuntimes())
935       StaticRuntimes.push_back("tsan_cxx");
936   }
937   if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
938     if (SanArgs.requiresMinimalRuntime()) {
939       StaticRuntimes.push_back("ubsan_minimal");
940     } else {
941       StaticRuntimes.push_back("ubsan_standalone");
942       if (SanArgs.linkCXXRuntimes())
943         StaticRuntimes.push_back("ubsan_standalone_cxx");
944     }
945   }
946   if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
947     NonWholeStaticRuntimes.push_back("safestack");
948     RequiredSymbols.push_back("__safestack_init");
949   }
950   if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
951     if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
952       StaticRuntimes.push_back("cfi");
953     if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
954       StaticRuntimes.push_back("cfi_diag");
955       if (SanArgs.linkCXXRuntimes())
956         StaticRuntimes.push_back("ubsan_standalone_cxx");
957     }
958   }
959   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
960     NonWholeStaticRuntimes.push_back("stats");
961     RequiredSymbols.push_back("__sanitizer_stats_register");
962   }
963   if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
964     if (SanArgs.requiresMinimalRuntime()) {
965       StaticRuntimes.push_back("scudo_minimal");
966       if (SanArgs.linkCXXRuntimes())
967         StaticRuntimes.push_back("scudo_cxx_minimal");
968     } else {
969       StaticRuntimes.push_back("scudo");
970       if (SanArgs.linkCXXRuntimes())
971         StaticRuntimes.push_back("scudo_cxx");
972     }
973   }
974 }
975 
976 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
977 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
978 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
979                                  ArgStringList &CmdArgs) {
980   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
981       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
982   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
983                            NonWholeStaticRuntimes, HelperStaticRuntimes,
984                            RequiredSymbols);
985 
986   const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
987   // Inject libfuzzer dependencies.
988   if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
989       !Args.hasArg(options::OPT_shared)) {
990 
991     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
992     if (SanArgs.needsFuzzerInterceptors())
993       addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
994                           true);
995     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
996       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
997                                  !Args.hasArg(options::OPT_static);
998       if (OnlyLibstdcxxStatic)
999         CmdArgs.push_back("-Bstatic");
1000       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1001       if (OnlyLibstdcxxStatic)
1002         CmdArgs.push_back("-Bdynamic");
1003     }
1004   }
1005 
1006   for (auto RT : SharedRuntimes)
1007     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
1008   for (auto RT : HelperStaticRuntimes)
1009     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1010   bool AddExportDynamic = false;
1011   for (auto RT : StaticRuntimes) {
1012     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1013     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1014   }
1015   for (auto RT : NonWholeStaticRuntimes) {
1016     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1017     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1018   }
1019   for (auto S : RequiredSymbols) {
1020     CmdArgs.push_back("-u");
1021     CmdArgs.push_back(Args.MakeArgString(S));
1022   }
1023   // If there is a static runtime with no dynamic list, force all the symbols
1024   // to be dynamic to be sure we export sanitizer interface functions.
1025   if (AddExportDynamic)
1026     CmdArgs.push_back("--export-dynamic");
1027 
1028   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1029     CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1030 
1031   if (SanArgs.hasMemTag()) {
1032     if (!TC.getTriple().isAndroid()) {
1033       TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1034           << "-fsanitize=memtag*" << TC.getTriple().str();
1035     }
1036     CmdArgs.push_back(
1037         Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1038     if (SanArgs.hasMemtagHeap())
1039       CmdArgs.push_back("--android-memtag-heap");
1040     if (SanArgs.hasMemtagStack())
1041       CmdArgs.push_back("--android-memtag-stack");
1042   }
1043 
1044   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1045 }
1046 
1047 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1048   if (Args.hasArg(options::OPT_shared))
1049     return false;
1050 
1051   if (TC.getXRayArgs().needsXRayRt()) {
1052     CmdArgs.push_back("-whole-archive");
1053     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
1054     for (const auto &Mode : TC.getXRayArgs().modeList())
1055       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
1056     CmdArgs.push_back("-no-whole-archive");
1057     return true;
1058   }
1059 
1060   return false;
1061 }
1062 
1063 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
1064   CmdArgs.push_back(getAsNeededOption(TC, false));
1065   CmdArgs.push_back("-lpthread");
1066   if (!TC.getTriple().isOSOpenBSD())
1067     CmdArgs.push_back("-lrt");
1068   CmdArgs.push_back("-lm");
1069 
1070   if (!TC.getTriple().isOSFreeBSD() &&
1071       !TC.getTriple().isOSNetBSD() &&
1072       !TC.getTriple().isOSOpenBSD())
1073     CmdArgs.push_back("-ldl");
1074 }
1075 
1076 bool tools::areOptimizationsEnabled(const ArgList &Args) {
1077   // Find the last -O arg and see if it is non-zero.
1078   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1079     return !A->getOption().matches(options::OPT_O0);
1080   // Defaults to -O0.
1081   return false;
1082 }
1083 
1084 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1085                                   const InputInfo &Input,
1086                                   const InputInfo &Output) {
1087   auto AddPostfix = [JA](auto &F) {
1088     if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1089       F += (Twine("_") + JA.getOffloadingArch()).str();
1090     F += ".dwo";
1091   };
1092   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1093     if (StringRef(A->getValue()) == "single")
1094       return Args.MakeArgString(Output.getFilename());
1095 
1096   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1097   if (FinalOutput && Args.hasArg(options::OPT_c)) {
1098     SmallString<128> T(FinalOutput->getValue());
1099     llvm::sys::path::remove_filename(T);
1100     llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1101     AddPostfix(T);
1102     return Args.MakeArgString(T);
1103   } else {
1104     // Use the compilation dir.
1105     Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
1106                              options::OPT_fdebug_compilation_dir_EQ);
1107     SmallString<128> T(A ? A->getValue() : "");
1108     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1109     AddPostfix(F);
1110     T += F;
1111     return Args.MakeArgString(T);
1112   }
1113 }
1114 
1115 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1116                            const JobAction &JA, const ArgList &Args,
1117                            const InputInfo &Output, const char *OutFile) {
1118   ArgStringList ExtractArgs;
1119   ExtractArgs.push_back("--extract-dwo");
1120 
1121   ArgStringList StripArgs;
1122   StripArgs.push_back("--strip-dwo");
1123 
1124   // Grabbing the output of the earlier compile step.
1125   StripArgs.push_back(Output.getFilename());
1126   ExtractArgs.push_back(Output.getFilename());
1127   ExtractArgs.push_back(OutFile);
1128 
1129   const char *Exec =
1130       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1131   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1132 
1133   // First extract the dwo sections.
1134   C.addCommand(std::make_unique<Command>(JA, T,
1135                                          ResponseFileSupport::AtFileCurCP(),
1136                                          Exec, ExtractArgs, II, Output));
1137 
1138   // Then remove them from the original .o file.
1139   C.addCommand(std::make_unique<Command>(
1140       JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1141 }
1142 
1143 // Claim options we don't want to warn if they are unused. We do this for
1144 // options that build systems might add but are unused when assembling or only
1145 // running the preprocessor for example.
1146 void tools::claimNoWarnArgs(const ArgList &Args) {
1147   // Don't warn about unused -f(no-)?lto.  This can happen when we're
1148   // preprocessing, precompiling or assembling.
1149   Args.ClaimAllArgs(options::OPT_flto_EQ);
1150   Args.ClaimAllArgs(options::OPT_flto);
1151   Args.ClaimAllArgs(options::OPT_fno_lto);
1152 }
1153 
1154 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1155   auto *ProfileUseArg = Args.getLastArg(
1156       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1157       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1158       options::OPT_fno_profile_instr_use);
1159 
1160   if (ProfileUseArg &&
1161       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1162     ProfileUseArg = nullptr;
1163 
1164   return ProfileUseArg;
1165 }
1166 
1167 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1168   auto *ProfileSampleUseArg = Args.getLastArg(
1169       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1170       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1171       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1172 
1173   if (ProfileSampleUseArg &&
1174       (ProfileSampleUseArg->getOption().matches(
1175            options::OPT_fno_profile_sample_use) ||
1176        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1177     return nullptr;
1178 
1179   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1180                          options::OPT_fauto_profile_EQ);
1181 }
1182 
1183 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
1184 /// smooshes them together with platform defaults, to decide whether
1185 /// this compile should be using PIC mode or not. Returns a tuple of
1186 /// (RelocationModel, PICLevel, IsPIE).
1187 std::tuple<llvm::Reloc::Model, unsigned, bool>
1188 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1189   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1190   const llvm::Triple &Triple = ToolChain.getTriple();
1191 
1192   bool PIE = ToolChain.isPIEDefault(Args);
1193   bool PIC = PIE || ToolChain.isPICDefault();
1194   // The Darwin/MachO default to use PIC does not apply when using -static.
1195   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1196     PIE = PIC = false;
1197   bool IsPICLevelTwo = PIC;
1198 
1199   bool KernelOrKext =
1200       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1201 
1202   // Android-specific defaults for PIC/PIE
1203   if (Triple.isAndroid()) {
1204     switch (Triple.getArch()) {
1205     case llvm::Triple::arm:
1206     case llvm::Triple::armeb:
1207     case llvm::Triple::thumb:
1208     case llvm::Triple::thumbeb:
1209     case llvm::Triple::aarch64:
1210     case llvm::Triple::mips:
1211     case llvm::Triple::mipsel:
1212     case llvm::Triple::mips64:
1213     case llvm::Triple::mips64el:
1214       PIC = true; // "-fpic"
1215       break;
1216 
1217     case llvm::Triple::x86:
1218     case llvm::Triple::x86_64:
1219       PIC = true; // "-fPIC"
1220       IsPICLevelTwo = true;
1221       break;
1222 
1223     default:
1224       break;
1225     }
1226   }
1227 
1228   // OpenBSD-specific defaults for PIE
1229   if (Triple.isOSOpenBSD()) {
1230     switch (ToolChain.getArch()) {
1231     case llvm::Triple::arm:
1232     case llvm::Triple::aarch64:
1233     case llvm::Triple::mips64:
1234     case llvm::Triple::mips64el:
1235     case llvm::Triple::x86:
1236     case llvm::Triple::x86_64:
1237       IsPICLevelTwo = false; // "-fpie"
1238       break;
1239 
1240     case llvm::Triple::ppc:
1241     case llvm::Triple::sparcv9:
1242       IsPICLevelTwo = true; // "-fPIE"
1243       break;
1244 
1245     default:
1246       break;
1247     }
1248   }
1249 
1250   // AMDGPU-specific defaults for PIC.
1251   if (Triple.getArch() == llvm::Triple::amdgcn)
1252     PIC = true;
1253 
1254   // The last argument relating to either PIC or PIE wins, and no
1255   // other argument is used. If the last argument is any flavor of the
1256   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1257   // option implicitly enables PIC at the same level.
1258   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1259                                     options::OPT_fpic, options::OPT_fno_pic,
1260                                     options::OPT_fPIE, options::OPT_fno_PIE,
1261                                     options::OPT_fpie, options::OPT_fno_pie);
1262   if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1263       LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1264                                     options::OPT_fPIE, options::OPT_fpie)) {
1265     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1266         << LastPICArg->getSpelling() << Triple.str();
1267     if (Triple.getArch() == llvm::Triple::x86_64)
1268       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1269     return std::make_tuple(llvm::Reloc::Static, 0U, false);
1270   }
1271 
1272   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1273   // is forced, then neither PIC nor PIE flags will have no effect.
1274   if (!ToolChain.isPICDefaultForced()) {
1275     if (LastPICArg) {
1276       Option O = LastPICArg->getOption();
1277       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1278           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1279         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1280         PIC =
1281             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1282         IsPICLevelTwo =
1283             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1284       } else {
1285         PIE = PIC = false;
1286         if (EffectiveTriple.isPS()) {
1287           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1288           StringRef Model = ModelArg ? ModelArg->getValue() : "";
1289           if (Model != "kernel") {
1290             PIC = true;
1291             ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1292                 << LastPICArg->getSpelling()
1293                 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1294           }
1295         }
1296       }
1297     }
1298   }
1299 
1300   // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1301   // the PIC level would've been set to level 1, force it back to level 2 PIC
1302   // instead.
1303   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1304     IsPICLevelTwo |= ToolChain.isPICDefault();
1305 
1306   // This kernel flags are a trump-card: they will disable PIC/PIE
1307   // generation, independent of the argument order.
1308   if (KernelOrKext &&
1309       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1310        !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1311     PIC = PIE = false;
1312 
1313   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1314     // This is a very special mode. It trumps the other modes, almost no one
1315     // uses it, and it isn't even valid on any OS but Darwin.
1316     if (!Triple.isOSDarwin())
1317       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1318           << A->getSpelling() << Triple.str();
1319 
1320     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1321 
1322     // Only a forced PIC mode can cause the actual compile to have PIC defines
1323     // etc., no flags are sufficient. This behavior was selected to closely
1324     // match that of llvm-gcc and Apple GCC before that.
1325     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1326 
1327     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1328   }
1329 
1330   bool EmbeddedPISupported;
1331   switch (Triple.getArch()) {
1332     case llvm::Triple::arm:
1333     case llvm::Triple::armeb:
1334     case llvm::Triple::thumb:
1335     case llvm::Triple::thumbeb:
1336       EmbeddedPISupported = true;
1337       break;
1338     default:
1339       EmbeddedPISupported = false;
1340       break;
1341   }
1342 
1343   bool ROPI = false, RWPI = false;
1344   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1345   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1346     if (!EmbeddedPISupported)
1347       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1348           << LastROPIArg->getSpelling() << Triple.str();
1349     ROPI = true;
1350   }
1351   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1352   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1353     if (!EmbeddedPISupported)
1354       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1355           << LastRWPIArg->getSpelling() << Triple.str();
1356     RWPI = true;
1357   }
1358 
1359   // ROPI and RWPI are not compatible with PIC or PIE.
1360   if ((ROPI || RWPI) && (PIC || PIE))
1361     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1362 
1363   if (Triple.isMIPS()) {
1364     StringRef CPUName;
1365     StringRef ABIName;
1366     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1367     // When targeting the N64 ABI, PIC is the default, except in the case
1368     // when the -mno-abicalls option is used. In that case we exit
1369     // at next check regardless of PIC being set below.
1370     if (ABIName == "n64")
1371       PIC = true;
1372     // When targettng MIPS with -mno-abicalls, it's always static.
1373     if(Args.hasArg(options::OPT_mno_abicalls))
1374       return std::make_tuple(llvm::Reloc::Static, 0U, false);
1375     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1376     // does not use PIC level 2 for historical reasons.
1377     IsPICLevelTwo = false;
1378   }
1379 
1380   if (PIC)
1381     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1382 
1383   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1384   if (ROPI && RWPI)
1385     RelocM = llvm::Reloc::ROPI_RWPI;
1386   else if (ROPI)
1387     RelocM = llvm::Reloc::ROPI;
1388   else if (RWPI)
1389     RelocM = llvm::Reloc::RWPI;
1390 
1391   return std::make_tuple(RelocM, 0U, false);
1392 }
1393 
1394 // `-falign-functions` indicates that the functions should be aligned to a
1395 // 16-byte boundary.
1396 //
1397 // `-falign-functions=1` is the same as `-fno-align-functions`.
1398 //
1399 // The scalar `n` in `-falign-functions=n` must be an integral value between
1400 // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1401 // the nearest power-of-two.
1402 //
1403 // If we return `0`, the frontend will default to the backend's preferred
1404 // alignment.
1405 //
1406 // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1407 // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1408 // alignment.  For unaligned functions, we default to the backend's preferred
1409 // alignment.
1410 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1411                                        const ArgList &Args) {
1412   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1413                                  options::OPT_falign_functions_EQ,
1414                                  options::OPT_fno_align_functions);
1415   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1416     return 0;
1417 
1418   if (A->getOption().matches(options::OPT_falign_functions))
1419     return 0;
1420 
1421   unsigned Value = 0;
1422   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1423     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1424         << A->getAsString(Args) << A->getValue();
1425   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1426 }
1427 
1428 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1429                                          const ArgList &Args) {
1430   const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1431 
1432   if (!A)
1433     return 0;
1434 
1435   unsigned Value = 0;
1436   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1437       Value < 2)
1438     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1439         << A->getAsString(Args) << A->getValue();
1440   return Value;
1441 }
1442 
1443 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1444                              ArgStringList &CmdArgs) {
1445   llvm::Reloc::Model RelocationModel;
1446   unsigned PICLevel;
1447   bool IsPIE;
1448   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1449 
1450   if (RelocationModel != llvm::Reloc::Static)
1451     CmdArgs.push_back("-KPIC");
1452 }
1453 
1454 /// Determine whether Objective-C automated reference counting is
1455 /// enabled.
1456 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1457   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1458 }
1459 
1460 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1461 
1462 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
1463                                 const ArgList &Args) {
1464   if (Args.hasArg(options::OPT_static_libgcc) ||
1465       Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
1466       // The Android NDK only provides libunwind.a, not libunwind.so.
1467       TC.getTriple().isAndroid())
1468     return LibGccType::StaticLibGcc;
1469   if (Args.hasArg(options::OPT_shared_libgcc))
1470     return LibGccType::SharedLibGcc;
1471   return LibGccType::UnspecifiedLibGcc;
1472 }
1473 
1474 // Gcc adds libgcc arguments in various ways:
1475 //
1476 // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
1477 // g++ <none>:                       -lgcc_s               -lgcc
1478 // gcc shared:                       -lgcc_s               -lgcc
1479 // g++ shared:                       -lgcc_s               -lgcc
1480 // gcc static:     -lgcc             -lgcc_eh
1481 // g++ static:     -lgcc             -lgcc_eh
1482 // gcc static-pie: -lgcc             -lgcc_eh
1483 // g++ static-pie: -lgcc             -lgcc_eh
1484 //
1485 // Also, certain targets need additional adjustments.
1486 
1487 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1488                              ArgStringList &CmdArgs, const ArgList &Args) {
1489   ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1490   // Targets that don't use unwind libraries.
1491   if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
1492       TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
1493       UNW == ToolChain::UNW_None)
1494     return;
1495 
1496   LibGccType LGT = getLibGccType(TC, D, Args);
1497   bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX() &&
1498                   !TC.getTriple().isAndroid() &&
1499                   !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
1500   if (AsNeeded)
1501     CmdArgs.push_back(getAsNeededOption(TC, true));
1502 
1503   switch (UNW) {
1504   case ToolChain::UNW_None:
1505     return;
1506   case ToolChain::UNW_Libgcc: {
1507     if (LGT == LibGccType::StaticLibGcc)
1508       CmdArgs.push_back("-lgcc_eh");
1509     else
1510       CmdArgs.push_back("-lgcc_s");
1511     break;
1512   }
1513   case ToolChain::UNW_CompilerRT:
1514     if (TC.getTriple().isOSAIX()) {
1515       // AIX only has libunwind as a shared library. So do not pass
1516       // anything in if -static is specified.
1517       if (LGT != LibGccType::StaticLibGcc)
1518         CmdArgs.push_back("-lunwind");
1519     } else if (LGT == LibGccType::StaticLibGcc) {
1520       CmdArgs.push_back("-l:libunwind.a");
1521     } else if (LGT == LibGccType::SharedLibGcc) {
1522       if (TC.getTriple().isOSCygMing())
1523         CmdArgs.push_back("-l:libunwind.dll.a");
1524       else
1525         CmdArgs.push_back("-l:libunwind.so");
1526     } else {
1527       // Let the linker choose between libunwind.so and libunwind.a
1528       // depending on what's available, and depending on the -static flag
1529       CmdArgs.push_back("-lunwind");
1530     }
1531     break;
1532   }
1533 
1534   if (AsNeeded)
1535     CmdArgs.push_back(getAsNeededOption(TC, false));
1536 }
1537 
1538 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1539                       ArgStringList &CmdArgs, const ArgList &Args) {
1540   LibGccType LGT = getLibGccType(TC, D, Args);
1541   if (LGT == LibGccType::StaticLibGcc ||
1542       (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
1543     CmdArgs.push_back("-lgcc");
1544   AddUnwindLibrary(TC, D, CmdArgs, Args);
1545   if (LGT == LibGccType::SharedLibGcc ||
1546       (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
1547     CmdArgs.push_back("-lgcc");
1548 }
1549 
1550 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1551                            ArgStringList &CmdArgs, const ArgList &Args) {
1552   // Make use of compiler-rt if --rtlib option is used
1553   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1554 
1555   switch (RLT) {
1556   case ToolChain::RLT_CompilerRT:
1557     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1558     AddUnwindLibrary(TC, D, CmdArgs, Args);
1559     break;
1560   case ToolChain::RLT_Libgcc:
1561     // Make sure libgcc is not used under MSVC environment by default
1562     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1563       // Issue error diagnostic if libgcc is explicitly specified
1564       // through command line as --rtlib option argument.
1565       if (Args.hasArg(options::OPT_rtlib_EQ)) {
1566         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1567             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1568       }
1569     } else
1570       AddLibgcc(TC, D, CmdArgs, Args);
1571     break;
1572   }
1573 
1574   // On Android, the unwinder uses dl_iterate_phdr (or one of
1575   // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
1576   // statically-linked executables, these functions come from libc.a instead.
1577   if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
1578       !Args.hasArg(options::OPT_static_pie))
1579     CmdArgs.push_back("-ldl");
1580 }
1581 
1582 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1583                                          const InputInfo &Output,
1584                                          const InputInfo &Input,
1585                                          const Driver &D) {
1586   const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1587   if (!A)
1588     return {};
1589 
1590   StringRef SaveStats = A->getValue();
1591   SmallString<128> StatsFile;
1592   if (SaveStats == "obj" && Output.isFilename()) {
1593     StatsFile.assign(Output.getFilename());
1594     llvm::sys::path::remove_filename(StatsFile);
1595   } else if (SaveStats != "cwd") {
1596     D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1597     return {};
1598   }
1599 
1600   StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1601   llvm::sys::path::append(StatsFile, BaseName);
1602   llvm::sys::path::replace_extension(StatsFile, "stats");
1603   return StatsFile;
1604 }
1605 
1606 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1607                             Multilib::flags_list &Flags) {
1608   Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1609 }
1610 
1611 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1612                                   ArgStringList &CmdArgs, bool IsLTO) {
1613   auto addArg = [&, IsLTO](const Twine &Arg) {
1614     if (IsLTO) {
1615       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1616     } else {
1617       CmdArgs.push_back("-mllvm");
1618       CmdArgs.push_back(Args.MakeArgString(Arg));
1619     }
1620   };
1621 
1622   if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1623     addArg(Twine("-x86-branches-within-32B-boundaries"));
1624   }
1625   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1626     StringRef Value = A->getValue();
1627     unsigned Boundary;
1628     if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1629         !llvm::isPowerOf2_64(Boundary)) {
1630       D.Diag(diag::err_drv_invalid_argument_to_option)
1631           << Value << A->getOption().getName();
1632     } else {
1633       addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1634     }
1635   }
1636   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1637     std::string AlignBranch;
1638     for (StringRef T : A->getValues()) {
1639       if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1640           T != "ret" && T != "indirect")
1641         D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1642             << T << "fused, jcc, jmp, call, ret, indirect";
1643       if (!AlignBranch.empty())
1644         AlignBranch += '+';
1645       AlignBranch += T;
1646     }
1647     addArg("-x86-align-branch=" + Twine(AlignBranch));
1648   }
1649   if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1650     StringRef Value = A->getValue();
1651     unsigned PrefixSize;
1652     if (Value.getAsInteger(10, PrefixSize)) {
1653       D.Diag(diag::err_drv_invalid_argument_to_option)
1654           << Value << A->getOption().getName();
1655     } else {
1656       addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1657     }
1658   }
1659 }
1660 
1661 /// SDLSearch: Search for Static Device Library
1662 /// The search for SDL bitcode files is consistent with how static host
1663 /// libraries are discovered. That is, the -l option triggers a search for
1664 /// files in a set of directories called the LINKPATH. The host library search
1665 /// procedure looks for a specific filename in the LINKPATH.  The filename for
1666 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
1667 /// ordered-set of filenames that are searched. We call this ordered-set of
1668 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
1669 /// architecture specific, or generic across all architectures, a naming
1670 /// convention and search order is used where the file name embeds the
1671 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
1672 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
1673 /// device-independent SDLs. To reduce congestion in host library directories,
1674 /// the search first looks for files in the “libdevice” subdirectory. SDLs that
1675 /// are bc files begin with the prefix “lib”.
1676 ///
1677 /// Machine-code SDLs can also be managed as an archive (*.a file). The
1678 /// convention has been to use the prefix “lib”. To avoid confusion with host
1679 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
1680 ///
1681 bool tools::SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
1682                       llvm::opt::ArgStringList &CC1Args,
1683                       SmallVector<std::string, 8> LibraryPaths, std::string Lib,
1684                       StringRef Arch, StringRef Target, bool isBitCodeSDL,
1685                       bool postClangLink) {
1686   SmallVector<std::string, 12> SDLs;
1687 
1688   std::string LibDeviceLoc = "/libdevice";
1689   std::string LibBcPrefix = "/libbc-";
1690   std::string LibPrefix = "/lib";
1691 
1692   if (isBitCodeSDL) {
1693     // SEARCH-ORDER for Bitcode SDLs:
1694     //       libdevice/libbc-<libname>-<arch-name>-<device-type>.a
1695     //       libbc-<libname>-<arch-name>-<device-type>.a
1696     //       libdevice/libbc-<libname>-<arch-name>.a
1697     //       libbc-<libname>-<arch-name>.a
1698     //       libdevice/libbc-<libname>.a
1699     //       libbc-<libname>.a
1700     //       libdevice/lib<libname>-<arch-name>-<device-type>.bc
1701     //       lib<libname>-<arch-name>-<device-type>.bc
1702     //       libdevice/lib<libname>-<arch-name>.bc
1703     //       lib<libname>-<arch-name>.bc
1704     //       libdevice/lib<libname>.bc
1705     //       lib<libname>.bc
1706 
1707     for (StringRef Base : {LibBcPrefix, LibPrefix}) {
1708       const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
1709 
1710       for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1711                           Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
1712         SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
1713         SDLs.push_back(Twine(Base + Suffix + Ext).str());
1714       }
1715     }
1716   } else {
1717     // SEARCH-ORDER for Machine-code SDLs:
1718     //    libdevice/lib<libname>-<arch-name>-<device-type>.a
1719     //    lib<libname>-<arch-name>-<device-type>.a
1720     //    libdevice/lib<libname>-<arch-name>.a
1721     //    lib<libname>-<arch-name>.a
1722 
1723     const auto *Ext = ".a";
1724 
1725     for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1726                         Twine(Lib + "-" + Arch).str()}) {
1727       SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
1728       SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
1729     }
1730   }
1731 
1732   // The CUDA toolchain does not use a global device llvm-link before the LLVM
1733   // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
1734   // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
1735   // will link libraries after clang compilation while the LLVM IR is still in
1736   // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
1737   // This is a clang -cc1 option that is generated by the clang driver. The
1738   // option value must a full path to an existing file.
1739   bool FoundSDL = false;
1740   for (auto LPath : LibraryPaths) {
1741     for (auto SDL : SDLs) {
1742       auto FullName = Twine(LPath + SDL).str();
1743       if (llvm::sys::fs::exists(FullName)) {
1744         if (postClangLink)
1745           CC1Args.push_back("-mlink-builtin-bitcode");
1746         CC1Args.push_back(DriverArgs.MakeArgString(FullName));
1747         FoundSDL = true;
1748         break;
1749       }
1750     }
1751     if (FoundSDL)
1752       break;
1753   }
1754   return FoundSDL;
1755 }
1756 
1757 /// Search if a user provided archive file lib<libname>.a exists in any of
1758 /// the library paths. If so, add a new command to clang-offload-bundler to
1759 /// unbundle this archive and create a temporary device specific archive. Name
1760 /// of this SDL is passed to the llvm-link (for amdgcn) or to the
1761 /// clang-nvlink-wrapper (for nvptx) commands by the driver.
1762 bool tools::GetSDLFromOffloadArchive(
1763     Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
1764     const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
1765     llvm::opt::ArgStringList &CC1Args, SmallVector<std::string, 8> LibraryPaths,
1766     StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
1767     bool postClangLink) {
1768 
1769   // We don't support bitcode archive bundles for nvptx
1770   if (isBitCodeSDL && Arch.contains("nvptx"))
1771     return false;
1772 
1773   bool FoundAOB = false;
1774   SmallVector<std::string, 2> AOBFileNames;
1775   std::string ArchiveOfBundles;
1776   for (auto LPath : LibraryPaths) {
1777     ArchiveOfBundles.clear();
1778 
1779     llvm::Triple Triple(D.getTargetTriple());
1780     bool IsMSVC = Triple.isWindowsMSVCEnvironment();
1781     for (auto Prefix : {"/libdevice/", "/"}) {
1782       if (IsMSVC)
1783         AOBFileNames.push_back(Twine(LPath + Prefix + Lib + ".lib").str());
1784       AOBFileNames.push_back(Twine(LPath + Prefix + "lib" + Lib + ".a").str());
1785     }
1786 
1787     for (auto AOB : AOBFileNames) {
1788       if (llvm::sys::fs::exists(AOB)) {
1789         ArchiveOfBundles = AOB;
1790         FoundAOB = true;
1791         break;
1792       }
1793     }
1794 
1795     if (!FoundAOB)
1796       continue;
1797 
1798     StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
1799     std::string OutputLib = D.GetTemporaryPath(
1800         Twine(Prefix + Lib + "-" + Arch + "-" + Target).str(), "a");
1801 
1802     C.addTempFile(C.getArgs().MakeArgString(OutputLib));
1803 
1804     ArgStringList CmdArgs;
1805     SmallString<128> DeviceTriple;
1806     DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind());
1807     DeviceTriple += '-';
1808     std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
1809     DeviceTriple += NormalizedTriple;
1810     if (!Target.empty()) {
1811       DeviceTriple += '-';
1812       DeviceTriple += Target;
1813     }
1814 
1815     std::string UnbundleArg("-unbundle");
1816     std::string TypeArg("-type=a");
1817     std::string InputArg("-input=" + ArchiveOfBundles);
1818     std::string OffloadArg("-targets=" + std::string(DeviceTriple));
1819     std::string OutputArg("-output=" + OutputLib);
1820 
1821     const char *UBProgram = DriverArgs.MakeArgString(
1822         T.getToolChain().GetProgramPath("clang-offload-bundler"));
1823 
1824     ArgStringList UBArgs;
1825     UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
1826     UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
1827     UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
1828     UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
1829     UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
1830 
1831     // Add this flag to not exit from clang-offload-bundler if no compatible
1832     // code object is found in heterogenous archive library.
1833     std::string AdditionalArgs("-allow-missing-bundles");
1834     UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
1835 
1836     // Add this flag to treat hip and hipv4 offload kinds as compatible with
1837     // openmp offload kind while extracting code objects from a heterogenous
1838     // archive library. Vice versa is also considered compatible.
1839     std::string HipCompatibleArgs("-hip-openmp-compatible");
1840     UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
1841 
1842     C.addCommand(std::make_unique<Command>(
1843         JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
1844         InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
1845     if (postClangLink)
1846       CC1Args.push_back("-mlink-builtin-bitcode");
1847 
1848     CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
1849     break;
1850   }
1851 
1852   return FoundAOB;
1853 }
1854 
1855 // Wrapper function used by driver for adding SDLs during link phase.
1856 void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T,
1857                                 const JobAction &JA,
1858                                 const InputInfoList &Inputs,
1859                                 const llvm::opt::ArgList &DriverArgs,
1860                                 llvm::opt::ArgStringList &CC1Args,
1861                                 StringRef Arch, StringRef Target,
1862                                 bool isBitCodeSDL, bool postClangLink) {
1863   AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
1864                       Arch, Target, isBitCodeSDL, postClangLink);
1865 }
1866 
1867 // Wrapper function used for post clang linking of bitcode SDLS for nvptx by
1868 // the CUDA toolchain.
1869 void tools::AddStaticDeviceLibsPostLinking(const Driver &D,
1870                                 const llvm::opt::ArgList &DriverArgs,
1871                                 llvm::opt::ArgStringList &CC1Args,
1872                                 StringRef Arch, StringRef Target,
1873                                 bool isBitCodeSDL, bool postClangLink) {
1874   AddStaticDeviceLibs(nullptr, nullptr, nullptr, nullptr, D, DriverArgs,
1875                       CC1Args, Arch, Target, isBitCodeSDL, postClangLink);
1876 }
1877 
1878 // User defined Static Device Libraries(SDLs) can be passed to clang for
1879 // offloading GPU compilers. Like static host libraries, the use of a SDL is
1880 // specified with the -l command line option. The primary difference between
1881 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
1882 // and SEARCH-ORDER for Machine-code SDLs for the naming convention).
1883 // SDLs are of following types:
1884 //
1885 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
1886 //           For NVPTX, these libraries are post-clang linked following each
1887 //           compilation. For AMDGPU, these libraries are linked one time
1888 //           during the application link phase.
1889 //
1890 // * Machine-code SDLs: They are archive files. For NVPTX, the archive members
1891 //           contain cubin for Nvidia GPUs and are linked one time during the
1892 //           link phase by the CUDA SDK linker called nvlink.	For AMDGPU, the
1893 //           process for machine code SDLs is still in development. But they
1894 //           will be linked by the LLVM tool lld.
1895 //
1896 // * Bundled objects that contain both host and device codes: Bundled objects
1897 //           may also contain library code compiled from source. For NVPTX, the
1898 //           bundle contains cubin. For AMDGPU, the bundle contains bitcode.
1899 //
1900 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
1901 // inclusion of specific SDLs such as math libraries and the OpenMP device
1902 // library libomptarget.
1903 void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T,
1904                                 const JobAction *JA,
1905                                 const InputInfoList *Inputs, const Driver &D,
1906                                 const llvm::opt::ArgList &DriverArgs,
1907                                 llvm::opt::ArgStringList &CC1Args,
1908                                 StringRef Arch, StringRef Target,
1909                                 bool isBitCodeSDL, bool postClangLink) {
1910 
1911   SmallVector<std::string, 8> LibraryPaths;
1912   // Add search directories from LIBRARY_PATH env variable
1913   llvm::Optional<std::string> LibPath =
1914       llvm::sys::Process::GetEnv("LIBRARY_PATH");
1915   if (LibPath) {
1916     SmallVector<StringRef, 8> Frags;
1917     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
1918     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
1919     for (StringRef Path : Frags)
1920       LibraryPaths.emplace_back(Path.trim());
1921   }
1922 
1923   // Add directories from user-specified -L options
1924   for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
1925     LibraryPaths.emplace_back(Search_Dir);
1926 
1927   // Add path to lib-debug folders
1928   SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
1929   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
1930   LibraryPaths.emplace_back(DefaultLibPath.c_str());
1931 
1932   // Build list of Static Device Libraries SDLs specified by -l option
1933   llvm::SmallSet<std::string, 16> SDLNames;
1934   static const StringRef HostOnlyArchives[] = {
1935       "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
1936   for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
1937     if (!HostOnlyArchives->contains(SDLName)) {
1938       SDLNames.insert(SDLName);
1939     }
1940   }
1941 
1942   // The search stops as soon as an SDL file is found. The driver then provides
1943   // the full filename of the SDL to the llvm-link or clang-nvlink-wrapper
1944   // command. If no SDL is found after searching each LINKPATH with
1945   // SEARCH-ORDER, it is possible that an archive file lib<libname>.a exists
1946   // and may contain bundled object files.
1947   for (auto SDLName : SDLNames) {
1948     // This is the only call to SDLSearch
1949     if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
1950                    isBitCodeSDL, postClangLink)) {
1951       GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
1952                                LibraryPaths, SDLName, Arch, Target,
1953                                isBitCodeSDL, postClangLink);
1954     }
1955   }
1956 }
1957 
1958 static llvm::opt::Arg *
1959 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
1960   // The last of -mcode-object-v3, -mno-code-object-v3 and
1961   // -mcode-object-version=<version> wins.
1962   return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
1963                          options::OPT_mno_code_object_v3_legacy,
1964                          options::OPT_mcode_object_version_EQ);
1965 }
1966 
1967 void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
1968                                          const llvm::opt::ArgList &Args) {
1969   const unsigned MinCodeObjVer = 2;
1970   const unsigned MaxCodeObjVer = 5;
1971 
1972   // Emit warnings for legacy options even if they are overridden.
1973   if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
1974     D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
1975                                           << "-mcode-object-version=2";
1976 
1977   if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
1978     D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
1979                                           << "-mcode-object-version=3";
1980 
1981   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
1982     if (CodeObjArg->getOption().getID() ==
1983         options::OPT_mcode_object_version_EQ) {
1984       unsigned CodeObjVer = MaxCodeObjVer;
1985       auto Remnant =
1986           StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1987       if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
1988         D.Diag(diag::err_drv_invalid_int_value)
1989             << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
1990     }
1991   }
1992 }
1993 
1994 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
1995                                            const llvm::opt::ArgList &Args) {
1996   unsigned CodeObjVer = 4; // default
1997   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
1998     if (CodeObjArg->getOption().getID() ==
1999         options::OPT_mno_code_object_v3_legacy) {
2000       CodeObjVer = 2;
2001     } else if (CodeObjArg->getOption().getID() ==
2002                options::OPT_mcode_object_v3_legacy) {
2003       CodeObjVer = 3;
2004     } else {
2005       StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2006     }
2007   }
2008   return CodeObjVer;
2009 }
2010 
2011 bool tools::haveAMDGPUCodeObjectVersionArgument(
2012     const Driver &D, const llvm::opt::ArgList &Args) {
2013   return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2014 }
2015 
2016 void tools::addMachineOutlinerArgs(const Driver &D,
2017                                    const llvm::opt::ArgList &Args,
2018                                    llvm::opt::ArgStringList &CmdArgs,
2019                                    const llvm::Triple &Triple, bool IsLTO) {
2020   auto addArg = [&, IsLTO](const Twine &Arg) {
2021     if (IsLTO) {
2022       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
2023     } else {
2024       CmdArgs.push_back("-mllvm");
2025       CmdArgs.push_back(Args.MakeArgString(Arg));
2026     }
2027   };
2028 
2029   if (Arg *A = Args.getLastArg(options::OPT_moutline,
2030                                options::OPT_mno_outline)) {
2031     if (A->getOption().matches(options::OPT_moutline)) {
2032       // We only support -moutline in AArch64 and ARM targets right now. If
2033       // we're not compiling for these, emit a warning and ignore the flag.
2034       // Otherwise, add the proper mllvm flags.
2035       if (!(Triple.isARM() || Triple.isThumb() ||
2036             Triple.getArch() == llvm::Triple::aarch64 ||
2037             Triple.getArch() == llvm::Triple::aarch64_32)) {
2038         D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2039       } else {
2040         addArg(Twine("-enable-machine-outliner"));
2041       }
2042     } else {
2043       // Disable all outlining behaviour.
2044       addArg(Twine("-enable-machine-outliner=never"));
2045     }
2046   }
2047 }
2048 
2049 void tools::addOpenMPDeviceRTL(const Driver &D,
2050                                const llvm::opt::ArgList &DriverArgs,
2051                                llvm::opt::ArgStringList &CC1Args,
2052                                StringRef BitcodeSuffix,
2053                                const llvm::Triple &Triple) {
2054   SmallVector<StringRef, 8> LibraryPaths;
2055 
2056   // Add path to clang lib / lib64 folder.
2057   SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2058   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
2059   LibraryPaths.emplace_back(DefaultLibPath.c_str());
2060 
2061   // Add user defined library paths from LIBRARY_PATH.
2062   llvm::Optional<std::string> LibPath =
2063       llvm::sys::Process::GetEnv("LIBRARY_PATH");
2064   if (LibPath) {
2065     SmallVector<StringRef, 8> Frags;
2066     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2067     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2068     for (StringRef Path : Frags)
2069       LibraryPaths.emplace_back(Path.trim());
2070   }
2071 
2072   OptSpecifier LibomptargetBCPathOpt =
2073       Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2074                         : options::OPT_libomptarget_nvptx_bc_path_EQ;
2075 
2076   StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2077   std::string LibOmpTargetName =
2078       ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2079 
2080   // First check whether user specifies bc library
2081   if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2082     SmallString<128> LibOmpTargetFile(A->getValue());
2083     if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2084         llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2085       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2086     }
2087 
2088     if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2089       CC1Args.push_back("-mlink-builtin-bitcode");
2090       CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2091     } else {
2092       D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2093           << LibOmpTargetFile;
2094     }
2095   } else {
2096     bool FoundBCLibrary = false;
2097 
2098     for (StringRef LibraryPath : LibraryPaths) {
2099       SmallString<128> LibOmpTargetFile(LibraryPath);
2100       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2101       if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2102         CC1Args.push_back("-mlink-builtin-bitcode");
2103         CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2104         FoundBCLibrary = true;
2105         break;
2106       }
2107     }
2108 
2109     if (!FoundBCLibrary)
2110       D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2111           << LibOmpTargetName << ArchPrefix;
2112   }
2113 }
2114 void tools::addHIPRuntimeLibArgs(const ToolChain &TC,
2115                                  const llvm::opt::ArgList &Args,
2116                                  llvm::opt::ArgStringList &CmdArgs) {
2117   if (Args.hasArg(options::OPT_hip_link) &&
2118       !Args.hasArg(options::OPT_nostdlib) &&
2119       !Args.hasArg(options::OPT_no_hip_rt)) {
2120     TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2121   } else {
2122     // Claim "no HIP libraries" arguments if any
2123     for (auto Arg : Args.filtered(options::OPT_no_hip_rt)) {
2124       Arg->claim();
2125     }
2126   }
2127 }
2128