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