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/Mips.h"
13 #include "Arch/PPC.h"
14 #include "Arch/SystemZ.h"
15 #include "Arch/X86.h"
16 #include "HIP.h"
17 #include "Hexagon.h"
18 #include "InputInfo.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/ObjCRuntime.h"
22 #include "clang/Basic/Version.h"
23 #include "clang/Config/config.h"
24 #include "clang/Driver/Action.h"
25 #include "clang/Driver/Compilation.h"
26 #include "clang/Driver/Driver.h"
27 #include "clang/Driver/DriverDiagnostic.h"
28 #include "clang/Driver/Job.h"
29 #include "clang/Driver/Options.h"
30 #include "clang/Driver/SanitizerArgs.h"
31 #include "clang/Driver/ToolChain.h"
32 #include "clang/Driver/Util.h"
33 #include "clang/Driver/XRayArgs.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/Option/Arg.h"
40 #include "llvm/Option/ArgList.h"
41 #include "llvm/Option/Option.h"
42 #include "llvm/Support/CodeGen.h"
43 #include "llvm/Support/Compression.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Host.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/Process.h"
50 #include "llvm/Support/Program.h"
51 #include "llvm/Support/ScopedPrinter.h"
52 #include "llvm/Support/TargetParser.h"
53 #include "llvm/Support/VirtualFileSystem.h"
54 #include "llvm/Support/YAMLParser.h"
55 
56 using namespace clang::driver;
57 using namespace clang::driver::tools;
58 using namespace clang;
59 using namespace llvm::opt;
60 
61 void tools::addPathIfExists(const Driver &D, const Twine &Path,
62                             ToolChain::path_list &Paths) {
63   if (D.getVFS().exists(Path))
64     Paths.push_back(Path.str());
65 }
66 
67 void tools::handleTargetFeaturesGroup(const ArgList &Args,
68                                       std::vector<StringRef> &Features,
69                                       OptSpecifier Group) {
70   for (const Arg *A : Args.filtered(Group)) {
71     StringRef Name = A->getOption().getName();
72     A->claim();
73 
74     // Skip over "-m".
75     assert(Name.startswith("m") && "Invalid feature name.");
76     Name = Name.substr(1);
77 
78     bool IsNegative = Name.startswith("no-");
79     if (IsNegative)
80       Name = Name.substr(3);
81     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
82   }
83 }
84 
85 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
86                              const char *ArgName, const char *EnvVar) {
87   const char *DirList = ::getenv(EnvVar);
88   bool CombinedArg = false;
89 
90   if (!DirList)
91     return; // Nothing to do.
92 
93   StringRef Name(ArgName);
94   if (Name.equals("-I") || Name.equals("-L") || Name.empty())
95     CombinedArg = true;
96 
97   StringRef Dirs(DirList);
98   if (Dirs.empty()) // Empty string should not add '.'.
99     return;
100 
101   StringRef::size_type Delim;
102   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
103     if (Delim == 0) { // Leading colon.
104       if (CombinedArg) {
105         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
106       } else {
107         CmdArgs.push_back(ArgName);
108         CmdArgs.push_back(".");
109       }
110     } else {
111       if (CombinedArg) {
112         CmdArgs.push_back(
113             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
114       } else {
115         CmdArgs.push_back(ArgName);
116         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
117       }
118     }
119     Dirs = Dirs.substr(Delim + 1);
120   }
121 
122   if (Dirs.empty()) { // Trailing colon.
123     if (CombinedArg) {
124       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
125     } else {
126       CmdArgs.push_back(ArgName);
127       CmdArgs.push_back(".");
128     }
129   } else { // Add the last path.
130     if (CombinedArg) {
131       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
132     } else {
133       CmdArgs.push_back(ArgName);
134       CmdArgs.push_back(Args.MakeArgString(Dirs));
135     }
136   }
137 }
138 
139 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
140                             const ArgList &Args, ArgStringList &CmdArgs,
141                             const JobAction &JA) {
142   const Driver &D = TC.getDriver();
143 
144   // Add extra linker input arguments which are not treated as inputs
145   // (constructed via -Xarch_).
146   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
147 
148   // LIBRARY_PATH are included before user inputs and only supported on native
149   // toolchains.
150   if (!TC.isCrossCompiling())
151     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
152 
153   for (const auto &II : Inputs) {
154     // If the current tool chain refers to an OpenMP or HIP offloading host, we
155     // should ignore inputs that refer to OpenMP or HIP offloading devices -
156     // they will be embedded according to a proper linker script.
157     if (auto *IA = II.getAction())
158       if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
159            IA->isDeviceOffloading(Action::OFK_OpenMP)) ||
160           (JA.isHostOffloading(Action::OFK_HIP) &&
161            IA->isDeviceOffloading(Action::OFK_HIP)))
162         continue;
163 
164     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
165       // Don't try to pass LLVM inputs unless we have native support.
166       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
167 
168     // Add filenames immediately.
169     if (II.isFilename()) {
170       CmdArgs.push_back(II.getFilename());
171       continue;
172     }
173 
174     // Otherwise, this is a linker input argument.
175     const Arg &A = II.getInputArg();
176 
177     // Handle reserved library options.
178     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
179       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
180     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
181       TC.AddCCKextLibArgs(Args, CmdArgs);
182     else if (A.getOption().matches(options::OPT_z)) {
183       // Pass -z prefix for gcc linker compatibility.
184       A.claim();
185       A.render(Args, CmdArgs);
186     } else {
187       A.renderAsInput(Args, CmdArgs);
188     }
189   }
190 }
191 
192 void tools::AddTargetFeature(const ArgList &Args,
193                              std::vector<StringRef> &Features,
194                              OptSpecifier OnOpt, OptSpecifier OffOpt,
195                              StringRef FeatureName) {
196   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
197     if (A->getOption().matches(OnOpt))
198       Features.push_back(Args.MakeArgString("+" + FeatureName));
199     else
200       Features.push_back(Args.MakeArgString("-" + FeatureName));
201   }
202 }
203 
204 /// Get the (LLVM) name of the R600 gpu we are targeting.
205 static std::string getR600TargetGPU(const ArgList &Args) {
206   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
207     const char *GPUName = A->getValue();
208     return llvm::StringSwitch<const char *>(GPUName)
209         .Cases("rv630", "rv635", "r600")
210         .Cases("rv610", "rv620", "rs780", "rs880")
211         .Case("rv740", "rv770")
212         .Case("palm", "cedar")
213         .Cases("sumo", "sumo2", "sumo")
214         .Case("hemlock", "cypress")
215         .Case("aruba", "cayman")
216         .Default(GPUName);
217   }
218   return "";
219 }
220 
221 static std::string getLanaiTargetCPU(const ArgList &Args) {
222   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
223     return A->getValue();
224   }
225   return "";
226 }
227 
228 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
229 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
230   // If we have -mcpu=, use that.
231   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
232     StringRef CPU = A->getValue();
233 
234 #ifdef __wasm__
235     // Handle "native" by examining the host. "native" isn't meaningful when
236     // cross compiling, so only support this when the host is also WebAssembly.
237     if (CPU == "native")
238       return llvm::sys::getHostCPUName();
239 #endif
240 
241     return CPU;
242   }
243 
244   return "generic";
245 }
246 
247 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
248                               bool FromAs) {
249   Arg *A;
250 
251   switch (T.getArch()) {
252   default:
253     return "";
254 
255   case llvm::Triple::aarch64:
256   case llvm::Triple::aarch64_32:
257   case llvm::Triple::aarch64_be:
258     return aarch64::getAArch64TargetCPU(Args, T, A);
259 
260   case llvm::Triple::arm:
261   case llvm::Triple::armeb:
262   case llvm::Triple::thumb:
263   case llvm::Triple::thumbeb: {
264     StringRef MArch, MCPU;
265     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
266     return arm::getARMTargetCPU(MCPU, MArch, T);
267   }
268 
269   case llvm::Triple::avr:
270     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
271       return A->getValue();
272     return "";
273 
274   case llvm::Triple::mips:
275   case llvm::Triple::mipsel:
276   case llvm::Triple::mips64:
277   case llvm::Triple::mips64el: {
278     StringRef CPUName;
279     StringRef ABIName;
280     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
281     return std::string(CPUName);
282   }
283 
284   case llvm::Triple::nvptx:
285   case llvm::Triple::nvptx64:
286     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
287       return A->getValue();
288     return "";
289 
290   case llvm::Triple::ppc:
291   case llvm::Triple::ppc64:
292   case llvm::Triple::ppc64le: {
293     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
294     // LLVM may default to generating code for the native CPU,
295     // but, like gcc, we default to a more generic option for
296     // each architecture. (except on Darwin)
297     if (TargetCPUName.empty() && !T.isOSDarwin()) {
298       if (T.getArch() == llvm::Triple::ppc64)
299         TargetCPUName = "ppc64";
300       else if (T.getArch() == llvm::Triple::ppc64le)
301         TargetCPUName = "ppc64le";
302       else
303         TargetCPUName = "ppc";
304     }
305     return TargetCPUName;
306   }
307 
308   case llvm::Triple::bpfel:
309   case llvm::Triple::bpfeb:
310   case llvm::Triple::sparc:
311   case llvm::Triple::sparcel:
312   case llvm::Triple::sparcv9:
313     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
314       return A->getValue();
315     return "";
316 
317   case llvm::Triple::x86:
318   case llvm::Triple::x86_64:
319     return x86::getX86TargetCPU(Args, T);
320 
321   case llvm::Triple::hexagon:
322     return "hexagon" +
323            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
324 
325   case llvm::Triple::lanai:
326     return getLanaiTargetCPU(Args);
327 
328   case llvm::Triple::systemz:
329     return systemz::getSystemZTargetCPU(Args);
330 
331   case llvm::Triple::r600:
332   case llvm::Triple::amdgcn:
333     return getR600TargetGPU(Args);
334 
335   case llvm::Triple::wasm32:
336   case llvm::Triple::wasm64:
337     return std::string(getWebAssemblyTargetCPU(Args));
338   }
339 }
340 
341 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
342   unsigned Parallelism = 0;
343   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
344   if (LtoJobsArg &&
345       StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
346     D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
347                                             << LtoJobsArg->getValue();
348   return Parallelism;
349 }
350 
351 // CloudABI uses -ffunction-sections and -fdata-sections by default.
352 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
353   return Triple.getOS() == llvm::Triple::CloudABI;
354 }
355 
356 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
357                           ArgStringList &CmdArgs, const InputInfo &Output,
358                           const InputInfo &Input, bool IsThinLTO) {
359   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
360   // as gold requires -plugin to come before any -plugin-opt that -Wl might
361   // forward.
362   CmdArgs.push_back("-plugin");
363 
364 #if defined(_WIN32)
365   const char *Suffix = ".dll";
366 #elif defined(__APPLE__)
367   const char *Suffix = ".dylib";
368 #else
369   const char *Suffix = ".so";
370 #endif
371 
372   SmallString<1024> Plugin;
373   llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
374                               "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
375                               Suffix,
376                           Plugin);
377   CmdArgs.push_back(Args.MakeArgString(Plugin));
378 
379   // Try to pass driver level flags relevant to LTO code generation down to
380   // the plugin.
381 
382   // Handle flags for selecting CPU variants.
383   std::string CPU = getCPUName(Args, ToolChain.getTriple());
384   if (!CPU.empty())
385     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
386 
387   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
388     StringRef OOpt;
389     if (A->getOption().matches(options::OPT_O4) ||
390         A->getOption().matches(options::OPT_Ofast))
391       OOpt = "3";
392     else if (A->getOption().matches(options::OPT_O))
393       OOpt = A->getValue();
394     else if (A->getOption().matches(options::OPT_O0))
395       OOpt = "0";
396     if (!OOpt.empty())
397       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
398   }
399 
400   if (Args.hasArg(options::OPT_gsplit_dwarf)) {
401     CmdArgs.push_back(
402         Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
403             Output.getFilename() + "_dwo"));
404   }
405 
406   if (IsThinLTO)
407     CmdArgs.push_back("-plugin-opt=thinlto");
408 
409   if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver()))
410     CmdArgs.push_back(
411         Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
412 
413   // If an explicit debugger tuning argument appeared, pass it along.
414   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
415                                options::OPT_ggdbN_Group)) {
416     if (A->getOption().matches(options::OPT_glldb))
417       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
418     else if (A->getOption().matches(options::OPT_gsce))
419       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
420     else
421       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
422   }
423 
424   bool UseSeparateSections =
425       isUseSeparateSections(ToolChain.getEffectiveTriple());
426 
427   if (Args.hasFlag(options::OPT_ffunction_sections,
428                    options::OPT_fno_function_sections, UseSeparateSections)) {
429     CmdArgs.push_back("-plugin-opt=-function-sections");
430   }
431 
432   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
433                    UseSeparateSections)) {
434     CmdArgs.push_back("-plugin-opt=-data-sections");
435   }
436 
437   if (Arg *A = getLastProfileSampleUseArg(Args)) {
438     StringRef FName = A->getValue();
439     if (!llvm::sys::fs::exists(FName))
440       ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName;
441     else
442       CmdArgs.push_back(
443           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
444   }
445 
446   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
447                                            options::OPT_fcs_profile_generate_EQ,
448                                            options::OPT_fno_profile_generate);
449   if (CSPGOGenerateArg &&
450       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
451     CSPGOGenerateArg = nullptr;
452 
453   auto *ProfileUseArg = getLastProfileUseArg(Args);
454 
455   if (CSPGOGenerateArg) {
456     CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
457     if (CSPGOGenerateArg->getOption().matches(
458             options::OPT_fcs_profile_generate_EQ)) {
459       SmallString<128> Path(CSPGOGenerateArg->getValue());
460       llvm::sys::path::append(Path, "default_%m.profraw");
461       CmdArgs.push_back(
462           Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
463     } else
464       CmdArgs.push_back(
465           Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
466   } else if (ProfileUseArg) {
467     SmallString<128> Path(
468         ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
469     if (Path.empty() || llvm::sys::fs::is_directory(Path))
470       llvm::sys::path::append(Path, "default.profdata");
471     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
472                                          Path));
473   }
474 
475   // Need this flag to turn on new pass manager via Gold plugin.
476   if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
477                    options::OPT_fno_experimental_new_pass_manager,
478                    /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
479     CmdArgs.push_back("-plugin-opt=new-pass-manager");
480   }
481 
482   // Setup statistics file output.
483   SmallString<128> StatsFile =
484       getStatsFileName(Args, Output, Input, ToolChain.getDriver());
485   if (!StatsFile.empty())
486     CmdArgs.push_back(
487         Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
488 }
489 
490 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
491                                  ArgStringList &CmdArgs) {
492   if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
493                     options::OPT_fno_rtlib_add_rpath, false))
494     return;
495 
496   std::string CandidateRPath = TC.getArchSpecificLibPath();
497   if (TC.getVFS().exists(CandidateRPath)) {
498     CmdArgs.push_back("-rpath");
499     CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
500   }
501 }
502 
503 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
504                              const ArgList &Args, bool ForceStaticHostRuntime,
505                              bool IsOffloadingHost, bool GompNeedsRT) {
506   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
507                     options::OPT_fno_openmp, false))
508     return false;
509 
510   Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
511 
512   if (RTKind == Driver::OMPRT_Unknown)
513     // Already diagnosed.
514     return false;
515 
516   if (ForceStaticHostRuntime)
517     CmdArgs.push_back("-Bstatic");
518 
519   switch (RTKind) {
520   case Driver::OMPRT_OMP:
521     CmdArgs.push_back("-lomp");
522     break;
523   case Driver::OMPRT_GOMP:
524     CmdArgs.push_back("-lgomp");
525     break;
526   case Driver::OMPRT_IOMP5:
527     CmdArgs.push_back("-liomp5");
528     break;
529   case Driver::OMPRT_Unknown:
530     break;
531   }
532 
533   if (ForceStaticHostRuntime)
534     CmdArgs.push_back("-Bdynamic");
535 
536   if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
537       CmdArgs.push_back("-lrt");
538 
539   if (IsOffloadingHost)
540     CmdArgs.push_back("-lomptarget");
541 
542   addArchSpecificRPath(TC, Args, CmdArgs);
543 
544   return true;
545 }
546 
547 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
548                                 ArgStringList &CmdArgs, StringRef Sanitizer,
549                                 bool IsShared, bool IsWhole) {
550   // Wrap any static runtimes that must be forced into executable in
551   // whole-archive.
552   if (IsWhole) CmdArgs.push_back("--whole-archive");
553   CmdArgs.push_back(TC.getCompilerRTArgString(
554       Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
555   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
556 
557   if (IsShared) {
558     addArchSpecificRPath(TC, Args, CmdArgs);
559   }
560 }
561 
562 // Tries to use a file with the list of dynamic symbols that need to be exported
563 // from the runtime library. Returns true if the file was found.
564 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
565                                     ArgStringList &CmdArgs,
566                                     StringRef Sanitizer) {
567   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
568   // the option, so don't try to pass it.
569   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
570     return true;
571   // Myriad is static linking only.  Furthermore, some versions of its
572   // linker have the bug where --export-dynamic overrides -static, so
573   // don't use --export-dynamic on that platform.
574   if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
575     return true;
576   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
577   if (llvm::sys::fs::exists(SanRT + ".syms")) {
578     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
579     return true;
580   }
581   return false;
582 }
583 
584 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
585                                      ArgStringList &CmdArgs) {
586   // Fuchsia never needs these.  Any sanitizer runtimes with system
587   // dependencies use the `.deplibs` feature instead.
588   if (TC.getTriple().isOSFuchsia())
589     return;
590 
591   // Force linking against the system libraries sanitizers depends on
592   // (see PR15823 why this is necessary).
593   CmdArgs.push_back("--no-as-needed");
594   // There's no libpthread or librt on RTEMS & Android.
595   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
596       !TC.getTriple().isAndroid()) {
597     CmdArgs.push_back("-lpthread");
598     if (!TC.getTriple().isOSOpenBSD())
599       CmdArgs.push_back("-lrt");
600   }
601   CmdArgs.push_back("-lm");
602   // There's no libdl on all OSes.
603   if (!TC.getTriple().isOSFreeBSD() &&
604       !TC.getTriple().isOSNetBSD() &&
605       !TC.getTriple().isOSOpenBSD() &&
606        TC.getTriple().getOS() != llvm::Triple::RTEMS)
607     CmdArgs.push_back("-ldl");
608   // Required for backtrace on some OSes
609   if (TC.getTriple().isOSFreeBSD() ||
610       TC.getTriple().isOSNetBSD())
611     CmdArgs.push_back("-lexecinfo");
612 }
613 
614 static void
615 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
616                          SmallVectorImpl<StringRef> &SharedRuntimes,
617                          SmallVectorImpl<StringRef> &StaticRuntimes,
618                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
619                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
620                          SmallVectorImpl<StringRef> &RequiredSymbols) {
621   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
622   // Collect shared runtimes.
623   if (SanArgs.needsSharedRt()) {
624     if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
625       SharedRuntimes.push_back("asan");
626       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
627         HelperStaticRuntimes.push_back("asan-preinit");
628     }
629     if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
630       if (SanArgs.requiresMinimalRuntime())
631         SharedRuntimes.push_back("ubsan_minimal");
632       else
633         SharedRuntimes.push_back("ubsan_standalone");
634     }
635     if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
636       if (SanArgs.requiresMinimalRuntime())
637         SharedRuntimes.push_back("scudo_minimal");
638       else
639         SharedRuntimes.push_back("scudo");
640     }
641     if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes())
642       SharedRuntimes.push_back("hwasan");
643   }
644 
645   // The stats_client library is also statically linked into DSOs.
646   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
647     StaticRuntimes.push_back("stats_client");
648 
649   // Collect static runtimes.
650   if (Args.hasArg(options::OPT_shared)) {
651     // Don't link static runtimes into DSOs.
652     return;
653   }
654 
655   // Each static runtime that has a DSO counterpart above is excluded below,
656   // but runtimes that exist only as static are not affected by needsSharedRt.
657 
658   if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
659     StaticRuntimes.push_back("asan");
660     if (SanArgs.linkCXXRuntimes())
661       StaticRuntimes.push_back("asan_cxx");
662   }
663 
664   if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
665     StaticRuntimes.push_back("hwasan");
666     if (SanArgs.linkCXXRuntimes())
667       StaticRuntimes.push_back("hwasan_cxx");
668   }
669   if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
670     StaticRuntimes.push_back("dfsan");
671   if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
672     StaticRuntimes.push_back("lsan");
673   if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
674     StaticRuntimes.push_back("msan");
675     if (SanArgs.linkCXXRuntimes())
676       StaticRuntimes.push_back("msan_cxx");
677   }
678   if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) {
679     StaticRuntimes.push_back("tsan");
680     if (SanArgs.linkCXXRuntimes())
681       StaticRuntimes.push_back("tsan_cxx");
682   }
683   if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
684     if (SanArgs.requiresMinimalRuntime()) {
685       StaticRuntimes.push_back("ubsan_minimal");
686     } else {
687       StaticRuntimes.push_back("ubsan_standalone");
688       if (SanArgs.linkCXXRuntimes())
689         StaticRuntimes.push_back("ubsan_standalone_cxx");
690     }
691   }
692   if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
693     NonWholeStaticRuntimes.push_back("safestack");
694     RequiredSymbols.push_back("__safestack_init");
695   }
696   if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
697     if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
698       StaticRuntimes.push_back("cfi");
699     if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
700       StaticRuntimes.push_back("cfi_diag");
701       if (SanArgs.linkCXXRuntimes())
702         StaticRuntimes.push_back("ubsan_standalone_cxx");
703     }
704   }
705   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
706     NonWholeStaticRuntimes.push_back("stats");
707     RequiredSymbols.push_back("__sanitizer_stats_register");
708   }
709   if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
710     if (SanArgs.requiresMinimalRuntime()) {
711       StaticRuntimes.push_back("scudo_minimal");
712       if (SanArgs.linkCXXRuntimes())
713         StaticRuntimes.push_back("scudo_cxx_minimal");
714     } else {
715       StaticRuntimes.push_back("scudo");
716       if (SanArgs.linkCXXRuntimes())
717         StaticRuntimes.push_back("scudo_cxx");
718     }
719   }
720 }
721 
722 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
723 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
724 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
725                                  ArgStringList &CmdArgs) {
726   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
727       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
728   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
729                            NonWholeStaticRuntimes, HelperStaticRuntimes,
730                            RequiredSymbols);
731 
732   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
733   // Inject libfuzzer dependencies.
734   if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
735       !Args.hasArg(options::OPT_shared)) {
736 
737     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
738     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
739       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
740   }
741 
742   for (auto RT : SharedRuntimes)
743     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
744   for (auto RT : HelperStaticRuntimes)
745     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
746   bool AddExportDynamic = false;
747   for (auto RT : StaticRuntimes) {
748     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
749     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
750   }
751   for (auto RT : NonWholeStaticRuntimes) {
752     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
753     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
754   }
755   for (auto S : RequiredSymbols) {
756     CmdArgs.push_back("-u");
757     CmdArgs.push_back(Args.MakeArgString(S));
758   }
759   // If there is a static runtime with no dynamic list, force all the symbols
760   // to be dynamic to be sure we export sanitizer interface functions.
761   if (AddExportDynamic)
762     CmdArgs.push_back("--export-dynamic");
763 
764   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
765     CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
766 
767   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
768 }
769 
770 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
771   if (Args.hasArg(options::OPT_shared))
772     return false;
773 
774   if (TC.getXRayArgs().needsXRayRt()) {
775     CmdArgs.push_back("-whole-archive");
776     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
777     for (const auto &Mode : TC.getXRayArgs().modeList())
778       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
779     CmdArgs.push_back("-no-whole-archive");
780     return true;
781   }
782 
783   return false;
784 }
785 
786 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
787   CmdArgs.push_back("--no-as-needed");
788   CmdArgs.push_back("-lpthread");
789   if (!TC.getTriple().isOSOpenBSD())
790     CmdArgs.push_back("-lrt");
791   CmdArgs.push_back("-lm");
792 
793   if (!TC.getTriple().isOSFreeBSD() &&
794       !TC.getTriple().isOSNetBSD() &&
795       !TC.getTriple().isOSOpenBSD())
796     CmdArgs.push_back("-ldl");
797 }
798 
799 bool tools::areOptimizationsEnabled(const ArgList &Args) {
800   // Find the last -O arg and see if it is non-zero.
801   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
802     return !A->getOption().matches(options::OPT_O0);
803   // Defaults to -O0.
804   return false;
805 }
806 
807 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input,
808                                   const InputInfo &Output) {
809   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
810     if (StringRef(A->getValue()) == "single")
811       return Args.MakeArgString(Output.getFilename());
812 
813   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
814   if (FinalOutput && Args.hasArg(options::OPT_c)) {
815     SmallString<128> T(FinalOutput->getValue());
816     llvm::sys::path::replace_extension(T, "dwo");
817     return Args.MakeArgString(T);
818   } else {
819     // Use the compilation dir.
820     SmallString<128> T(
821         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
822     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
823     llvm::sys::path::replace_extension(F, "dwo");
824     T += F;
825     return Args.MakeArgString(F);
826   }
827 }
828 
829 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
830                            const JobAction &JA, const ArgList &Args,
831                            const InputInfo &Output, const char *OutFile) {
832   ArgStringList ExtractArgs;
833   ExtractArgs.push_back("--extract-dwo");
834 
835   ArgStringList StripArgs;
836   StripArgs.push_back("--strip-dwo");
837 
838   // Grabbing the output of the earlier compile step.
839   StripArgs.push_back(Output.getFilename());
840   ExtractArgs.push_back(Output.getFilename());
841   ExtractArgs.push_back(OutFile);
842 
843   const char *Exec =
844       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
845   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
846 
847   // First extract the dwo sections.
848   C.addCommand(std::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
849 
850   // Then remove them from the original .o file.
851   C.addCommand(std::make_unique<Command>(JA, T, Exec, StripArgs, II));
852 }
853 
854 // Claim options we don't want to warn if they are unused. We do this for
855 // options that build systems might add but are unused when assembling or only
856 // running the preprocessor for example.
857 void tools::claimNoWarnArgs(const ArgList &Args) {
858   // Don't warn about unused -f(no-)?lto.  This can happen when we're
859   // preprocessing, precompiling or assembling.
860   Args.ClaimAllArgs(options::OPT_flto_EQ);
861   Args.ClaimAllArgs(options::OPT_flto);
862   Args.ClaimAllArgs(options::OPT_fno_lto);
863 }
864 
865 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
866   auto *ProfileUseArg = Args.getLastArg(
867       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
868       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
869       options::OPT_fno_profile_instr_use);
870 
871   if (ProfileUseArg &&
872       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
873     ProfileUseArg = nullptr;
874 
875   return ProfileUseArg;
876 }
877 
878 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
879   auto *ProfileSampleUseArg = Args.getLastArg(
880       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
881       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
882       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
883 
884   if (ProfileSampleUseArg &&
885       (ProfileSampleUseArg->getOption().matches(
886            options::OPT_fno_profile_sample_use) ||
887        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
888     return nullptr;
889 
890   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
891                          options::OPT_fauto_profile_EQ);
892 }
893 
894 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
895 /// smooshes them together with platform defaults, to decide whether
896 /// this compile should be using PIC mode or not. Returns a tuple of
897 /// (RelocationModel, PICLevel, IsPIE).
898 std::tuple<llvm::Reloc::Model, unsigned, bool>
899 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
900   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
901   const llvm::Triple &Triple = ToolChain.getTriple();
902 
903   bool PIE = ToolChain.isPIEDefault();
904   bool PIC = PIE || ToolChain.isPICDefault();
905   // The Darwin/MachO default to use PIC does not apply when using -static.
906   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
907     PIE = PIC = false;
908   bool IsPICLevelTwo = PIC;
909 
910   bool KernelOrKext =
911       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
912 
913   // Android-specific defaults for PIC/PIE
914   if (Triple.isAndroid()) {
915     switch (Triple.getArch()) {
916     case llvm::Triple::arm:
917     case llvm::Triple::armeb:
918     case llvm::Triple::thumb:
919     case llvm::Triple::thumbeb:
920     case llvm::Triple::aarch64:
921     case llvm::Triple::mips:
922     case llvm::Triple::mipsel:
923     case llvm::Triple::mips64:
924     case llvm::Triple::mips64el:
925       PIC = true; // "-fpic"
926       break;
927 
928     case llvm::Triple::x86:
929     case llvm::Triple::x86_64:
930       PIC = true; // "-fPIC"
931       IsPICLevelTwo = true;
932       break;
933 
934     default:
935       break;
936     }
937   }
938 
939   // OpenBSD-specific defaults for PIE
940   if (Triple.isOSOpenBSD()) {
941     switch (ToolChain.getArch()) {
942     case llvm::Triple::arm:
943     case llvm::Triple::aarch64:
944     case llvm::Triple::mips64:
945     case llvm::Triple::mips64el:
946     case llvm::Triple::x86:
947     case llvm::Triple::x86_64:
948       IsPICLevelTwo = false; // "-fpie"
949       break;
950 
951     case llvm::Triple::ppc:
952     case llvm::Triple::sparc:
953     case llvm::Triple::sparcel:
954     case llvm::Triple::sparcv9:
955       IsPICLevelTwo = true; // "-fPIE"
956       break;
957 
958     default:
959       break;
960     }
961   }
962 
963   // AMDGPU-specific defaults for PIC.
964   if (Triple.getArch() == llvm::Triple::amdgcn)
965     PIC = true;
966 
967   // The last argument relating to either PIC or PIE wins, and no
968   // other argument is used. If the last argument is any flavor of the
969   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
970   // option implicitly enables PIC at the same level.
971   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
972                                     options::OPT_fpic, options::OPT_fno_pic,
973                                     options::OPT_fPIE, options::OPT_fno_PIE,
974                                     options::OPT_fpie, options::OPT_fno_pie);
975   if (Triple.isOSWindows() && LastPICArg &&
976       LastPICArg ==
977           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
978                           options::OPT_fPIE, options::OPT_fpie)) {
979     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
980         << LastPICArg->getSpelling() << Triple.str();
981     if (Triple.getArch() == llvm::Triple::x86_64)
982       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
983     return std::make_tuple(llvm::Reloc::Static, 0U, false);
984   }
985 
986   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
987   // is forced, then neither PIC nor PIE flags will have no effect.
988   if (!ToolChain.isPICDefaultForced()) {
989     if (LastPICArg) {
990       Option O = LastPICArg->getOption();
991       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
992           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
993         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
994         PIC =
995             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
996         IsPICLevelTwo =
997             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
998       } else {
999         PIE = PIC = false;
1000         if (EffectiveTriple.isPS4CPU()) {
1001           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1002           StringRef Model = ModelArg ? ModelArg->getValue() : "";
1003           if (Model != "kernel") {
1004             PIC = true;
1005             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
1006                 << LastPICArg->getSpelling();
1007           }
1008         }
1009       }
1010     }
1011   }
1012 
1013   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
1014   // PIC level would've been set to level 1, force it back to level 2 PIC
1015   // instead.
1016   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
1017     IsPICLevelTwo |= ToolChain.isPICDefault();
1018 
1019   // This kernel flags are a trump-card: they will disable PIC/PIE
1020   // generation, independent of the argument order.
1021   if (KernelOrKext &&
1022       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1023        !EffectiveTriple.isWatchOS()))
1024     PIC = PIE = false;
1025 
1026   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1027     // This is a very special mode. It trumps the other modes, almost no one
1028     // uses it, and it isn't even valid on any OS but Darwin.
1029     if (!Triple.isOSDarwin())
1030       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1031           << A->getSpelling() << Triple.str();
1032 
1033     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1034 
1035     // Only a forced PIC mode can cause the actual compile to have PIC defines
1036     // etc., no flags are sufficient. This behavior was selected to closely
1037     // match that of llvm-gcc and Apple GCC before that.
1038     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1039 
1040     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1041   }
1042 
1043   bool EmbeddedPISupported;
1044   switch (Triple.getArch()) {
1045     case llvm::Triple::arm:
1046     case llvm::Triple::armeb:
1047     case llvm::Triple::thumb:
1048     case llvm::Triple::thumbeb:
1049       EmbeddedPISupported = true;
1050       break;
1051     default:
1052       EmbeddedPISupported = false;
1053       break;
1054   }
1055 
1056   bool ROPI = false, RWPI = false;
1057   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1058   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1059     if (!EmbeddedPISupported)
1060       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1061           << LastROPIArg->getSpelling() << Triple.str();
1062     ROPI = true;
1063   }
1064   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1065   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1066     if (!EmbeddedPISupported)
1067       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1068           << LastRWPIArg->getSpelling() << Triple.str();
1069     RWPI = true;
1070   }
1071 
1072   // ROPI and RWPI are not compatible with PIC or PIE.
1073   if ((ROPI || RWPI) && (PIC || PIE))
1074     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1075 
1076   if (Triple.isMIPS()) {
1077     StringRef CPUName;
1078     StringRef ABIName;
1079     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1080     // When targeting the N64 ABI, PIC is the default, except in the case
1081     // when the -mno-abicalls option is used. In that case we exit
1082     // at next check regardless of PIC being set below.
1083     if (ABIName == "n64")
1084       PIC = true;
1085     // When targettng MIPS with -mno-abicalls, it's always static.
1086     if(Args.hasArg(options::OPT_mno_abicalls))
1087       return std::make_tuple(llvm::Reloc::Static, 0U, false);
1088     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1089     // does not use PIC level 2 for historical reasons.
1090     IsPICLevelTwo = false;
1091   }
1092 
1093   if (PIC)
1094     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1095 
1096   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1097   if (ROPI && RWPI)
1098     RelocM = llvm::Reloc::ROPI_RWPI;
1099   else if (ROPI)
1100     RelocM = llvm::Reloc::ROPI;
1101   else if (RWPI)
1102     RelocM = llvm::Reloc::RWPI;
1103 
1104   return std::make_tuple(RelocM, 0U, false);
1105 }
1106 
1107 // `-falign-functions` indicates that the functions should be aligned to a
1108 // 16-byte boundary.
1109 //
1110 // `-falign-functions=1` is the same as `-fno-align-functions`.
1111 //
1112 // The scalar `n` in `-falign-functions=n` must be an integral value between
1113 // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1114 // the nearest power-of-two.
1115 //
1116 // If we return `0`, the frontend will default to the backend's preferred
1117 // alignment.
1118 //
1119 // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1120 // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1121 // alignment.  For unaligned functions, we default to the backend's preferred
1122 // alignment.
1123 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1124                                        const ArgList &Args) {
1125   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1126                                  options::OPT_falign_functions_EQ,
1127                                  options::OPT_fno_align_functions);
1128   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1129     return 0;
1130 
1131   if (A->getOption().matches(options::OPT_falign_functions))
1132     return 0;
1133 
1134   unsigned Value = 0;
1135   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1136     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1137         << A->getAsString(Args) << A->getValue();
1138   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1139 }
1140 
1141 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1142                                          const ArgList &Args) {
1143   const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1144 
1145   if (!A)
1146     return 0;
1147 
1148   unsigned Value = 0;
1149   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1150       Value < 2)
1151     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1152         << A->getAsString(Args) << A->getValue();
1153   return Value;
1154 }
1155 
1156 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1157                              ArgStringList &CmdArgs) {
1158   llvm::Reloc::Model RelocationModel;
1159   unsigned PICLevel;
1160   bool IsPIE;
1161   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1162 
1163   if (RelocationModel != llvm::Reloc::Static)
1164     CmdArgs.push_back("-KPIC");
1165 }
1166 
1167 /// Determine whether Objective-C automated reference counting is
1168 /// enabled.
1169 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1170   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1171 }
1172 
1173 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1174 
1175 static LibGccType getLibGccType(const Driver &D, const ArgList &Args) {
1176   if (Args.hasArg(options::OPT_static_libgcc) ||
1177       Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie))
1178     return LibGccType::StaticLibGcc;
1179   if (Args.hasArg(options::OPT_shared_libgcc) || D.CCCIsCXX())
1180     return LibGccType::SharedLibGcc;
1181   return LibGccType::UnspecifiedLibGcc;
1182 }
1183 
1184 // Gcc adds libgcc arguments in various ways:
1185 //
1186 // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
1187 // g++ <none>:                       -lgcc_s               -lgcc
1188 // gcc shared:                       -lgcc_s               -lgcc
1189 // g++ shared:                       -lgcc_s               -lgcc
1190 // gcc static:     -lgcc             -lgcc_eh
1191 // g++ static:     -lgcc             -lgcc_eh
1192 // gcc static-pie: -lgcc             -lgcc_eh
1193 // g++ static-pie: -lgcc             -lgcc_eh
1194 //
1195 // Also, certain targets need additional adjustments.
1196 
1197 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1198                              ArgStringList &CmdArgs, const ArgList &Args) {
1199   ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1200   // Targets that don't use unwind libraries.
1201   if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() ||
1202       TC.getTriple().isOSBinFormatWasm() ||
1203       UNW == ToolChain::UNW_None)
1204     return;
1205 
1206   LibGccType LGT = getLibGccType(D, Args);
1207   bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1208                   !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing();
1209   if (AsNeeded)
1210     CmdArgs.push_back("--as-needed");
1211 
1212   switch (UNW) {
1213   case ToolChain::UNW_None:
1214     return;
1215   case ToolChain::UNW_Libgcc: {
1216     if (LGT == LibGccType::StaticLibGcc)
1217       CmdArgs.push_back("-lgcc_eh");
1218     else
1219       CmdArgs.push_back("-lgcc_s");
1220     break;
1221   }
1222   case ToolChain::UNW_CompilerRT:
1223     if (LGT == LibGccType::StaticLibGcc)
1224       CmdArgs.push_back("-l:libunwind.a");
1225     else
1226       CmdArgs.push_back("-l:libunwind.so");
1227     break;
1228   }
1229 
1230   if (AsNeeded)
1231     CmdArgs.push_back("--no-as-needed");
1232 }
1233 
1234 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1235                       ArgStringList &CmdArgs, const ArgList &Args) {
1236   LibGccType LGT = getLibGccType(D, Args);
1237   if (LGT != LibGccType::SharedLibGcc)
1238     CmdArgs.push_back("-lgcc");
1239   AddUnwindLibrary(TC, D, CmdArgs, Args);
1240   if (LGT == LibGccType::SharedLibGcc)
1241     CmdArgs.push_back("-lgcc");
1242 
1243   // According to Android ABI, we have to link with libdl if we are
1244   // linking with non-static libgcc.
1245   //
1246   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
1247   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1248   if (TC.getTriple().isAndroid() && LGT != LibGccType::StaticLibGcc)
1249     CmdArgs.push_back("-ldl");
1250 }
1251 
1252 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1253                            ArgStringList &CmdArgs, const ArgList &Args) {
1254   // Make use of compiler-rt if --rtlib option is used
1255   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1256 
1257   switch (RLT) {
1258   case ToolChain::RLT_CompilerRT:
1259     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1260     AddUnwindLibrary(TC, D, CmdArgs, Args);
1261     break;
1262   case ToolChain::RLT_Libgcc:
1263     // Make sure libgcc is not used under MSVC environment by default
1264     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1265       // Issue error diagnostic if libgcc is explicitly specified
1266       // through command line as --rtlib option argument.
1267       if (Args.hasArg(options::OPT_rtlib_EQ)) {
1268         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1269             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1270       }
1271     } else
1272       AddLibgcc(TC, D, CmdArgs, Args);
1273     break;
1274   }
1275 }
1276 
1277 /// Add HIP linker script arguments at the end of the argument list so that
1278 /// the fat binary is built by embedding the device images into the host. The
1279 /// linker script also defines a symbol required by the code generation so that
1280 /// the image can be retrieved at runtime. This should be used only in tool
1281 /// chains that support linker scripts.
1282 void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C,
1283                                const InputInfo &Output,
1284                                const InputInfoList &Inputs, const ArgList &Args,
1285                                ArgStringList &CmdArgs, const JobAction &JA,
1286                                const Tool &T) {
1287 
1288   // If this is not a HIP host toolchain, we don't need to do anything.
1289   if (!JA.isHostOffloading(Action::OFK_HIP))
1290     return;
1291 
1292   InputInfoList DeviceInputs;
1293   for (const auto &II : Inputs) {
1294     const Action *A = II.getAction();
1295     // Is this a device linking action?
1296     if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) {
1297       DeviceInputs.push_back(II);
1298     }
1299   }
1300 
1301   if (DeviceInputs.empty())
1302     return;
1303 
1304   // Create temporary linker script. Keep it if save-temps is enabled.
1305   const char *LKS;
1306   std::string Name =
1307       std::string(llvm::sys::path::filename(Output.getFilename()));
1308   if (C.getDriver().isSaveTempsEnabled()) {
1309     LKS = C.getArgs().MakeArgString(Name + ".lk");
1310   } else {
1311     auto TmpName = C.getDriver().GetTemporaryPath(Name, "lk");
1312     LKS = C.addTempFile(C.getArgs().MakeArgString(TmpName));
1313   }
1314 
1315   // Add linker script option to the command.
1316   CmdArgs.push_back("-T");
1317   CmdArgs.push_back(LKS);
1318 
1319   // Create a buffer to write the contents of the linker script.
1320   std::string LksBuffer;
1321   llvm::raw_string_ostream LksStream(LksBuffer);
1322 
1323   // Get the HIP offload tool chain.
1324   auto *HIPTC = static_cast<const toolchains::CudaToolChain *>(
1325       C.getSingleOffloadToolChain<Action::OFK_HIP>());
1326   assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn &&
1327          "Wrong platform");
1328   (void)HIPTC;
1329 
1330   const char *BundleFile;
1331   if (C.getDriver().isSaveTempsEnabled()) {
1332     BundleFile = C.getArgs().MakeArgString(Name + ".hipfb");
1333   } else {
1334     auto TmpName = C.getDriver().GetTemporaryPath(Name, "hipfb");
1335     BundleFile = C.addTempFile(C.getArgs().MakeArgString(TmpName));
1336   }
1337   AMDGCN::constructHIPFatbinCommand(C, JA, BundleFile, DeviceInputs, Args, T);
1338 
1339   // Add commands to embed target binaries. We ensure that each section and
1340   // image is 16-byte aligned. This is not mandatory, but increases the
1341   // likelihood of data to be aligned with a cache block in several main host
1342   // machines.
1343   LksStream << "/*\n";
1344   LksStream << "       HIP Offload Linker Script\n";
1345   LksStream << " *** Automatically generated by Clang ***\n";
1346   LksStream << "*/\n";
1347   LksStream << "TARGET(binary)\n";
1348   LksStream << "INPUT(" << BundleFile << ")\n";
1349   LksStream << "SECTIONS\n";
1350   LksStream << "{\n";
1351   LksStream << "  .hip_fatbin :\n";
1352   LksStream << "  ALIGN(0x10)\n";
1353   LksStream << "  {\n";
1354   LksStream << "    PROVIDE_HIDDEN(__hip_fatbin = .);\n";
1355   LksStream << "    " << BundleFile << "\n";
1356   LksStream << "  }\n";
1357   LksStream << "  /DISCARD/ :\n";
1358   LksStream << "  {\n";
1359   LksStream << "    * ( __CLANG_OFFLOAD_BUNDLE__* )\n";
1360   LksStream << "  }\n";
1361   LksStream << "}\n";
1362   LksStream << "INSERT BEFORE .data\n";
1363   LksStream.flush();
1364 
1365   // Dump the contents of the linker script if the user requested that. We
1366   // support this option to enable testing of behavior with -###.
1367   if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
1368     llvm::errs() << LksBuffer;
1369 
1370   // If this is a dry run, do not create the linker script file.
1371   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1372     return;
1373 
1374   // Open script file and write the contents.
1375   std::error_code EC;
1376   llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::OF_None);
1377 
1378   if (EC) {
1379     C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1380     return;
1381   }
1382 
1383   Lksf << LksBuffer;
1384 }
1385 
1386 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1387                                          const InputInfo &Output,
1388                                          const InputInfo &Input,
1389                                          const Driver &D) {
1390   const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1391   if (!A)
1392     return {};
1393 
1394   StringRef SaveStats = A->getValue();
1395   SmallString<128> StatsFile;
1396   if (SaveStats == "obj" && Output.isFilename()) {
1397     StatsFile.assign(Output.getFilename());
1398     llvm::sys::path::remove_filename(StatsFile);
1399   } else if (SaveStats != "cwd") {
1400     D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1401     return {};
1402   }
1403 
1404   StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1405   llvm::sys::path::append(StatsFile, BaseName);
1406   llvm::sys::path::replace_extension(StatsFile, "stats");
1407   return StatsFile;
1408 }
1409 
1410 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1411                             Multilib::flags_list &Flags) {
1412   Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1413 }
1414