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