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