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