clang  16.0.0git
CommonArgs.cpp
Go to the documentation of this file.
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/M68k.h"
13 #include "Arch/Mips.h"
14 #include "Arch/PPC.h"
15 #include "Arch/Sparc.h"
16 #include "Arch/SystemZ.h"
17 #include "Arch/VE.h"
18 #include "Arch/X86.h"
19 #include "HIPAMD.h"
20 #include "Hexagon.h"
21 #include "clang/Basic/CharInfo.h"
24 #include "clang/Basic/Version.h"
25 #include "clang/Config/config.h"
26 #include "clang/Driver/Action.h"
28 #include "clang/Driver/Driver.h"
30 #include "clang/Driver/InputInfo.h"
31 #include "clang/Driver/Job.h"
32 #include "clang/Driver/Options.h"
34 #include "clang/Driver/ToolChain.h"
35 #include "clang/Driver/Util.h"
36 #include "clang/Driver/XRayArgs.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/ADT/Twine.h"
43 #include "llvm/BinaryFormat/Magic.h"
44 #include "llvm/Config/llvm-config.h"
45 #include "llvm/Option/Arg.h"
46 #include "llvm/Option/ArgList.h"
47 #include "llvm/Option/Option.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/Compression.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Host.h"
54 #include "llvm/Support/Path.h"
55 #include "llvm/Support/Process.h"
56 #include "llvm/Support/Program.h"
57 #include "llvm/Support/ScopedPrinter.h"
58 #include "llvm/Support/TargetParser.h"
59 #include "llvm/Support/Threading.h"
60 #include "llvm/Support/VirtualFileSystem.h"
61 #include "llvm/Support/YAMLParser.h"
62 
63 using namespace clang::driver;
64 using namespace clang::driver::tools;
65 using namespace clang;
66 using namespace llvm::opt;
67 
68 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
69  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
70  CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=-pass-remarks=") +
71  A->getValue()));
72 
73  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
74  CmdArgs.push_back(Args.MakeArgString(
75  Twine("-plugin-opt=-pass-remarks-missed=") + A->getValue()));
76 
77  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
78  CmdArgs.push_back(Args.MakeArgString(
79  Twine("-plugin-opt=-pass-remarks-analysis=") + A->getValue()));
80 }
81 
82 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
83  const llvm::Triple &Triple,
84  const InputInfo &Input,
85  const InputInfo &Output) {
86  StringRef Format = "yaml";
87  if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
88  Format = A->getValue();
89 
91  const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
92  if (A)
93  F = A->getValue();
94  else if (Output.isFilename())
95  F = Output.getFilename();
96 
97  assert(!F.empty() && "Cannot determine remarks output name.");
98  // Append "opt.ld.<format>" to the end of the file name.
99  CmdArgs.push_back(
100  Args.MakeArgString(Twine("-plugin-opt=opt-remarks-filename=") + F +
101  Twine(".opt.ld.") + Format));
102 
103  if (const Arg *A =
104  Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
105  CmdArgs.push_back(Args.MakeArgString(
106  Twine("-plugin-opt=opt-remarks-passes=") + A->getValue()));
107 
108  CmdArgs.push_back(Args.MakeArgString(
109  Twine("-plugin-opt=opt-remarks-format=") + Format.data()));
110 }
111 
112 static void renderRemarksHotnessOptions(const ArgList &Args,
113  ArgStringList &CmdArgs) {
114  if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
115  options::OPT_fno_diagnostics_show_hotness, false))
116  CmdArgs.push_back("-plugin-opt=opt-remarks-with-hotness");
117 
118  if (const Arg *A =
119  Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
120  CmdArgs.push_back(Args.MakeArgString(
121  Twine("-plugin-opt=opt-remarks-hotness-threshold=") + A->getValue()));
122 }
123 
124 void tools::addPathIfExists(const Driver &D, const Twine &Path,
125  ToolChain::path_list &Paths) {
126  if (D.getVFS().exists(Path))
127  Paths.push_back(Path.str());
128 }
129 
130 void tools::handleTargetFeaturesGroup(const ArgList &Args,
131  std::vector<StringRef> &Features,
132  OptSpecifier Group) {
133  for (const Arg *A : Args.filtered(Group)) {
134  StringRef Name = A->getOption().getName();
135  A->claim();
136 
137  // Skip over "-m".
138  assert(Name.startswith("m") && "Invalid feature name.");
139  Name = Name.substr(1);
140 
141  bool IsNegative = Name.startswith("no-");
142  if (IsNegative)
143  Name = Name.substr(3);
144  Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
145  }
146 }
147 
148 SmallVector<StringRef>
150  // Only add a feature if it hasn't been seen before starting from the end.
151  SmallVector<StringRef> UnifiedFeatures;
152  llvm::DenseSet<StringRef> UsedFeatures;
153  for (StringRef Feature : llvm::reverse(Features)) {
154  if (UsedFeatures.insert(Feature.drop_front()).second)
155  UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature);
156  }
157 
158  return UnifiedFeatures;
159 }
160 
161 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
162  const char *ArgName, const char *EnvVar) {
163  const char *DirList = ::getenv(EnvVar);
164  bool CombinedArg = false;
165 
166  if (!DirList)
167  return; // Nothing to do.
168 
169  StringRef Name(ArgName);
170  if (Name.equals("-I") || Name.equals("-L") || Name.empty())
171  CombinedArg = true;
172 
173  StringRef Dirs(DirList);
174  if (Dirs.empty()) // Empty string should not add '.'.
175  return;
176 
177  StringRef::size_type Delim;
178  while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
179  if (Delim == 0) { // Leading colon.
180  if (CombinedArg) {
181  CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
182  } else {
183  CmdArgs.push_back(ArgName);
184  CmdArgs.push_back(".");
185  }
186  } else {
187  if (CombinedArg) {
188  CmdArgs.push_back(
189  Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
190  } else {
191  CmdArgs.push_back(ArgName);
192  CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
193  }
194  }
195  Dirs = Dirs.substr(Delim + 1);
196  }
197 
198  if (Dirs.empty()) { // Trailing colon.
199  if (CombinedArg) {
200  CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
201  } else {
202  CmdArgs.push_back(ArgName);
203  CmdArgs.push_back(".");
204  }
205  } else { // Add the last path.
206  if (CombinedArg) {
207  CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
208  } else {
209  CmdArgs.push_back(ArgName);
210  CmdArgs.push_back(Args.MakeArgString(Dirs));
211  }
212  }
213 }
214 
215 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
216  const ArgList &Args, ArgStringList &CmdArgs,
217  const JobAction &JA) {
218  const Driver &D = TC.getDriver();
219 
220  // Add extra linker input arguments which are not treated as inputs
221  // (constructed via -Xarch_).
222  Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
223 
224  // LIBRARY_PATH are included before user inputs and only supported on native
225  // toolchains.
226  if (!TC.isCrossCompiling())
227  addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
228 
229  for (const auto &II : Inputs) {
230  // If the current tool chain refers to an OpenMP offloading host, we
231  // should ignore inputs that refer to OpenMP offloading devices -
232  // they will be embedded according to a proper linker script.
233  if (auto *IA = II.getAction())
235  IA->isDeviceOffloading(Action::OFK_OpenMP)))
236  continue;
237 
238  if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
239  // Don't try to pass LLVM inputs unless we have native support.
240  D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
241 
242  // Add filenames immediately.
243  if (II.isFilename()) {
244  CmdArgs.push_back(II.getFilename());
245  continue;
246  }
247 
248  // In some error cases, the input could be Nothing; skip those.
249  if (II.isNothing())
250  continue;
251 
252  // Otherwise, this is a linker input argument.
253  const Arg &A = II.getInputArg();
254 
255  // Handle reserved library options.
256  if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
257  TC.AddCXXStdlibLibArgs(Args, CmdArgs);
258  else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
259  TC.AddCCKextLibArgs(Args, CmdArgs);
260  else if (A.getOption().matches(options::OPT_z)) {
261  // Pass -z prefix for gcc linker compatibility.
262  A.claim();
263  A.render(Args, CmdArgs);
264  } else if (A.getOption().matches(options::OPT_b)) {
265  const llvm::Triple &T = TC.getTriple();
266  if (!T.isOSAIX()) {
267  TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
268  << A.getSpelling() << T.str();
269  }
270  // Pass -b prefix for AIX linker.
271  A.claim();
272  A.render(Args, CmdArgs);
273  } else {
274  A.renderAsInput(Args, CmdArgs);
275  }
276  }
277 }
278 
280  const ToolChain &TC, const llvm::opt::ArgList &Args,
281  llvm::opt::ArgStringList &CmdArgs) {
282  // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
283  // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
284  // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
285  // is not translated since ld --compress-debug-sections option requires an
286  // argument.
287  if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
288  StringRef V = A->getValue();
289  if (V == "none" || V == "zlib" || V == "zstd")
290  CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
291  else
292  TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
293  << A->getOption().getName() << V;
294  }
295 }
296 
297 void tools::AddTargetFeature(const ArgList &Args,
298  std::vector<StringRef> &Features,
299  OptSpecifier OnOpt, OptSpecifier OffOpt,
300  StringRef FeatureName) {
301  if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
302  if (A->getOption().matches(OnOpt))
303  Features.push_back(Args.MakeArgString("+" + FeatureName));
304  else
305  Features.push_back(Args.MakeArgString("-" + FeatureName));
306  }
307 }
308 
309 /// Get the (LLVM) name of the AMDGPU gpu we are targeting.
310 static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
311  const ArgList &Args) {
312  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
313  auto GPUName = getProcessorFromTargetID(T, A->getValue());
314  return llvm::StringSwitch<std::string>(GPUName)
315  .Cases("rv630", "rv635", "r600")
316  .Cases("rv610", "rv620", "rs780", "rs880")
317  .Case("rv740", "rv770")
318  .Case("palm", "cedar")
319  .Cases("sumo", "sumo2", "sumo")
320  .Case("hemlock", "cypress")
321  .Case("aruba", "cayman")
322  .Default(GPUName.str());
323  }
324  return "";
325 }
326 
327 static std::string getLanaiTargetCPU(const ArgList &Args) {
328  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
329  return A->getValue();
330  }
331  return "";
332 }
333 
334 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
335 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
336  // If we have -mcpu=, use that.
337  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
338  StringRef CPU = A->getValue();
339 
340 #ifdef __wasm__
341  // Handle "native" by examining the host. "native" isn't meaningful when
342  // cross compiling, so only support this when the host is also WebAssembly.
343  if (CPU == "native")
344  return llvm::sys::getHostCPUName();
345 #endif
346 
347  return CPU;
348  }
349 
350  return "generic";
351 }
352 
353 std::string tools::getCPUName(const Driver &D, const ArgList &Args,
354  const llvm::Triple &T, bool FromAs) {
355  Arg *A;
356 
357  switch (T.getArch()) {
358  default:
359  return "";
360 
361  case llvm::Triple::aarch64:
362  case llvm::Triple::aarch64_32:
363  case llvm::Triple::aarch64_be:
364  return aarch64::getAArch64TargetCPU(Args, T, A);
365 
366  case llvm::Triple::arm:
367  case llvm::Triple::armeb:
368  case llvm::Triple::thumb:
369  case llvm::Triple::thumbeb: {
370  StringRef MArch, MCPU;
371  arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
372  return arm::getARMTargetCPU(MCPU, MArch, T);
373  }
374 
375  case llvm::Triple::avr:
376  if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
377  return A->getValue();
378  return "";
379 
380  case llvm::Triple::m68k:
381  return m68k::getM68kTargetCPU(Args);
382 
383  case llvm::Triple::mips:
384  case llvm::Triple::mipsel:
385  case llvm::Triple::mips64:
386  case llvm::Triple::mips64el: {
387  StringRef CPUName;
388  StringRef ABIName;
389  mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
390  return std::string(CPUName);
391  }
392 
393  case llvm::Triple::nvptx:
394  case llvm::Triple::nvptx64:
395  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
396  return A->getValue();
397  return "";
398 
399  case llvm::Triple::ppc:
400  case llvm::Triple::ppcle:
401  case llvm::Triple::ppc64:
402  case llvm::Triple::ppc64le: {
403  std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
404  // LLVM may default to generating code for the native CPU,
405  // but, like gcc, we default to a more generic option for
406  // each architecture. (except on AIX)
407  if (!TargetCPUName.empty())
408  return TargetCPUName;
409 
410  if (T.isOSAIX())
411  TargetCPUName = "pwr7";
412  else if (T.getArch() == llvm::Triple::ppc64le)
413  TargetCPUName = "ppc64le";
414  else if (T.getArch() == llvm::Triple::ppc64)
415  TargetCPUName = "ppc64";
416  else
417  TargetCPUName = "ppc";
418 
419  return TargetCPUName;
420  }
421  case llvm::Triple::csky:
422  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
423  return A->getValue();
424  else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
425  return A->getValue();
426  else
427  return "ck810";
428  case llvm::Triple::riscv32:
429  case llvm::Triple::riscv64:
430  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
431  return A->getValue();
432  return "";
433 
434  case llvm::Triple::bpfel:
435  case llvm::Triple::bpfeb:
436  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
437  return A->getValue();
438  return "";
439 
440  case llvm::Triple::sparc:
441  case llvm::Triple::sparcel:
442  case llvm::Triple::sparcv9:
443  return sparc::getSparcTargetCPU(D, Args, T);
444 
445  case llvm::Triple::x86:
446  case llvm::Triple::x86_64:
447  return x86::getX86TargetCPU(D, Args, T);
448 
449  case llvm::Triple::hexagon:
450  return "hexagon" +
452 
453  case llvm::Triple::lanai:
454  return getLanaiTargetCPU(Args);
455 
456  case llvm::Triple::systemz:
457  return systemz::getSystemZTargetCPU(Args);
458 
459  case llvm::Triple::r600:
460  case llvm::Triple::amdgcn:
461  return getAMDGPUTargetGPU(T, Args);
462 
463  case llvm::Triple::wasm32:
464  case llvm::Triple::wasm64:
465  return std::string(getWebAssemblyTargetCPU(Args));
466  }
467 }
468 
469 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
470  Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
471  if (!LtoJobsArg)
472  return {};
473  if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
474  D.Diag(diag::err_drv_invalid_int_value)
475  << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
476  return LtoJobsArg->getValue();
477 }
478 
479 // CloudABI and PS4/PS5 use -ffunction-sections and -fdata-sections by default.
480 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
481  return Triple.getOS() == llvm::Triple::CloudABI || Triple.isPS();
482 }
483 
484 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
485  ArgStringList &CmdArgs, const InputInfo &Output,
486  const InputInfo &Input, bool IsThinLTO) {
487  const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
488  const Driver &D = ToolChain.getDriver();
489  if (llvm::sys::path::filename(Linker) != "ld.lld" &&
490  llvm::sys::path::stem(Linker) != "ld.lld") {
491  // Tell the linker to load the plugin. This has to come before
492  // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
493  // that -Wl might forward.
494  CmdArgs.push_back("-plugin");
495 
496 #if defined(_WIN32)
497  const char *Suffix = ".dll";
498 #elif defined(__APPLE__)
499  const char *Suffix = ".dylib";
500 #else
501  const char *Suffix = ".so";
502 #endif
503 
504  SmallString<1024> Plugin;
505  llvm::sys::path::native(
506  Twine(D.Dir) + "/../" CLANG_INSTALL_LIBDIR_BASENAME "/LLVMgold" +
507  Suffix,
508  Plugin);
509  CmdArgs.push_back(Args.MakeArgString(Plugin));
510  }
511 
512  // Note, this solution is far from perfect, better to encode it into IR
513  // metadata, but this may not be worth it, since it looks like aranges is on
514  // the way out.
515  if (Args.hasArg(options::OPT_gdwarf_aranges)) {
516  CmdArgs.push_back(
517  Args.MakeArgString("--plugin-opt=-generate-arange-section"));
518  }
519 
520  // Try to pass driver level flags relevant to LTO code generation down to
521  // the plugin.
522 
523  // Handle flags for selecting CPU variants.
524  std::string CPU = getCPUName(D, Args, ToolChain.getTriple());
525  if (!CPU.empty())
526  CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
527 
528  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
529  // The optimization level matches
530  // CompilerInvocation.cpp:getOptimizationLevel().
531  StringRef OOpt;
532  if (A->getOption().matches(options::OPT_O4) ||
533  A->getOption().matches(options::OPT_Ofast))
534  OOpt = "3";
535  else if (A->getOption().matches(options::OPT_O)) {
536  OOpt = A->getValue();
537  if (OOpt == "g")
538  OOpt = "1";
539  else if (OOpt == "s" || OOpt == "z")
540  OOpt = "2";
541  } else if (A->getOption().matches(options::OPT_O0))
542  OOpt = "0";
543  if (!OOpt.empty())
544  CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
545  }
546 
547  if (Args.hasArg(options::OPT_gsplit_dwarf)) {
548  CmdArgs.push_back(
549  Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
550  Output.getFilename() + "_dwo"));
551  }
552 
553  if (IsThinLTO)
554  CmdArgs.push_back("-plugin-opt=thinlto");
555 
556  StringRef Parallelism = getLTOParallelism(Args, D);
557  if (!Parallelism.empty())
558  CmdArgs.push_back(
559  Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
560 
561  if (!CLANG_ENABLE_OPAQUE_POINTERS_INTERNAL)
562  CmdArgs.push_back(Args.MakeArgString("-plugin-opt=no-opaque-pointers"));
563 
564  // If an explicit debugger tuning argument appeared, pass it along.
565  if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
566  options::OPT_ggdbN_Group)) {
567  if (A->getOption().matches(options::OPT_glldb))
568  CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
569  else if (A->getOption().matches(options::OPT_gsce))
570  CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
571  else if (A->getOption().matches(options::OPT_gdbx))
572  CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx");
573  else
574  CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
575  }
576 
577  bool UseSeparateSections =
579 
580  if (Args.hasFlag(options::OPT_ffunction_sections,
581  options::OPT_fno_function_sections, UseSeparateSections))
582  CmdArgs.push_back("-plugin-opt=-function-sections=1");
583  else if (Args.hasArg(options::OPT_fno_function_sections))
584  CmdArgs.push_back("-plugin-opt=-function-sections=0");
585 
586  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
587  UseSeparateSections))
588  CmdArgs.push_back("-plugin-opt=-data-sections=1");
589  else if (Args.hasArg(options::OPT_fno_data_sections))
590  CmdArgs.push_back("-plugin-opt=-data-sections=0");
591 
592  // Pass an option to enable split machine functions.
593  if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
594  options::OPT_fno_split_machine_functions)) {
595  if (A->getOption().matches(options::OPT_fsplit_machine_functions))
596  CmdArgs.push_back("-plugin-opt=-split-machine-functions");
597  }
598 
599  if (Arg *A = getLastProfileSampleUseArg(Args)) {
600  StringRef FName = A->getValue();
601  if (!llvm::sys::fs::exists(FName))
602  D.Diag(diag::err_drv_no_such_file) << FName;
603  else
604  CmdArgs.push_back(
605  Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
606  }
607 
608  auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
609  options::OPT_fcs_profile_generate_EQ,
610  options::OPT_fno_profile_generate);
611  if (CSPGOGenerateArg &&
612  CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
613  CSPGOGenerateArg = nullptr;
614 
615  auto *ProfileUseArg = getLastProfileUseArg(Args);
616 
617  if (CSPGOGenerateArg) {
618  CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
619  if (CSPGOGenerateArg->getOption().matches(
620  options::OPT_fcs_profile_generate_EQ)) {
621  SmallString<128> Path(CSPGOGenerateArg->getValue());
622  llvm::sys::path::append(Path, "default_%m.profraw");
623  CmdArgs.push_back(
624  Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
625  } else
626  CmdArgs.push_back(
627  Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
628  } else if (ProfileUseArg) {
629  SmallString<128> Path(
630  ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
631  if (Path.empty() || llvm::sys::fs::is_directory(Path))
632  llvm::sys::path::append(Path, "default.profdata");
633  CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
634  Path));
635  }
636 
637  // This controls whether or not we perform JustMyCode instrumentation.
638  if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
639  if (ToolChain.getEffectiveTriple().isOSBinFormatELF())
640  CmdArgs.push_back("-plugin-opt=-enable-jmc-instrument");
641  else
642  D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
643  }
644 
645  // Setup statistics file output.
646  SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
647  if (!StatsFile.empty())
648  CmdArgs.push_back(
649  Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
650 
651  // Setup crash diagnostics dir.
652  if (Arg *A = Args.getLastArg(options::OPT_fcrash_diagnostics_dir))
653  CmdArgs.push_back(Args.MakeArgString(
654  Twine("-plugin-opt=-crash-diagnostics-dir=") + A->getValue()));
655 
656  addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true);
657 
658  // Handle remark diagnostics on screen options: '-Rpass-*'.
659  renderRpassOptions(Args, CmdArgs);
660 
661  // Handle serialized remarks options: '-fsave-optimization-record'
662  // and '-foptimization-record-*'.
663  if (willEmitRemarks(Args))
664  renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
665  Output);
666 
667  // Handle remarks hotness/threshold related options.
668  renderRemarksHotnessOptions(Args, CmdArgs);
669 
671  /*IsLTO=*/true);
672 }
673 
675  const ArgList &Args,
676  ArgStringList &CmdArgs) {
677 
678  if (Args.hasFlag(options::OPT_fopenmp_implicit_rpath,
679  options::OPT_fno_openmp_implicit_rpath, true)) {
680  // Default to clang lib / lib64 folder, i.e. the same location as device
681  // runtime
682  SmallString<256> DefaultLibPath =
683  llvm::sys::path::parent_path(TC.getDriver().Dir);
684  llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
685  CmdArgs.push_back("-rpath");
686  CmdArgs.push_back(Args.MakeArgString(DefaultLibPath));
687  }
688 }
689 
691  const ArgList &Args,
692  ArgStringList &CmdArgs) {
693  // Default to clang lib / lib64 folder, i.e. the same location as device
694  // runtime.
695  SmallString<256> DefaultLibPath =
696  llvm::sys::path::parent_path(TC.getDriver().Dir);
697  llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
698  CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
699 }
700 
701 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
702  ArgStringList &CmdArgs) {
703  // Enable -frtlib-add-rpath by default for the case of VE.
704  const bool IsVE = TC.getTriple().isVE();
705  bool DefaultValue = IsVE;
706  if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
707  options::OPT_fno_rtlib_add_rpath, DefaultValue))
708  return;
709 
710  std::string CandidateRPath = TC.getArchSpecificLibPath();
711  if (TC.getVFS().exists(CandidateRPath)) {
712  CmdArgs.push_back("-rpath");
713  CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
714  }
715 }
716 
717 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
718  const ArgList &Args, bool ForceStaticHostRuntime,
719  bool IsOffloadingHost, bool GompNeedsRT) {
720  if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
721  options::OPT_fno_openmp, false))
722  return false;
723 
725 
726  if (RTKind == Driver::OMPRT_Unknown)
727  // Already diagnosed.
728  return false;
729 
730  if (ForceStaticHostRuntime)
731  CmdArgs.push_back("-Bstatic");
732 
733  switch (RTKind) {
734  case Driver::OMPRT_OMP:
735  CmdArgs.push_back("-lomp");
736  break;
737  case Driver::OMPRT_GOMP:
738  CmdArgs.push_back("-lgomp");
739  break;
740  case Driver::OMPRT_IOMP5:
741  CmdArgs.push_back("-liomp5");
742  break;
744  break;
745  }
746 
747  if (ForceStaticHostRuntime)
748  CmdArgs.push_back("-Bdynamic");
749 
750  if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
751  CmdArgs.push_back("-lrt");
752 
753  if (IsOffloadingHost)
754  CmdArgs.push_back("-lomptarget");
755 
756  if (IsOffloadingHost && TC.getDriver().isUsingLTO(/* IsOffload */ true) &&
757  !Args.hasArg(options::OPT_nogpulib))
758  CmdArgs.push_back("-lomptarget.devicertl");
759 
760  addArchSpecificRPath(TC, Args, CmdArgs);
761 
762  if (RTKind == Driver::OMPRT_OMP)
763  addOpenMPRuntimeSpecificRPath(TC, Args, CmdArgs);
764  addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
765 
766  return true;
767 }
768 
770  llvm::opt::ArgStringList &CmdArgs) {
771  if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
772  CmdArgs.push_back("Fortran_main.lib");
773  CmdArgs.push_back("FortranRuntime.lib");
774  CmdArgs.push_back("FortranDecimal.lib");
775  } else {
776  CmdArgs.push_back("-lFortran_main");
777  CmdArgs.push_back("-lFortranRuntime");
778  CmdArgs.push_back("-lFortranDecimal");
779  }
780 }
781 
783  const llvm::opt::ArgList &Args,
784  ArgStringList &CmdArgs) {
785  // NOTE: Generating executables by Flang is considered an "experimental"
786  // feature and hence this is guarded with a command line option.
787  // TODO: Make this work unconditionally once Flang is mature enough.
788  if (!Args.hasArg(options::OPT_flang_experimental_exec))
789  return;
790 
791  // Default to the <driver-path>/../lib directory. This works fine on the
792  // platforms that we have tested so far. We will probably have to re-fine
793  // this in the future. In particular, on some platforms, we may need to use
794  // lib64 instead of lib.
795  SmallString<256> DefaultLibPath =
796  llvm::sys::path::parent_path(TC.getDriver().Dir);
797  llvm::sys::path::append(DefaultLibPath, "lib");
798  if (TC.getTriple().isKnownWindowsMSVCEnvironment())
799  CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
800  else
801  CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
802 }
803 
804 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
805  ArgStringList &CmdArgs, StringRef Sanitizer,
806  bool IsShared, bool IsWhole) {
807  // Wrap any static runtimes that must be forced into executable in
808  // whole-archive.
809  if (IsWhole) CmdArgs.push_back("--whole-archive");
810  CmdArgs.push_back(TC.getCompilerRTArgString(
811  Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
812  if (IsWhole) CmdArgs.push_back("--no-whole-archive");
813 
814  if (IsShared) {
815  addArchSpecificRPath(TC, Args, CmdArgs);
816  }
817 }
818 
819 // Tries to use a file with the list of dynamic symbols that need to be exported
820 // from the runtime library. Returns true if the file was found.
821 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
822  ArgStringList &CmdArgs,
823  StringRef Sanitizer) {
824  // Solaris ld defaults to --export-dynamic behaviour but doesn't support
825  // the option, so don't try to pass it.
826  if (TC.getTriple().getOS() == llvm::Triple::Solaris)
827  return true;
828  SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
829  if (llvm::sys::fs::exists(SanRT + ".syms")) {
830  CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
831  return true;
832  }
833  return false;
834 }
835 
836 const char *tools::getAsNeededOption(const ToolChain &TC, bool as_needed) {
837  assert(!TC.getTriple().isOSAIX() &&
838  "AIX linker does not support any form of --as-needed option yet.");
839 
840  // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
841  // for the native forms -z ignore/-z record, they are missing in Illumos,
842  // so always use the native form.
843  if (TC.getTriple().isOSSolaris())
844  return as_needed ? "-zignore" : "-zrecord";
845  else
846  return as_needed ? "--as-needed" : "--no-as-needed";
847 }
848 
850  ArgStringList &CmdArgs) {
851  // Force linking against the system libraries sanitizers depends on
852  // (see PR15823 why this is necessary).
853  CmdArgs.push_back(getAsNeededOption(TC, false));
854  // There's no libpthread or librt on RTEMS & Android.
855  if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
856  !TC.getTriple().isAndroid()) {
857  CmdArgs.push_back("-lpthread");
858  if (!TC.getTriple().isOSOpenBSD())
859  CmdArgs.push_back("-lrt");
860  }
861  CmdArgs.push_back("-lm");
862  // There's no libdl on all OSes.
863  if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
864  !TC.getTriple().isOSOpenBSD() &&
865  TC.getTriple().getOS() != llvm::Triple::RTEMS)
866  CmdArgs.push_back("-ldl");
867  // Required for backtrace on some OSes
868  if (TC.getTriple().isOSFreeBSD() ||
869  TC.getTriple().isOSNetBSD() ||
870  TC.getTriple().isOSOpenBSD())
871  CmdArgs.push_back("-lexecinfo");
872  // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
873  // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
874  // requirement.
875  if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
876  !TC.getTriple().isMusl())
877  CmdArgs.push_back("-lresolv");
878 }
879 
880 static void
881 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
882  SmallVectorImpl<StringRef> &SharedRuntimes,
883  SmallVectorImpl<StringRef> &StaticRuntimes,
884  SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
885  SmallVectorImpl<StringRef> &HelperStaticRuntimes,
886  SmallVectorImpl<StringRef> &RequiredSymbols) {
887  const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
888  // Collect shared runtimes.
889  if (SanArgs.needsSharedRt()) {
890  if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
891  SharedRuntimes.push_back("asan");
892  if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
893  HelperStaticRuntimes.push_back("asan-preinit");
894  }
895  if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
896  SharedRuntimes.push_back("memprof");
897  if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
898  HelperStaticRuntimes.push_back("memprof-preinit");
899  }
900  if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
901  if (SanArgs.requiresMinimalRuntime())
902  SharedRuntimes.push_back("ubsan_minimal");
903  else
904  SharedRuntimes.push_back("ubsan_standalone");
905  }
906  if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
907  if (SanArgs.requiresMinimalRuntime())
908  SharedRuntimes.push_back("scudo_minimal");
909  else
910  SharedRuntimes.push_back("scudo");
911  }
912  if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
913  SharedRuntimes.push_back("tsan");
914  if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
915  if (SanArgs.needsHwasanAliasesRt())
916  SharedRuntimes.push_back("hwasan_aliases");
917  else
918  SharedRuntimes.push_back("hwasan");
919  if (!Args.hasArg(options::OPT_shared))
920  HelperStaticRuntimes.push_back("hwasan-preinit");
921  }
922  }
923 
924  // The stats_client library is also statically linked into DSOs.
925  if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
926  StaticRuntimes.push_back("stats_client");
927 
928  // Always link the static runtime regardless of DSO or executable.
929  if (SanArgs.needsAsanRt())
930  HelperStaticRuntimes.push_back("asan_static");
931 
932  // Collect static runtimes.
933  if (Args.hasArg(options::OPT_shared)) {
934  // Don't link static runtimes into DSOs.
935  return;
936  }
937 
938  // Each static runtime that has a DSO counterpart above is excluded below,
939  // but runtimes that exist only as static are not affected by needsSharedRt.
940 
941  if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
942  StaticRuntimes.push_back("asan");
943  if (SanArgs.linkCXXRuntimes())
944  StaticRuntimes.push_back("asan_cxx");
945  }
946 
947  if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
948  SanArgs.linkRuntimes()) {
949  StaticRuntimes.push_back("memprof");
950  if (SanArgs.linkCXXRuntimes())
951  StaticRuntimes.push_back("memprof_cxx");
952  }
953 
954  if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
955  if (SanArgs.needsHwasanAliasesRt()) {
956  StaticRuntimes.push_back("hwasan_aliases");
957  if (SanArgs.linkCXXRuntimes())
958  StaticRuntimes.push_back("hwasan_aliases_cxx");
959  } else {
960  StaticRuntimes.push_back("hwasan");
961  if (SanArgs.linkCXXRuntimes())
962  StaticRuntimes.push_back("hwasan_cxx");
963  }
964  }
965  if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
966  StaticRuntimes.push_back("dfsan");
967  if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
968  StaticRuntimes.push_back("lsan");
969  if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
970  StaticRuntimes.push_back("msan");
971  if (SanArgs.linkCXXRuntimes())
972  StaticRuntimes.push_back("msan_cxx");
973  }
974  if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
975  SanArgs.linkRuntimes()) {
976  StaticRuntimes.push_back("tsan");
977  if (SanArgs.linkCXXRuntimes())
978  StaticRuntimes.push_back("tsan_cxx");
979  }
980  if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
981  if (SanArgs.requiresMinimalRuntime()) {
982  StaticRuntimes.push_back("ubsan_minimal");
983  } else {
984  StaticRuntimes.push_back("ubsan_standalone");
985  if (SanArgs.linkCXXRuntimes())
986  StaticRuntimes.push_back("ubsan_standalone_cxx");
987  }
988  }
989  if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
990  NonWholeStaticRuntimes.push_back("safestack");
991  RequiredSymbols.push_back("__safestack_init");
992  }
993  if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
994  if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
995  StaticRuntimes.push_back("cfi");
996  if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
997  StaticRuntimes.push_back("cfi_diag");
998  if (SanArgs.linkCXXRuntimes())
999  StaticRuntimes.push_back("ubsan_standalone_cxx");
1000  }
1001  }
1002  if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
1003  NonWholeStaticRuntimes.push_back("stats");
1004  RequiredSymbols.push_back("__sanitizer_stats_register");
1005  }
1006  if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
1007  if (SanArgs.requiresMinimalRuntime()) {
1008  StaticRuntimes.push_back("scudo_minimal");
1009  if (SanArgs.linkCXXRuntimes())
1010  StaticRuntimes.push_back("scudo_cxx_minimal");
1011  } else {
1012  StaticRuntimes.push_back("scudo");
1013  if (SanArgs.linkCXXRuntimes())
1014  StaticRuntimes.push_back("scudo_cxx");
1015  }
1016  }
1017 }
1018 
1019 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
1020 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
1021 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1022  ArgStringList &CmdArgs) {
1023  SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
1024  NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
1025  collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1026  NonWholeStaticRuntimes, HelperStaticRuntimes,
1027  RequiredSymbols);
1028 
1029  const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1030  // Inject libfuzzer dependencies.
1031  if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1032  !Args.hasArg(options::OPT_shared)) {
1033 
1034  addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
1035  if (SanArgs.needsFuzzerInterceptors())
1036  addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
1037  true);
1038  if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
1039  bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
1040  !Args.hasArg(options::OPT_static);
1041  if (OnlyLibstdcxxStatic)
1042  CmdArgs.push_back("-Bstatic");
1043  TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1044  if (OnlyLibstdcxxStatic)
1045  CmdArgs.push_back("-Bdynamic");
1046  }
1047  }
1048 
1049  for (auto RT : SharedRuntimes)
1050  addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
1051  for (auto RT : HelperStaticRuntimes)
1052  addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1053  bool AddExportDynamic = false;
1054  for (auto RT : StaticRuntimes) {
1055  addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1056  AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1057  }
1058  for (auto RT : NonWholeStaticRuntimes) {
1059  addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1060  AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1061  }
1062  for (auto S : RequiredSymbols) {
1063  CmdArgs.push_back("-u");
1064  CmdArgs.push_back(Args.MakeArgString(S));
1065  }
1066  // If there is a static runtime with no dynamic list, force all the symbols
1067  // to be dynamic to be sure we export sanitizer interface functions.
1068  if (AddExportDynamic)
1069  CmdArgs.push_back("--export-dynamic");
1070 
1071  if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1072  CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1073 
1074  if (SanArgs.hasMemTag()) {
1075  if (!TC.getTriple().isAndroid()) {
1076  TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1077  << "-fsanitize=memtag*" << TC.getTriple().str();
1078  }
1079  CmdArgs.push_back(
1080  Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1081  if (SanArgs.hasMemtagHeap())
1082  CmdArgs.push_back("--android-memtag-heap");
1083  if (SanArgs.hasMemtagStack())
1084  CmdArgs.push_back("--android-memtag-stack");
1085  }
1086 
1087  return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1088 }
1089 
1090 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1091  if (Args.hasArg(options::OPT_shared))
1092  return false;
1093 
1094  if (TC.getXRayArgs().needsXRayRt()) {
1095  CmdArgs.push_back("-whole-archive");
1096  CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
1097  for (const auto &Mode : TC.getXRayArgs().modeList())
1098  CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
1099  CmdArgs.push_back("-no-whole-archive");
1100  return true;
1101  }
1102 
1103  return false;
1104 }
1105 
1106 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
1107  CmdArgs.push_back(getAsNeededOption(TC, false));
1108  CmdArgs.push_back("-lpthread");
1109  if (!TC.getTriple().isOSOpenBSD())
1110  CmdArgs.push_back("-lrt");
1111  CmdArgs.push_back("-lm");
1112 
1113  if (!TC.getTriple().isOSFreeBSD() &&
1114  !TC.getTriple().isOSNetBSD() &&
1115  !TC.getTriple().isOSOpenBSD())
1116  CmdArgs.push_back("-ldl");
1117 }
1118 
1119 bool tools::areOptimizationsEnabled(const ArgList &Args) {
1120  // Find the last -O arg and see if it is non-zero.
1121  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1122  return !A->getOption().matches(options::OPT_O0);
1123  // Defaults to -O0.
1124  return false;
1125 }
1126 
1127 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1128  const InputInfo &Input,
1129  const InputInfo &Output) {
1130  auto AddPostfix = [JA](auto &F) {
1132  F += (Twine("_") + JA.getOffloadingArch()).str();
1133  F += ".dwo";
1134  };
1135  if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1136  if (StringRef(A->getValue()) == "single")
1137  return Args.MakeArgString(Output.getFilename());
1138 
1139  Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1140  if (FinalOutput && Args.hasArg(options::OPT_c)) {
1141  SmallString<128> T(FinalOutput->getValue());
1142  llvm::sys::path::remove_filename(T);
1143  llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1144  AddPostfix(T);
1145  return Args.MakeArgString(T);
1146  } else {
1147  // Use the compilation dir.
1148  Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
1149  options::OPT_fdebug_compilation_dir_EQ);
1150  SmallString<128> T(A ? A->getValue() : "");
1151  SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1152  AddPostfix(F);
1153  T += F;
1154  return Args.MakeArgString(T);
1155  }
1156 }
1157 
1158 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1159  const JobAction &JA, const ArgList &Args,
1160  const InputInfo &Output, const char *OutFile) {
1161  ArgStringList ExtractArgs;
1162  ExtractArgs.push_back("--extract-dwo");
1163 
1164  ArgStringList StripArgs;
1165  StripArgs.push_back("--strip-dwo");
1166 
1167  // Grabbing the output of the earlier compile step.
1168  StripArgs.push_back(Output.getFilename());
1169  ExtractArgs.push_back(Output.getFilename());
1170  ExtractArgs.push_back(OutFile);
1171 
1172  const char *Exec =
1173  Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1174  InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1175 
1176  // First extract the dwo sections.
1177  C.addCommand(std::make_unique<Command>(JA, T,
1179  Exec, ExtractArgs, II, Output));
1180 
1181  // Then remove them from the original .o file.
1182  C.addCommand(std::make_unique<Command>(
1183  JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1184 }
1185 
1186 // Claim options we don't want to warn if they are unused. We do this for
1187 // options that build systems might add but are unused when assembling or only
1188 // running the preprocessor for example.
1189 void tools::claimNoWarnArgs(const ArgList &Args) {
1190  // Don't warn about unused -f(no-)?lto. This can happen when we're
1191  // preprocessing, precompiling or assembling.
1192  Args.ClaimAllArgs(options::OPT_flto_EQ);
1193  Args.ClaimAllArgs(options::OPT_flto);
1194  Args.ClaimAllArgs(options::OPT_fno_lto);
1195 }
1196 
1197 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1198  auto *ProfileUseArg = Args.getLastArg(
1199  options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1200  options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1201  options::OPT_fno_profile_instr_use);
1202 
1203  if (ProfileUseArg &&
1204  ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1205  ProfileUseArg = nullptr;
1206 
1207  return ProfileUseArg;
1208 }
1209 
1210 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1211  auto *ProfileSampleUseArg = Args.getLastArg(
1212  options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1213  options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1214  options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1215 
1216  if (ProfileSampleUseArg &&
1217  (ProfileSampleUseArg->getOption().matches(
1218  options::OPT_fno_profile_sample_use) ||
1219  ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1220  return nullptr;
1221 
1222  return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1223  options::OPT_fauto_profile_EQ);
1224 }
1225 
1226 const char *tools::RelocationModelName(llvm::Reloc::Model Model) {
1227  switch (Model) {
1228  case llvm::Reloc::Static:
1229  return "static";
1230  case llvm::Reloc::PIC_:
1231  return "pic";
1232  case llvm::Reloc::DynamicNoPIC:
1233  return "dynamic-no-pic";
1234  case llvm::Reloc::ROPI:
1235  return "ropi";
1236  case llvm::Reloc::RWPI:
1237  return "rwpi";
1238  case llvm::Reloc::ROPI_RWPI:
1239  return "ropi-rwpi";
1240  }
1241  llvm_unreachable("Unknown Reloc::Model kind");
1242 }
1243 
1244 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
1245 /// smooshes them together with platform defaults, to decide whether
1246 /// this compile should be using PIC mode or not. Returns a tuple of
1247 /// (RelocationModel, PICLevel, IsPIE).
1248 std::tuple<llvm::Reloc::Model, unsigned, bool>
1249 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1250  const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1251  const llvm::Triple &Triple = ToolChain.getTriple();
1252 
1253  bool PIE = ToolChain.isPIEDefault(Args);
1254  bool PIC = PIE || ToolChain.isPICDefault();
1255  // The Darwin/MachO default to use PIC does not apply when using -static.
1256  if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1257  PIE = PIC = false;
1258  bool IsPICLevelTwo = PIC;
1259 
1260  bool KernelOrKext =
1261  Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1262 
1263  // Android-specific defaults for PIC/PIE
1264  if (Triple.isAndroid()) {
1265  switch (Triple.getArch()) {
1266  case llvm::Triple::arm:
1267  case llvm::Triple::armeb:
1268  case llvm::Triple::thumb:
1269  case llvm::Triple::thumbeb:
1270  case llvm::Triple::aarch64:
1271  case llvm::Triple::mips:
1272  case llvm::Triple::mipsel:
1273  case llvm::Triple::mips64:
1274  case llvm::Triple::mips64el:
1275  PIC = true; // "-fpic"
1276  break;
1277 
1278  case llvm::Triple::x86:
1279  case llvm::Triple::x86_64:
1280  PIC = true; // "-fPIC"
1281  IsPICLevelTwo = true;
1282  break;
1283 
1284  default:
1285  break;
1286  }
1287  }
1288 
1289  // OpenBSD-specific defaults for PIE
1290  if (Triple.isOSOpenBSD()) {
1291  switch (ToolChain.getArch()) {
1292  case llvm::Triple::arm:
1293  case llvm::Triple::aarch64:
1294  case llvm::Triple::mips64:
1295  case llvm::Triple::mips64el:
1296  case llvm::Triple::x86:
1297  case llvm::Triple::x86_64:
1298  IsPICLevelTwo = false; // "-fpie"
1299  break;
1300 
1301  case llvm::Triple::ppc:
1302  case llvm::Triple::sparcv9:
1303  IsPICLevelTwo = true; // "-fPIE"
1304  break;
1305 
1306  default:
1307  break;
1308  }
1309  }
1310 
1311  // AMDGPU-specific defaults for PIC.
1312  if (Triple.getArch() == llvm::Triple::amdgcn)
1313  PIC = true;
1314 
1315  // The last argument relating to either PIC or PIE wins, and no
1316  // other argument is used. If the last argument is any flavor of the
1317  // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1318  // option implicitly enables PIC at the same level.
1319  Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1320  options::OPT_fpic, options::OPT_fno_pic,
1321  options::OPT_fPIE, options::OPT_fno_PIE,
1322  options::OPT_fpie, options::OPT_fno_pie);
1323  if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1324  LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1325  options::OPT_fPIE, options::OPT_fpie)) {
1326  ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1327  << LastPICArg->getSpelling() << Triple.str();
1328  if (Triple.getArch() == llvm::Triple::x86_64)
1329  return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1330  return std::make_tuple(llvm::Reloc::Static, 0U, false);
1331  }
1332 
1333  // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1334  // is forced, then neither PIC nor PIE flags will have no effect.
1335  if (!ToolChain.isPICDefaultForced()) {
1336  if (LastPICArg) {
1337  Option O = LastPICArg->getOption();
1338  if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1339  O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1340  PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1341  PIC =
1342  PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1343  IsPICLevelTwo =
1344  O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1345  } else {
1346  PIE = PIC = false;
1347  if (EffectiveTriple.isPS()) {
1348  Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1349  StringRef Model = ModelArg ? ModelArg->getValue() : "";
1350  if (Model != "kernel") {
1351  PIC = true;
1352  ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1353  << LastPICArg->getSpelling()
1354  << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1355  }
1356  }
1357  }
1358  }
1359  }
1360 
1361  // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1362  // the PIC level would've been set to level 1, force it back to level 2 PIC
1363  // instead.
1364  if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1365  IsPICLevelTwo |= ToolChain.isPICDefault();
1366 
1367  // This kernel flags are a trump-card: they will disable PIC/PIE
1368  // generation, independent of the argument order.
1369  if (KernelOrKext &&
1370  ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1371  !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1372  PIC = PIE = false;
1373 
1374  if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1375  // This is a very special mode. It trumps the other modes, almost no one
1376  // uses it, and it isn't even valid on any OS but Darwin.
1377  if (!Triple.isOSDarwin())
1378  ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1379  << A->getSpelling() << Triple.str();
1380 
1381  // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1382 
1383  // Only a forced PIC mode can cause the actual compile to have PIC defines
1384  // etc., no flags are sufficient. This behavior was selected to closely
1385  // match that of llvm-gcc and Apple GCC before that.
1387 
1388  return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1389  }
1390 
1391  bool EmbeddedPISupported;
1392  switch (Triple.getArch()) {
1393  case llvm::Triple::arm:
1394  case llvm::Triple::armeb:
1395  case llvm::Triple::thumb:
1396  case llvm::Triple::thumbeb:
1397  EmbeddedPISupported = true;
1398  break;
1399  default:
1400  EmbeddedPISupported = false;
1401  break;
1402  }
1403 
1404  bool ROPI = false, RWPI = false;
1405  Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1406  if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1407  if (!EmbeddedPISupported)
1408  ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1409  << LastROPIArg->getSpelling() << Triple.str();
1410  ROPI = true;
1411  }
1412  Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1413  if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1414  if (!EmbeddedPISupported)
1415  ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1416  << LastRWPIArg->getSpelling() << Triple.str();
1417  RWPI = true;
1418  }
1419 
1420  // ROPI and RWPI are not compatible with PIC or PIE.
1421  if ((ROPI || RWPI) && (PIC || PIE))
1422  ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1423 
1424  if (Triple.isMIPS()) {
1425  StringRef CPUName;
1426  StringRef ABIName;
1427  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1428  // When targeting the N64 ABI, PIC is the default, except in the case
1429  // when the -mno-abicalls option is used. In that case we exit
1430  // at next check regardless of PIC being set below.
1431  if (ABIName == "n64")
1432  PIC = true;
1433  // When targettng MIPS with -mno-abicalls, it's always static.
1434  if(Args.hasArg(options::OPT_mno_abicalls))
1435  return std::make_tuple(llvm::Reloc::Static, 0U, false);
1436  // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1437  // does not use PIC level 2 for historical reasons.
1438  IsPICLevelTwo = false;
1439  }
1440 
1441  if (PIC)
1442  return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1443 
1444  llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1445  if (ROPI && RWPI)
1446  RelocM = llvm::Reloc::ROPI_RWPI;
1447  else if (ROPI)
1448  RelocM = llvm::Reloc::ROPI;
1449  else if (RWPI)
1450  RelocM = llvm::Reloc::RWPI;
1451 
1452  return std::make_tuple(RelocM, 0U, false);
1453 }
1454 
1455 // `-falign-functions` indicates that the functions should be aligned to a
1456 // 16-byte boundary.
1457 //
1458 // `-falign-functions=1` is the same as `-fno-align-functions`.
1459 //
1460 // The scalar `n` in `-falign-functions=n` must be an integral value between
1461 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1462 // the nearest power-of-two.
1463 //
1464 // If we return `0`, the frontend will default to the backend's preferred
1465 // alignment.
1466 //
1467 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1468 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1469 // alignment. For unaligned functions, we default to the backend's preferred
1470 // alignment.
1471 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1472  const ArgList &Args) {
1473  const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1474  options::OPT_falign_functions_EQ,
1475  options::OPT_fno_align_functions);
1476  if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1477  return 0;
1478 
1479  if (A->getOption().matches(options::OPT_falign_functions))
1480  return 0;
1481 
1482  unsigned Value = 0;
1483  if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1484  TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1485  << A->getAsString(Args) << A->getValue();
1486  return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1487 }
1488 
1489 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1490  const ArgList &Args) {
1491  const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1492 
1493  if (!A)
1494  return 0;
1495 
1496  unsigned Value = 0;
1497  if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1498  Value < 2)
1499  TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1500  << A->getAsString(Args) << A->getValue();
1501  return Value;
1502 }
1503 
1504 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1505  ArgStringList &CmdArgs) {
1506  llvm::Reloc::Model RelocationModel;
1507  unsigned PICLevel;
1508  bool IsPIE;
1509  std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1510 
1511  if (RelocationModel != llvm::Reloc::Static)
1512  CmdArgs.push_back("-KPIC");
1513 }
1514 
1515 /// Determine whether Objective-C automated reference counting is
1516 /// enabled.
1517 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1518  return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1519 }
1520 
1522 
1523 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
1524  const ArgList &Args) {
1525  if (Args.hasArg(options::OPT_static_libgcc) ||
1526  Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
1527  // The Android NDK only provides libunwind.a, not libunwind.so.
1528  TC.getTriple().isAndroid())
1529  return LibGccType::StaticLibGcc;
1530  if (Args.hasArg(options::OPT_shared_libgcc))
1531  return LibGccType::SharedLibGcc;
1533 }
1534 
1535 // Gcc adds libgcc arguments in various ways:
1536 //
1537 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
1538 // g++ <none>: -lgcc_s -lgcc
1539 // gcc shared: -lgcc_s -lgcc
1540 // g++ shared: -lgcc_s -lgcc
1541 // gcc static: -lgcc -lgcc_eh
1542 // g++ static: -lgcc -lgcc_eh
1543 // gcc static-pie: -lgcc -lgcc_eh
1544 // g++ static-pie: -lgcc -lgcc_eh
1545 //
1546 // Also, certain targets need additional adjustments.
1547 
1548 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1549  ArgStringList &CmdArgs, const ArgList &Args) {
1551  // Targets that don't use unwind libraries.
1552  if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
1553  TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
1554  TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
1555  return;
1556 
1557  LibGccType LGT = getLibGccType(TC, D, Args);
1558  bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1559  (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
1560  !TC.getTriple().isAndroid() &&
1561  !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
1562  if (AsNeeded)
1563  CmdArgs.push_back(getAsNeededOption(TC, true));
1564 
1565  switch (UNW) {
1566  case ToolChain::UNW_None:
1567  return;
1568  case ToolChain::UNW_Libgcc: {
1569  if (LGT == LibGccType::StaticLibGcc)
1570  CmdArgs.push_back("-lgcc_eh");
1571  else
1572  CmdArgs.push_back("-lgcc_s");
1573  break;
1574  }
1576  if (TC.getTriple().isOSAIX()) {
1577  // AIX only has libunwind as a shared library. So do not pass
1578  // anything in if -static is specified.
1579  if (LGT != LibGccType::StaticLibGcc)
1580  CmdArgs.push_back("-lunwind");
1581  } else if (LGT == LibGccType::StaticLibGcc) {
1582  CmdArgs.push_back("-l:libunwind.a");
1583  } else if (LGT == LibGccType::SharedLibGcc) {
1584  if (TC.getTriple().isOSCygMing())
1585  CmdArgs.push_back("-l:libunwind.dll.a");
1586  else
1587  CmdArgs.push_back("-l:libunwind.so");
1588  } else {
1589  // Let the linker choose between libunwind.so and libunwind.a
1590  // depending on what's available, and depending on the -static flag
1591  CmdArgs.push_back("-lunwind");
1592  }
1593  break;
1594  }
1595 
1596  if (AsNeeded)
1597  CmdArgs.push_back(getAsNeededOption(TC, false));
1598 }
1599 
1600 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1601  ArgStringList &CmdArgs, const ArgList &Args) {
1602  LibGccType LGT = getLibGccType(TC, D, Args);
1603  if (LGT == LibGccType::StaticLibGcc ||
1604  (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
1605  CmdArgs.push_back("-lgcc");
1606  AddUnwindLibrary(TC, D, CmdArgs, Args);
1607  if (LGT == LibGccType::SharedLibGcc ||
1608  (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
1609  CmdArgs.push_back("-lgcc");
1610 }
1611 
1612 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1613  ArgStringList &CmdArgs, const ArgList &Args) {
1614  // Make use of compiler-rt if --rtlib option is used
1616 
1617  switch (RLT) {
1619  CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1620  AddUnwindLibrary(TC, D, CmdArgs, Args);
1621  break;
1622  case ToolChain::RLT_Libgcc:
1623  // Make sure libgcc is not used under MSVC environment by default
1624  if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1625  // Issue error diagnostic if libgcc is explicitly specified
1626  // through command line as --rtlib option argument.
1627  Arg *A = Args.getLastArg(options::OPT_rtlib_EQ);
1628  if (A && A->getValue() != StringRef("platform")) {
1629  TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1630  << A->getValue() << "MSVC";
1631  }
1632  } else
1633  AddLibgcc(TC, D, CmdArgs, Args);
1634  break;
1635  }
1636 
1637  // On Android, the unwinder uses dl_iterate_phdr (or one of
1638  // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
1639  // statically-linked executables, these functions come from libc.a instead.
1640  if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
1641  !Args.hasArg(options::OPT_static_pie))
1642  CmdArgs.push_back("-ldl");
1643 }
1644 
1645 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1646  const InputInfo &Output,
1647  const InputInfo &Input,
1648  const Driver &D) {
1649  const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1650  if (!A)
1651  return {};
1652 
1653  StringRef SaveStats = A->getValue();
1654  SmallString<128> StatsFile;
1655  if (SaveStats == "obj" && Output.isFilename()) {
1656  StatsFile.assign(Output.getFilename());
1657  llvm::sys::path::remove_filename(StatsFile);
1658  } else if (SaveStats != "cwd") {
1659  D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1660  return {};
1661  }
1662 
1663  StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1664  llvm::sys::path::append(StatsFile, BaseName);
1665  llvm::sys::path::replace_extension(StatsFile, "stats");
1666  return StatsFile;
1667 }
1668 
1669 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1670  Multilib::flags_list &Flags) {
1671  Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1672 }
1673 
1674 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1675  ArgStringList &CmdArgs, bool IsLTO) {
1676  auto addArg = [&, IsLTO](const Twine &Arg) {
1677  if (IsLTO) {
1678  CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1679  } else {
1680  CmdArgs.push_back("-mllvm");
1681  CmdArgs.push_back(Args.MakeArgString(Arg));
1682  }
1683  };
1684 
1685  if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1686  addArg(Twine("-x86-branches-within-32B-boundaries"));
1687  }
1688  if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1689  StringRef Value = A->getValue();
1690  unsigned Boundary;
1691  if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1692  !llvm::isPowerOf2_64(Boundary)) {
1693  D.Diag(diag::err_drv_invalid_argument_to_option)
1694  << Value << A->getOption().getName();
1695  } else {
1696  addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1697  }
1698  }
1699  if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1700  std::string AlignBranch;
1701  for (StringRef T : A->getValues()) {
1702  if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1703  T != "ret" && T != "indirect")
1704  D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1705  << T << "fused, jcc, jmp, call, ret, indirect";
1706  if (!AlignBranch.empty())
1707  AlignBranch += '+';
1708  AlignBranch += T;
1709  }
1710  addArg("-x86-align-branch=" + Twine(AlignBranch));
1711  }
1712  if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1713  StringRef Value = A->getValue();
1714  unsigned PrefixSize;
1715  if (Value.getAsInteger(10, PrefixSize)) {
1716  D.Diag(diag::err_drv_invalid_argument_to_option)
1717  << Value << A->getOption().getName();
1718  } else {
1719  addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1720  }
1721  }
1722 }
1723 
1724 /// SDLSearch: Search for Static Device Library
1725 /// The search for SDL bitcode files is consistent with how static host
1726 /// libraries are discovered. That is, the -l option triggers a search for
1727 /// files in a set of directories called the LINKPATH. The host library search
1728 /// procedure looks for a specific filename in the LINKPATH. The filename for
1729 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
1730 /// ordered-set of filenames that are searched. We call this ordered-set of
1731 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
1732 /// architecture specific, or generic across all architectures, a naming
1733 /// convention and search order is used where the file name embeds the
1734 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
1735 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
1736 /// device-independent SDLs. To reduce congestion in host library directories,
1737 /// the search first looks for files in the “libdevice” subdirectory. SDLs that
1738 /// are bc files begin with the prefix “lib”.
1739 ///
1740 /// Machine-code SDLs can also be managed as an archive (*.a file). The
1741 /// convention has been to use the prefix “lib”. To avoid confusion with host
1742 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
1743 ///
1744 bool tools::SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
1745  llvm::opt::ArgStringList &CC1Args,
1746  SmallVector<std::string, 8> LibraryPaths, std::string Lib,
1747  StringRef Arch, StringRef Target, bool isBitCodeSDL,
1748  bool postClangLink) {
1750 
1751  std::string LibDeviceLoc = "/libdevice";
1752  std::string LibBcPrefix = "/libbc-";
1753  std::string LibPrefix = "/lib";
1754 
1755  if (isBitCodeSDL) {
1756  // SEARCH-ORDER for Bitcode SDLs:
1757  // libdevice/libbc-<libname>-<arch-name>-<device-type>.a
1758  // libbc-<libname>-<arch-name>-<device-type>.a
1759  // libdevice/libbc-<libname>-<arch-name>.a
1760  // libbc-<libname>-<arch-name>.a
1761  // libdevice/libbc-<libname>.a
1762  // libbc-<libname>.a
1763  // libdevice/lib<libname>-<arch-name>-<device-type>.bc
1764  // lib<libname>-<arch-name>-<device-type>.bc
1765  // libdevice/lib<libname>-<arch-name>.bc
1766  // lib<libname>-<arch-name>.bc
1767  // libdevice/lib<libname>.bc
1768  // lib<libname>.bc
1769 
1770  for (StringRef Base : {LibBcPrefix, LibPrefix}) {
1771  const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
1772 
1773  for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1774  Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
1775  SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
1776  SDLs.push_back(Twine(Base + Suffix + Ext).str());
1777  }
1778  }
1779  } else {
1780  // SEARCH-ORDER for Machine-code SDLs:
1781  // libdevice/lib<libname>-<arch-name>-<device-type>.a
1782  // lib<libname>-<arch-name>-<device-type>.a
1783  // libdevice/lib<libname>-<arch-name>.a
1784  // lib<libname>-<arch-name>.a
1785 
1786  const auto *Ext = ".a";
1787 
1788  for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1789  Twine(Lib + "-" + Arch).str()}) {
1790  SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
1791  SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
1792  }
1793  }
1794 
1795  // The CUDA toolchain does not use a global device llvm-link before the LLVM
1796  // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
1797  // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
1798  // will link libraries after clang compilation while the LLVM IR is still in
1799  // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
1800  // This is a clang -cc1 option that is generated by the clang driver. The
1801  // option value must a full path to an existing file.
1802  bool FoundSDL = false;
1803  for (auto LPath : LibraryPaths) {
1804  for (auto SDL : SDLs) {
1805  auto FullName = Twine(LPath + SDL).str();
1806  if (llvm::sys::fs::exists(FullName)) {
1807  if (postClangLink)
1808  CC1Args.push_back("-mlink-builtin-bitcode");
1809  CC1Args.push_back(DriverArgs.MakeArgString(FullName));
1810  FoundSDL = true;
1811  break;
1812  }
1813  }
1814  if (FoundSDL)
1815  break;
1816  }
1817  return FoundSDL;
1818 }
1819 
1820 /// Search if a user provided archive file lib<libname>.a exists in any of
1821 /// the library paths. If so, add a new command to clang-offload-bundler to
1822 /// unbundle this archive and create a temporary device specific archive. Name
1823 /// of this SDL is passed to the llvm-link (for amdgcn) or to the
1824 /// clang-nvlink-wrapper (for nvptx) commands by the driver.
1826  Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
1827  const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
1828  llvm::opt::ArgStringList &CC1Args, SmallVector<std::string, 8> LibraryPaths,
1829  StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
1830  bool postClangLink) {
1831 
1832  // We don't support bitcode archive bundles for nvptx
1833  if (isBitCodeSDL && Arch.contains("nvptx"))
1834  return false;
1835 
1836  bool FoundAOB = false;
1837  std::string ArchiveOfBundles;
1838 
1839  llvm::Triple Triple(D.getTargetTriple());
1840  bool IsMSVC = Triple.isWindowsMSVCEnvironment();
1841  auto Ext = IsMSVC ? ".lib" : ".a";
1842  if (!Lib.startswith(":") && llvm::sys::fs::exists(Lib)) {
1843  ArchiveOfBundles = Lib;
1844  FoundAOB = true;
1845  } else {
1846  for (auto LPath : LibraryPaths) {
1847  ArchiveOfBundles.clear();
1848  SmallVector<std::string, 2> AOBFileNames;
1849  auto LibFile =
1850  (Lib.startswith(":") ? Lib.drop_front()
1851  : IsMSVC ? Lib + Ext : "lib" + Lib + Ext)
1852  .str();
1853  for (auto Prefix : {"/libdevice/", "/"}) {
1854  auto AOB = Twine(LPath + Prefix + LibFile).str();
1855  if (llvm::sys::fs::exists(AOB)) {
1856  ArchiveOfBundles = AOB;
1857  FoundAOB = true;
1858  break;
1859  }
1860  }
1861  if (FoundAOB)
1862  break;
1863  }
1864  }
1865 
1866  if (!FoundAOB)
1867  return false;
1868 
1869  llvm::file_magic Magic;
1870  auto EC = llvm::identify_magic(ArchiveOfBundles, Magic);
1871  if (EC || Magic != llvm::file_magic::archive)
1872  return false;
1873 
1874  StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
1875  std::string OutputLib =
1876  D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" +
1877  Arch + "-" + Target)
1878  .str(),
1879  "a");
1880 
1881  C.addTempFile(C.getArgs().MakeArgString(OutputLib));
1882 
1883  ArgStringList CmdArgs;
1884  SmallString<128> DeviceTriple;
1886  DeviceTriple += '-';
1887  std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
1888  DeviceTriple += NormalizedTriple;
1889  if (!Target.empty()) {
1890  DeviceTriple += '-';
1891  DeviceTriple += Target;
1892  }
1893 
1894  std::string UnbundleArg("-unbundle");
1895  std::string TypeArg("-type=a");
1896  std::string InputArg("-input=" + ArchiveOfBundles);
1897  std::string OffloadArg("-targets=" + std::string(DeviceTriple));
1898  std::string OutputArg("-output=" + OutputLib);
1899 
1900  const char *UBProgram = DriverArgs.MakeArgString(
1901  T.getToolChain().GetProgramPath("clang-offload-bundler"));
1902 
1903  ArgStringList UBArgs;
1904  UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
1905  UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
1906  UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
1907  UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
1908  UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
1909 
1910  // Add this flag to not exit from clang-offload-bundler if no compatible
1911  // code object is found in heterogenous archive library.
1912  std::string AdditionalArgs("-allow-missing-bundles");
1913  UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
1914 
1915  // Add this flag to treat hip and hipv4 offload kinds as compatible with
1916  // openmp offload kind while extracting code objects from a heterogenous
1917  // archive library. Vice versa is also considered compatible.
1918  std::string HipCompatibleArgs("-hip-openmp-compatible");
1919  UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
1920 
1921  C.addCommand(std::make_unique<Command>(
1922  JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
1923  InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
1924  if (postClangLink)
1925  CC1Args.push_back("-mlink-builtin-bitcode");
1926 
1927  CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
1928 
1929  return true;
1930 }
1931 
1932 // Wrapper function used by driver for adding SDLs during link phase.
1934  const JobAction &JA,
1935  const InputInfoList &Inputs,
1936  const llvm::opt::ArgList &DriverArgs,
1937  llvm::opt::ArgStringList &CC1Args,
1938  StringRef Arch, StringRef Target,
1939  bool isBitCodeSDL, bool postClangLink) {
1940  AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
1941  Arch, Target, isBitCodeSDL, postClangLink);
1942 }
1943 
1944 // Wrapper function used for post clang linking of bitcode SDLS for nvptx by
1945 // the CUDA toolchain.
1947  const llvm::opt::ArgList &DriverArgs,
1948  llvm::opt::ArgStringList &CC1Args,
1949  StringRef Arch, StringRef Target,
1950  bool isBitCodeSDL, bool postClangLink) {
1951  AddStaticDeviceLibs(nullptr, nullptr, nullptr, nullptr, D, DriverArgs,
1952  CC1Args, Arch, Target, isBitCodeSDL, postClangLink);
1953 }
1954 
1955 // User defined Static Device Libraries(SDLs) can be passed to clang for
1956 // offloading GPU compilers. Like static host libraries, the use of a SDL is
1957 // specified with the -l command line option. The primary difference between
1958 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
1959 // and SEARCH-ORDER for Machine-code SDLs for the naming convention).
1960 // SDLs are of following types:
1961 //
1962 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
1963 // For NVPTX, these libraries are post-clang linked following each
1964 // compilation. For AMDGPU, these libraries are linked one time
1965 // during the application link phase.
1966 //
1967 // * Machine-code SDLs: They are archive files. For NVPTX, the archive members
1968 // contain cubin for Nvidia GPUs and are linked one time during the
1969 // link phase by the CUDA SDK linker called nvlink. For AMDGPU, the
1970 // process for machine code SDLs is still in development. But they
1971 // will be linked by the LLVM tool lld.
1972 //
1973 // * Bundled objects that contain both host and device codes: Bundled objects
1974 // may also contain library code compiled from source. For NVPTX, the
1975 // bundle contains cubin. For AMDGPU, the bundle contains bitcode.
1976 //
1977 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
1978 // inclusion of specific SDLs such as math libraries and the OpenMP device
1979 // library libomptarget.
1981  const JobAction *JA,
1982  const InputInfoList *Inputs, const Driver &D,
1983  const llvm::opt::ArgList &DriverArgs,
1984  llvm::opt::ArgStringList &CC1Args,
1985  StringRef Arch, StringRef Target,
1986  bool isBitCodeSDL, bool postClangLink) {
1987 
1988  SmallVector<std::string, 8> LibraryPaths;
1989  // Add search directories from LIBRARY_PATH env variable
1990  llvm::Optional<std::string> LibPath =
1991  llvm::sys::Process::GetEnv("LIBRARY_PATH");
1992  if (LibPath) {
1994  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
1995  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
1996  for (StringRef Path : Frags)
1997  LibraryPaths.emplace_back(Path.trim());
1998  }
1999 
2000  // Add directories from user-specified -L options
2001  for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
2002  LibraryPaths.emplace_back(Search_Dir);
2003 
2004  // Add path to lib-debug folders
2005  SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2006  llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
2007  LibraryPaths.emplace_back(DefaultLibPath.c_str());
2008 
2009  // Build list of Static Device Libraries SDLs specified by -l option
2010  llvm::SmallSet<std::string, 16> SDLNames;
2011  static const StringRef HostOnlyArchives[] = {
2012  "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
2013  for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
2014  if (!HostOnlyArchives->contains(SDLName)) {
2015  SDLNames.insert(SDLName);
2016  }
2017  }
2018 
2019  for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) {
2020  auto FileName = StringRef(Input);
2021  // Clang treats any unknown file types as archives and passes them to the
2022  // linker. Files with extension 'lib' are classified as TY_Object by clang
2023  // but they are usually archives. It is OK if the file is not really an
2024  // archive since GetSDLFromOffloadArchive will check the magic of the file
2025  // and only unbundle it if it is really an archive.
2026  const StringRef LibFileExt = ".lib";
2027  if (!llvm::sys::path::has_extension(FileName) ||
2029  llvm::sys::path::extension(FileName).drop_front()) ==
2031  llvm::sys::path::extension(FileName) == LibFileExt)
2032  SDLNames.insert(Input);
2033  }
2034 
2035  // The search stops as soon as an SDL file is found. The driver then provides
2036  // the full filename of the SDL to the llvm-link or clang-nvlink-wrapper
2037  // command. If no SDL is found after searching each LINKPATH with
2038  // SEARCH-ORDER, it is possible that an archive file lib<libname>.a exists
2039  // and may contain bundled object files.
2040  for (auto SDLName : SDLNames) {
2041  // This is the only call to SDLSearch
2042  if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
2043  isBitCodeSDL, postClangLink)) {
2044  GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
2045  LibraryPaths, SDLName, Arch, Target,
2046  isBitCodeSDL, postClangLink);
2047  }
2048  }
2049 }
2050 
2051 static llvm::opt::Arg *
2052 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
2053  // The last of -mcode-object-v3, -mno-code-object-v3 and
2054  // -mcode-object-version=<version> wins.
2055  return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
2056  options::OPT_mno_code_object_v3_legacy,
2057  options::OPT_mcode_object_version_EQ);
2058 }
2059 
2061  const llvm::opt::ArgList &Args) {
2062  const unsigned MinCodeObjVer = 2;
2063  const unsigned MaxCodeObjVer = 5;
2064 
2065  // Emit warnings for legacy options even if they are overridden.
2066  if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
2067  D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
2068  << "-mcode-object-version=2";
2069 
2070  if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
2071  D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
2072  << "-mcode-object-version=3";
2073 
2074  if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2075  if (CodeObjArg->getOption().getID() ==
2076  options::OPT_mcode_object_version_EQ) {
2077  unsigned CodeObjVer = MaxCodeObjVer;
2078  auto Remnant =
2079  StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2080  if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
2081  D.Diag(diag::err_drv_invalid_int_value)
2082  << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
2083  }
2084  }
2085 }
2086 
2088  const llvm::opt::ArgList &Args) {
2089  unsigned CodeObjVer = 4; // default
2090  if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2091  if (CodeObjArg->getOption().getID() ==
2092  options::OPT_mno_code_object_v3_legacy) {
2093  CodeObjVer = 2;
2094  } else if (CodeObjArg->getOption().getID() ==
2095  options::OPT_mcode_object_v3_legacy) {
2096  CodeObjVer = 3;
2097  } else {
2098  StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2099  }
2100  }
2101  return CodeObjVer;
2102 }
2103 
2105  const Driver &D, const llvm::opt::ArgList &Args) {
2106  return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2107 }
2108 
2110  const llvm::opt::ArgList &Args,
2111  llvm::opt::ArgStringList &CmdArgs,
2112  const llvm::Triple &Triple, bool IsLTO) {
2113  auto addArg = [&, IsLTO](const Twine &Arg) {
2114  if (IsLTO) {
2115  CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
2116  } else {
2117  CmdArgs.push_back("-mllvm");
2118  CmdArgs.push_back(Args.MakeArgString(Arg));
2119  }
2120  };
2121 
2122  if (Arg *A = Args.getLastArg(options::OPT_moutline,
2123  options::OPT_mno_outline)) {
2124  if (A->getOption().matches(options::OPT_moutline)) {
2125  // We only support -moutline in AArch64 and ARM targets right now. If
2126  // we're not compiling for these, emit a warning and ignore the flag.
2127  // Otherwise, add the proper mllvm flags.
2128  if (!(Triple.isARM() || Triple.isThumb() ||
2129  Triple.getArch() == llvm::Triple::aarch64 ||
2130  Triple.getArch() == llvm::Triple::aarch64_32)) {
2131  D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2132  } else {
2133  addArg(Twine("-enable-machine-outliner"));
2134  }
2135  } else {
2136  // Disable all outlining behaviour.
2137  addArg(Twine("-enable-machine-outliner=never"));
2138  }
2139  }
2140 }
2141 
2143  const llvm::opt::ArgList &DriverArgs,
2144  llvm::opt::ArgStringList &CC1Args,
2145  StringRef BitcodeSuffix,
2146  const llvm::Triple &Triple) {
2147  SmallVector<StringRef, 8> LibraryPaths;
2148 
2149  // Add path to clang lib / lib64 folder.
2150  SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2151  llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
2152  LibraryPaths.emplace_back(DefaultLibPath.c_str());
2153 
2154  // Add user defined library paths from LIBRARY_PATH.
2155  llvm::Optional<std::string> LibPath =
2156  llvm::sys::Process::GetEnv("LIBRARY_PATH");
2157  if (LibPath) {
2159  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2160  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2161  for (StringRef Path : Frags)
2162  LibraryPaths.emplace_back(Path.trim());
2163  }
2164 
2165  OptSpecifier LibomptargetBCPathOpt =
2166  Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2167  : options::OPT_libomptarget_nvptx_bc_path_EQ;
2168 
2169  StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2170  std::string LibOmpTargetName =
2171  ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2172 
2173  // First check whether user specifies bc library
2174  if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2175  SmallString<128> LibOmpTargetFile(A->getValue());
2176  if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2177  llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2178  llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2179  }
2180 
2181  if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2182  CC1Args.push_back("-mlink-builtin-bitcode");
2183  CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2184  } else {
2185  D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2186  << LibOmpTargetFile;
2187  }
2188  } else {
2189  bool FoundBCLibrary = false;
2190 
2191  for (StringRef LibraryPath : LibraryPaths) {
2192  SmallString<128> LibOmpTargetFile(LibraryPath);
2193  llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2194  if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2195  CC1Args.push_back("-mlink-builtin-bitcode");
2196  CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2197  FoundBCLibrary = true;
2198  break;
2199  }
2200  }
2201 
2202  if (!FoundBCLibrary)
2203  D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2204  << LibOmpTargetName << ArchPrefix;
2205  }
2206 }
2208  const llvm::opt::ArgList &Args,
2209  llvm::opt::ArgStringList &CmdArgs) {
2210  if (Args.hasArg(options::OPT_hip_link) &&
2211  !Args.hasArg(options::OPT_nostdlib) &&
2212  !Args.hasArg(options::OPT_no_hip_rt)) {
2213  TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2214  } else {
2215  // Claim "no HIP libraries" arguments if any
2216  for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) {
2217  Arg->claim();
2218  }
2219  }
2220 }
clang::driver::SanitizerArgs::getMemtagMode
const std::string & getMemtagMode() const
Definition: SanitizerArgs.h:115
Mips.h
clang::driver::Multilib::flags_list
std::vector< std::string > flags_list
Definition: Multilib.h:30
clang::driver::SanitizerArgs::hasCrossDsoCfi
bool hasCrossDsoCfi() const
Definition: SanitizerArgs.h:125
clang::driver::tools::ParseFunctionAlignment
unsigned ParseFunctionAlignment(const ToolChain &TC, const llvm::opt::ArgList &Args)
LibGccType::StaticLibGcc
@ StaticLibGcc
Util.h
clang::driver::Action::getOffloadingArch
const char * getOffloadingArch() const
Definition: Action.h:211
clang::driver::tools::AddAssemblerKPIC
void AddAssemblerKPIC(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
clang::driver::ToolChain::getEffectiveTriple
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition: ToolChain.h:262
clang::driver::tools::GetSDLFromOffloadArchive
bool GetSDLFromOffloadArchive(Compilation &C, const Driver &D, const Tool &T, const JobAction &JA, const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, SmallVector< std::string, 8 > LibraryPaths, StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL, bool postClangLink)
Search if a user provided archive file lib<libname>.a exists in any of the library paths.
Definition: CommonArgs.cpp:1825
getLanaiTargetCPU
static std::string getLanaiTargetCPU(const ArgList &Args)
Definition: CommonArgs.cpp:327
clang::driver::ToolChain::getCompilerRT
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:510
clang::driver::ToolChain::getVFS
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:99
XRayArgs.h
ObjCRuntime.h
Driver.h
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::driver::Driver::Dir
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:150
clang::driver::tools::ParsePICArgs
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
clang::driver::SanitizerArgs::hasMemtagStack
bool hasMemtagStack() const
Definition: SanitizerArgs.h:109
clang::driver::tools::getLastProfileSampleUseArg
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
llvm::SmallVector< std::string, 16 >
clang::driver::toolchains::HexagonToolChain::GetTargetCPUVersion
static StringRef GetTargetCPUVersion(const llvm::opt::ArgList &Args)
Definition: Hexagon.cpp:788
X86.h
addSanitizerDynamicList
static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, StringRef Sanitizer)
Definition: CommonArgs.cpp:821
collectSanitizerRuntimes
static void collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, SmallVectorImpl< StringRef > &SharedRuntimes, SmallVectorImpl< StringRef > &StaticRuntimes, SmallVectorImpl< StringRef > &NonWholeStaticRuntimes, SmallVectorImpl< StringRef > &HelperStaticRuntimes, SmallVectorImpl< StringRef > &RequiredSymbols)
Definition: CommonArgs.cpp:881
clang::driver::ToolChain::GetProgramPath
std::string GetProgramPath(const char *Name) const
Definition: ToolChain.cpp:608
clang::MultiVersionKind::Target
@ Target
clang::driver::tools::addOpenMPRuntimeLibraryPath
void addOpenMPRuntimeLibraryPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
clang::driver::SanitizerArgs::needsSafeStackRt
bool needsSafeStackRt() const
Definition: SanitizerArgs.h:97
clang::driver::tools
Definition: AIX.h:17
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:55
clang::driver::tools::addX86AlignBranchArgs
void addX86AlignBranchArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsLTO)
clang::driver::tools::AddStaticDeviceLibs
void AddStaticDeviceLibs(Compilation *C, const Tool *T, const JobAction *JA, const InputInfoList *Inputs, const Driver &D, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CmdArgs, StringRef Arch, StringRef Target, bool isBitCodeSDL, bool postClangLink)
Definition: CommonArgs.cpp:1980
clang::driver::tools::m68k::getM68kTargetCPU
std::string getM68kTargetCPU(const llvm::opt::ArgList &Args)
clang::driver::ToolChain::getDriver
const Driver & getDriver() const
Definition: ToolChain.h:232
Job.h
clang::driver::SanitizerArgs::needsTsanRt
bool needsTsanRt() const
Definition: SanitizerArgs.h:85
clang::driver::ToolChain::getTripleString
std::string getTripleString() const
Definition: ToolChain.h:257
clang::driver::Action::OFK_HIP
@ OFK_HIP
Definition: Action.h:96
Sparc.h
clang::driver::Driver::OpenMPRuntimeKind
OpenMPRuntimeKind
Definition: Driver.h:118
clang::driver::XRayArgs::modeList
llvm::ArrayRef< std::string > modeList() const
Definition: XRayArgs.h:45
clang::driver::tools::getCPUName
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
clang::driver::SanitizerArgs::needsHwasanRt
bool needsHwasanRt() const
Definition: SanitizerArgs.h:79
llvm::Optional< std::string >
getWebAssemblyTargetCPU
static StringRef getWebAssemblyTargetCPU(const ArgList &Args)
Get the (LLVM) name of the WebAssembly cpu we are targeting.
Definition: CommonArgs.cpp:335
clang::driver::ToolChain::isPICDefault
virtual bool isPICDefault() const =0
Test whether this toolchain defaults to PIC.
clang::driver::Driver::getOpenMPRuntime
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition: Driver.cpp:709
clang::driver::ToolChain::HasNativeLLVMSupport
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: ToolChain.cpp:703
clang::driver::tools::getLastProfileUseArg
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
AArch64.h
clang::diag::Group
Group
Definition: DiagnosticCategories.h:23
clang::driver::tools::SplitDebugInfo
void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Output, const char *OutFile)
clang::driver::Action::GetOffloadKindName
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition: Action.cpp:155
clang::driver::tools::SDLSearch
bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CmdArgs, SmallVector< std::string, 8 > LibraryPaths, std::string Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL, bool postClangLink)
SDLSearch: Search for Static Device Library The search for SDL bitcode files is consistent with how s...
Definition: CommonArgs.cpp:1744
clang::driver::ToolChain::getSanitizerArgs
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const
Definition: ToolChain.cpp:146
clang::driver::InputInfo
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
VE.h
clang::driver::Action::OFK_OpenMP
@ OFK_OpenMP
Definition: Action.h:95
clang::driver::ToolChain::RuntimeLibType
RuntimeLibType
Definition: ToolChain.h:100
SystemZ.h
InputInfo.h
clang::driver::types::lookupTypeForExtension
ID lookupTypeForExtension(llvm::StringRef Ext)
lookupTypeForExtension - Lookup the type to use for the file extension Ext.
Definition: Types.cpp:295
clang::driver::tools::AddLinkerInputs
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
Action.h
U
clang::driver::tools::areOptimizationsEnabled
bool areOptimizationsEnabled(const llvm::opt::ArgList &Args)
V
#define V(N, I)
Definition: ASTContext.h:3233
clang::driver::Driver::Diag
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:139
clang::driver::tools::AddStaticDeviceLibsLinking
void AddStaticDeviceLibsLinking(Compilation &C, const Tool &T, const JobAction &JA, const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CmdArgs, StringRef Arch, StringRef Target, bool isBitCodeSDL, bool postClangLink)
Definition: CommonArgs.cpp:1933
clang::driver::SanitizerArgs::requiresMinimalRuntime
bool requiresMinimalRuntime() const
Definition: SanitizerArgs.h:95
clang::driver::ToolChain::isPIEDefault
virtual bool isPIEDefault(const llvm::opt::ArgList &Args) const =0
Test whether this toolchain defaults to PIE.
min
__DEVICE__ int min(int __a, int __b)
Definition: __clang_cuda_math.h:197
clang::driver::InputInfo::getBaseInput
const char * getBaseInput() const
Definition: InputInfo.h:78
clang::driver::tools::addFortranRuntimeLibs
void addFortranRuntimeLibs(const ToolChain &TC, llvm::opt::ArgStringList &CmdArgs)
Adds Fortran runtime libraries to CmdArgs.
Definition: CommonArgs.cpp:769
clang::driver::SanitizerArgs::linkRuntimes
bool linkRuntimes() const
Definition: SanitizerArgs.h:123
clang::driver::Tool
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
clang::driver::tools::ParseDebugDefaultVersion
unsigned ParseDebugDefaultVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
clang::driver::tools::getAsNeededOption
const char * getAsNeededOption(const ToolChain &TC, bool as_needed)
Definition: CommonArgs.cpp:836
clang::driver::tools::claimNoWarnArgs
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
Options.h
clang::driver::InputInfo::isFilename
bool isFilename() const
Definition: InputInfo.h:75
clang::driver::SanitizerArgs::needsFuzzer
bool needsFuzzer() const
Definition: SanitizerArgs.h:87
clang::driver::XRayArgs::needsXRayRt
bool needsXRayRt() const
Definition: XRayArgs.h:44
clang::driver::tools::aarch64::getAArch64TargetCPU
std::string getAArch64TargetCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, llvm::opt::Arg *&A)
clang::driver::ToolChain::UNW_None
@ UNW_None
Definition: ToolChain.h:106
Version.h
LangOptions.h
llvm::opt
Definition: DiagnosticOptions.h:19
DriverDiagnostic.h
clang::driver::types::TY_INVALID
@ TY_INVALID
Definition: Types.h:24
clang::driver::ResponseFileSupport::AtFileCurCP
static constexpr ResponseFileSupport AtFileCurCP()
Definition: Job.h:92
clang::driver::ToolChain::RLT_Libgcc
@ RLT_Libgcc
Definition: ToolChain.h:102
clang::driver::ToolChain::AddCCKextLibArgs
virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCCKextLibArgs - Add the system specific linker arguments to use for kernel extensions (Darwin-spec...
Definition: ToolChain.cpp:1037
clang::getProcessorFromTargetID
llvm::StringRef getProcessorFromTargetID(const llvm::Triple &T, llvm::StringRef OffloadArch)
Get processor name from target ID.
Definition: TargetID.cpp:53
clang::driver::tools::getLTOParallelism
llvm::StringRef getLTOParallelism(const llvm::opt::ArgList &Args, const Driver &D)
clang::driver::tools::addPathIfExists
void addPathIfExists(const Driver &D, const Twine &Path, ToolChain::path_list &Paths)
Definition: CommonArgs.cpp:124
clang::driver::tools::systemz::getSystemZTargetCPU
std::string getSystemZTargetCPU(const llvm::opt::ArgList &Args)
clang::driver::SanitizerArgs::hasMemTag
bool hasMemTag() const
Definition: SanitizerArgs.h:103
clang::driver::Driver::OMPRT_IOMP5
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition: Driver.h:135
llvm::SmallString< 128 >
clang::driver::ToolChain::getTriple
const llvm::Triple & getTriple() const
Definition: ToolChain.h:234
clang::driver::SanitizerArgs::needsAsanRt
bool needsAsanRt() const
Definition: SanitizerArgs.h:78
clang::driver::Action::isHostOffloading
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition: Action.h:218
clang::driver::tools::unifyTargetFeatures
SmallVector< StringRef > unifyTargetFeatures(ArrayRef< StringRef > Features)
If there are multiple +xxx or -xxx features, keep the last one.
Definition: CommonArgs.cpp:149
llvm::DenseSet
Definition: Sema.h:77
clang::driver::Driver::CCCIsCXX
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition: Driver.h:208
clang::driver::SanitizerArgs::hasMemtagHeap
bool hasMemtagHeap() const
Definition: SanitizerArgs.h:106
clang::driver::Driver::OMPRT_OMP
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition: Driver.h:125
clang::driver::tools::handleTargetFeaturesGroup
void handleTargetFeaturesGroup(const llvm::opt::ArgList &Args, std::vector< StringRef > &Features, llvm::opt::OptSpecifier Group)
Iterate Args and convert -mxxx to +xxx and -mno-xxx to -xxx and append it to Features.
clang::driver::ToolChain::UNW_CompilerRT
@ UNW_CompilerRT
Definition: ToolChain.h:107
clang::driver::tools::addXRayRuntime
bool addXRayRuntime(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
getLibGccType
static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition: CommonArgs.cpp:1523
clang::driver::SanitizerArgs::needsScudoRt
bool needsScudoRt() const
Definition: SanitizerArgs.h:101
clang::driver::types::isLLVMIR
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition: Types.cpp:252
Base
clang::driver::SanitizerArgs::needsFuzzerInterceptors
bool needsFuzzerInterceptors() const
Definition: SanitizerArgs.cpp:268
clang::driver::tools::addMachineOutlinerArgs
void addMachineOutlinerArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple, bool IsLTO)
Definition: CommonArgs.cpp:2109
clang::driver::tools::getAMDGPUCodeObjectVersion
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
Definition: CommonArgs.cpp:2087
clang::driver::SanitizerArgs
Definition: SanitizerArgs.h:24
SanitizerArgs.h
clang::driver::ToolChain::UNW_Libgcc
@ UNW_Libgcc
Definition: ToolChain.h:108
clang::driver::tools::addOpenMPDeviceRTL
void addOpenMPDeviceRTL(const Driver &D, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, StringRef BitcodeSuffix, const llvm::Triple &Triple)
Definition: CommonArgs.cpp:2142
clang::driver::tools::isUseSeparateSections
bool isUseSeparateSections(const llvm::Triple &Triple)
Definition: CommonArgs.cpp:480
clang::driver::ToolChain::getArch
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:248
AddLibgcc
static void AddLibgcc(const ToolChain &TC, const Driver &D, ArgStringList &CmdArgs, const ArgList &Args)
Definition: CommonArgs.cpp:1600
clang::driver::tools::haveAMDGPUCodeObjectVersionArgument
bool haveAMDGPUCodeObjectVersionArgument(const Driver &D, const llvm::opt::ArgList &Args)
Definition: CommonArgs.cpp:2104
clang::driver::SanitizerArgs::needsLsanRt
bool needsLsanRt() const
Definition: SanitizerArgs.h:88
renderRemarksHotnessOptions
static void renderRemarksHotnessOptions(const ArgList &Args, ArgStringList &CmdArgs)
Definition: CommonArgs.cpp:112
clang::driver::tools::addLTOOptions
void addLTOOptions(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const InputInfo &Output, const InputInfo &Input, bool IsThinLTO)
ToolChain.h
clang::driver::ToolChain::FT_Static
@ FT_Static
Definition: ToolChain.h:129
clang::driver::tools::addHIPRuntimeLibArgs
void addHIPRuntimeLibArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Definition: CommonArgs.cpp:2207
clang::driver::ToolChain::GetUnwindLibType
virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:848
CharInfo.h
clang::driver::Driver::isUsingLTO
bool isUsingLTO(bool IsOffload=false) const
Returns true if we are performing any kind of LTO.
Definition: Driver.h:660
clang::driver::ToolChain::AddCXXStdlibLibArgs
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChain.cpp:1011
clang::driver::ToolChain::getArchSpecificLibPath
std::string getArchSpecificLibPath() const
Definition: ToolChain.cpp:568
clang::driver::ToolChain::GetRuntimeLibType
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:822
Compilation.h
clang::driver::ToolChain::isPICDefaultForced
virtual bool isPICDefaultForced() const =0
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
clang::driver::SanitizerArgs::needsHwasanAliasesRt
bool needsHwasanAliasesRt() const
Definition: SanitizerArgs.h:82
addSanitizerRuntime
static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, StringRef Sanitizer, bool IsShared, bool IsWhole)
Definition: CommonArgs.cpp:804
clang::driver::Driver::GetTemporaryPath
std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const
GetTemporaryPath - Return the pathname of a temporary file to use as part of compilation; the file wi...
Definition: Driver.cpp:5812
clang::driver::ToolChain::getCompilerRTArgString
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:531
clang::driver::ToolChain
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:91
clang::driver::ToolChain::GetLinkerPath
std::string GetLinkerPath(bool *LinkerIsLLD=nullptr) const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name.
Definition: ToolChain.cpp:612
clang::driver::ToolChain::RLT_CompilerRT
@ RLT_CompilerRT
Definition: ToolChain.h:101
llvm::ArrayRef
Definition: LLVM.h:34
Value
Value
Definition: UninitializedValues.cpp:102
clang::driver::SanitizerArgs::needsCfiRt
bool needsCfiRt() const
Definition: SanitizerArgs.cpp:283
clang::driver::tools::arm::getARMTargetCPU
std::string getARMTargetCPU(StringRef CPU, llvm::StringRef Arch, const llvm::Triple &Triple)
clang::driver::tools::sparc::getSparcTargetCPU
std::string getSparcTargetCPU(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
clang::driver::tools::ppc::getPPCTargetCPU
std::string getPPCTargetCPU(const llvm::opt::ArgList &Args)
clang::driver::tools::AddRunTimeLibs
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
clang::driver::Action::getOffloadingDeviceKind
OffloadKind getOffloadingDeviceKind() const
Definition: Action.h:210
clang::driver::SanitizerArgs::needsMemProfRt
bool needsMemProfRt() const
Definition: SanitizerArgs.h:77
clang::driver::SanitizerArgs::needsCfiDiagRt
bool needsCfiDiagRt() const
Definition: SanitizerArgs.cpp:288
clang::driver::tools::AddTargetFeature
void AddTargetFeature(const llvm::opt::ArgList &Args, std::vector< StringRef > &Features, llvm::opt::OptSpecifier OnOpt, llvm::opt::OptSpecifier OffOpt, StringRef FeatureName)
clang::driver::Compilation
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
LibGccType::UnspecifiedLibGcc
@ UnspecifiedLibGcc
clang::driver::tools::arm::getARMArchCPUFromArgs
void getARMArchCPUFromArgs(const llvm::opt::ArgList &Args, llvm::StringRef &Arch, llvm::StringRef &CPU, bool FromAs=false)
AddUnwindLibrary
static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, ArgStringList &CmdArgs, const ArgList &Args)
Definition: CommonArgs.cpp:1548
clang::driver::willEmitRemarks
bool willEmitRemarks(const llvm::opt::ArgList &Args)
renderRemarksOptions
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output)
Definition: CommonArgs.cpp:82
clang::driver::Tool::getToolChain
const ToolChain & getToolChain() const
Definition: Tool.h:52
LibGccType::SharedLibGcc
@ SharedLibGcc
clang::driver::tools::addOpenMPRuntime
bool addOpenMPRuntime(llvm::opt::ArgStringList &CmdArgs, const ToolChain &TC, const llvm::opt::ArgList &Args, bool ForceStaticHostRuntime=false, bool IsOffloadingHost=false, bool GompNeedsRT=false)
Returns true, if an OpenMP runtime has been added.
clang::driver::tools::addArchSpecificRPath
void addArchSpecificRPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
clang::driver::InputInfo::getFilename
const char * getFilename() const
Definition: InputInfo.h:83
clang::driver::tools::mips::getMipsCPUAndABI
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
clang::driver::tools::RelocationModelName
const char * RelocationModelName(llvm::Reloc::Model Model)
Definition: CommonArgs.cpp:1226
clang::driver::tools::linkSanitizerRuntimeDeps
void linkSanitizerRuntimeDeps(const ToolChain &TC, llvm::opt::ArgStringList &CmdArgs)
CommonArgs.h
clang
Definition: CalledOnceCheck.h:17
M68k.h
clang::driver::Driver
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:72
clang::driver::ToolChain::AddHIPRuntimeLibArgs
virtual void AddHIPRuntimeLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Add the system specific linker arguments to use for the given HIP runtime library type.
Definition: ToolChain.h:729
Hexagon.h
clang::driver::Driver::getTargetTriple
std::string getTargetTriple() const
Definition: Driver.h:380
clang::driver::SanitizerArgs::linkCXXRuntimes
bool linkCXXRuntimes() const
Definition: SanitizerArgs.h:124
clang::driver::Driver::OMPRT_Unknown
@ OMPRT_Unknown
An unknown OpenMP runtime.
Definition: Driver.h:121
clang::driver::tools::addSanitizerRuntimes
bool addSanitizerRuntimes(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
clang::driver::tools::addMultilibFlag
void addMultilibFlag(bool Enabled, const char *const Flag, Multilib::flags_list &Flags)
Flag must be a flag accepted by the driver with its leading '-' removed,
Definition: CommonArgs.cpp:1669
clang::driver::tools::checkAMDGPUCodeObjectVersion
void checkAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
Definition: CommonArgs.cpp:2060
clang::driver::ToolChain::UnwindLibType
UnwindLibType
Definition: ToolChain.h:105
clang::driver::SanitizerArgs::needsUbsanRt
bool needsUbsanRt() const
Definition: SanitizerArgs.cpp:272
clang::driver::tools::linkXRayRuntimeDeps
void linkXRayRuntimeDeps(const ToolChain &TC, llvm::opt::ArgStringList &CmdArgs)
clang::driver::tools::addDirectoryList
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
clang::driver::Driver::getVFS
llvm::vfs::FileSystem & getVFS() const
Definition: Driver.h:366
clang::driver::SanitizerArgs::needsDfsanRt
bool needsDfsanRt() const
Definition: SanitizerArgs.h:96
clang::driver::ToolChain::isCrossCompiling
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
Definition: ToolChain.cpp:707
clang::driver::tools::addLinkerCompressDebugSectionsOption
void addLinkerCompressDebugSectionsOption(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Definition: CommonArgs.cpp:279
ARM.h
clang::driver::ToolChain::getXRayArgs
const XRayArgs & getXRayArgs() const
Definition: ToolChain.cpp:152
clang::driver
Definition: Action.h:31
llvm::SmallVectorImpl
Definition: Randstruct.h:18
clang::driver::tools::x86::getX86TargetCPU
std::string getX86TargetCPU(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
clang::driver::tools::AddStaticDeviceLibsPostLinking
void AddStaticDeviceLibsPostLinking(const Driver &D, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CmdArgs, StringRef Arch, StringRef Target, bool isBitCodeSDL, bool postClangLink)
Definition: CommonArgs.cpp:1946
clang::driver::SanitizerArgs::needsSharedRt
bool needsSharedRt() const
Definition: SanitizerArgs.h:75
clang::driver::ToolChain::FT_Shared
@ FT_Shared
Definition: ToolChain.h:129
clang::driver::Driver::OMPRT_GOMP
@ OMPRT_GOMP
The GNU OpenMP runtime.
Definition: Driver.h:130
clang::driver::JobAction
Definition: Action.h:399
PPC.h
clang::driver::SanitizerArgs::needsStatsRt
bool needsStatsRt() const
Definition: SanitizerArgs.h:100
LibGccType
LibGccType
Definition: CommonArgs.cpp:1521
clang::driver::tools::addOpenMPRuntimeSpecificRPath
void addOpenMPRuntimeSpecificRPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
getAMDGPUTargetGPU
static std::string getAMDGPUTargetGPU(const llvm::Triple &T, const ArgList &Args)
Get the (LLVM) name of the AMDGPU gpu we are targeting.
Definition: CommonArgs.cpp:310
clang::driver::tools::getStatsFileName
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
Definition: CommonArgs.cpp:1645
clang::driver::tools::addFortranRuntimeLibraryPath
void addFortranRuntimeLibraryPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds the path for the Fortran runtime libraries to CmdArgs.
getAMDGPUCodeObjectArgument
static llvm::opt::Arg * getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args)
Definition: CommonArgs.cpp:2052
renderRpassOptions
static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs)
Definition: CommonArgs.cpp:68
clang::driver::tools::SplitDebugName
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
clang::driver::tools::isObjCAutoRefCount
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
HIPAMD.h
clang::driver::SanitizerArgs::needsMsanRt
bool needsMsanRt() const
Definition: SanitizerArgs.h:86