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