xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CommonArgs.h"
10 #include "Arch/AArch64.h"
11 #include "Arch/ARM.h"
12 #include "Arch/CSKY.h"
13 #include "Arch/LoongArch.h"
14 #include "Arch/M68k.h"
15 #include "Arch/Mips.h"
16 #include "Arch/PPC.h"
17 #include "Arch/RISCV.h"
18 #include "Arch/Sparc.h"
19 #include "Arch/SystemZ.h"
20 #include "Arch/VE.h"
21 #include "Arch/X86.h"
22 #include "HIPAMD.h"
23 #include "Hexagon.h"
24 #include "MSP430.h"
25 #include "Solaris.h"
26 #include "clang/Basic/CharInfo.h"
27 #include "clang/Basic/CodeGenOptions.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/ObjCRuntime.h"
30 #include "clang/Basic/Version.h"
31 #include "clang/Config/config.h"
32 #include "clang/Driver/Action.h"
33 #include "clang/Driver/Compilation.h"
34 #include "clang/Driver/Driver.h"
35 #include "clang/Driver/DriverDiagnostic.h"
36 #include "clang/Driver/InputInfo.h"
37 #include "clang/Driver/Job.h"
38 #include "clang/Driver/Options.h"
39 #include "clang/Driver/SanitizerArgs.h"
40 #include "clang/Driver/ToolChain.h"
41 #include "clang/Driver/Util.h"
42 #include "clang/Driver/XRayArgs.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/StringSwitch.h"
48 #include "llvm/ADT/Twine.h"
49 #include "llvm/BinaryFormat/Magic.h"
50 #include "llvm/Config/llvm-config.h"
51 #include "llvm/Option/Arg.h"
52 #include "llvm/Option/ArgList.h"
53 #include "llvm/Option/Option.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Compression.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/FileSystem.h"
59 #include "llvm/Support/Path.h"
60 #include "llvm/Support/Process.h"
61 #include "llvm/Support/Program.h"
62 #include "llvm/Support/ScopedPrinter.h"
63 #include "llvm/Support/Threading.h"
64 #include "llvm/Support/VirtualFileSystem.h"
65 #include "llvm/Support/YAMLParser.h"
66 #include "llvm/TargetParser/Host.h"
67 #include "llvm/TargetParser/TargetParser.h"
68 #include <optional>
69 
70 using namespace clang::driver;
71 using namespace clang::driver::tools;
72 using namespace clang;
73 using namespace llvm::opt;
74 
useFramePointerForTargetByDefault(const llvm::opt::ArgList & Args,const llvm::Triple & Triple)75 static bool useFramePointerForTargetByDefault(const llvm::opt::ArgList &Args,
76                                               const llvm::Triple &Triple) {
77   if (Args.hasArg(clang::driver::options::OPT_pg) &&
78       !Args.hasArg(clang::driver::options::OPT_mfentry))
79     return true;
80 
81   if (Triple.isAndroid())
82     return true;
83 
84   switch (Triple.getArch()) {
85   case llvm::Triple::xcore:
86   case llvm::Triple::wasm32:
87   case llvm::Triple::wasm64:
88   case llvm::Triple::msp430:
89     // XCore never wants frame pointers, regardless of OS.
90     // WebAssembly never wants frame pointers.
91     return false;
92   case llvm::Triple::ppc:
93   case llvm::Triple::ppcle:
94   case llvm::Triple::ppc64:
95   case llvm::Triple::ppc64le:
96   case llvm::Triple::riscv32:
97   case llvm::Triple::riscv64:
98   case llvm::Triple::sparc:
99   case llvm::Triple::sparcel:
100   case llvm::Triple::sparcv9:
101   case llvm::Triple::amdgcn:
102   case llvm::Triple::r600:
103   case llvm::Triple::csky:
104   case llvm::Triple::loongarch32:
105   case llvm::Triple::loongarch64:
106   case llvm::Triple::m68k:
107     return !clang::driver::tools::areOptimizationsEnabled(Args);
108   default:
109     break;
110   }
111 
112   if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
113     return !clang::driver::tools::areOptimizationsEnabled(Args);
114   }
115 
116   if (Triple.isOSLinux() || Triple.isOSHurd()) {
117     switch (Triple.getArch()) {
118     // Don't use a frame pointer on linux if optimizing for certain targets.
119     case llvm::Triple::arm:
120     case llvm::Triple::armeb:
121     case llvm::Triple::thumb:
122     case llvm::Triple::thumbeb:
123     case llvm::Triple::mips64:
124     case llvm::Triple::mips64el:
125     case llvm::Triple::mips:
126     case llvm::Triple::mipsel:
127     case llvm::Triple::systemz:
128     case llvm::Triple::x86:
129     case llvm::Triple::x86_64:
130       return !clang::driver::tools::areOptimizationsEnabled(Args);
131     default:
132       return true;
133     }
134   }
135 
136   if (Triple.isOSWindows()) {
137     switch (Triple.getArch()) {
138     case llvm::Triple::x86:
139       return !clang::driver::tools::areOptimizationsEnabled(Args);
140     case llvm::Triple::x86_64:
141       return Triple.isOSBinFormatMachO();
142     case llvm::Triple::arm:
143     case llvm::Triple::thumb:
144       // Windows on ARM builds with FPO disabled to aid fast stack walking
145       return true;
146     default:
147       // All other supported Windows ISAs use xdata unwind information, so frame
148       // pointers are not generally useful.
149       return false;
150     }
151   }
152 
153   return true;
154 }
155 
useLeafFramePointerForTargetByDefault(const llvm::Triple & Triple)156 static bool useLeafFramePointerForTargetByDefault(const llvm::Triple &Triple) {
157   if (Triple.isAArch64() || Triple.isPS() || Triple.isVE() ||
158       (Triple.isAndroid() && !Triple.isARM()))
159     return false;
160 
161   return true;
162 }
163 
mustUseNonLeafFramePointerForTarget(const llvm::Triple & Triple)164 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
165   switch (Triple.getArch()) {
166   default:
167     return false;
168   case llvm::Triple::arm:
169   case llvm::Triple::thumb:
170     // ARM Darwin targets require a frame pointer to be always present to aid
171     // offline debugging via backtraces.
172     return Triple.isOSDarwin();
173   }
174 }
175 
176 // True if a target-specific option requires the frame chain to be preserved,
177 // even if new frame records are not created.
mustMaintainValidFrameChain(const llvm::opt::ArgList & Args,const llvm::Triple & Triple)178 static bool mustMaintainValidFrameChain(const llvm::opt::ArgList &Args,
179                                         const llvm::Triple &Triple) {
180   if (Triple.isARM() || Triple.isThumb()) {
181     // For 32-bit Arm, the -mframe-chain=aapcs and -mframe-chain=aapcs+leaf
182     // options require the frame pointer register to be reserved (or point to a
183     // new AAPCS-compilant frame record), even with	-fno-omit-frame-pointer.
184     if (Arg *A = Args.getLastArg(options::OPT_mframe_chain)) {
185       StringRef V = A->getValue();
186       return V != "none";
187     }
188     return false;
189   }
190   return false;
191 }
192 
193 // True if a target-specific option causes -fno-omit-frame-pointer to also
194 // cause frame records to be created in leaf functions.
framePointerImpliesLeafFramePointer(const llvm::opt::ArgList & Args,const llvm::Triple & Triple)195 static bool framePointerImpliesLeafFramePointer(const llvm::opt::ArgList &Args,
196                                                 const llvm::Triple &Triple) {
197   if (Triple.isARM() || Triple.isThumb()) {
198     // For 32-bit Arm, the -mframe-chain=aapcs+leaf option causes the
199     // -fno-omit-frame-pointer optiion to imply -mno-omit-leaf-frame-pointer,
200     // but does not by itself imply either option.
201     if (Arg *A = Args.getLastArg(options::OPT_mframe_chain)) {
202       StringRef V = A->getValue();
203       return V == "aapcs+leaf";
204     }
205     return false;
206   }
207   return false;
208 }
209 
210 clang::CodeGenOptions::FramePointerKind
getFramePointerKind(const llvm::opt::ArgList & Args,const llvm::Triple & Triple)211 getFramePointerKind(const llvm::opt::ArgList &Args,
212                     const llvm::Triple &Triple) {
213   // There are three things to consider here:
214   // * Should a frame record be created for non-leaf functions?
215   // * Should a frame record be created for leaf functions?
216   // * Is the frame pointer register reserved, i.e. must it always point to
217   //   either a new, valid frame record or be un-modified?
218   //
219   //  Not all combinations of these are valid:
220   //  * It's not useful to have leaf frame records without non-leaf ones.
221   //  * It's not useful to have frame records without reserving the frame
222   //    pointer.
223   //
224   // | Non-leaf | Leaf | Reserved |
225   // | N        | N    | N        | FramePointerKind::None
226   // | N        | N    | Y        | FramePointerKind::Reserved
227   // | N        | Y    | N        | Invalid
228   // | N        | Y    | Y        | Invalid
229   // | Y        | N    | N        | Invalid
230   // | Y        | N    | Y        | FramePointerKind::NonLeaf
231   // | Y        | Y    | N        | Invalid
232   // | Y        | Y    | Y        | FramePointerKind::All
233   //
234   // The FramePointerKind::Reserved case is currently only reachable for Arm,
235   // which has the -mframe-chain= option which can (in combination with
236   // -fno-omit-frame-pointer) specify that the frame chain must be valid,
237   // without requiring new frame records to be created.
238 
239   bool DefaultFP = useFramePointerForTargetByDefault(Args, Triple);
240   bool EnableFP =
241       mustUseNonLeafFramePointerForTarget(Triple) ||
242       Args.hasFlag(clang::driver::options::OPT_fno_omit_frame_pointer,
243                    clang::driver::options::OPT_fomit_frame_pointer, DefaultFP);
244 
245   bool DefaultLeafFP =
246       useLeafFramePointerForTargetByDefault(Triple) ||
247       (EnableFP && framePointerImpliesLeafFramePointer(Args, Triple));
248   bool EnableLeafFP = Args.hasFlag(
249       clang::driver::options::OPT_mno_omit_leaf_frame_pointer,
250       clang::driver::options::OPT_momit_leaf_frame_pointer, DefaultLeafFP);
251 
252   bool FPRegReserved = EnableFP || mustMaintainValidFrameChain(Args, Triple);
253 
254   if (EnableFP) {
255     if (EnableLeafFP)
256       return clang::CodeGenOptions::FramePointerKind::All;
257     return clang::CodeGenOptions::FramePointerKind::NonLeaf;
258   }
259   if (FPRegReserved)
260     return clang::CodeGenOptions::FramePointerKind::Reserved;
261   return clang::CodeGenOptions::FramePointerKind::None;
262 }
263 
renderRpassOptions(const ArgList & Args,ArgStringList & CmdArgs,const StringRef PluginOptPrefix)264 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs,
265                                const StringRef PluginOptPrefix) {
266   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
267     CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
268                                          "-pass-remarks=" + A->getValue()));
269 
270   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
271     CmdArgs.push_back(Args.MakeArgString(
272         Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue()));
273 
274   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
275     CmdArgs.push_back(Args.MakeArgString(
276         Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue()));
277 }
278 
renderRemarksOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input,const InputInfo & Output,const StringRef PluginOptPrefix)279 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
280                                  const llvm::Triple &Triple,
281                                  const InputInfo &Input,
282                                  const InputInfo &Output,
283                                  const StringRef PluginOptPrefix) {
284   StringRef Format = "yaml";
285   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
286     Format = A->getValue();
287 
288   SmallString<128> F;
289   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
290   if (A)
291     F = A->getValue();
292   else if (Output.isFilename())
293     F = Output.getFilename();
294 
295   assert(!F.empty() && "Cannot determine remarks output name.");
296   // Append "opt.ld.<format>" to the end of the file name.
297   CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
298                                        "opt-remarks-filename=" + F +
299                                        ".opt.ld." + Format));
300 
301   if (const Arg *A =
302           Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
303     CmdArgs.push_back(Args.MakeArgString(
304         Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue()));
305 
306   CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
307                                        "opt-remarks-format=" + Format.data()));
308 }
309 
renderRemarksHotnessOptions(const ArgList & Args,ArgStringList & CmdArgs,const StringRef PluginOptPrefix)310 static void renderRemarksHotnessOptions(const ArgList &Args,
311                                         ArgStringList &CmdArgs,
312                                         const StringRef PluginOptPrefix) {
313   if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
314                    options::OPT_fno_diagnostics_show_hotness, false))
315     CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
316                                          "opt-remarks-with-hotness"));
317 
318   if (const Arg *A =
319           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
320     CmdArgs.push_back(
321         Args.MakeArgString(Twine(PluginOptPrefix) +
322                            "opt-remarks-hotness-threshold=" + A->getValue()));
323 }
324 
shouldIgnoreUnsupportedTargetFeature(const Arg & TargetFeatureArg,llvm::Triple T,StringRef Processor)325 static bool shouldIgnoreUnsupportedTargetFeature(const Arg &TargetFeatureArg,
326                                                  llvm::Triple T,
327                                                  StringRef Processor) {
328   // Warn no-cumode for AMDGCN processors not supporing WGP mode.
329   if (!T.isAMDGPU())
330     return false;
331   auto GPUKind = T.isAMDGCN() ? llvm::AMDGPU::parseArchAMDGCN(Processor)
332                               : llvm::AMDGPU::parseArchR600(Processor);
333   auto GPUFeatures = T.isAMDGCN() ? llvm::AMDGPU::getArchAttrAMDGCN(GPUKind)
334                                   : llvm::AMDGPU::getArchAttrR600(GPUKind);
335   if (GPUFeatures & llvm::AMDGPU::FEATURE_WGP)
336     return false;
337   return TargetFeatureArg.getOption().matches(options::OPT_mno_cumode);
338 }
339 
addPathIfExists(const Driver & D,const Twine & Path,ToolChain::path_list & Paths)340 void tools::addPathIfExists(const Driver &D, const Twine &Path,
341                             ToolChain::path_list &Paths) {
342   if (D.getVFS().exists(Path))
343     Paths.push_back(Path.str());
344 }
345 
handleTargetFeaturesGroup(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<StringRef> & Features,OptSpecifier Group)346 void tools::handleTargetFeaturesGroup(const Driver &D,
347                                       const llvm::Triple &Triple,
348                                       const ArgList &Args,
349                                       std::vector<StringRef> &Features,
350                                       OptSpecifier Group) {
351   std::set<StringRef> Warned;
352   for (const Arg *A : Args.filtered(Group)) {
353     StringRef Name = A->getOption().getName();
354     A->claim();
355 
356     // Skip over "-m".
357     assert(Name.starts_with("m") && "Invalid feature name.");
358     Name = Name.substr(1);
359 
360     auto Proc = getCPUName(D, Args, Triple);
361     if (shouldIgnoreUnsupportedTargetFeature(*A, Triple, Proc)) {
362       if (Warned.count(Name) == 0) {
363         D.getDiags().Report(
364             clang::diag::warn_drv_unsupported_option_for_processor)
365             << A->getAsString(Args) << Proc;
366         Warned.insert(Name);
367       }
368       continue;
369     }
370 
371     bool IsNegative = Name.consume_front("no-");
372 
373     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
374   }
375 }
376 
377 SmallVector<StringRef>
unifyTargetFeatures(ArrayRef<StringRef> Features)378 tools::unifyTargetFeatures(ArrayRef<StringRef> Features) {
379   // Only add a feature if it hasn't been seen before starting from the end.
380   SmallVector<StringRef> UnifiedFeatures;
381   llvm::DenseSet<StringRef> UsedFeatures;
382   for (StringRef Feature : llvm::reverse(Features)) {
383     if (UsedFeatures.insert(Feature.drop_front()).second)
384       UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature);
385   }
386 
387   return UnifiedFeatures;
388 }
389 
addDirectoryList(const ArgList & Args,ArgStringList & CmdArgs,const char * ArgName,const char * EnvVar)390 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
391                              const char *ArgName, const char *EnvVar) {
392   const char *DirList = ::getenv(EnvVar);
393   bool CombinedArg = false;
394 
395   if (!DirList)
396     return; // Nothing to do.
397 
398   StringRef Name(ArgName);
399   if (Name == "-I" || Name == "-L" || Name.empty())
400     CombinedArg = true;
401 
402   StringRef Dirs(DirList);
403   if (Dirs.empty()) // Empty string should not add '.'.
404     return;
405 
406   StringRef::size_type Delim;
407   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
408     if (Delim == 0) { // Leading colon.
409       if (CombinedArg) {
410         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
411       } else {
412         CmdArgs.push_back(ArgName);
413         CmdArgs.push_back(".");
414       }
415     } else {
416       if (CombinedArg) {
417         CmdArgs.push_back(
418             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
419       } else {
420         CmdArgs.push_back(ArgName);
421         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
422       }
423     }
424     Dirs = Dirs.substr(Delim + 1);
425   }
426 
427   if (Dirs.empty()) { // Trailing colon.
428     if (CombinedArg) {
429       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
430     } else {
431       CmdArgs.push_back(ArgName);
432       CmdArgs.push_back(".");
433     }
434   } else { // Add the last path.
435     if (CombinedArg) {
436       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
437     } else {
438       CmdArgs.push_back(ArgName);
439       CmdArgs.push_back(Args.MakeArgString(Dirs));
440     }
441   }
442 }
443 
AddLinkerInputs(const ToolChain & TC,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)444 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
445                             const ArgList &Args, ArgStringList &CmdArgs,
446                             const JobAction &JA) {
447   const Driver &D = TC.getDriver();
448 
449   // Add extra linker input arguments which are not treated as inputs
450   // (constructed via -Xarch_).
451   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
452 
453   // LIBRARY_PATH are included before user inputs and only supported on native
454   // toolchains.
455   if (!TC.isCrossCompiling())
456     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
457 
458   for (const auto &II : Inputs) {
459     // If the current tool chain refers to an OpenMP offloading host, we
460     // should ignore inputs that refer to OpenMP offloading devices -
461     // they will be embedded according to a proper linker script.
462     if (auto *IA = II.getAction())
463       if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
464            IA->isDeviceOffloading(Action::OFK_OpenMP)))
465         continue;
466 
467     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
468       // Don't try to pass LLVM inputs unless we have native support.
469       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
470 
471     // Add filenames immediately.
472     if (II.isFilename()) {
473       CmdArgs.push_back(II.getFilename());
474       continue;
475     }
476 
477     // In some error cases, the input could be Nothing; skip those.
478     if (II.isNothing())
479       continue;
480 
481     // Otherwise, this is a linker input argument.
482     const Arg &A = II.getInputArg();
483 
484     // Handle reserved library options.
485     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
486       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
487     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
488       TC.AddCCKextLibArgs(Args, CmdArgs);
489     else
490       A.renderAsInput(Args, CmdArgs);
491   }
492 }
493 
addLinkerCompressDebugSectionsOption(const ToolChain & TC,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs)494 void tools::addLinkerCompressDebugSectionsOption(
495     const ToolChain &TC, const llvm::opt::ArgList &Args,
496     llvm::opt::ArgStringList &CmdArgs) {
497   // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
498   // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
499   // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
500   // is not translated since ld --compress-debug-sections option requires an
501   // argument.
502   if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
503     StringRef V = A->getValue();
504     if (V == "none" || V == "zlib" || V == "zstd")
505       CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
506     else
507       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
508           << A->getSpelling() << V;
509   }
510 }
511 
AddTargetFeature(const ArgList & Args,std::vector<StringRef> & Features,OptSpecifier OnOpt,OptSpecifier OffOpt,StringRef FeatureName)512 void tools::AddTargetFeature(const ArgList &Args,
513                              std::vector<StringRef> &Features,
514                              OptSpecifier OnOpt, OptSpecifier OffOpt,
515                              StringRef FeatureName) {
516   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
517     if (A->getOption().matches(OnOpt))
518       Features.push_back(Args.MakeArgString("+" + FeatureName));
519     else
520       Features.push_back(Args.MakeArgString("-" + FeatureName));
521   }
522 }
523 
524 /// Get the (LLVM) name of the AMDGPU gpu we are targeting.
getAMDGPUTargetGPU(const llvm::Triple & T,const ArgList & Args)525 static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
526                                       const ArgList &Args) {
527   Arg *MArch = Args.getLastArg(options::OPT_march_EQ);
528   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
529     auto GPUName = getProcessorFromTargetID(T, A->getValue());
530     return llvm::StringSwitch<std::string>(GPUName)
531         .Cases("rv630", "rv635", "r600")
532         .Cases("rv610", "rv620", "rs780", "rs880")
533         .Case("rv740", "rv770")
534         .Case("palm", "cedar")
535         .Cases("sumo", "sumo2", "sumo")
536         .Case("hemlock", "cypress")
537         .Case("aruba", "cayman")
538         .Default(GPUName.str());
539   }
540   if (MArch)
541     return getProcessorFromTargetID(T, MArch->getValue()).str();
542   return "";
543 }
544 
getLanaiTargetCPU(const ArgList & Args)545 static std::string getLanaiTargetCPU(const ArgList &Args) {
546   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
547     return A->getValue();
548   }
549   return "";
550 }
551 
552 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
getWebAssemblyTargetCPU(const ArgList & Args)553 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
554   // If we have -mcpu=, use that.
555   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
556     StringRef CPU = A->getValue();
557 
558 #ifdef __wasm__
559     // Handle "native" by examining the host. "native" isn't meaningful when
560     // cross compiling, so only support this when the host is also WebAssembly.
561     if (CPU == "native")
562       return llvm::sys::getHostCPUName();
563 #endif
564 
565     return CPU;
566   }
567 
568   return "generic";
569 }
570 
getCPUName(const Driver & D,const ArgList & Args,const llvm::Triple & T,bool FromAs)571 std::string tools::getCPUName(const Driver &D, const ArgList &Args,
572                               const llvm::Triple &T, bool FromAs) {
573   Arg *A;
574 
575   switch (T.getArch()) {
576   default:
577     return "";
578 
579   case llvm::Triple::aarch64:
580   case llvm::Triple::aarch64_32:
581   case llvm::Triple::aarch64_be:
582     return aarch64::getAArch64TargetCPU(Args, T, A);
583 
584   case llvm::Triple::arm:
585   case llvm::Triple::armeb:
586   case llvm::Triple::thumb:
587   case llvm::Triple::thumbeb: {
588     StringRef MArch, MCPU;
589     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
590     return arm::getARMTargetCPU(MCPU, MArch, T);
591   }
592 
593   case llvm::Triple::avr:
594     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
595       return A->getValue();
596     return "";
597 
598   case llvm::Triple::m68k:
599     return m68k::getM68kTargetCPU(Args);
600 
601   case llvm::Triple::mips:
602   case llvm::Triple::mipsel:
603   case llvm::Triple::mips64:
604   case llvm::Triple::mips64el: {
605     StringRef CPUName;
606     StringRef ABIName;
607     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
608     return std::string(CPUName);
609   }
610 
611   case llvm::Triple::nvptx:
612   case llvm::Triple::nvptx64:
613     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
614       return A->getValue();
615     return "";
616 
617   case llvm::Triple::ppc:
618   case llvm::Triple::ppcle:
619   case llvm::Triple::ppc64:
620   case llvm::Triple::ppc64le:
621     return ppc::getPPCTargetCPU(D, Args, T);
622 
623   case llvm::Triple::csky:
624     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
625       return A->getValue();
626     else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
627       return A->getValue();
628     else
629       return "ck810";
630   case llvm::Triple::riscv32:
631   case llvm::Triple::riscv64:
632     return riscv::getRISCVTargetCPU(Args, T);
633 
634   case llvm::Triple::bpfel:
635   case llvm::Triple::bpfeb:
636     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
637       return A->getValue();
638     return "";
639 
640   case llvm::Triple::sparc:
641   case llvm::Triple::sparcel:
642   case llvm::Triple::sparcv9:
643     return sparc::getSparcTargetCPU(D, Args, T);
644 
645   case llvm::Triple::x86:
646   case llvm::Triple::x86_64:
647     return x86::getX86TargetCPU(D, Args, T);
648 
649   case llvm::Triple::hexagon:
650     return "hexagon" +
651            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
652 
653   case llvm::Triple::lanai:
654     return getLanaiTargetCPU(Args);
655 
656   case llvm::Triple::systemz:
657     return systemz::getSystemZTargetCPU(Args);
658 
659   case llvm::Triple::r600:
660   case llvm::Triple::amdgcn:
661     return getAMDGPUTargetGPU(T, Args);
662 
663   case llvm::Triple::wasm32:
664   case llvm::Triple::wasm64:
665     return std::string(getWebAssemblyTargetCPU(Args));
666 
667   case llvm::Triple::loongarch32:
668   case llvm::Triple::loongarch64:
669     return loongarch::getLoongArchTargetCPU(Args, T);
670   }
671 }
672 
getWebAssemblyTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<StringRef> & Features)673 static void getWebAssemblyTargetFeatures(const Driver &D,
674                                          const llvm::Triple &Triple,
675                                          const ArgList &Args,
676                                          std::vector<StringRef> &Features) {
677   handleTargetFeaturesGroup(D, Triple, Args, Features,
678                             options::OPT_m_wasm_Features_Group);
679 }
680 
getTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool ForAS,bool IsAux)681 void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
682                               const ArgList &Args, ArgStringList &CmdArgs,
683                               bool ForAS, bool IsAux) {
684   std::vector<StringRef> Features;
685   switch (Triple.getArch()) {
686   default:
687     break;
688   case llvm::Triple::mips:
689   case llvm::Triple::mipsel:
690   case llvm::Triple::mips64:
691   case llvm::Triple::mips64el:
692     mips::getMIPSTargetFeatures(D, Triple, Args, Features);
693     break;
694   case llvm::Triple::arm:
695   case llvm::Triple::armeb:
696   case llvm::Triple::thumb:
697   case llvm::Triple::thumbeb:
698     arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS);
699     break;
700   case llvm::Triple::ppc:
701   case llvm::Triple::ppcle:
702   case llvm::Triple::ppc64:
703   case llvm::Triple::ppc64le:
704     ppc::getPPCTargetFeatures(D, Triple, Args, Features);
705     break;
706   case llvm::Triple::riscv32:
707   case llvm::Triple::riscv64:
708     riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
709     break;
710   case llvm::Triple::systemz:
711     systemz::getSystemZTargetFeatures(D, Args, Features);
712     break;
713   case llvm::Triple::aarch64:
714   case llvm::Triple::aarch64_32:
715   case llvm::Triple::aarch64_be:
716     aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS);
717     break;
718   case llvm::Triple::x86:
719   case llvm::Triple::x86_64:
720     x86::getX86TargetFeatures(D, Triple, Args, Features);
721     break;
722   case llvm::Triple::hexagon:
723     hexagon::getHexagonTargetFeatures(D, Triple, Args, Features);
724     break;
725   case llvm::Triple::wasm32:
726   case llvm::Triple::wasm64:
727     getWebAssemblyTargetFeatures(D, Triple, Args, Features);
728     break;
729   case llvm::Triple::sparc:
730   case llvm::Triple::sparcel:
731   case llvm::Triple::sparcv9:
732     sparc::getSparcTargetFeatures(D, Args, Features);
733     break;
734   case llvm::Triple::r600:
735   case llvm::Triple::amdgcn:
736     amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
737     break;
738   case llvm::Triple::nvptx:
739   case llvm::Triple::nvptx64:
740     NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features);
741     break;
742   case llvm::Triple::m68k:
743     m68k::getM68kTargetFeatures(D, Triple, Args, Features);
744     break;
745   case llvm::Triple::msp430:
746     msp430::getMSP430TargetFeatures(D, Args, Features);
747     break;
748   case llvm::Triple::ve:
749     ve::getVETargetFeatures(D, Args, Features);
750     break;
751   case llvm::Triple::csky:
752     csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features);
753     break;
754   case llvm::Triple::loongarch32:
755   case llvm::Triple::loongarch64:
756     loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features);
757     break;
758   }
759 
760   for (auto Feature : unifyTargetFeatures(Features)) {
761     CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature");
762     CmdArgs.push_back(Feature.data());
763   }
764 }
765 
getLTOParallelism(const ArgList & Args,const Driver & D)766 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
767   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
768   if (!LtoJobsArg)
769     return {};
770   if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
771     D.Diag(diag::err_drv_invalid_int_value)
772         << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
773   return LtoJobsArg->getValue();
774 }
775 
776 // PS4/PS5 uses -ffunction-sections and -fdata-sections by default.
isUseSeparateSections(const llvm::Triple & Triple)777 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
778   return Triple.isPS();
779 }
780 
isTLSDESCEnabled(const ToolChain & TC,const llvm::opt::ArgList & Args)781 bool tools::isTLSDESCEnabled(const ToolChain &TC,
782                              const llvm::opt::ArgList &Args) {
783   const llvm::Triple &Triple = TC.getEffectiveTriple();
784   Arg *A = Args.getLastArg(options::OPT_mtls_dialect_EQ);
785   if (!A)
786     return Triple.hasDefaultTLSDESC();
787   StringRef V = A->getValue();
788   bool SupportedArgument = false, EnableTLSDESC = false;
789   bool Unsupported = !Triple.isOSBinFormatELF();
790   if (Triple.isLoongArch() || Triple.isRISCV()) {
791     SupportedArgument = V == "desc" || V == "trad";
792     EnableTLSDESC = V == "desc";
793   } else if (Triple.isX86()) {
794     SupportedArgument = V == "gnu" || V == "gnu2";
795     EnableTLSDESC = V == "gnu2";
796   } else {
797     Unsupported = true;
798   }
799   if (Unsupported) {
800     TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
801         << A->getSpelling() << Triple.getTriple();
802   } else if (!SupportedArgument) {
803     TC.getDriver().Diag(diag::err_drv_unsupported_option_argument_for_target)
804         << A->getSpelling() << V << Triple.getTriple();
805   }
806   return EnableTLSDESC;
807 }
808 
addLTOOptions(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfo & Input,bool IsThinLTO)809 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
810                           ArgStringList &CmdArgs, const InputInfo &Output,
811                           const InputInfo &Input, bool IsThinLTO) {
812   const llvm::Triple &Triple = ToolChain.getTriple();
813   const bool IsOSAIX = Triple.isOSAIX();
814   const bool IsAMDGCN = Triple.isAMDGCN();
815   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
816   const Driver &D = ToolChain.getDriver();
817   const bool IsFatLTO = Args.hasArg(options::OPT_ffat_lto_objects);
818   const bool IsUnifiedLTO = Args.hasArg(options::OPT_funified_lto);
819   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
820       llvm::sys::path::stem(Linker) != "ld.lld" && !Triple.isOSOpenBSD()) {
821     // Tell the linker to load the plugin. This has to come before
822     // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to
823     // come before any -plugin-opt/-bplugin_opt that -Wl might forward.
824     const char *PluginPrefix = IsOSAIX ? "-bplugin:" : "";
825     const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold";
826 
827     if (!IsOSAIX)
828       CmdArgs.push_back("-plugin");
829 
830 #if defined(_WIN32)
831     const char *Suffix = ".dll";
832 #elif defined(__APPLE__)
833     const char *Suffix = ".dylib";
834 #else
835     const char *Suffix = ".so";
836 #endif
837 
838     SmallString<1024> Plugin;
839     llvm::sys::path::native(Twine(D.Dir) +
840                                 "/../" CLANG_INSTALL_LIBDIR_BASENAME +
841                                 PluginName + Suffix,
842                             Plugin);
843     CmdArgs.push_back(Args.MakeArgString(Twine(PluginPrefix) + Plugin));
844   } else {
845     // Tell LLD to find and use .llvm.lto section in regular relocatable object
846     // files
847     if (IsFatLTO)
848       CmdArgs.push_back("--fat-lto-objects");
849   }
850 
851   const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt=";
852   const char *ExtraDash = IsOSAIX ? "-" : "";
853   const char *ParallelismOpt = IsOSAIX ? "-threads=" : "jobs=";
854 
855   // Note, this solution is far from perfect, better to encode it into IR
856   // metadata, but this may not be worth it, since it looks like aranges is on
857   // the way out.
858   if (Args.hasArg(options::OPT_gdwarf_aranges)) {
859     CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
860                                          "-generate-arange-section"));
861   }
862 
863   // Pass vector library arguments to LTO.
864   Arg *ArgVecLib = Args.getLastArg(options::OPT_fveclib);
865   if (ArgVecLib && ArgVecLib->getNumValues() == 1) {
866     // Map the vector library names from clang front-end to opt front-end. The
867     // values are taken from the TargetLibraryInfo class command line options.
868     std::optional<StringRef> OptVal =
869         llvm::StringSwitch<std::optional<StringRef>>(ArgVecLib->getValue())
870             .Case("Accelerate", "Accelerate")
871             .Case("LIBMVEC", "LIBMVEC-X86")
872             .Case("MASSV", "MASSV")
873             .Case("SVML", "SVML")
874             .Case("SLEEF", "sleefgnuabi")
875             .Case("Darwin_libsystem_m", "Darwin_libsystem_m")
876             .Case("ArmPL", "ArmPL")
877             .Case("none", "none")
878             .Default(std::nullopt);
879 
880     if (OptVal)
881       CmdArgs.push_back(Args.MakeArgString(
882           Twine(PluginOptPrefix) + "-vector-library=" + OptVal.value()));
883   }
884 
885   // Try to pass driver level flags relevant to LTO code generation down to
886   // the plugin.
887 
888   // Handle flags for selecting CPU variants.
889   std::string CPU = getCPUName(D, Args, Triple);
890   if (!CPU.empty())
891     CmdArgs.push_back(
892         Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU));
893 
894   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
895     // The optimization level matches
896     // CompilerInvocation.cpp:getOptimizationLevel().
897     StringRef OOpt;
898     if (A->getOption().matches(options::OPT_O4) ||
899         A->getOption().matches(options::OPT_Ofast))
900       OOpt = "3";
901     else if (A->getOption().matches(options::OPT_O)) {
902       OOpt = A->getValue();
903       if (OOpt == "g")
904         OOpt = "1";
905       else if (OOpt == "s" || OOpt == "z")
906         OOpt = "2";
907     } else if (A->getOption().matches(options::OPT_O0))
908       OOpt = "0";
909     if (!OOpt.empty()) {
910       CmdArgs.push_back(
911           Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt));
912       if (IsAMDGCN)
913         CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt));
914     }
915   }
916 
917   if (Args.hasArg(options::OPT_gsplit_dwarf))
918     CmdArgs.push_back(Args.MakeArgString(
919         Twine(PluginOptPrefix) + "dwo_dir=" + Output.getFilename() + "_dwo"));
920 
921   if (IsThinLTO && !IsOSAIX)
922     CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "thinlto"));
923   else if (IsThinLTO && IsOSAIX)
924     CmdArgs.push_back(Args.MakeArgString(Twine("-bdbg:thinlto")));
925 
926   // Matrix intrinsic lowering happens at link time with ThinLTO. Enable
927   // LowerMatrixIntrinsicsPass, which is transitively called by
928   // buildThinLTODefaultPipeline under EnableMatrix.
929   if ((IsThinLTO || IsFatLTO || IsUnifiedLTO) &&
930         Args.hasArg(options::OPT_fenable_matrix))
931     CmdArgs.push_back(
932         Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-matrix"));
933 
934   StringRef Parallelism = getLTOParallelism(Args, D);
935   if (!Parallelism.empty())
936     CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
937                                          ParallelismOpt + Parallelism));
938 
939   // Pass down GlobalISel options.
940   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
941                                options::OPT_fno_global_isel)) {
942     // Parsing -fno-global-isel explicitly gives architectures that enable GISel
943     // by default a chance to disable it.
944     CmdArgs.push_back(Args.MakeArgString(
945         Twine(PluginOptPrefix) + "-global-isel=" +
946         (A->getOption().matches(options::OPT_fglobal_isel) ? "1" : "0")));
947   }
948 
949   // If an explicit debugger tuning argument appeared, pass it along.
950   if (Arg *A =
951           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
952     if (A->getOption().matches(options::OPT_glldb))
953       CmdArgs.push_back(
954           Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=lldb"));
955     else if (A->getOption().matches(options::OPT_gsce))
956       CmdArgs.push_back(
957           Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=sce"));
958     else if (A->getOption().matches(options::OPT_gdbx))
959       CmdArgs.push_back(
960           Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=dbx"));
961     else
962       CmdArgs.push_back(
963           Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=gdb"));
964   }
965 
966   if (IsOSAIX) {
967     if (!ToolChain.useIntegratedAs())
968       CmdArgs.push_back(
969           Args.MakeArgString(Twine(PluginOptPrefix) + "-no-integrated-as=1"));
970 
971     // On AIX, clang assumes strict-dwarf is true if any debug option is
972     // specified, unless it is told explicitly not to assume so.
973     Arg *A = Args.getLastArg(options::OPT_g_Group);
974     bool EnableDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
975                            !A->getOption().matches(options::OPT_ggdb0);
976     if (EnableDebugInfo && Args.hasFlag(options::OPT_gstrict_dwarf,
977                                         options::OPT_gno_strict_dwarf, true))
978       CmdArgs.push_back(
979           Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true"));
980 
981     for (const Arg *A : Args.filtered_reverse(options::OPT_mabi_EQ)) {
982       StringRef V = A->getValue();
983       if (V == "vec-default")
984         break;
985       if (V == "vec-extabi") {
986         CmdArgs.push_back(
987             Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi"));
988         break;
989       }
990     }
991   }
992 
993   bool UseSeparateSections =
994       isUseSeparateSections(ToolChain.getEffectiveTriple());
995 
996   if (Args.hasFlag(options::OPT_ffunction_sections,
997                    options::OPT_fno_function_sections, UseSeparateSections))
998     CmdArgs.push_back(
999         Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=1"));
1000   else if (Args.hasArg(options::OPT_fno_function_sections))
1001     CmdArgs.push_back(
1002         Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=0"));
1003 
1004   bool DataSectionsTurnedOff = false;
1005   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
1006                    UseSeparateSections)) {
1007     CmdArgs.push_back(
1008         Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1"));
1009   } else if (Args.hasArg(options::OPT_fno_data_sections)) {
1010     DataSectionsTurnedOff = true;
1011     CmdArgs.push_back(
1012         Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=0"));
1013   }
1014 
1015   if (Args.hasArg(options::OPT_mxcoff_roptr) ||
1016       Args.hasArg(options::OPT_mno_xcoff_roptr)) {
1017     bool HasRoptr = Args.hasFlag(options::OPT_mxcoff_roptr,
1018                                  options::OPT_mno_xcoff_roptr, false);
1019     StringRef OptStr = HasRoptr ? "-mxcoff-roptr" : "-mno-xcoff-roptr";
1020     if (!IsOSAIX)
1021       D.Diag(diag::err_drv_unsupported_opt_for_target)
1022           << OptStr << Triple.str();
1023 
1024     if (HasRoptr) {
1025       // The data sections option is on by default on AIX. We only need to error
1026       // out when -fno-data-sections is specified explicitly to turn off data
1027       // sections.
1028       if (DataSectionsTurnedOff)
1029         D.Diag(diag::err_roptr_requires_data_sections);
1030 
1031       CmdArgs.push_back(
1032           Args.MakeArgString(Twine(PluginOptPrefix) + "-mxcoff-roptr"));
1033     }
1034   }
1035 
1036   // Pass an option to enable split machine functions.
1037   if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
1038                                 options::OPT_fno_split_machine_functions)) {
1039     if (A->getOption().matches(options::OPT_fsplit_machine_functions))
1040       CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
1041                                            "-split-machine-functions"));
1042   }
1043 
1044   if (Arg *A = getLastProfileSampleUseArg(Args)) {
1045     StringRef FName = A->getValue();
1046     if (!llvm::sys::fs::exists(FName))
1047       D.Diag(diag::err_drv_no_such_file) << FName;
1048     else
1049       CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
1050                                            "sample-profile=" + FName));
1051   }
1052 
1053   if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) {
1054     CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1055                                          "cs-profile-generate"));
1056     if (CSPGOGenerateArg->getOption().matches(
1057             options::OPT_fcs_profile_generate_EQ)) {
1058       SmallString<128> Path(CSPGOGenerateArg->getValue());
1059       llvm::sys::path::append(Path, "default_%m.profraw");
1060       CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1061                                            "cs-profile-path=" + Path));
1062     } else
1063       CmdArgs.push_back(
1064           Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1065                              "cs-profile-path=default_%m.profraw"));
1066   } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) {
1067     SmallString<128> Path(
1068         ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
1069     if (Path.empty() || llvm::sys::fs::is_directory(Path))
1070       llvm::sys::path::append(Path, "default.profdata");
1071     CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
1072                                          "cs-profile-path=" + Path));
1073   }
1074 
1075   // This controls whether or not we perform JustMyCode instrumentation.
1076   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
1077     if (ToolChain.getEffectiveTriple().isOSBinFormatELF())
1078       CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
1079                                            "-enable-jmc-instrument"));
1080     else
1081       D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
1082   }
1083 
1084   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
1085                    Triple.hasDefaultEmulatedTLS())) {
1086     CmdArgs.push_back(
1087         Args.MakeArgString(Twine(PluginOptPrefix) + "-emulated-tls"));
1088   }
1089   if (isTLSDESCEnabled(ToolChain, Args))
1090     CmdArgs.push_back(
1091         Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-tlsdesc"));
1092 
1093   if (Args.hasFlag(options::OPT_fstack_size_section,
1094                    options::OPT_fno_stack_size_section, false))
1095     CmdArgs.push_back(
1096         Args.MakeArgString(Twine(PluginOptPrefix) + "-stack-size-section"));
1097 
1098   // Setup statistics file output.
1099   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
1100   if (!StatsFile.empty())
1101     CmdArgs.push_back(
1102         Args.MakeArgString(Twine(PluginOptPrefix) + "stats-file=" + StatsFile));
1103 
1104   // Setup crash diagnostics dir.
1105   if (Arg *A = Args.getLastArg(options::OPT_fcrash_diagnostics_dir))
1106     CmdArgs.push_back(Args.MakeArgString(
1107         Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue()));
1108 
1109   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix);
1110 
1111   // Handle remark diagnostics on screen options: '-Rpass-*'.
1112   renderRpassOptions(Args, CmdArgs, PluginOptPrefix);
1113 
1114   // Handle serialized remarks options: '-fsave-optimization-record'
1115   // and '-foptimization-record-*'.
1116   if (willEmitRemarks(Args))
1117     renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
1118                          Output, PluginOptPrefix);
1119 
1120   // Handle remarks hotness/threshold related options.
1121   renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix);
1122 
1123   addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(),
1124                          /*IsLTO=*/true, PluginOptPrefix);
1125 
1126   for (const Arg *A : Args.filtered(options::OPT_Wa_COMMA)) {
1127     bool Crel = false;
1128     for (StringRef V : A->getValues()) {
1129       if (V == "--crel")
1130         Crel = true;
1131       else if (V == "--no-crel")
1132         Crel = false;
1133       else
1134         continue;
1135       A->claim();
1136     }
1137     if (Crel) {
1138       if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
1139         CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "-crel"));
1140       } else {
1141         D.Diag(diag::err_drv_unsupported_opt_for_target)
1142             << "-Wa,--crel" << D.getTargetTriple();
1143       }
1144     }
1145   }
1146 }
1147 
1148 /// Adds the '-lcgpu' and '-lmgpu' libraries to the compilation to include the
1149 /// LLVM C library for GPUs.
addOpenMPDeviceLibC(const Compilation & C,const ArgList & Args,ArgStringList & CmdArgs)1150 static void addOpenMPDeviceLibC(const Compilation &C, const ArgList &Args,
1151                                 ArgStringList &CmdArgs) {
1152   if (Args.hasArg(options::OPT_nogpulib) || Args.hasArg(options::OPT_nolibc))
1153     return;
1154 
1155   // Check the resource directory for the LLVM libc GPU declarations. If it's
1156   // found we can assume that LLVM was built with support for the GPU libc.
1157   SmallString<256> LibCDecls(C.getDriver().ResourceDir);
1158   llvm::sys::path::append(LibCDecls, "include", "llvm_libc_wrappers",
1159                           "llvm-libc-decls");
1160   bool HasLibC = llvm::sys::fs::exists(LibCDecls) &&
1161                  llvm::sys::fs::is_directory(LibCDecls);
1162   if (!Args.hasFlag(options::OPT_gpulibc, options::OPT_nogpulibc, HasLibC))
1163     return;
1164 
1165   SmallVector<const ToolChain *> ToolChains;
1166   auto TCRange = C.getOffloadToolChains(Action::OFK_OpenMP);
1167   for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
1168     ToolChains.push_back(TI->second);
1169 
1170   if (llvm::any_of(ToolChains, [](const ToolChain *TC) {
1171         return TC->getTriple().isAMDGPU();
1172       })) {
1173     CmdArgs.push_back("-lcgpu-amdgpu");
1174     CmdArgs.push_back("-lmgpu-amdgpu");
1175   }
1176   if (llvm::any_of(ToolChains, [](const ToolChain *TC) {
1177         return TC->getTriple().isNVPTX();
1178       })) {
1179     CmdArgs.push_back("-lcgpu-nvptx");
1180     CmdArgs.push_back("-lmgpu-nvptx");
1181   }
1182 }
1183 
addOpenMPRuntimeLibraryPath(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)1184 void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC,
1185                                         const ArgList &Args,
1186                                         ArgStringList &CmdArgs) {
1187   // Default to clang lib / lib64 folder, i.e. the same location as device
1188   // runtime.
1189   SmallString<256> DefaultLibPath =
1190       llvm::sys::path::parent_path(TC.getDriver().Dir);
1191   llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
1192   CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
1193 }
1194 
addArchSpecificRPath(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)1195 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
1196                                  ArgStringList &CmdArgs) {
1197   if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
1198                     options::OPT_fno_rtlib_add_rpath, false))
1199     return;
1200 
1201   SmallVector<std::string> CandidateRPaths(TC.getArchSpecificLibPaths());
1202   if (const auto CandidateRPath = TC.getStdlibPath())
1203     CandidateRPaths.emplace_back(*CandidateRPath);
1204 
1205   for (const auto &CandidateRPath : CandidateRPaths) {
1206     if (TC.getVFS().exists(CandidateRPath)) {
1207       CmdArgs.push_back("-rpath");
1208       CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
1209     }
1210   }
1211 }
1212 
addOpenMPRuntime(const Compilation & C,ArgStringList & CmdArgs,const ToolChain & TC,const ArgList & Args,bool ForceStaticHostRuntime,bool IsOffloadingHost,bool GompNeedsRT)1213 bool tools::addOpenMPRuntime(const Compilation &C, ArgStringList &CmdArgs,
1214                              const ToolChain &TC, const ArgList &Args,
1215                              bool ForceStaticHostRuntime, bool IsOffloadingHost,
1216                              bool GompNeedsRT) {
1217   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
1218                     options::OPT_fno_openmp, false))
1219     return false;
1220 
1221   Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
1222 
1223   if (RTKind == Driver::OMPRT_Unknown)
1224     // Already diagnosed.
1225     return false;
1226 
1227   if (ForceStaticHostRuntime)
1228     CmdArgs.push_back("-Bstatic");
1229 
1230   switch (RTKind) {
1231   case Driver::OMPRT_OMP:
1232     CmdArgs.push_back("-lomp");
1233     break;
1234   case Driver::OMPRT_GOMP:
1235     CmdArgs.push_back("-lgomp");
1236     break;
1237   case Driver::OMPRT_IOMP5:
1238     CmdArgs.push_back("-liomp5");
1239     break;
1240   case Driver::OMPRT_Unknown:
1241     break;
1242   }
1243 
1244   if (ForceStaticHostRuntime)
1245     CmdArgs.push_back("-Bdynamic");
1246 
1247   if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
1248       CmdArgs.push_back("-lrt");
1249 
1250   if (IsOffloadingHost)
1251     CmdArgs.push_back("-lomptarget");
1252 
1253   if (IsOffloadingHost && !Args.hasArg(options::OPT_nogpulib))
1254     CmdArgs.push_back("-lomptarget.devicertl");
1255 
1256   if (IsOffloadingHost)
1257     addOpenMPDeviceLibC(C, Args, CmdArgs);
1258 
1259   addArchSpecificRPath(TC, Args, CmdArgs);
1260   addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
1261 
1262   return true;
1263 }
1264 
1265 /// Add Fortran runtime libs
addFortranRuntimeLibs(const ToolChain & TC,const ArgList & Args,llvm::opt::ArgStringList & CmdArgs)1266 void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args,
1267                                   llvm::opt::ArgStringList &CmdArgs) {
1268   // Link FortranRuntime and FortranDecimal
1269   // These are handled earlier on Windows by telling the frontend driver to
1270   // add the correct libraries to link against as dependents in the object
1271   // file.
1272   if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1273     StringRef F128LibName = TC.getDriver().getFlangF128MathLibrary();
1274     F128LibName.consume_front_insensitive("lib");
1275     if (!F128LibName.empty()) {
1276       bool AsNeeded = !TC.getTriple().isOSAIX();
1277       CmdArgs.push_back("-lFortranFloat128Math");
1278       if (AsNeeded)
1279         addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true);
1280       CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
1281       if (AsNeeded)
1282         addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
1283     }
1284     CmdArgs.push_back("-lFortranRuntime");
1285     CmdArgs.push_back("-lFortranDecimal");
1286   }
1287 }
1288 
addFortranRuntimeLibraryPath(const ToolChain & TC,const llvm::opt::ArgList & Args,ArgStringList & CmdArgs)1289 void tools::addFortranRuntimeLibraryPath(const ToolChain &TC,
1290                                          const llvm::opt::ArgList &Args,
1291                                          ArgStringList &CmdArgs) {
1292   // Default to the <driver-path>/../lib directory. This works fine on the
1293   // platforms that we have tested so far. We will probably have to re-fine
1294   // this in the future. In particular, on some platforms, we may need to use
1295   // lib64 instead of lib.
1296   SmallString<256> DefaultLibPath =
1297       llvm::sys::path::parent_path(TC.getDriver().Dir);
1298   llvm::sys::path::append(DefaultLibPath, "lib");
1299   if (TC.getTriple().isKnownWindowsMSVCEnvironment())
1300     CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
1301   else
1302     CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
1303 }
1304 
addSanitizerRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer,bool IsShared,bool IsWhole)1305 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
1306                                 ArgStringList &CmdArgs, StringRef Sanitizer,
1307                                 bool IsShared, bool IsWhole) {
1308   // Wrap any static runtimes that must be forced into executable in
1309   // whole-archive.
1310   if (IsWhole) CmdArgs.push_back("--whole-archive");
1311   CmdArgs.push_back(TC.getCompilerRTArgString(
1312       Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
1313   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
1314 
1315   if (IsShared) {
1316     addArchSpecificRPath(TC, Args, CmdArgs);
1317   }
1318 }
1319 
1320 // Tries to use a file with the list of dynamic symbols that need to be exported
1321 // from the runtime library. Returns true if the file was found.
addSanitizerDynamicList(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer)1322 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
1323                                     ArgStringList &CmdArgs,
1324                                     StringRef Sanitizer) {
1325   bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1326 
1327   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
1328   // the option, so don't try to pass it.
1329   if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd)
1330     return true;
1331   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
1332   if (llvm::sys::fs::exists(SanRT + ".syms")) {
1333     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
1334     return true;
1335   }
1336   return false;
1337 }
1338 
addAsNeededOption(const ToolChain & TC,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs,bool as_needed)1339 void tools::addAsNeededOption(const ToolChain &TC,
1340                               const llvm::opt::ArgList &Args,
1341                               llvm::opt::ArgStringList &CmdArgs,
1342                               bool as_needed) {
1343   assert(!TC.getTriple().isOSAIX() &&
1344          "AIX linker does not support any form of --as-needed option yet.");
1345   bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1346 
1347   // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
1348   // for the native forms -z ignore/-z record, they are missing in Illumos,
1349   // so always use the native form.
1350   // GNU ld doesn't support -z ignore/-z record, so don't use them even on
1351   // Solaris.
1352   if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) {
1353     CmdArgs.push_back("-z");
1354     CmdArgs.push_back(as_needed ? "ignore" : "record");
1355   } else {
1356     CmdArgs.push_back(as_needed ? "--as-needed" : "--no-as-needed");
1357   }
1358 }
1359 
linkSanitizerRuntimeDeps(const ToolChain & TC,const llvm::opt::ArgList & Args,ArgStringList & CmdArgs)1360 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
1361                                      const llvm::opt::ArgList &Args,
1362                                      ArgStringList &CmdArgs) {
1363   // Force linking against the system libraries sanitizers depends on
1364   // (see PR15823 why this is necessary).
1365   addAsNeededOption(TC, Args, CmdArgs, false);
1366   // There's no libpthread or librt on RTEMS & Android.
1367   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
1368       !TC.getTriple().isAndroid() && !TC.getTriple().isOHOSFamily()) {
1369     CmdArgs.push_back("-lpthread");
1370     if (!TC.getTriple().isOSOpenBSD())
1371       CmdArgs.push_back("-lrt");
1372   }
1373   CmdArgs.push_back("-lm");
1374   // There's no libdl on all OSes.
1375   if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
1376       !TC.getTriple().isOSOpenBSD() &&
1377       TC.getTriple().getOS() != llvm::Triple::RTEMS)
1378     CmdArgs.push_back("-ldl");
1379   // Required for backtrace on some OSes
1380   if (TC.getTriple().isOSFreeBSD() ||
1381       TC.getTriple().isOSNetBSD() ||
1382       TC.getTriple().isOSOpenBSD())
1383     CmdArgs.push_back("-lexecinfo");
1384   // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
1385   // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
1386   // requirement.
1387   if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
1388       !TC.getTriple().isMusl())
1389     CmdArgs.push_back("-lresolv");
1390 }
1391 
1392 static void
collectSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,SmallVectorImpl<StringRef> & SharedRuntimes,SmallVectorImpl<StringRef> & StaticRuntimes,SmallVectorImpl<StringRef> & NonWholeStaticRuntimes,SmallVectorImpl<StringRef> & HelperStaticRuntimes,SmallVectorImpl<StringRef> & RequiredSymbols)1393 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1394                          SmallVectorImpl<StringRef> &SharedRuntimes,
1395                          SmallVectorImpl<StringRef> &StaticRuntimes,
1396                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
1397                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
1398                          SmallVectorImpl<StringRef> &RequiredSymbols) {
1399   const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1400   // Collect shared runtimes.
1401   if (SanArgs.needsSharedRt()) {
1402     if (SanArgs.needsAsanRt()) {
1403       SharedRuntimes.push_back("asan");
1404       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1405         HelperStaticRuntimes.push_back("asan-preinit");
1406     }
1407     if (SanArgs.needsMemProfRt()) {
1408       SharedRuntimes.push_back("memprof");
1409       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1410         HelperStaticRuntimes.push_back("memprof-preinit");
1411     }
1412     if (SanArgs.needsNsanRt())
1413       SharedRuntimes.push_back("nsan");
1414     if (SanArgs.needsUbsanRt()) {
1415       if (SanArgs.requiresMinimalRuntime())
1416         SharedRuntimes.push_back("ubsan_minimal");
1417       else
1418         SharedRuntimes.push_back("ubsan_standalone");
1419     }
1420     if (SanArgs.needsScudoRt()) {
1421       SharedRuntimes.push_back("scudo_standalone");
1422     }
1423     if (SanArgs.needsTsanRt())
1424       SharedRuntimes.push_back("tsan");
1425     if (SanArgs.needsHwasanRt()) {
1426       if (SanArgs.needsHwasanAliasesRt())
1427         SharedRuntimes.push_back("hwasan_aliases");
1428       else
1429         SharedRuntimes.push_back("hwasan");
1430       if (!Args.hasArg(options::OPT_shared))
1431         HelperStaticRuntimes.push_back("hwasan-preinit");
1432     }
1433   }
1434 
1435   // The stats_client library is also statically linked into DSOs.
1436   if (SanArgs.needsStatsRt())
1437     StaticRuntimes.push_back("stats_client");
1438 
1439   // Always link the static runtime regardless of DSO or executable.
1440   if (SanArgs.needsAsanRt())
1441     HelperStaticRuntimes.push_back("asan_static");
1442 
1443   // Collect static runtimes.
1444   if (Args.hasArg(options::OPT_shared)) {
1445     // Don't link static runtimes into DSOs.
1446     return;
1447   }
1448 
1449   // Each static runtime that has a DSO counterpart above is excluded below,
1450   // but runtimes that exist only as static are not affected by needsSharedRt.
1451 
1452   if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt()) {
1453     StaticRuntimes.push_back("asan");
1454     if (SanArgs.linkCXXRuntimes())
1455       StaticRuntimes.push_back("asan_cxx");
1456   }
1457 
1458   if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt()) {
1459     StaticRuntimes.push_back("memprof");
1460     if (SanArgs.linkCXXRuntimes())
1461       StaticRuntimes.push_back("memprof_cxx");
1462   }
1463 
1464   if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt()) {
1465     if (SanArgs.needsHwasanAliasesRt()) {
1466       StaticRuntimes.push_back("hwasan_aliases");
1467       if (SanArgs.linkCXXRuntimes())
1468         StaticRuntimes.push_back("hwasan_aliases_cxx");
1469     } else {
1470       StaticRuntimes.push_back("hwasan");
1471       if (SanArgs.linkCXXRuntimes())
1472         StaticRuntimes.push_back("hwasan_cxx");
1473     }
1474   }
1475   if (SanArgs.needsDfsanRt())
1476     StaticRuntimes.push_back("dfsan");
1477   if (SanArgs.needsLsanRt())
1478     StaticRuntimes.push_back("lsan");
1479   if (SanArgs.needsMsanRt()) {
1480     StaticRuntimes.push_back("msan");
1481     if (SanArgs.linkCXXRuntimes())
1482       StaticRuntimes.push_back("msan_cxx");
1483   }
1484   if (!SanArgs.needsSharedRt() && SanArgs.needsNsanRt())
1485     StaticRuntimes.push_back("nsan");
1486   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) {
1487     StaticRuntimes.push_back("tsan");
1488     if (SanArgs.linkCXXRuntimes())
1489       StaticRuntimes.push_back("tsan_cxx");
1490   }
1491   if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt()) {
1492     if (SanArgs.requiresMinimalRuntime()) {
1493       StaticRuntimes.push_back("ubsan_minimal");
1494     } else {
1495       StaticRuntimes.push_back("ubsan_standalone");
1496       if (SanArgs.linkCXXRuntimes())
1497         StaticRuntimes.push_back("ubsan_standalone_cxx");
1498     }
1499   }
1500   if (SanArgs.needsSafeStackRt()) {
1501     NonWholeStaticRuntimes.push_back("safestack");
1502     RequiredSymbols.push_back("__safestack_init");
1503   }
1504   if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt())) {
1505     if (SanArgs.needsCfiRt())
1506       StaticRuntimes.push_back("cfi");
1507     if (SanArgs.needsCfiDiagRt()) {
1508       StaticRuntimes.push_back("cfi_diag");
1509       if (SanArgs.linkCXXRuntimes())
1510         StaticRuntimes.push_back("ubsan_standalone_cxx");
1511     }
1512   }
1513   if (SanArgs.needsStatsRt()) {
1514     NonWholeStaticRuntimes.push_back("stats");
1515     RequiredSymbols.push_back("__sanitizer_stats_register");
1516   }
1517   if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt()) {
1518     StaticRuntimes.push_back("scudo_standalone");
1519     if (SanArgs.linkCXXRuntimes())
1520       StaticRuntimes.push_back("scudo_standalone_cxx");
1521   }
1522 }
1523 
1524 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
1525 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
addSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)1526 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1527                                  ArgStringList &CmdArgs) {
1528   const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1529   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
1530       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
1531   if (SanArgs.linkRuntimes()) {
1532     collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1533                              NonWholeStaticRuntimes, HelperStaticRuntimes,
1534                              RequiredSymbols);
1535   }
1536 
1537   // -u options must be added before the runtime libs that resolve them.
1538   for (auto S : RequiredSymbols) {
1539     CmdArgs.push_back("-u");
1540     CmdArgs.push_back(Args.MakeArgString(S));
1541   }
1542 
1543   // Inject libfuzzer dependencies.
1544   if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1545       !Args.hasArg(options::OPT_shared)) {
1546 
1547     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
1548     if (SanArgs.needsFuzzerInterceptors())
1549       addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
1550                           true);
1551     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
1552       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
1553                                  !Args.hasArg(options::OPT_static);
1554       if (OnlyLibstdcxxStatic)
1555         CmdArgs.push_back("-Bstatic");
1556       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1557       if (OnlyLibstdcxxStatic)
1558         CmdArgs.push_back("-Bdynamic");
1559     }
1560   }
1561 
1562   for (auto RT : SharedRuntimes)
1563     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
1564   for (auto RT : HelperStaticRuntimes)
1565     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1566   bool AddExportDynamic = false;
1567   for (auto RT : StaticRuntimes) {
1568     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1569     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1570   }
1571   for (auto RT : NonWholeStaticRuntimes) {
1572     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1573     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1574   }
1575   // If there is a static runtime with no dynamic list, force all the symbols
1576   // to be dynamic to be sure we export sanitizer interface functions.
1577   if (AddExportDynamic)
1578     CmdArgs.push_back("--export-dynamic");
1579 
1580   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1581     CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1582 
1583   if (SanArgs.hasMemTag()) {
1584     if (!TC.getTriple().isAndroid()) {
1585       TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1586           << "-fsanitize=memtag*" << TC.getTriple().str();
1587     }
1588     CmdArgs.push_back(
1589         Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1590     if (SanArgs.hasMemtagHeap())
1591       CmdArgs.push_back("--android-memtag-heap");
1592     if (SanArgs.hasMemtagStack())
1593       CmdArgs.push_back("--android-memtag-stack");
1594   }
1595 
1596   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1597 }
1598 
addXRayRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)1599 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1600   if (Args.hasArg(options::OPT_shared))
1601     return false;
1602 
1603   if (TC.getXRayArgs().needsXRayRt()) {
1604     CmdArgs.push_back("--whole-archive");
1605     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
1606     for (const auto &Mode : TC.getXRayArgs().modeList())
1607       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
1608     CmdArgs.push_back("--no-whole-archive");
1609     return true;
1610   }
1611 
1612   return false;
1613 }
1614 
linkXRayRuntimeDeps(const ToolChain & TC,const llvm::opt::ArgList & Args,ArgStringList & CmdArgs)1615 void tools::linkXRayRuntimeDeps(const ToolChain &TC,
1616                                 const llvm::opt::ArgList &Args,
1617                                 ArgStringList &CmdArgs) {
1618   addAsNeededOption(TC, Args, CmdArgs, false);
1619   CmdArgs.push_back("-lpthread");
1620   if (!TC.getTriple().isOSOpenBSD())
1621     CmdArgs.push_back("-lrt");
1622   CmdArgs.push_back("-lm");
1623 
1624   if (!TC.getTriple().isOSFreeBSD() &&
1625       !TC.getTriple().isOSNetBSD() &&
1626       !TC.getTriple().isOSOpenBSD())
1627     CmdArgs.push_back("-ldl");
1628 }
1629 
areOptimizationsEnabled(const ArgList & Args)1630 bool tools::areOptimizationsEnabled(const ArgList &Args) {
1631   // Find the last -O arg and see if it is non-zero.
1632   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1633     return !A->getOption().matches(options::OPT_O0);
1634   // Defaults to -O0.
1635   return false;
1636 }
1637 
SplitDebugName(const JobAction & JA,const ArgList & Args,const InputInfo & Input,const InputInfo & Output)1638 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1639                                   const InputInfo &Input,
1640                                   const InputInfo &Output) {
1641   auto AddPostfix = [JA](auto &F) {
1642     if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1643       F += (Twine("_") + JA.getOffloadingArch()).str();
1644     F += ".dwo";
1645   };
1646   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1647     if (StringRef(A->getValue()) == "single" && Output.isFilename())
1648       return Args.MakeArgString(Output.getFilename());
1649 
1650   SmallString<128> T;
1651   if (const Arg *A = Args.getLastArg(options::OPT_dumpdir)) {
1652     T = A->getValue();
1653   } else {
1654     Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o);
1655     if (FinalOutput && Args.hasArg(options::OPT_c)) {
1656       T = FinalOutput->getValue();
1657       llvm::sys::path::remove_filename(T);
1658       llvm::sys::path::append(T,
1659                               llvm::sys::path::stem(FinalOutput->getValue()));
1660       AddPostfix(T);
1661       return Args.MakeArgString(T);
1662     }
1663   }
1664 
1665   T += llvm::sys::path::stem(Input.getBaseInput());
1666   AddPostfix(T);
1667   return Args.MakeArgString(T);
1668 }
1669 
SplitDebugInfo(const ToolChain & TC,Compilation & C,const Tool & T,const JobAction & JA,const ArgList & Args,const InputInfo & Output,const char * OutFile)1670 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1671                            const JobAction &JA, const ArgList &Args,
1672                            const InputInfo &Output, const char *OutFile) {
1673   ArgStringList ExtractArgs;
1674   ExtractArgs.push_back("--extract-dwo");
1675 
1676   ArgStringList StripArgs;
1677   StripArgs.push_back("--strip-dwo");
1678 
1679   // Grabbing the output of the earlier compile step.
1680   StripArgs.push_back(Output.getFilename());
1681   ExtractArgs.push_back(Output.getFilename());
1682   ExtractArgs.push_back(OutFile);
1683 
1684   const char *Exec =
1685       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1686   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1687 
1688   // First extract the dwo sections.
1689   C.addCommand(std::make_unique<Command>(JA, T,
1690                                          ResponseFileSupport::AtFileCurCP(),
1691                                          Exec, ExtractArgs, II, Output));
1692 
1693   // Then remove them from the original .o file.
1694   C.addCommand(std::make_unique<Command>(
1695       JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1696 }
1697 
1698 // Claim options we don't want to warn if they are unused. We do this for
1699 // options that build systems might add but are unused when assembling or only
1700 // running the preprocessor for example.
claimNoWarnArgs(const ArgList & Args)1701 void tools::claimNoWarnArgs(const ArgList &Args) {
1702   // Don't warn about unused -f(no-)?lto.  This can happen when we're
1703   // preprocessing, precompiling or assembling.
1704   Args.ClaimAllArgs(options::OPT_flto_EQ);
1705   Args.ClaimAllArgs(options::OPT_flto);
1706   Args.ClaimAllArgs(options::OPT_fno_lto);
1707 }
1708 
getLastCSProfileGenerateArg(const ArgList & Args)1709 Arg *tools::getLastCSProfileGenerateArg(const ArgList &Args) {
1710   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
1711                                            options::OPT_fcs_profile_generate_EQ,
1712                                            options::OPT_fno_profile_generate);
1713   if (CSPGOGenerateArg &&
1714       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
1715     CSPGOGenerateArg = nullptr;
1716 
1717   return CSPGOGenerateArg;
1718 }
1719 
getLastProfileUseArg(const ArgList & Args)1720 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1721   auto *ProfileUseArg = Args.getLastArg(
1722       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1723       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1724       options::OPT_fno_profile_instr_use);
1725 
1726   if (ProfileUseArg &&
1727       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1728     ProfileUseArg = nullptr;
1729 
1730   return ProfileUseArg;
1731 }
1732 
getLastProfileSampleUseArg(const ArgList & Args)1733 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1734   auto *ProfileSampleUseArg = Args.getLastArg(
1735       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1736       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1737       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1738 
1739   if (ProfileSampleUseArg &&
1740       (ProfileSampleUseArg->getOption().matches(
1741            options::OPT_fno_profile_sample_use) ||
1742        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1743     return nullptr;
1744 
1745   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1746                          options::OPT_fauto_profile_EQ);
1747 }
1748 
RelocationModelName(llvm::Reloc::Model Model)1749 const char *tools::RelocationModelName(llvm::Reloc::Model Model) {
1750   switch (Model) {
1751   case llvm::Reloc::Static:
1752     return "static";
1753   case llvm::Reloc::PIC_:
1754     return "pic";
1755   case llvm::Reloc::DynamicNoPIC:
1756     return "dynamic-no-pic";
1757   case llvm::Reloc::ROPI:
1758     return "ropi";
1759   case llvm::Reloc::RWPI:
1760     return "rwpi";
1761   case llvm::Reloc::ROPI_RWPI:
1762     return "ropi-rwpi";
1763   }
1764   llvm_unreachable("Unknown Reloc::Model kind");
1765 }
1766 
1767 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
1768 /// smooshes them together with platform defaults, to decide whether
1769 /// this compile should be using PIC mode or not. Returns a tuple of
1770 /// (RelocationModel, PICLevel, IsPIE).
1771 std::tuple<llvm::Reloc::Model, unsigned, bool>
ParsePICArgs(const ToolChain & ToolChain,const ArgList & Args)1772 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1773   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1774   const llvm::Triple &Triple = ToolChain.getTriple();
1775 
1776   bool PIE = ToolChain.isPIEDefault(Args);
1777   bool PIC = PIE || ToolChain.isPICDefault();
1778   // The Darwin/MachO default to use PIC does not apply when using -static.
1779   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1780     PIE = PIC = false;
1781   bool IsPICLevelTwo = PIC;
1782 
1783   bool KernelOrKext =
1784       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1785 
1786   // Android-specific defaults for PIC/PIE
1787   if (Triple.isAndroid()) {
1788     switch (Triple.getArch()) {
1789     case llvm::Triple::arm:
1790     case llvm::Triple::armeb:
1791     case llvm::Triple::thumb:
1792     case llvm::Triple::thumbeb:
1793     case llvm::Triple::aarch64:
1794     case llvm::Triple::mips:
1795     case llvm::Triple::mipsel:
1796     case llvm::Triple::mips64:
1797     case llvm::Triple::mips64el:
1798       PIC = true; // "-fpic"
1799       break;
1800 
1801     case llvm::Triple::x86:
1802     case llvm::Triple::x86_64:
1803       PIC = true; // "-fPIC"
1804       IsPICLevelTwo = true;
1805       break;
1806 
1807     default:
1808       break;
1809     }
1810   }
1811 
1812   // OHOS-specific defaults for PIC/PIE
1813   if (Triple.isOHOSFamily() && Triple.getArch() == llvm::Triple::aarch64)
1814     PIC = true;
1815 
1816   // OpenBSD-specific defaults for PIE
1817   if (Triple.isOSOpenBSD()) {
1818     switch (ToolChain.getArch()) {
1819     case llvm::Triple::arm:
1820     case llvm::Triple::aarch64:
1821     case llvm::Triple::mips64:
1822     case llvm::Triple::mips64el:
1823     case llvm::Triple::x86:
1824     case llvm::Triple::x86_64:
1825       IsPICLevelTwo = false; // "-fpie"
1826       break;
1827 
1828     case llvm::Triple::ppc:
1829     case llvm::Triple::sparcv9:
1830       IsPICLevelTwo = true; // "-fPIE"
1831       break;
1832 
1833     default:
1834       break;
1835     }
1836   }
1837 
1838   // The last argument relating to either PIC or PIE wins, and no
1839   // other argument is used. If the last argument is any flavor of the
1840   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1841   // option implicitly enables PIC at the same level.
1842   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1843                                     options::OPT_fpic, options::OPT_fno_pic,
1844                                     options::OPT_fPIE, options::OPT_fno_PIE,
1845                                     options::OPT_fpie, options::OPT_fno_pie);
1846   if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1847       LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1848                                     options::OPT_fPIE, options::OPT_fpie)) {
1849     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1850         << LastPICArg->getSpelling() << Triple.str();
1851     if (Triple.getArch() == llvm::Triple::x86_64)
1852       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1853     return std::make_tuple(llvm::Reloc::Static, 0U, false);
1854   }
1855 
1856   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1857   // is forced, then neither PIC nor PIE flags will have no effect.
1858   if (!ToolChain.isPICDefaultForced()) {
1859     if (LastPICArg) {
1860       Option O = LastPICArg->getOption();
1861       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1862           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1863         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1864         PIC =
1865             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1866         IsPICLevelTwo =
1867             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1868       } else {
1869         PIE = PIC = false;
1870         if (EffectiveTriple.isPS()) {
1871           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1872           StringRef Model = ModelArg ? ModelArg->getValue() : "";
1873           if (Model != "kernel") {
1874             PIC = true;
1875             ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1876                 << LastPICArg->getSpelling()
1877                 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1878           }
1879         }
1880       }
1881     }
1882   }
1883 
1884   // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1885   // the PIC level would've been set to level 1, force it back to level 2 PIC
1886   // instead.
1887   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1888     IsPICLevelTwo |= ToolChain.isPICDefault();
1889 
1890   // This kernel flags are a trump-card: they will disable PIC/PIE
1891   // generation, independent of the argument order.
1892   if (KernelOrKext &&
1893       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1894        !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1895     PIC = PIE = false;
1896 
1897   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1898     // This is a very special mode. It trumps the other modes, almost no one
1899     // uses it, and it isn't even valid on any OS but Darwin.
1900     if (!Triple.isOSDarwin())
1901       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1902           << A->getSpelling() << Triple.str();
1903 
1904     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1905 
1906     // Only a forced PIC mode can cause the actual compile to have PIC defines
1907     // etc., no flags are sufficient. This behavior was selected to closely
1908     // match that of llvm-gcc and Apple GCC before that.
1909     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1910 
1911     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1912   }
1913 
1914   bool EmbeddedPISupported;
1915   switch (Triple.getArch()) {
1916     case llvm::Triple::arm:
1917     case llvm::Triple::armeb:
1918     case llvm::Triple::thumb:
1919     case llvm::Triple::thumbeb:
1920       EmbeddedPISupported = true;
1921       break;
1922     default:
1923       EmbeddedPISupported = false;
1924       break;
1925   }
1926 
1927   bool ROPI = false, RWPI = false;
1928   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1929   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1930     if (!EmbeddedPISupported)
1931       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1932           << LastROPIArg->getSpelling() << Triple.str();
1933     ROPI = true;
1934   }
1935   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1936   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1937     if (!EmbeddedPISupported)
1938       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1939           << LastRWPIArg->getSpelling() << Triple.str();
1940     RWPI = true;
1941   }
1942 
1943   // ROPI and RWPI are not compatible with PIC or PIE.
1944   if ((ROPI || RWPI) && (PIC || PIE))
1945     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1946 
1947   if (Triple.isMIPS()) {
1948     StringRef CPUName;
1949     StringRef ABIName;
1950     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1951     // When targeting the N64 ABI, PIC is the default, except in the case
1952     // when the -mno-abicalls option is used. In that case we exit
1953     // at next check regardless of PIC being set below.
1954     if (ABIName == "n64")
1955       PIC = true;
1956     // When targettng MIPS with -mno-abicalls, it's always static.
1957     if(Args.hasArg(options::OPT_mno_abicalls))
1958       return std::make_tuple(llvm::Reloc::Static, 0U, false);
1959     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1960     // does not use PIC level 2 for historical reasons.
1961     IsPICLevelTwo = false;
1962   }
1963 
1964   if (PIC)
1965     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1966 
1967   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1968   if (ROPI && RWPI)
1969     RelocM = llvm::Reloc::ROPI_RWPI;
1970   else if (ROPI)
1971     RelocM = llvm::Reloc::ROPI;
1972   else if (RWPI)
1973     RelocM = llvm::Reloc::RWPI;
1974 
1975   return std::make_tuple(RelocM, 0U, false);
1976 }
1977 
1978 // `-falign-functions` indicates that the functions should be aligned to a
1979 // 16-byte boundary.
1980 //
1981 // `-falign-functions=1` is the same as `-fno-align-functions`.
1982 //
1983 // The scalar `n` in `-falign-functions=n` must be an integral value between
1984 // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1985 // the nearest power-of-two.
1986 //
1987 // If we return `0`, the frontend will default to the backend's preferred
1988 // alignment.
1989 //
1990 // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1991 // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1992 // alignment.  For unaligned functions, we default to the backend's preferred
1993 // alignment.
ParseFunctionAlignment(const ToolChain & TC,const ArgList & Args)1994 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1995                                        const ArgList &Args) {
1996   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1997                                  options::OPT_falign_functions_EQ,
1998                                  options::OPT_fno_align_functions);
1999   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
2000     return 0;
2001 
2002   if (A->getOption().matches(options::OPT_falign_functions))
2003     return 0;
2004 
2005   unsigned Value = 0;
2006   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
2007     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
2008         << A->getAsString(Args) << A->getValue();
2009   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
2010 }
2011 
addDebugInfoKind(ArgStringList & CmdArgs,llvm::codegenoptions::DebugInfoKind DebugInfoKind)2012 void tools::addDebugInfoKind(
2013     ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) {
2014   switch (DebugInfoKind) {
2015   case llvm::codegenoptions::DebugDirectivesOnly:
2016     CmdArgs.push_back("-debug-info-kind=line-directives-only");
2017     break;
2018   case llvm::codegenoptions::DebugLineTablesOnly:
2019     CmdArgs.push_back("-debug-info-kind=line-tables-only");
2020     break;
2021   case llvm::codegenoptions::DebugInfoConstructor:
2022     CmdArgs.push_back("-debug-info-kind=constructor");
2023     break;
2024   case llvm::codegenoptions::LimitedDebugInfo:
2025     CmdArgs.push_back("-debug-info-kind=limited");
2026     break;
2027   case llvm::codegenoptions::FullDebugInfo:
2028     CmdArgs.push_back("-debug-info-kind=standalone");
2029     break;
2030   case llvm::codegenoptions::UnusedTypeInfo:
2031     CmdArgs.push_back("-debug-info-kind=unused-types");
2032     break;
2033   default:
2034     break;
2035   }
2036 }
2037 
2038 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2039 // to the corresponding DebugInfoKind.
debugLevelToInfoKind(const Arg & A)2040 llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) {
2041   assert(A.getOption().matches(options::OPT_gN_Group) &&
2042          "Not a -g option that specifies a debug-info level");
2043   if (A.getOption().matches(options::OPT_g0) ||
2044       A.getOption().matches(options::OPT_ggdb0))
2045     return llvm::codegenoptions::NoDebugInfo;
2046   if (A.getOption().matches(options::OPT_gline_tables_only) ||
2047       A.getOption().matches(options::OPT_ggdb1))
2048     return llvm::codegenoptions::DebugLineTablesOnly;
2049   if (A.getOption().matches(options::OPT_gline_directives_only))
2050     return llvm::codegenoptions::DebugDirectivesOnly;
2051   return llvm::codegenoptions::DebugInfoConstructor;
2052 }
2053 
ParseDebugDefaultVersion(const ToolChain & TC,const ArgList & Args)2054 static unsigned ParseDebugDefaultVersion(const ToolChain &TC,
2055                                          const ArgList &Args) {
2056   const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
2057 
2058   if (!A)
2059     return 0;
2060 
2061   unsigned Value = 0;
2062   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
2063       Value < 2)
2064     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
2065         << A->getAsString(Args) << A->getValue();
2066   return Value;
2067 }
2068 
DwarfVersionNum(StringRef ArgValue)2069 unsigned tools::DwarfVersionNum(StringRef ArgValue) {
2070   return llvm::StringSwitch<unsigned>(ArgValue)
2071       .Case("-gdwarf-2", 2)
2072       .Case("-gdwarf-3", 3)
2073       .Case("-gdwarf-4", 4)
2074       .Case("-gdwarf-5", 5)
2075       .Default(0);
2076 }
2077 
getDwarfNArg(const ArgList & Args)2078 const Arg *tools::getDwarfNArg(const ArgList &Args) {
2079   return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2080                          options::OPT_gdwarf_4, options::OPT_gdwarf_5,
2081                          options::OPT_gdwarf);
2082 }
2083 
getDwarfVersion(const ToolChain & TC,const llvm::opt::ArgList & Args)2084 unsigned tools::getDwarfVersion(const ToolChain &TC,
2085                                 const llvm::opt::ArgList &Args) {
2086   unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args);
2087   if (const Arg *GDwarfN = getDwarfNArg(Args))
2088     if (int N = DwarfVersionNum(GDwarfN->getSpelling())) {
2089       DwarfVersion = N;
2090       if (DwarfVersion == 5 && TC.getTriple().isOSAIX())
2091         TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
2092             << GDwarfN->getSpelling() << TC.getTriple().str();
2093     }
2094   if (DwarfVersion == 0) {
2095     DwarfVersion = TC.GetDefaultDwarfVersion();
2096     assert(DwarfVersion && "toolchain default DWARF version must be nonzero");
2097   }
2098   return DwarfVersion;
2099 }
2100 
AddAssemblerKPIC(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs)2101 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
2102                              ArgStringList &CmdArgs) {
2103   llvm::Reloc::Model RelocationModel;
2104   unsigned PICLevel;
2105   bool IsPIE;
2106   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
2107 
2108   if (RelocationModel != llvm::Reloc::Static)
2109     CmdArgs.push_back("-KPIC");
2110 }
2111 
2112 /// Determine whether Objective-C automated reference counting is
2113 /// enabled.
isObjCAutoRefCount(const ArgList & Args)2114 bool tools::isObjCAutoRefCount(const ArgList &Args) {
2115   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
2116 }
2117 
2118 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
2119 
getLibGccType(const ToolChain & TC,const Driver & D,const ArgList & Args)2120 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
2121                                 const ArgList &Args) {
2122   if (Args.hasArg(options::OPT_static_libgcc) ||
2123       Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
2124       // The Android NDK only provides libunwind.a, not libunwind.so.
2125       TC.getTriple().isAndroid())
2126     return LibGccType::StaticLibGcc;
2127   if (Args.hasArg(options::OPT_shared_libgcc))
2128     return LibGccType::SharedLibGcc;
2129   return LibGccType::UnspecifiedLibGcc;
2130 }
2131 
2132 // Gcc adds libgcc arguments in various ways:
2133 //
2134 // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
2135 // g++ <none>:                       -lgcc_s               -lgcc
2136 // gcc shared:                       -lgcc_s               -lgcc
2137 // g++ shared:                       -lgcc_s               -lgcc
2138 // gcc static:     -lgcc             -lgcc_eh
2139 // g++ static:     -lgcc             -lgcc_eh
2140 // gcc static-pie: -lgcc             -lgcc_eh
2141 // g++ static-pie: -lgcc             -lgcc_eh
2142 //
2143 // Also, certain targets need additional adjustments.
2144 
AddUnwindLibrary(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)2145 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
2146                              ArgStringList &CmdArgs, const ArgList &Args) {
2147   ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
2148   // By default OHOS binaries are linked statically to libunwind.
2149   if (TC.getTriple().isOHOSFamily() && UNW == ToolChain::UNW_CompilerRT) {
2150     CmdArgs.push_back("-l:libunwind.a");
2151     return;
2152   }
2153 
2154   // Targets that don't use unwind libraries.
2155   if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
2156       TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
2157       TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
2158     return;
2159 
2160   LibGccType LGT = getLibGccType(TC, D, Args);
2161   bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
2162                   (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
2163                   !TC.getTriple().isAndroid() &&
2164                   !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
2165   if (AsNeeded)
2166     addAsNeededOption(TC, Args, CmdArgs, true);
2167 
2168   switch (UNW) {
2169   case ToolChain::UNW_None:
2170     return;
2171   case ToolChain::UNW_Libgcc: {
2172     if (LGT == LibGccType::StaticLibGcc)
2173       CmdArgs.push_back("-lgcc_eh");
2174     else
2175       CmdArgs.push_back("-lgcc_s");
2176     break;
2177   }
2178   case ToolChain::UNW_CompilerRT:
2179     if (TC.getTriple().isOSAIX()) {
2180       // AIX only has libunwind as a shared library. So do not pass
2181       // anything in if -static is specified.
2182       if (LGT != LibGccType::StaticLibGcc)
2183         CmdArgs.push_back("-lunwind");
2184     } else if (LGT == LibGccType::StaticLibGcc) {
2185       CmdArgs.push_back("-l:libunwind.a");
2186     } else if (LGT == LibGccType::SharedLibGcc) {
2187       if (TC.getTriple().isOSCygMing())
2188         CmdArgs.push_back("-l:libunwind.dll.a");
2189       else
2190         CmdArgs.push_back("-l:libunwind.so");
2191     } else {
2192       // Let the linker choose between libunwind.so and libunwind.a
2193       // depending on what's available, and depending on the -static flag
2194       CmdArgs.push_back("-lunwind");
2195     }
2196     break;
2197   }
2198 
2199   if (AsNeeded)
2200     addAsNeededOption(TC, Args, CmdArgs, false);
2201 }
2202 
AddLibgcc(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)2203 static void AddLibgcc(const ToolChain &TC, const Driver &D,
2204                       ArgStringList &CmdArgs, const ArgList &Args) {
2205   LibGccType LGT = getLibGccType(TC, D, Args);
2206   if (LGT == LibGccType::StaticLibGcc ||
2207       (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
2208     CmdArgs.push_back("-lgcc");
2209   AddUnwindLibrary(TC, D, CmdArgs, Args);
2210   if (LGT == LibGccType::SharedLibGcc ||
2211       (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
2212     CmdArgs.push_back("-lgcc");
2213 }
2214 
AddRunTimeLibs(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)2215 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
2216                            ArgStringList &CmdArgs, const ArgList &Args) {
2217   // Make use of compiler-rt if --rtlib option is used
2218   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
2219 
2220   switch (RLT) {
2221   case ToolChain::RLT_CompilerRT:
2222     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2223     AddUnwindLibrary(TC, D, CmdArgs, Args);
2224     break;
2225   case ToolChain::RLT_Libgcc:
2226     // Make sure libgcc is not used under MSVC environment by default
2227     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
2228       // Issue error diagnostic if libgcc is explicitly specified
2229       // through command line as --rtlib option argument.
2230       Arg *A = Args.getLastArg(options::OPT_rtlib_EQ);
2231       if (A && A->getValue() != StringRef("platform")) {
2232         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
2233             << A->getValue() << "MSVC";
2234       }
2235     } else
2236       AddLibgcc(TC, D, CmdArgs, Args);
2237     break;
2238   }
2239 
2240   // On Android, the unwinder uses dl_iterate_phdr (or one of
2241   // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
2242   // statically-linked executables, these functions come from libc.a instead.
2243   if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
2244       !Args.hasArg(options::OPT_static_pie))
2245     CmdArgs.push_back("-ldl");
2246 }
2247 
getStatsFileName(const llvm::opt::ArgList & Args,const InputInfo & Output,const InputInfo & Input,const Driver & D)2248 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
2249                                          const InputInfo &Output,
2250                                          const InputInfo &Input,
2251                                          const Driver &D) {
2252   const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
2253   if (!A && !D.CCPrintInternalStats)
2254     return {};
2255 
2256   SmallString<128> StatsFile;
2257   if (A) {
2258     StringRef SaveStats = A->getValue();
2259     if (SaveStats == "obj" && Output.isFilename()) {
2260       StatsFile.assign(Output.getFilename());
2261       llvm::sys::path::remove_filename(StatsFile);
2262     } else if (SaveStats != "cwd") {
2263       D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
2264       return {};
2265     }
2266 
2267     StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
2268     llvm::sys::path::append(StatsFile, BaseName);
2269     llvm::sys::path::replace_extension(StatsFile, "stats");
2270   } else {
2271     assert(D.CCPrintInternalStats);
2272     StatsFile.assign(D.CCPrintInternalStatReportFilename.empty()
2273                          ? "-"
2274                          : D.CCPrintInternalStatReportFilename);
2275   }
2276   return StatsFile;
2277 }
2278 
addMultilibFlag(bool Enabled,const StringRef Flag,Multilib::flags_list & Flags)2279 void tools::addMultilibFlag(bool Enabled, const StringRef Flag,
2280                             Multilib::flags_list &Flags) {
2281   assert(Flag.front() == '-');
2282   if (Enabled) {
2283     Flags.push_back(Flag.str());
2284   } else {
2285     Flags.push_back(("!" + Flag.substr(1)).str());
2286   }
2287 }
2288 
addX86AlignBranchArgs(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,bool IsLTO,const StringRef PluginOptPrefix)2289 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
2290                                   ArgStringList &CmdArgs, bool IsLTO,
2291                                   const StringRef PluginOptPrefix) {
2292   auto addArg = [&, IsLTO](const Twine &Arg) {
2293     if (IsLTO) {
2294       assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2295       CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2296     } else {
2297       CmdArgs.push_back("-mllvm");
2298       CmdArgs.push_back(Args.MakeArgString(Arg));
2299     }
2300   };
2301 
2302   if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
2303     addArg(Twine("-x86-branches-within-32B-boundaries"));
2304   }
2305   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
2306     StringRef Value = A->getValue();
2307     unsigned Boundary;
2308     if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
2309         !llvm::isPowerOf2_64(Boundary)) {
2310       D.Diag(diag::err_drv_invalid_argument_to_option)
2311           << Value << A->getOption().getName();
2312     } else {
2313       addArg("-x86-align-branch-boundary=" + Twine(Boundary));
2314     }
2315   }
2316   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
2317     std::string AlignBranch;
2318     for (StringRef T : A->getValues()) {
2319       if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
2320           T != "ret" && T != "indirect")
2321         D.Diag(diag::err_drv_invalid_malign_branch_EQ)
2322             << T << "fused, jcc, jmp, call, ret, indirect";
2323       if (!AlignBranch.empty())
2324         AlignBranch += '+';
2325       AlignBranch += T;
2326     }
2327     addArg("-x86-align-branch=" + Twine(AlignBranch));
2328   }
2329   if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
2330     StringRef Value = A->getValue();
2331     unsigned PrefixSize;
2332     if (Value.getAsInteger(10, PrefixSize)) {
2333       D.Diag(diag::err_drv_invalid_argument_to_option)
2334           << Value << A->getOption().getName();
2335     } else {
2336       addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
2337     }
2338   }
2339 }
2340 
2341 /// SDLSearch: Search for Static Device Library
2342 /// The search for SDL bitcode files is consistent with how static host
2343 /// libraries are discovered. That is, the -l option triggers a search for
2344 /// files in a set of directories called the LINKPATH. The host library search
2345 /// procedure looks for a specific filename in the LINKPATH.  The filename for
2346 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
2347 /// ordered-set of filenames that are searched. We call this ordered-set of
2348 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
2349 /// architecture specific, or generic across all architectures, a naming
2350 /// convention and search order is used where the file name embeds the
2351 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
2352 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
2353 /// device-independent SDLs. To reduce congestion in host library directories,
2354 /// the search first looks for files in the “libdevice” subdirectory. SDLs that
2355 /// are bc files begin with the prefix “lib”.
2356 ///
2357 /// Machine-code SDLs can also be managed as an archive (*.a file). The
2358 /// convention has been to use the prefix “lib”. To avoid confusion with host
2359 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
2360 ///
SDLSearch(const Driver & D,const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,const SmallVectorImpl<std::string> & LibraryPaths,StringRef Lib,StringRef Arch,StringRef Target,bool isBitCodeSDL)2361 static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
2362                       llvm::opt::ArgStringList &CC1Args,
2363                       const SmallVectorImpl<std::string> &LibraryPaths,
2364                       StringRef Lib, StringRef Arch, StringRef Target,
2365                       bool isBitCodeSDL) {
2366   SmallVector<std::string, 12> SDLs;
2367 
2368   std::string LibDeviceLoc = "/libdevice";
2369   std::string LibBcPrefix = "/libbc-";
2370   std::string LibPrefix = "/lib";
2371 
2372   if (isBitCodeSDL) {
2373     // SEARCH-ORDER for Bitcode SDLs:
2374     //       libdevice/libbc-<libname>-<arch-name>-<device-type>.a
2375     //       libbc-<libname>-<arch-name>-<device-type>.a
2376     //       libdevice/libbc-<libname>-<arch-name>.a
2377     //       libbc-<libname>-<arch-name>.a
2378     //       libdevice/libbc-<libname>.a
2379     //       libbc-<libname>.a
2380     //       libdevice/lib<libname>-<arch-name>-<device-type>.bc
2381     //       lib<libname>-<arch-name>-<device-type>.bc
2382     //       libdevice/lib<libname>-<arch-name>.bc
2383     //       lib<libname>-<arch-name>.bc
2384     //       libdevice/lib<libname>.bc
2385     //       lib<libname>.bc
2386 
2387     for (StringRef Base : {LibBcPrefix, LibPrefix}) {
2388       const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
2389 
2390       for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2391                           Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
2392         SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
2393         SDLs.push_back(Twine(Base + Suffix + Ext).str());
2394       }
2395     }
2396   } else {
2397     // SEARCH-ORDER for Machine-code SDLs:
2398     //    libdevice/lib<libname>-<arch-name>-<device-type>.a
2399     //    lib<libname>-<arch-name>-<device-type>.a
2400     //    libdevice/lib<libname>-<arch-name>.a
2401     //    lib<libname>-<arch-name>.a
2402 
2403     const auto *Ext = ".a";
2404 
2405     for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2406                         Twine(Lib + "-" + Arch).str()}) {
2407       SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
2408       SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
2409     }
2410   }
2411 
2412   // The CUDA toolchain does not use a global device llvm-link before the LLVM
2413   // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
2414   // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
2415   // will link libraries after clang compilation while the LLVM IR is still in
2416   // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
2417   // This is a clang -cc1 option that is generated by the clang driver. The
2418   // option value must a full path to an existing file.
2419   bool FoundSDL = false;
2420   for (auto LPath : LibraryPaths) {
2421     for (auto SDL : SDLs) {
2422       auto FullName = Twine(LPath + SDL).str();
2423       if (llvm::sys::fs::exists(FullName)) {
2424         CC1Args.push_back(DriverArgs.MakeArgString(FullName));
2425         FoundSDL = true;
2426         break;
2427       }
2428     }
2429     if (FoundSDL)
2430       break;
2431   }
2432   return FoundSDL;
2433 }
2434 
2435 /// Search if a user provided archive file lib<libname>.a exists in any of
2436 /// the library paths. If so, add a new command to clang-offload-bundler to
2437 /// unbundle this archive and create a temporary device specific archive. Name
2438 /// of this SDL is passed to the llvm-link tool.
GetSDLFromOffloadArchive(Compilation & C,const Driver & D,const Tool & T,const JobAction & JA,const InputInfoList & Inputs,const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,const SmallVectorImpl<std::string> & LibraryPaths,StringRef Lib,StringRef Arch,StringRef Target,bool isBitCodeSDL)2439 static void GetSDLFromOffloadArchive(
2440     Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
2441     const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
2442     llvm::opt::ArgStringList &CC1Args,
2443     const SmallVectorImpl<std::string> &LibraryPaths, StringRef Lib,
2444     StringRef Arch, StringRef Target, bool isBitCodeSDL) {
2445 
2446   // We don't support bitcode archive bundles for nvptx
2447   if (isBitCodeSDL && Arch.contains("nvptx"))
2448     return;
2449 
2450   bool FoundAOB = false;
2451   std::string ArchiveOfBundles;
2452 
2453   llvm::Triple Triple(D.getTargetTriple());
2454   bool IsMSVC = Triple.isWindowsMSVCEnvironment();
2455   auto Ext = IsMSVC ? ".lib" : ".a";
2456   if (!Lib.starts_with(":") && !Lib.starts_with("-l")) {
2457     if (llvm::sys::fs::exists(Lib)) {
2458       ArchiveOfBundles = Lib;
2459       FoundAOB = true;
2460     }
2461   } else {
2462     Lib.consume_front("-l");
2463     for (auto LPath : LibraryPaths) {
2464       ArchiveOfBundles.clear();
2465       auto LibFile = (Lib.starts_with(":") ? Lib.drop_front()
2466                       : IsMSVC             ? Lib + Ext
2467                                            : "lib" + Lib + Ext)
2468                          .str();
2469       for (auto Prefix : {"/libdevice/", "/"}) {
2470         auto AOB = Twine(LPath + Prefix + LibFile).str();
2471         if (llvm::sys::fs::exists(AOB)) {
2472           ArchiveOfBundles = AOB;
2473           FoundAOB = true;
2474           break;
2475         }
2476       }
2477       if (FoundAOB)
2478         break;
2479     }
2480   }
2481 
2482   if (!FoundAOB)
2483     return;
2484 
2485   llvm::file_magic Magic;
2486   auto EC = llvm::identify_magic(ArchiveOfBundles, Magic);
2487   if (EC || Magic != llvm::file_magic::archive)
2488     return;
2489 
2490   StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
2491   std::string OutputLib =
2492       D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" +
2493                                Arch + "-" + Target)
2494                              .str(),
2495                          "a");
2496 
2497   C.addTempFile(C.getArgs().MakeArgString(OutputLib));
2498 
2499   ArgStringList CmdArgs;
2500   SmallString<128> DeviceTriple;
2501   DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind());
2502   DeviceTriple += '-';
2503   std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
2504   DeviceTriple += NormalizedTriple;
2505   if (!Target.empty()) {
2506     DeviceTriple += '-';
2507     DeviceTriple += Target;
2508   }
2509 
2510   std::string UnbundleArg("-unbundle");
2511   std::string TypeArg("-type=a");
2512   std::string InputArg("-input=" + ArchiveOfBundles);
2513   std::string OffloadArg("-targets=" + std::string(DeviceTriple));
2514   std::string OutputArg("-output=" + OutputLib);
2515 
2516   const char *UBProgram = DriverArgs.MakeArgString(
2517       T.getToolChain().GetProgramPath("clang-offload-bundler"));
2518 
2519   ArgStringList UBArgs;
2520   UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
2521   UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
2522   UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
2523   UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
2524   UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
2525 
2526   // Add this flag to not exit from clang-offload-bundler if no compatible
2527   // code object is found in heterogenous archive library.
2528   std::string AdditionalArgs("-allow-missing-bundles");
2529   UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
2530 
2531   // Add this flag to treat hip and hipv4 offload kinds as compatible with
2532   // openmp offload kind while extracting code objects from a heterogenous
2533   // archive library. Vice versa is also considered compatible.
2534   std::string HipCompatibleArgs("-hip-openmp-compatible");
2535   UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
2536 
2537   C.addCommand(std::make_unique<Command>(
2538       JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
2539       InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
2540 
2541   CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
2542 
2543   return;
2544 }
2545 
2546 // Wrapper function used by driver for adding SDLs during link phase.
AddStaticDeviceLibsLinking(Compilation & C,const Tool & T,const JobAction & JA,const InputInfoList & Inputs,const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,StringRef Arch,StringRef Target,bool isBitCodeSDL)2547 void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T,
2548                                        const JobAction &JA,
2549                                        const InputInfoList &Inputs,
2550                                        const llvm::opt::ArgList &DriverArgs,
2551                                        llvm::opt::ArgStringList &CC1Args,
2552                                        StringRef Arch, StringRef Target,
2553                                        bool isBitCodeSDL) {
2554   AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
2555                       Arch, Target, isBitCodeSDL);
2556 }
2557 
2558 // User defined Static Device Libraries(SDLs) can be passed to clang for
2559 // offloading GPU compilers. Like static host libraries, the use of a SDL is
2560 // specified with the -l command line option. The primary difference between
2561 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
2562 // and SEARCH-ORDER for Machine-code SDLs for the naming convention).
2563 // SDLs are of following types:
2564 //
2565 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
2566 //           For NVPTX, these libraries are post-clang linked following each
2567 //           compilation. For AMDGPU, these libraries are linked one time
2568 //           during the application link phase.
2569 //
2570 // * Machine-code SDLs: They are archive files. For AMDGPU, the process for
2571 //           machine code SDLs is still in development. But they will be linked
2572 //           by the LLVM tool lld.
2573 //
2574 // * Bundled objects that contain both host and device codes: Bundled objects
2575 //           may also contain library code compiled from source. For NVPTX, the
2576 //           bundle contains cubin. For AMDGPU, the bundle contains bitcode.
2577 //
2578 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
2579 // inclusion of specific SDLs such as math libraries and the OpenMP device
2580 // library libomptarget.
AddStaticDeviceLibs(Compilation * C,const Tool * T,const JobAction * JA,const InputInfoList * Inputs,const Driver & D,const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,StringRef Arch,StringRef Target,bool isBitCodeSDL)2581 void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T,
2582                                 const JobAction *JA,
2583                                 const InputInfoList *Inputs, const Driver &D,
2584                                 const llvm::opt::ArgList &DriverArgs,
2585                                 llvm::opt::ArgStringList &CC1Args,
2586                                 StringRef Arch, StringRef Target,
2587                                 bool isBitCodeSDL) {
2588 
2589   SmallVector<std::string, 8> LibraryPaths;
2590   // Add search directories from LIBRARY_PATH env variable
2591   std::optional<std::string> LibPath =
2592       llvm::sys::Process::GetEnv("LIBRARY_PATH");
2593   if (LibPath) {
2594     SmallVector<StringRef, 8> Frags;
2595     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2596     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2597     for (StringRef Path : Frags)
2598       LibraryPaths.emplace_back(Path.trim());
2599   }
2600 
2601   // Add directories from user-specified -L options
2602   for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
2603     LibraryPaths.emplace_back(Search_Dir);
2604 
2605   // Add path to lib-debug folders
2606   SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2607   llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
2608   LibraryPaths.emplace_back(DefaultLibPath.c_str());
2609 
2610   // Build list of Static Device Libraries SDLs specified by -l option
2611   llvm::SmallSet<std::string, 16> SDLNames;
2612   static const StringRef HostOnlyArchives[] = {
2613       "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
2614   for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
2615     if (!llvm::is_contained(HostOnlyArchives, SDLName)) {
2616       SDLNames.insert(std::string("-l") + SDLName);
2617     }
2618   }
2619 
2620   for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) {
2621     auto FileName = StringRef(Input);
2622     // Clang treats any unknown file types as archives and passes them to the
2623     // linker. Files with extension 'lib' are classified as TY_Object by clang
2624     // but they are usually archives. It is OK if the file is not really an
2625     // archive since GetSDLFromOffloadArchive will check the magic of the file
2626     // and only unbundle it if it is really an archive.
2627     const StringRef LibFileExt = ".lib";
2628     if (!llvm::sys::path::has_extension(FileName) ||
2629         types::lookupTypeForExtension(
2630             llvm::sys::path::extension(FileName).drop_front()) ==
2631             types::TY_INVALID ||
2632         llvm::sys::path::extension(FileName) == LibFileExt)
2633       SDLNames.insert(Input);
2634   }
2635 
2636   // The search stops as soon as an SDL file is found. The driver then provides
2637   // the full filename of the SDL to the llvm-link command. If no SDL is found
2638   // after searching each LINKPATH with SEARCH-ORDER, it is possible that an
2639   // archive file lib<libname>.a exists and may contain bundled object files.
2640   for (auto SDLName : SDLNames) {
2641     // This is the only call to SDLSearch
2642     if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
2643                    isBitCodeSDL)) {
2644       GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
2645                                LibraryPaths, SDLName, Arch, Target,
2646                                isBitCodeSDL);
2647     }
2648   }
2649 }
2650 
2651 static llvm::opt::Arg *
getAMDGPUCodeObjectArgument(const Driver & D,const llvm::opt::ArgList & Args)2652 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
2653   return Args.getLastArg(options::OPT_mcode_object_version_EQ);
2654 }
2655 
checkAMDGPUCodeObjectVersion(const Driver & D,const llvm::opt::ArgList & Args)2656 void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
2657                                          const llvm::opt::ArgList &Args) {
2658   const unsigned MinCodeObjVer = 4;
2659   const unsigned MaxCodeObjVer = 6;
2660 
2661   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2662     if (CodeObjArg->getOption().getID() ==
2663         options::OPT_mcode_object_version_EQ) {
2664       unsigned CodeObjVer = MaxCodeObjVer;
2665       auto Remnant =
2666           StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2667       if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
2668         D.Diag(diag::err_drv_invalid_int_value)
2669             << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
2670 
2671       // COV6 is only supported by LLVM at the time of writing this, and it's
2672       // expected to take some time before all ROCm components fully
2673       // support it. In the meantime, make sure users are aware of this.
2674       if (CodeObjVer == 6)
2675         D.Diag(diag::warn_drv_amdgpu_cov6);
2676     }
2677   }
2678 }
2679 
getAMDGPUCodeObjectVersion(const Driver & D,const llvm::opt::ArgList & Args)2680 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
2681                                            const llvm::opt::ArgList &Args) {
2682   unsigned CodeObjVer = 4; // default
2683   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args))
2684     StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2685   return CodeObjVer;
2686 }
2687 
haveAMDGPUCodeObjectVersionArgument(const Driver & D,const llvm::opt::ArgList & Args)2688 bool tools::haveAMDGPUCodeObjectVersionArgument(
2689     const Driver &D, const llvm::opt::ArgList &Args) {
2690   return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2691 }
2692 
addMachineOutlinerArgs(const Driver & D,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs,const llvm::Triple & Triple,bool IsLTO,const StringRef PluginOptPrefix)2693 void tools::addMachineOutlinerArgs(const Driver &D,
2694                                    const llvm::opt::ArgList &Args,
2695                                    llvm::opt::ArgStringList &CmdArgs,
2696                                    const llvm::Triple &Triple, bool IsLTO,
2697                                    const StringRef PluginOptPrefix) {
2698   auto addArg = [&, IsLTO](const Twine &Arg) {
2699     if (IsLTO) {
2700       assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2701       CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2702     } else {
2703       CmdArgs.push_back("-mllvm");
2704       CmdArgs.push_back(Args.MakeArgString(Arg));
2705     }
2706   };
2707 
2708   if (Arg *A = Args.getLastArg(options::OPT_moutline,
2709                                options::OPT_mno_outline)) {
2710     if (A->getOption().matches(options::OPT_moutline)) {
2711       // We only support -moutline in AArch64 and ARM targets right now. If
2712       // we're not compiling for these, emit a warning and ignore the flag.
2713       // Otherwise, add the proper mllvm flags.
2714       if (!(Triple.isARM() || Triple.isThumb() || Triple.isAArch64())) {
2715         D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2716       } else {
2717         addArg(Twine("-enable-machine-outliner"));
2718       }
2719     } else {
2720       // Disable all outlining behaviour.
2721       addArg(Twine("-enable-machine-outliner=never"));
2722     }
2723   }
2724 }
2725 
addOpenMPDeviceRTL(const Driver & D,const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,StringRef BitcodeSuffix,const llvm::Triple & Triple,const ToolChain & HostTC)2726 void tools::addOpenMPDeviceRTL(const Driver &D,
2727                                const llvm::opt::ArgList &DriverArgs,
2728                                llvm::opt::ArgStringList &CC1Args,
2729                                StringRef BitcodeSuffix,
2730                                const llvm::Triple &Triple,
2731                                const ToolChain &HostTC) {
2732   SmallVector<StringRef, 8> LibraryPaths;
2733 
2734   // Add user defined library paths from LIBRARY_PATH.
2735   std::optional<std::string> LibPath =
2736       llvm::sys::Process::GetEnv("LIBRARY_PATH");
2737   if (LibPath) {
2738     SmallVector<StringRef, 8> Frags;
2739     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2740     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2741     for (StringRef Path : Frags)
2742       LibraryPaths.emplace_back(Path.trim());
2743   }
2744 
2745   // Check all of the standard library search paths used by the compiler.
2746   for (const auto &LibPath : HostTC.getFilePaths())
2747     LibraryPaths.emplace_back(LibPath);
2748 
2749   OptSpecifier LibomptargetBCPathOpt =
2750       Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2751                         : options::OPT_libomptarget_nvptx_bc_path_EQ;
2752 
2753   StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2754   std::string LibOmpTargetName =
2755       ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2756 
2757   // First check whether user specifies bc library
2758   if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2759     SmallString<128> LibOmpTargetFile(A->getValue());
2760     if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2761         llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2762       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2763     }
2764 
2765     if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2766       CC1Args.push_back("-mlink-builtin-bitcode");
2767       CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2768     } else {
2769       D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2770           << LibOmpTargetFile;
2771     }
2772   } else {
2773     bool FoundBCLibrary = false;
2774 
2775     for (StringRef LibraryPath : LibraryPaths) {
2776       SmallString<128> LibOmpTargetFile(LibraryPath);
2777       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2778       if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2779         CC1Args.push_back("-mlink-builtin-bitcode");
2780         CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2781         FoundBCLibrary = true;
2782         break;
2783       }
2784     }
2785 
2786     if (!FoundBCLibrary)
2787       D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2788           << LibOmpTargetName << ArchPrefix;
2789   }
2790 }
addHIPRuntimeLibArgs(const ToolChain & TC,Compilation & C,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs)2791 void tools::addHIPRuntimeLibArgs(const ToolChain &TC, Compilation &C,
2792                                  const llvm::opt::ArgList &Args,
2793                                  llvm::opt::ArgStringList &CmdArgs) {
2794   if ((C.getActiveOffloadKinds() & Action::OFK_HIP) &&
2795       !Args.hasArg(options::OPT_nostdlib) &&
2796       !Args.hasArg(options::OPT_no_hip_rt) && !Args.hasArg(options::OPT_r)) {
2797     TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2798   } else {
2799     // Claim "no HIP libraries" arguments if any
2800     for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) {
2801       Arg->claim();
2802     }
2803   }
2804 }
2805 
addOutlineAtomicsArgs(const Driver & D,const ToolChain & TC,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs,const llvm::Triple & Triple)2806 void tools::addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC,
2807                                   const llvm::opt::ArgList &Args,
2808                                   llvm::opt::ArgStringList &CmdArgs,
2809                                   const llvm::Triple &Triple) {
2810   if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
2811                                options::OPT_mno_outline_atomics)) {
2812     // Option -moutline-atomics supported for AArch64 target only.
2813     if (!Triple.isAArch64()) {
2814       D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
2815           << Triple.getArchName() << A->getOption().getName();
2816     } else {
2817       if (A->getOption().matches(options::OPT_moutline_atomics)) {
2818         CmdArgs.push_back("-target-feature");
2819         CmdArgs.push_back("+outline-atomics");
2820       } else {
2821         CmdArgs.push_back("-target-feature");
2822         CmdArgs.push_back("-outline-atomics");
2823       }
2824     }
2825   } else if (Triple.isAArch64() && TC.IsAArch64OutlineAtomicsDefault(Args)) {
2826     CmdArgs.push_back("-target-feature");
2827     CmdArgs.push_back("+outline-atomics");
2828   }
2829 }
2830 
addOffloadCompressArgs(const llvm::opt::ArgList & TCArgs,llvm::opt::ArgStringList & CmdArgs)2831 void tools::addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs,
2832                                    llvm::opt::ArgStringList &CmdArgs) {
2833   if (TCArgs.hasFlag(options::OPT_offload_compress,
2834                      options::OPT_no_offload_compress, false))
2835     CmdArgs.push_back("-compress");
2836   if (TCArgs.hasArg(options::OPT_v))
2837     CmdArgs.push_back("-verbose");
2838   if (auto *Arg = TCArgs.getLastArg(options::OPT_offload_compression_level_EQ))
2839     CmdArgs.push_back(
2840         TCArgs.MakeArgString(Twine("-compression-level=") + Arg->getValue()));
2841 }
2842 
addMCModel(const Driver & D,const llvm::opt::ArgList & Args,const llvm::Triple & Triple,const llvm::Reloc::Model & RelocationModel,llvm::opt::ArgStringList & CmdArgs)2843 void tools::addMCModel(const Driver &D, const llvm::opt::ArgList &Args,
2844                        const llvm::Triple &Triple,
2845                        const llvm::Reloc::Model &RelocationModel,
2846                        llvm::opt::ArgStringList &CmdArgs) {
2847   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2848     StringRef CM = A->getValue();
2849     bool Ok = false;
2850     if (Triple.isOSAIX() && CM == "medium")
2851       CM = "large";
2852     if (Triple.isAArch64(64)) {
2853       Ok = CM == "tiny" || CM == "small" || CM == "large";
2854       if (CM == "large" && !Triple.isOSBinFormatMachO() &&
2855           RelocationModel != llvm::Reloc::Static)
2856         D.Diag(diag::err_drv_argument_only_allowed_with)
2857             << A->getAsString(Args) << "-fno-pic";
2858     } else if (Triple.isLoongArch()) {
2859       if (CM == "extreme" &&
2860           Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false))
2861         D.Diag(diag::err_drv_argument_not_allowed_with)
2862             << A->getAsString(Args) << "-fplt";
2863       Ok = CM == "normal" || CM == "medium" || CM == "extreme";
2864       // Convert to LLVM recognizable names.
2865       if (Ok)
2866         CM = llvm::StringSwitch<StringRef>(CM)
2867                  .Case("normal", "small")
2868                  .Case("extreme", "large")
2869                  .Default(CM);
2870     } else if (Triple.isPPC64() || Triple.isOSAIX()) {
2871       Ok = CM == "small" || CM == "medium" || CM == "large";
2872     } else if (Triple.isRISCV()) {
2873       if (CM == "medlow")
2874         CM = "small";
2875       else if (CM == "medany")
2876         CM = "medium";
2877       Ok = CM == "small" || CM == "medium";
2878     } else if (Triple.getArch() == llvm::Triple::x86_64) {
2879       Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"},
2880                               CM);
2881     } else if (Triple.isNVPTX() || Triple.isAMDGPU() || Triple.isSPIRV()) {
2882       // NVPTX/AMDGPU/SPIRV does not care about the code model and will accept
2883       // whatever works for the host.
2884       Ok = true;
2885     } else if (Triple.isSPARC64()) {
2886       if (CM == "medlow")
2887         CM = "small";
2888       else if (CM == "medmid")
2889         CM = "medium";
2890       else if (CM == "medany")
2891         CM = "large";
2892       Ok = CM == "small" || CM == "medium" || CM == "large";
2893     }
2894     if (Ok) {
2895       CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM));
2896     } else {
2897       D.Diag(diag::err_drv_unsupported_option_argument_for_target)
2898           << A->getSpelling() << CM << Triple.getTriple();
2899     }
2900   }
2901 
2902   if (Triple.getArch() == llvm::Triple::x86_64) {
2903     bool IsMediumCM = false;
2904     bool IsLargeCM = false;
2905     if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2906       IsMediumCM = StringRef(A->getValue()) == "medium";
2907       IsLargeCM = StringRef(A->getValue()) == "large";
2908     }
2909     if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) {
2910       if (!IsMediumCM && !IsLargeCM) {
2911         D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model)
2912             << A->getOption().getRenderName();
2913       } else {
2914         A->render(Args, CmdArgs);
2915       }
2916     } else if (IsMediumCM) {
2917       CmdArgs.push_back("-mlarge-data-threshold=65536");
2918     } else if (IsLargeCM) {
2919       CmdArgs.push_back("-mlarge-data-threshold=0");
2920     }
2921   }
2922 }
2923