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