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