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