clang  16.0.0git
Clang.cpp
Go to the documentation of this file.
1 //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- 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 "Clang.h"
10 #include "AMDGPU.h"
11 #include "Arch/AArch64.h"
12 #include "Arch/ARM.h"
13 #include "Arch/CSKY.h"
14 #include "Arch/LoongArch.h"
15 #include "Arch/M68k.h"
16 #include "Arch/Mips.h"
17 #include "Arch/PPC.h"
18 #include "Arch/RISCV.h"
19 #include "Arch/Sparc.h"
20 #include "Arch/SystemZ.h"
21 #include "Arch/VE.h"
22 #include "Arch/X86.h"
23 #include "CommonArgs.h"
24 #include "Hexagon.h"
25 #include "MSP430.h"
26 #include "PS4CPU.h"
27 #include "clang/Basic/CLWarnings.h"
28 #include "clang/Basic/CharInfo.h"
33 #include "clang/Basic/Version.h"
34 #include "clang/Config/config.h"
35 #include "clang/Driver/Action.h"
36 #include "clang/Driver/Distro.h"
38 #include "clang/Driver/InputInfo.h"
39 #include "clang/Driver/Options.h"
41 #include "clang/Driver/Types.h"
42 #include "clang/Driver/XRayArgs.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/Config/llvm-config.h"
46 #include "llvm/Option/ArgList.h"
47 #include "llvm/Support/CodeGen.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/Compression.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/Host.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/Process.h"
54 #include "llvm/Support/TargetParser.h"
55 #include "llvm/Support/YAMLParser.h"
56 #include <cctype>
57 
58 using namespace clang::driver;
59 using namespace clang::driver::tools;
60 using namespace clang;
61 using namespace llvm::opt;
62 
63 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
64  if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
65  options::OPT_fminimize_whitespace,
66  options::OPT_fno_minimize_whitespace)) {
67  if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
68  !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
69  D.Diag(clang::diag::err_drv_argument_only_allowed_with)
70  << A->getBaseArg().getAsString(Args)
71  << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
72  }
73  }
74 }
75 
76 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
77  // In gcc, only ARM checks this, but it seems reasonable to check universally.
78  if (Args.hasArg(options::OPT_static))
79  if (const Arg *A =
80  Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
81  D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
82  << "-static";
83 }
84 
85 // Add backslashes to escape spaces and other backslashes.
86 // This is used for the space-separated argument list specified with
87 // the -dwarf-debug-flags option.
88 static void EscapeSpacesAndBackslashes(const char *Arg,
89  SmallVectorImpl<char> &Res) {
90  for (; *Arg; ++Arg) {
91  switch (*Arg) {
92  default:
93  break;
94  case ' ':
95  case '\\':
96  Res.push_back('\\');
97  break;
98  }
99  Res.push_back(*Arg);
100  }
101 }
102 
103 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
104 /// offloading tool chain that is associated with the current action \a JA.
105 static void
107  const ToolChain &RegularToolChain,
108  llvm::function_ref<void(const ToolChain &)> Work) {
109  // Apply Work on the current/regular tool chain.
110  Work(RegularToolChain);
111 
112  // Apply Work on all the offloading tool chains associated with the current
113  // action.
115  Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
117  Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
118  else if (JA.isHostOffloading(Action::OFK_HIP))
119  Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
120  else if (JA.isDeviceOffloading(Action::OFK_HIP))
121  Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
122 
124  auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
125  for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
126  Work(*II->second);
127  } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
128  Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
129 
130  //
131  // TODO: Add support for other offloading programming models here.
132  //
133 }
134 
135 /// This is a helper function for validating the optional refinement step
136 /// parameter in reciprocal argument strings. Return false if there is an error
137 /// parsing the refinement step. Otherwise, return true and set the Position
138 /// of the refinement step in the input string.
139 static bool getRefinementStep(StringRef In, const Driver &D,
140  const Arg &A, size_t &Position) {
141  const char RefinementStepToken = ':';
142  Position = In.find(RefinementStepToken);
143  if (Position != StringRef::npos) {
144  StringRef Option = A.getOption().getName();
145  StringRef RefStep = In.substr(Position + 1);
146  // Allow exactly one numeric character for the additional refinement
147  // step parameter. This is reasonable for all currently-supported
148  // operations and architectures because we would expect that a larger value
149  // of refinement steps would cause the estimate "optimization" to
150  // under-perform the native operation. Also, if the estimate does not
151  // converge quickly, it probably will not ever converge, so further
152  // refinement steps will not produce a better answer.
153  if (RefStep.size() != 1) {
154  D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
155  return false;
156  }
157  char RefStepChar = RefStep[0];
158  if (RefStepChar < '0' || RefStepChar > '9') {
159  D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
160  return false;
161  }
162  }
163  return true;
164 }
165 
166 /// The -mrecip flag requires processing of many optional parameters.
167 static void ParseMRecip(const Driver &D, const ArgList &Args,
168  ArgStringList &OutStrings) {
169  StringRef DisabledPrefixIn = "!";
170  StringRef DisabledPrefixOut = "!";
171  StringRef EnabledPrefixOut = "";
172  StringRef Out = "-mrecip=";
173 
174  Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
175  if (!A)
176  return;
177 
178  unsigned NumOptions = A->getNumValues();
179  if (NumOptions == 0) {
180  // No option is the same as "all".
181  OutStrings.push_back(Args.MakeArgString(Out + "all"));
182  return;
183  }
184 
185  // Pass through "all", "none", or "default" with an optional refinement step.
186  if (NumOptions == 1) {
187  StringRef Val = A->getValue(0);
188  size_t RefStepLoc;
189  if (!getRefinementStep(Val, D, *A, RefStepLoc))
190  return;
191  StringRef ValBase = Val.slice(0, RefStepLoc);
192  if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
193  OutStrings.push_back(Args.MakeArgString(Out + Val));
194  return;
195  }
196  }
197 
198  // Each reciprocal type may be enabled or disabled individually.
199  // Check each input value for validity, concatenate them all back together,
200  // and pass through.
201 
202  llvm::StringMap<bool> OptionStrings;
203  OptionStrings.insert(std::make_pair("divd", false));
204  OptionStrings.insert(std::make_pair("divf", false));
205  OptionStrings.insert(std::make_pair("divh", false));
206  OptionStrings.insert(std::make_pair("vec-divd", false));
207  OptionStrings.insert(std::make_pair("vec-divf", false));
208  OptionStrings.insert(std::make_pair("vec-divh", false));
209  OptionStrings.insert(std::make_pair("sqrtd", false));
210  OptionStrings.insert(std::make_pair("sqrtf", false));
211  OptionStrings.insert(std::make_pair("sqrth", false));
212  OptionStrings.insert(std::make_pair("vec-sqrtd", false));
213  OptionStrings.insert(std::make_pair("vec-sqrtf", false));
214  OptionStrings.insert(std::make_pair("vec-sqrth", false));
215 
216  for (unsigned i = 0; i != NumOptions; ++i) {
217  StringRef Val = A->getValue(i);
218 
219  bool IsDisabled = Val.startswith(DisabledPrefixIn);
220  // Ignore the disablement token for string matching.
221  if (IsDisabled)
222  Val = Val.substr(1);
223 
224  size_t RefStep;
225  if (!getRefinementStep(Val, D, *A, RefStep))
226  return;
227 
228  StringRef ValBase = Val.slice(0, RefStep);
229  llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
230  if (OptionIter == OptionStrings.end()) {
231  // Try again specifying float suffix.
232  OptionIter = OptionStrings.find(ValBase.str() + 'f');
233  if (OptionIter == OptionStrings.end()) {
234  // The input name did not match any known option string.
235  D.Diag(diag::err_drv_unknown_argument) << Val;
236  return;
237  }
238  // The option was specified without a half or float or double suffix.
239  // Make sure that the double or half entry was not already specified.
240  // The float entry will be checked below.
241  if (OptionStrings[ValBase.str() + 'd'] ||
242  OptionStrings[ValBase.str() + 'h']) {
243  D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
244  return;
245  }
246  }
247 
248  if (OptionIter->second == true) {
249  // Duplicate option specified.
250  D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
251  return;
252  }
253 
254  // Mark the matched option as found. Do not allow duplicate specifiers.
255  OptionIter->second = true;
256 
257  // If the precision was not specified, also mark the double and half entry
258  // as found.
259  if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
260  OptionStrings[ValBase.str() + 'd'] = true;
261  OptionStrings[ValBase.str() + 'h'] = true;
262  }
263 
264  // Build the output string.
265  StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
266  Out = Args.MakeArgString(Out + Prefix + Val);
267  if (i != NumOptions - 1)
268  Out = Args.MakeArgString(Out + ",");
269  }
270 
271  OutStrings.push_back(Args.MakeArgString(Out));
272 }
273 
274 /// The -mprefer-vector-width option accepts either a positive integer
275 /// or the string "none".
276 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
277  ArgStringList &CmdArgs) {
278  Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
279  if (!A)
280  return;
281 
282  StringRef Value = A->getValue();
283  if (Value == "none") {
284  CmdArgs.push_back("-mprefer-vector-width=none");
285  } else {
286  unsigned Width;
287  if (Value.getAsInteger(10, Width)) {
288  D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
289  return;
290  }
291  CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
292  }
293 }
294 
295 static void getWebAssemblyTargetFeatures(const ArgList &Args,
296  std::vector<StringRef> &Features) {
297  handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
298 }
299 
300 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
301  const ArgList &Args, ArgStringList &CmdArgs,
302  bool ForAS, bool IsAux = false) {
303  std::vector<StringRef> Features;
304  switch (Triple.getArch()) {
305  default:
306  break;
307  case llvm::Triple::mips:
308  case llvm::Triple::mipsel:
309  case llvm::Triple::mips64:
310  case llvm::Triple::mips64el:
311  mips::getMIPSTargetFeatures(D, Triple, Args, Features);
312  break;
313 
314  case llvm::Triple::arm:
315  case llvm::Triple::armeb:
316  case llvm::Triple::thumb:
317  case llvm::Triple::thumbeb:
318  arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS);
319  break;
320 
321  case llvm::Triple::ppc:
322  case llvm::Triple::ppcle:
323  case llvm::Triple::ppc64:
324  case llvm::Triple::ppc64le:
325  ppc::getPPCTargetFeatures(D, Triple, Args, Features);
326  break;
327  case llvm::Triple::riscv32:
328  case llvm::Triple::riscv64:
329  riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
330  break;
331  case llvm::Triple::systemz:
332  systemz::getSystemZTargetFeatures(D, Args, Features);
333  break;
334  case llvm::Triple::aarch64:
335  case llvm::Triple::aarch64_32:
336  case llvm::Triple::aarch64_be:
337  aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS);
338  break;
339  case llvm::Triple::x86:
340  case llvm::Triple::x86_64:
341  x86::getX86TargetFeatures(D, Triple, Args, Features);
342  break;
343  case llvm::Triple::hexagon:
344  hexagon::getHexagonTargetFeatures(D, Args, Features);
345  break;
346  case llvm::Triple::wasm32:
347  case llvm::Triple::wasm64:
348  getWebAssemblyTargetFeatures(Args, Features);
349  break;
350  case llvm::Triple::sparc:
351  case llvm::Triple::sparcel:
352  case llvm::Triple::sparcv9:
353  sparc::getSparcTargetFeatures(D, Args, Features);
354  break;
355  case llvm::Triple::r600:
356  case llvm::Triple::amdgcn:
357  amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
358  break;
359  case llvm::Triple::nvptx:
360  case llvm::Triple::nvptx64:
361  NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features);
362  break;
363  case llvm::Triple::m68k:
364  m68k::getM68kTargetFeatures(D, Triple, Args, Features);
365  break;
366  case llvm::Triple::msp430:
367  msp430::getMSP430TargetFeatures(D, Args, Features);
368  break;
369  case llvm::Triple::ve:
370  ve::getVETargetFeatures(D, Args, Features);
371  break;
372  case llvm::Triple::csky:
373  csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features);
374  break;
375  }
376 
377  for (auto Feature : unifyTargetFeatures(Features)) {
378  CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature");
379  CmdArgs.push_back(Feature.data());
380  }
381 }
382 
383 static bool
385  const llvm::Triple &Triple) {
386  // We use the zero-cost exception tables for Objective-C if the non-fragile
387  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
388  // later.
389  if (runtime.isNonFragile())
390  return true;
391 
392  if (!Triple.isMacOSX())
393  return false;
394 
395  return (!Triple.isMacOSXVersionLT(10, 5) &&
396  (Triple.getArch() == llvm::Triple::x86_64 ||
397  Triple.getArch() == llvm::Triple::arm));
398 }
399 
400 /// Adds exception related arguments to the driver command arguments. There's a
401 /// main flag, -fexceptions and also language specific flags to enable/disable
402 /// C++ and Objective-C exceptions. This makes it possible to for example
403 /// disable C++ exceptions but enable Objective-C exceptions.
404 static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
405  const ToolChain &TC, bool KernelOrKext,
406  const ObjCRuntime &objcRuntime,
407  ArgStringList &CmdArgs) {
408  const llvm::Triple &Triple = TC.getTriple();
409 
410  if (KernelOrKext) {
411  // -mkernel and -fapple-kext imply no exceptions, so claim exception related
412  // arguments now to avoid warnings about unused arguments.
413  Args.ClaimAllArgs(options::OPT_fexceptions);
414  Args.ClaimAllArgs(options::OPT_fno_exceptions);
415  Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
416  Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
417  Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
418  Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
419  Args.ClaimAllArgs(options::OPT_fasync_exceptions);
420  Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
421  return false;
422  }
423 
424  // See if the user explicitly enabled exceptions.
425  bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
426  false);
427 
428  bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
429  options::OPT_fno_async_exceptions, false);
430  if (EHa) {
431  CmdArgs.push_back("-fasync-exceptions");
432  EH = true;
433  }
434 
435  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
436  // is not necessarily sensible, but follows GCC.
437  if (types::isObjC(InputType) &&
438  Args.hasFlag(options::OPT_fobjc_exceptions,
439  options::OPT_fno_objc_exceptions, true)) {
440  CmdArgs.push_back("-fobjc-exceptions");
441 
442  EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
443  }
444 
445  if (types::isCXX(InputType)) {
446  // Disable C++ EH by default on XCore and PS4/PS5.
447  bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
448  !Triple.isPS() && !Triple.isDriverKit();
449  Arg *ExceptionArg = Args.getLastArg(
450  options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
451  options::OPT_fexceptions, options::OPT_fno_exceptions);
452  if (ExceptionArg)
453  CXXExceptionsEnabled =
454  ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
455  ExceptionArg->getOption().matches(options::OPT_fexceptions);
456 
457  if (CXXExceptionsEnabled) {
458  CmdArgs.push_back("-fcxx-exceptions");
459 
460  EH = true;
461  }
462  }
463 
464  // OPT_fignore_exceptions means exception could still be thrown,
465  // but no clean up or catch would happen in current module.
466  // So we do not set EH to false.
467  Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
468 
469  if (EH)
470  CmdArgs.push_back("-fexceptions");
471  return EH;
472 }
473 
474 static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
475  const JobAction &JA) {
476  bool Default = true;
477  if (TC.getTriple().isOSDarwin()) {
478  // The native darwin assembler doesn't support the linker_option directives,
479  // so we disable them if we think the .s file will be passed to it.
480  Default = TC.useIntegratedAs();
481  }
482  // The linker_option directives are intended for host compilation.
485  Default = false;
486  return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
487  Default);
488 }
489 
490 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
491 // to the corresponding DebugInfoKind.
493  assert(A.getOption().matches(options::OPT_gN_Group) &&
494  "Not a -g option that specifies a debug-info level");
495  if (A.getOption().matches(options::OPT_g0) ||
496  A.getOption().matches(options::OPT_ggdb0))
498  if (A.getOption().matches(options::OPT_gline_tables_only) ||
499  A.getOption().matches(options::OPT_ggdb1))
501  if (A.getOption().matches(options::OPT_gline_directives_only))
504 }
505 
506 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
507  switch (Triple.getArch()){
508  default:
509  return false;
510  case llvm::Triple::arm:
511  case llvm::Triple::thumb:
512  // ARM Darwin targets require a frame pointer to be always present to aid
513  // offline debugging via backtraces.
514  return Triple.isOSDarwin();
515  }
516 }
517 
518 static bool useFramePointerForTargetByDefault(const ArgList &Args,
519  const llvm::Triple &Triple) {
520  if (Args.hasArg(options::OPT_pg) && !Args.hasArg(options::OPT_mfentry))
521  return true;
522 
523  switch (Triple.getArch()) {
524  case llvm::Triple::xcore:
525  case llvm::Triple::wasm32:
526  case llvm::Triple::wasm64:
527  case llvm::Triple::msp430:
528  // XCore never wants frame pointers, regardless of OS.
529  // WebAssembly never wants frame pointers.
530  return false;
531  case llvm::Triple::ppc:
532  case llvm::Triple::ppcle:
533  case llvm::Triple::ppc64:
534  case llvm::Triple::ppc64le:
535  case llvm::Triple::riscv32:
536  case llvm::Triple::riscv64:
537  case llvm::Triple::amdgcn:
538  case llvm::Triple::r600:
539  case llvm::Triple::csky:
540  case llvm::Triple::loongarch32:
541  case llvm::Triple::loongarch64:
542  return !areOptimizationsEnabled(Args);
543  default:
544  break;
545  }
546 
547  if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
548  return !areOptimizationsEnabled(Args);
549  }
550 
551  if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
552  Triple.isOSHurd()) {
553  switch (Triple.getArch()) {
554  // Don't use a frame pointer on linux if optimizing for certain targets.
555  case llvm::Triple::arm:
556  case llvm::Triple::armeb:
557  case llvm::Triple::thumb:
558  case llvm::Triple::thumbeb:
559  if (Triple.isAndroid())
560  return true;
561  [[fallthrough]];
562  case llvm::Triple::mips64:
563  case llvm::Triple::mips64el:
564  case llvm::Triple::mips:
565  case llvm::Triple::mipsel:
566  case llvm::Triple::systemz:
567  case llvm::Triple::x86:
568  case llvm::Triple::x86_64:
569  return !areOptimizationsEnabled(Args);
570  default:
571  return true;
572  }
573  }
574 
575  if (Triple.isOSWindows()) {
576  switch (Triple.getArch()) {
577  case llvm::Triple::x86:
578  return !areOptimizationsEnabled(Args);
579  case llvm::Triple::x86_64:
580  return Triple.isOSBinFormatMachO();
581  case llvm::Triple::arm:
582  case llvm::Triple::thumb:
583  // Windows on ARM builds with FPO disabled to aid fast stack walking
584  return true;
585  default:
586  // All other supported Windows ISAs use xdata unwind information, so frame
587  // pointers are not generally useful.
588  return false;
589  }
590  }
591 
592  return true;
593 }
594 
596 getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
597  // We have 4 states:
598  //
599  // 00) leaf retained, non-leaf retained
600  // 01) leaf retained, non-leaf omitted (this is invalid)
601  // 10) leaf omitted, non-leaf retained
602  // (what -momit-leaf-frame-pointer was designed for)
603  // 11) leaf omitted, non-leaf omitted
604  //
605  // "omit" options taking precedence over "no-omit" options is the only way
606  // to make 3 valid states representable
607  Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
608  options::OPT_fno_omit_frame_pointer);
609  bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
610  bool NoOmitFP =
611  A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
612  bool OmitLeafFP =
613  Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
614  options::OPT_mno_omit_leaf_frame_pointer,
615  Triple.isAArch64() || Triple.isPS() || Triple.isVE());
616  if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
617  (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
618  if (OmitLeafFP)
621  }
623 }
624 
625 /// Add a CC1 option to specify the debug compilation directory.
626 static const char *addDebugCompDirArg(const ArgList &Args,
627  ArgStringList &CmdArgs,
628  const llvm::vfs::FileSystem &VFS) {
629  if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
630  options::OPT_fdebug_compilation_dir_EQ)) {
631  if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
632  CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
633  A->getValue()));
634  else
635  A->render(Args, CmdArgs);
636  } else if (llvm::ErrorOr<std::string> CWD =
637  VFS.getCurrentWorkingDirectory()) {
638  CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
639  }
640  StringRef Path(CmdArgs.back());
641  return Path.substr(Path.find('=') + 1).data();
642 }
643 
644 static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
645  const char *DebugCompilationDir,
646  const char *OutputFileName) {
647  // No need to generate a value for -object-file-name if it was provided.
648  for (auto *Arg : Args.filtered(options::OPT_Xclang))
649  if (StringRef(Arg->getValue()).startswith("-object-file-name"))
650  return;
651 
652  if (Args.hasArg(options::OPT_object_file_name_EQ))
653  return;
654 
655  SmallString<128> ObjFileNameForDebug(OutputFileName);
656  if (ObjFileNameForDebug != "-" &&
657  !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
658  (!DebugCompilationDir ||
659  llvm::sys::path::is_absolute(DebugCompilationDir))) {
660  // Make the path absolute in the debug infos like MSVC does.
661  llvm::sys::fs::make_absolute(ObjFileNameForDebug);
662  }
663  CmdArgs.push_back(
664  Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
665 }
666 
667 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
668 static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
669  const ArgList &Args, ArgStringList &CmdArgs) {
670  auto AddOneArg = [&](StringRef Map, StringRef Name) {
671  if (!Map.contains('='))
672  D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
673  else
674  CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
675  };
676 
677  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
678  options::OPT_fdebug_prefix_map_EQ)) {
679  AddOneArg(A->getValue(), A->getOption().getName());
680  A->claim();
681  }
682  std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
683  if (GlobalRemapEntry.empty())
684  return;
685  AddOneArg(GlobalRemapEntry, "environment");
686 }
687 
688 /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
689 static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
690  ArgStringList &CmdArgs) {
691  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
692  options::OPT_fmacro_prefix_map_EQ)) {
693  StringRef Map = A->getValue();
694  if (!Map.contains('='))
695  D.Diag(diag::err_drv_invalid_argument_to_option)
696  << Map << A->getOption().getName();
697  else
698  CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
699  A->claim();
700  }
701 }
702 
703 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
704 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
705  ArgStringList &CmdArgs) {
706  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
707  options::OPT_fcoverage_prefix_map_EQ)) {
708  StringRef Map = A->getValue();
709  if (!Map.contains('='))
710  D.Diag(diag::err_drv_invalid_argument_to_option)
711  << Map << A->getOption().getName();
712  else
713  CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
714  A->claim();
715  }
716 }
717 
718 /// Vectorize at all optimization levels greater than 1 except for -Oz.
719 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
720 /// enabled.
721 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
722  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
723  if (A->getOption().matches(options::OPT_O4) ||
724  A->getOption().matches(options::OPT_Ofast))
725  return true;
726 
727  if (A->getOption().matches(options::OPT_O0))
728  return false;
729 
730  assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
731 
732  // Vectorize -Os.
733  StringRef S(A->getValue());
734  if (S == "s")
735  return true;
736 
737  // Don't vectorize -Oz, unless it's the slp vectorizer.
738  if (S == "z")
739  return isSlpVec;
740 
741  unsigned OptLevel = 0;
742  if (S.getAsInteger(10, OptLevel))
743  return false;
744 
745  return OptLevel > 1;
746  }
747 
748  return false;
749 }
750 
751 /// Add -x lang to \p CmdArgs for \p Input.
752 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
753  ArgStringList &CmdArgs) {
754  // When using -verify-pch, we don't want to provide the type
755  // 'precompiled-header' if it was inferred from the file extension
756  if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
757  return;
758 
759  CmdArgs.push_back("-x");
760  if (Args.hasArg(options::OPT_rewrite_objc))
761  CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
762  else {
763  // Map the driver type to the frontend type. This is mostly an identity
764  // mapping, except that the distinction between module interface units
765  // and other source files does not exist at the frontend layer.
766  const char *ClangType;
767  switch (Input.getType()) {
768  case types::TY_CXXModule:
769  ClangType = "c++";
770  break;
771  case types::TY_PP_CXXModule:
772  ClangType = "c++-cpp-output";
773  break;
774  default:
775  ClangType = types::getTypeName(Input.getType());
776  break;
777  }
778  CmdArgs.push_back(ClangType);
779  }
780 }
781 
782 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
783  const Driver &D, const InputInfo &Output,
784  const ArgList &Args, SanitizerArgs &SanArgs,
785  ArgStringList &CmdArgs) {
786 
787  auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
788  options::OPT_fprofile_generate_EQ,
789  options::OPT_fno_profile_generate);
790  if (PGOGenerateArg &&
791  PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
792  PGOGenerateArg = nullptr;
793 
794  auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
795  options::OPT_fcs_profile_generate_EQ,
796  options::OPT_fno_profile_generate);
797  if (CSPGOGenerateArg &&
798  CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
799  CSPGOGenerateArg = nullptr;
800 
801  auto *ProfileGenerateArg = Args.getLastArg(
802  options::OPT_fprofile_instr_generate,
803  options::OPT_fprofile_instr_generate_EQ,
804  options::OPT_fno_profile_instr_generate);
805  if (ProfileGenerateArg &&
806  ProfileGenerateArg->getOption().matches(
807  options::OPT_fno_profile_instr_generate))
808  ProfileGenerateArg = nullptr;
809 
810  if (PGOGenerateArg && ProfileGenerateArg)
811  D.Diag(diag::err_drv_argument_not_allowed_with)
812  << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
813 
814  auto *ProfileUseArg = getLastProfileUseArg(Args);
815 
816  if (PGOGenerateArg && ProfileUseArg)
817  D.Diag(diag::err_drv_argument_not_allowed_with)
818  << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
819 
820  if (ProfileGenerateArg && ProfileUseArg)
821  D.Diag(diag::err_drv_argument_not_allowed_with)
822  << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
823 
824  if (CSPGOGenerateArg && PGOGenerateArg) {
825  D.Diag(diag::err_drv_argument_not_allowed_with)
826  << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
827  PGOGenerateArg = nullptr;
828  }
829 
830  if (TC.getTriple().isOSAIX()) {
831  if (ProfileGenerateArg)
832  D.Diag(diag::err_drv_unsupported_opt_for_target)
833  << ProfileGenerateArg->getSpelling() << TC.getTriple().str();
834  if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
835  D.Diag(diag::err_drv_unsupported_opt_for_target)
836  << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
837  }
838 
839  if (ProfileGenerateArg) {
840  if (ProfileGenerateArg->getOption().matches(
841  options::OPT_fprofile_instr_generate_EQ))
842  CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
843  ProfileGenerateArg->getValue()));
844  // The default is to use Clang Instrumentation.
845  CmdArgs.push_back("-fprofile-instrument=clang");
846  if (TC.getTriple().isWindowsMSVCEnvironment()) {
847  // Add dependent lib for clang_rt.profile
848  CmdArgs.push_back(Args.MakeArgString(
849  "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
850  }
851  }
852 
853  Arg *PGOGenArg = nullptr;
854  if (PGOGenerateArg) {
855  assert(!CSPGOGenerateArg);
856  PGOGenArg = PGOGenerateArg;
857  CmdArgs.push_back("-fprofile-instrument=llvm");
858  }
859  if (CSPGOGenerateArg) {
860  assert(!PGOGenerateArg);
861  PGOGenArg = CSPGOGenerateArg;
862  CmdArgs.push_back("-fprofile-instrument=csllvm");
863  }
864  if (PGOGenArg) {
865  if (TC.getTriple().isWindowsMSVCEnvironment()) {
866  // Add dependent lib for clang_rt.profile
867  CmdArgs.push_back(Args.MakeArgString(
868  "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
869  }
870  if (PGOGenArg->getOption().matches(
871  PGOGenerateArg ? options::OPT_fprofile_generate_EQ
872  : options::OPT_fcs_profile_generate_EQ)) {
873  SmallString<128> Path(PGOGenArg->getValue());
874  llvm::sys::path::append(Path, "default_%m.profraw");
875  CmdArgs.push_back(
876  Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
877  }
878  }
879 
880  if (ProfileUseArg) {
881  if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
882  CmdArgs.push_back(Args.MakeArgString(
883  Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
884  else if ((ProfileUseArg->getOption().matches(
885  options::OPT_fprofile_use_EQ) ||
886  ProfileUseArg->getOption().matches(
887  options::OPT_fprofile_instr_use))) {
888  SmallString<128> Path(
889  ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
890  if (Path.empty() || llvm::sys::fs::is_directory(Path))
891  llvm::sys::path::append(Path, "default.profdata");
892  CmdArgs.push_back(
893  Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
894  }
895  }
896 
897  bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
898  options::OPT_fno_test_coverage, false) ||
899  Args.hasArg(options::OPT_coverage);
900  bool EmitCovData = TC.needsGCovInstrumentation(Args);
901  if (EmitCovNotes)
902  CmdArgs.push_back("-ftest-coverage");
903  if (EmitCovData)
904  CmdArgs.push_back("-fprofile-arcs");
905 
906  if (Args.hasFlag(options::OPT_fcoverage_mapping,
907  options::OPT_fno_coverage_mapping, false)) {
908  if (!ProfileGenerateArg)
909  D.Diag(clang::diag::err_drv_argument_only_allowed_with)
910  << "-fcoverage-mapping"
911  << "-fprofile-instr-generate";
912 
913  CmdArgs.push_back("-fcoverage-mapping");
914  }
915 
916  if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
917  options::OPT_fcoverage_compilation_dir_EQ)) {
918  if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
919  CmdArgs.push_back(Args.MakeArgString(
920  Twine("-fcoverage-compilation-dir=") + A->getValue()));
921  else
922  A->render(Args, CmdArgs);
923  } else if (llvm::ErrorOr<std::string> CWD =
924  D.getVFS().getCurrentWorkingDirectory()) {
925  CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
926  }
927 
928  if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
929  auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
930  if (!Args.hasArg(options::OPT_coverage))
931  D.Diag(clang::diag::err_drv_argument_only_allowed_with)
932  << "-fprofile-exclude-files="
933  << "--coverage";
934 
935  StringRef v = Arg->getValue();
936  CmdArgs.push_back(
937  Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
938  }
939 
940  if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
941  auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
942  if (!Args.hasArg(options::OPT_coverage))
943  D.Diag(clang::diag::err_drv_argument_only_allowed_with)
944  << "-fprofile-filter-files="
945  << "--coverage";
946 
947  StringRef v = Arg->getValue();
948  CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
949  }
950 
951  if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
952  StringRef Val = A->getValue();
953  if (Val == "atomic" || Val == "prefer-atomic")
954  CmdArgs.push_back("-fprofile-update=atomic");
955  else if (Val != "single")
956  D.Diag(diag::err_drv_unsupported_option_argument)
957  << A->getOption().getName() << Val;
958  } else if (SanArgs.needsTsanRt()) {
959  CmdArgs.push_back("-fprofile-update=atomic");
960  }
961 
962  int FunctionGroups = 1;
963  int SelectedFunctionGroup = 0;
964  if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
965  StringRef Val = A->getValue();
966  if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
967  D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
968  }
969  if (const auto *A =
970  Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
971  StringRef Val = A->getValue();
972  if (Val.getAsInteger(0, SelectedFunctionGroup) ||
973  SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
974  D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
975  }
976  if (FunctionGroups != 1)
977  CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
978  Twine(FunctionGroups)));
979  if (SelectedFunctionGroup != 0)
980  CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
981  Twine(SelectedFunctionGroup)));
982 
983  // Leave -fprofile-dir= an unused argument unless .gcda emission is
984  // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
985  // the flag used. There is no -fno-profile-dir, so the user has no
986  // targeted way to suppress the warning.
987  Arg *FProfileDir = nullptr;
988  if (Args.hasArg(options::OPT_fprofile_arcs) ||
989  Args.hasArg(options::OPT_coverage))
990  FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
991 
992  // Put the .gcno and .gcda files (if needed) next to the object file or
993  // bitcode file in the case of LTO.
994  // FIXME: There should be a simpler way to find the object file for this
995  // input, and this code probably does the wrong thing for commands that
996  // compile and link all at once.
997  if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
998  (EmitCovNotes || EmitCovData) && Output.isFilename()) {
999  SmallString<128> OutputFilename;
1000  if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT__SLASH_Fo))
1001  OutputFilename = FinalOutput->getValue();
1002  else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1003  OutputFilename = FinalOutput->getValue();
1004  else
1005  OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
1006  SmallString<128> CoverageFilename = OutputFilename;
1007  if (llvm::sys::path::is_relative(CoverageFilename))
1008  (void)D.getVFS().makeAbsolute(CoverageFilename);
1009  llvm::sys::path::replace_extension(CoverageFilename, "gcno");
1010 
1011  CmdArgs.push_back("-coverage-notes-file");
1012  CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
1013 
1014  if (EmitCovData) {
1015  if (FProfileDir) {
1016  CoverageFilename = FProfileDir->getValue();
1017  llvm::sys::path::append(CoverageFilename, OutputFilename);
1018  }
1019  llvm::sys::path::replace_extension(CoverageFilename, "gcda");
1020  CmdArgs.push_back("-coverage-data-file");
1021  CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
1022  }
1023  }
1024 }
1025 
1026 /// Check whether the given input tree contains any compilation actions.
1027 static bool ContainsCompileAction(const Action *A) {
1028  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
1029  return true;
1030 
1031  return llvm::any_of(A->inputs(), ContainsCompileAction);
1032 }
1033 
1034 /// Check if -relax-all should be passed to the internal assembler.
1035 /// This is done by default when compiling non-assembler source with -O0.
1036 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
1037  bool RelaxDefault = true;
1038 
1039  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1040  RelaxDefault = A->getOption().matches(options::OPT_O0);
1041 
1042  if (RelaxDefault) {
1043  RelaxDefault = false;
1044  for (const auto &Act : C.getActions()) {
1045  if (ContainsCompileAction(Act)) {
1046  RelaxDefault = true;
1047  break;
1048  }
1049  }
1050  }
1051 
1052  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1053  RelaxDefault);
1054 }
1055 
1056 // Extract the integer N from a string spelled "-dwarf-N", returning 0
1057 // on mismatch. The StringRef input (rather than an Arg) allows
1058 // for use by the "-Xassembler" option parser.
1059 static unsigned DwarfVersionNum(StringRef ArgValue) {
1060  return llvm::StringSwitch<unsigned>(ArgValue)
1061  .Case("-gdwarf-2", 2)
1062  .Case("-gdwarf-3", 3)
1063  .Case("-gdwarf-4", 4)
1064  .Case("-gdwarf-5", 5)
1065  .Default(0);
1066 }
1067 
1068 // Find a DWARF format version option.
1069 // This function is a complementary for DwarfVersionNum().
1070 static const Arg *getDwarfNArg(const ArgList &Args) {
1071  return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
1072  options::OPT_gdwarf_4, options::OPT_gdwarf_5,
1073  options::OPT_gdwarf);
1074 }
1075 
1076 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
1078  unsigned DwarfVersion,
1079  llvm::DebuggerKind DebuggerTuning) {
1080  switch (DebugInfoKind) {
1082  CmdArgs.push_back("-debug-info-kind=line-directives-only");
1083  break;
1085  CmdArgs.push_back("-debug-info-kind=line-tables-only");
1086  break;
1088  CmdArgs.push_back("-debug-info-kind=constructor");
1089  break;
1091  CmdArgs.push_back("-debug-info-kind=limited");
1092  break;
1094  CmdArgs.push_back("-debug-info-kind=standalone");
1095  break;
1097  CmdArgs.push_back("-debug-info-kind=unused-types");
1098  break;
1099  default:
1100  break;
1101  }
1102  if (DwarfVersion > 0)
1103  CmdArgs.push_back(
1104  Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
1105  switch (DebuggerTuning) {
1106  case llvm::DebuggerKind::GDB:
1107  CmdArgs.push_back("-debugger-tuning=gdb");
1108  break;
1109  case llvm::DebuggerKind::LLDB:
1110  CmdArgs.push_back("-debugger-tuning=lldb");
1111  break;
1112  case llvm::DebuggerKind::SCE:
1113  CmdArgs.push_back("-debugger-tuning=sce");
1114  break;
1115  case llvm::DebuggerKind::DBX:
1116  CmdArgs.push_back("-debugger-tuning=dbx");
1117  break;
1118  default:
1119  break;
1120  }
1121 }
1122 
1123 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1124  const Driver &D, const ToolChain &TC) {
1125  assert(A && "Expected non-nullptr argument.");
1126  if (TC.supportsDebugInfoOption(A))
1127  return true;
1128  D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1129  << A->getAsString(Args) << TC.getTripleString();
1130  return false;
1131 }
1132 
1133 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1134  ArgStringList &CmdArgs,
1135  const Driver &D,
1136  const ToolChain &TC) {
1137  const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
1138  if (!A)
1139  return;
1140  if (checkDebugInfoOption(A, Args, D, TC)) {
1141  StringRef Value = A->getValue();
1142  if (Value == "none") {
1143  CmdArgs.push_back("--compress-debug-sections=none");
1144  } else if (Value == "zlib") {
1145  if (llvm::compression::zlib::isAvailable()) {
1146  CmdArgs.push_back(
1147  Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1148  } else {
1149  D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
1150  }
1151  } else if (Value == "zstd") {
1152  if (llvm::compression::zstd::isAvailable()) {
1153  CmdArgs.push_back(
1154  Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1155  } else {
1156  D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
1157  }
1158  } else {
1159  D.Diag(diag::err_drv_unsupported_option_argument)
1160  << A->getOption().getName() << Value;
1161  }
1162  }
1163 }
1164 
1166  const ArgList &Args,
1167  ArgStringList &CmdArgs,
1168  bool IsCC1As = false) {
1169  // If no version was requested by the user, use the default value from the
1170  // back end. This is consistent with the value returned from
1171  // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
1172  // requiring the corresponding llvm to have the AMDGPU target enabled,
1173  // provided the user (e.g. front end tests) can use the default.
1174  if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
1175  unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
1176  CmdArgs.insert(CmdArgs.begin() + 1,
1177  Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
1178  Twine(CodeObjVer)));
1179  CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
1180  // -cc1as does not accept -mcode-object-version option.
1181  if (!IsCC1As)
1182  CmdArgs.insert(CmdArgs.begin() + 1,
1183  Args.MakeArgString(Twine("-mcode-object-version=") +
1184  Twine(CodeObjVer)));
1185  }
1186 }
1187 
1188 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1189  const Driver &D, const ArgList &Args,
1190  ArgStringList &CmdArgs,
1191  const InputInfo &Output,
1192  const InputInfoList &Inputs) const {
1193  const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1194 
1195  CheckPreprocessingOptions(D, Args);
1196 
1197  Args.AddLastArg(CmdArgs, options::OPT_C);
1198  Args.AddLastArg(CmdArgs, options::OPT_CC);
1199 
1200  // Handle dependency file generation.
1201  Arg *ArgM = Args.getLastArg(options::OPT_MM);
1202  if (!ArgM)
1203  ArgM = Args.getLastArg(options::OPT_M);
1204  Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1205  if (!ArgMD)
1206  ArgMD = Args.getLastArg(options::OPT_MD);
1207 
1208  // -M and -MM imply -w.
1209  if (ArgM)
1210  CmdArgs.push_back("-w");
1211  else
1212  ArgM = ArgMD;
1213 
1214  if (ArgM) {
1215  // Determine the output location.
1216  const char *DepFile;
1217  if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1218  DepFile = MF->getValue();
1219  C.addFailureResultFile(DepFile, &JA);
1220  } else if (Output.getType() == types::TY_Dependencies) {
1221  DepFile = Output.getFilename();
1222  } else if (!ArgMD) {
1223  DepFile = "-";
1224  } else {
1225  DepFile = getDependencyFileName(Args, Inputs);
1226  C.addFailureResultFile(DepFile, &JA);
1227  }
1228  CmdArgs.push_back("-dependency-file");
1229  CmdArgs.push_back(DepFile);
1230 
1231  bool HasTarget = false;
1232  for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1233  HasTarget = true;
1234  A->claim();
1235  if (A->getOption().matches(options::OPT_MT)) {
1236  A->render(Args, CmdArgs);
1237  } else {
1238  CmdArgs.push_back("-MT");
1240  quoteMakeTarget(A->getValue(), Quoted);
1241  CmdArgs.push_back(Args.MakeArgString(Quoted));
1242  }
1243  }
1244 
1245  // Add a default target if one wasn't specified.
1246  if (!HasTarget) {
1247  const char *DepTarget;
1248 
1249  // If user provided -o, that is the dependency target, except
1250  // when we are only generating a dependency file.
1251  Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1252  if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1253  DepTarget = OutputOpt->getValue();
1254  } else {
1255  // Otherwise derive from the base input.
1256  //
1257  // FIXME: This should use the computed output file location.
1258  SmallString<128> P(Inputs[0].getBaseInput());
1259  llvm::sys::path::replace_extension(P, "o");
1260  DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1261  }
1262 
1263  CmdArgs.push_back("-MT");
1265  quoteMakeTarget(DepTarget, Quoted);
1266  CmdArgs.push_back(Args.MakeArgString(Quoted));
1267  }
1268 
1269  if (ArgM->getOption().matches(options::OPT_M) ||
1270  ArgM->getOption().matches(options::OPT_MD))
1271  CmdArgs.push_back("-sys-header-deps");
1272  if ((isa<PrecompileJobAction>(JA) &&
1273  !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1274  Args.hasArg(options::OPT_fmodule_file_deps))
1275  CmdArgs.push_back("-module-file-deps");
1276  }
1277 
1278  if (Args.hasArg(options::OPT_MG)) {
1279  if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1280  ArgM->getOption().matches(options::OPT_MMD))
1281  D.Diag(diag::err_drv_mg_requires_m_or_mm);
1282  CmdArgs.push_back("-MG");
1283  }
1284 
1285  Args.AddLastArg(CmdArgs, options::OPT_MP);
1286  Args.AddLastArg(CmdArgs, options::OPT_MV);
1287 
1288  // Add offload include arguments specific for CUDA/HIP. This must happen
1289  // before we -I or -include anything else, because we must pick up the
1290  // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1291  // from e.g. /usr/local/include.
1293  getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1294  if (JA.isOffloading(Action::OFK_HIP))
1295  getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1296 
1297  // If we are offloading to a target via OpenMP we need to include the
1298  // openmp_wrappers folder which contains alternative system headers.
1300  !Args.hasArg(options::OPT_nostdinc) &&
1301  (getToolChain().getTriple().isNVPTX() ||
1302  getToolChain().getTriple().isAMDGCN())) {
1303  if (!Args.hasArg(options::OPT_nobuiltininc)) {
1304  // Add openmp_wrappers/* to our system include path. This lets us wrap
1305  // standard library headers.
1307  llvm::sys::path::append(P, "include");
1308  llvm::sys::path::append(P, "openmp_wrappers");
1309  CmdArgs.push_back("-internal-isystem");
1310  CmdArgs.push_back(Args.MakeArgString(P));
1311  }
1312 
1313  CmdArgs.push_back("-include");
1314  CmdArgs.push_back("__clang_openmp_device_functions.h");
1315  }
1316 
1317  // Add -i* options, and automatically translate to
1318  // -include-pch/-include-pth for transparent PCH support. It's
1319  // wonky, but we include looking for .gch so we can support seamless
1320  // replacement into a build system already set up to be generating
1321  // .gch files.
1322 
1323  if (getToolChain().getDriver().IsCLMode()) {
1324  const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1325  const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1326  if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1328  CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1329  // -fpch-instantiate-templates is the default when creating
1330  // precomp using /Yc
1331  if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1332  options::OPT_fno_pch_instantiate_templates, true))
1333  CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1334  }
1335  if (YcArg || YuArg) {
1336  StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1337  if (!isa<PrecompileJobAction>(JA)) {
1338  CmdArgs.push_back("-include-pch");
1339  CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1340  C, !ThroughHeader.empty()
1341  ? ThroughHeader
1342  : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1343  }
1344 
1345  if (ThroughHeader.empty()) {
1346  CmdArgs.push_back(Args.MakeArgString(
1347  Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1348  } else {
1349  CmdArgs.push_back(
1350  Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1351  }
1352  }
1353  }
1354 
1355  bool RenderedImplicitInclude = false;
1356  for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1357  if (A->getOption().matches(options::OPT_include) &&
1358  D.getProbePrecompiled()) {
1359  // Handling of gcc-style gch precompiled headers.
1360  bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1361  RenderedImplicitInclude = true;
1362 
1363  bool FoundPCH = false;
1364  SmallString<128> P(A->getValue());
1365  // We want the files to have a name like foo.h.pch. Add a dummy extension
1366  // so that replace_extension does the right thing.
1367  P += ".dummy";
1368  llvm::sys::path::replace_extension(P, "pch");
1369  if (D.getVFS().exists(P))
1370  FoundPCH = true;
1371 
1372  if (!FoundPCH) {
1373  llvm::sys::path::replace_extension(P, "gch");
1374  if (D.getVFS().exists(P)) {
1375  FoundPCH = true;
1376  }
1377  }
1378 
1379  if (FoundPCH) {
1380  if (IsFirstImplicitInclude) {
1381  A->claim();
1382  CmdArgs.push_back("-include-pch");
1383  CmdArgs.push_back(Args.MakeArgString(P));
1384  continue;
1385  } else {
1386  // Ignore the PCH if not first on command line and emit warning.
1387  D.Diag(diag::warn_drv_pch_not_first_include) << P
1388  << A->getAsString(Args);
1389  }
1390  }
1391  } else if (A->getOption().matches(options::OPT_isystem_after)) {
1392  // Handling of paths which must come late. These entries are handled by
1393  // the toolchain itself after the resource dir is inserted in the right
1394  // search order.
1395  // Do not claim the argument so that the use of the argument does not
1396  // silently go unnoticed on toolchains which do not honour the option.
1397  continue;
1398  } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1399  // Translated to -internal-isystem by the driver, no need to pass to cc1.
1400  continue;
1401  }
1402 
1403  // Not translated, render as usual.
1404  A->claim();
1405  A->render(Args, CmdArgs);
1406  }
1407 
1408  Args.AddAllArgs(CmdArgs,
1409  {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1410  options::OPT_F, options::OPT_index_header_map});
1411 
1412  // Add -Wp, and -Xpreprocessor if using the preprocessor.
1413 
1414  // FIXME: There is a very unfortunate problem here, some troubled
1415  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1416  // really support that we would have to parse and then translate
1417  // those options. :(
1418  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1419  options::OPT_Xpreprocessor);
1420 
1421  // -I- is a deprecated GCC feature, reject it.
1422  if (Arg *A = Args.getLastArg(options::OPT_I_))
1423  D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1424 
1425  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1426  // -isysroot to the CC1 invocation.
1427  StringRef sysroot = C.getSysRoot();
1428  if (sysroot != "") {
1429  if (!Args.hasArg(options::OPT_isysroot)) {
1430  CmdArgs.push_back("-isysroot");
1431  CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1432  }
1433  }
1434 
1435  // Parse additional include paths from environment variables.
1436  // FIXME: We should probably sink the logic for handling these from the
1437  // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1438  // CPATH - included following the user specified includes (but prior to
1439  // builtin and standard includes).
1440  addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1441  // C_INCLUDE_PATH - system includes enabled when compiling C.
1442  addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1443  // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1444  addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1445  // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1446  addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1447  // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1448  addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1449 
1450  // While adding the include arguments, we also attempt to retrieve the
1451  // arguments of related offloading toolchains or arguments that are specific
1452  // of an offloading programming model.
1453 
1454  // Add C++ include arguments, if needed.
1455  if (types::isCXX(Inputs[0].getType())) {
1456  bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1458  C, JA, getToolChain(),
1459  [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1460  HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1461  : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1462  });
1463  }
1464 
1465  // Add system include arguments for all targets but IAMCU.
1466  if (!IsIAMCU)
1467  forAllAssociatedToolChains(C, JA, getToolChain(),
1468  [&Args, &CmdArgs](const ToolChain &TC) {
1469  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1470  });
1471  else {
1472  // For IAMCU add special include arguments.
1473  getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1474  }
1475 
1476  addMacroPrefixMapArg(D, Args, CmdArgs);
1477  addCoveragePrefixMapArg(D, Args, CmdArgs);
1478 
1479  Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1480  options::OPT_fno_file_reproducible);
1481 }
1482 
1483 // FIXME: Move to target hook.
1484 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1485  switch (Triple.getArch()) {
1486  default:
1487  return true;
1488 
1489  case llvm::Triple::aarch64:
1490  case llvm::Triple::aarch64_32:
1491  case llvm::Triple::aarch64_be:
1492  case llvm::Triple::arm:
1493  case llvm::Triple::armeb:
1494  case llvm::Triple::thumb:
1495  case llvm::Triple::thumbeb:
1496  if (Triple.isOSDarwin() || Triple.isOSWindows())
1497  return true;
1498  return false;
1499 
1500  case llvm::Triple::ppc:
1501  case llvm::Triple::ppc64:
1502  if (Triple.isOSDarwin())
1503  return true;
1504  return false;
1505 
1506  case llvm::Triple::hexagon:
1507  case llvm::Triple::ppcle:
1508  case llvm::Triple::ppc64le:
1509  case llvm::Triple::riscv32:
1510  case llvm::Triple::riscv64:
1511  case llvm::Triple::systemz:
1512  case llvm::Triple::xcore:
1513  return false;
1514  }
1515 }
1516 
1517 static bool hasMultipleInvocations(const llvm::Triple &Triple,
1518  const ArgList &Args) {
1519  // Supported only on Darwin where we invoke the compiler multiple times
1520  // followed by an invocation to lipo.
1521  if (!Triple.isOSDarwin())
1522  return false;
1523  // If more than one "-arch <arch>" is specified, we're targeting multiple
1524  // architectures resulting in a fat binary.
1525  return Args.getAllArgValues(options::OPT_arch).size() > 1;
1526 }
1527 
1528 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1529  const llvm::Triple &Triple) {
1530  // When enabling remarks, we need to error if:
1531  // * The remark file is specified but we're targeting multiple architectures,
1532  // which means more than one remark file is being generated.
1533  bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1534  bool hasExplicitOutputFile =
1535  Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1536  if (hasMultipleInvocations && hasExplicitOutputFile) {
1537  D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1538  << "-foptimization-record-file";
1539  return false;
1540  }
1541  return true;
1542 }
1543 
1544 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1545  const llvm::Triple &Triple,
1546  const InputInfo &Input,
1547  const InputInfo &Output, const JobAction &JA) {
1548  StringRef Format = "yaml";
1549  if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1550  Format = A->getValue();
1551 
1552  CmdArgs.push_back("-opt-record-file");
1553 
1554  const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1555  if (A) {
1556  CmdArgs.push_back(A->getValue());
1557  } else {
1558  bool hasMultipleArchs =
1559  Triple.isOSDarwin() && // Only supported on Darwin platforms.
1560  Args.getAllArgValues(options::OPT_arch).size() > 1;
1561 
1562  SmallString<128> F;
1563 
1564  if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1565  if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1566  F = FinalOutput->getValue();
1567  } else {
1568  if (Format != "yaml" && // For YAML, keep the original behavior.
1569  Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1570  Output.isFilename())
1571  F = Output.getFilename();
1572  }
1573 
1574  if (F.empty()) {
1575  // Use the input filename.
1576  F = llvm::sys::path::stem(Input.getBaseInput());
1577 
1578  // If we're compiling for an offload architecture (i.e. a CUDA device),
1579  // we need to make the file name for the device compilation different
1580  // from the host compilation.
1583  llvm::sys::path::replace_extension(F, "");
1585  Triple.normalize());
1586  F += "-";
1587  F += JA.getOffloadingArch();
1588  }
1589  }
1590 
1591  // If we're having more than one "-arch", we should name the files
1592  // differently so that every cc1 invocation writes to a different file.
1593  // We're doing that by appending "-<arch>" with "<arch>" being the arch
1594  // name from the triple.
1595  if (hasMultipleArchs) {
1596  // First, remember the extension.
1597  SmallString<64> OldExtension = llvm::sys::path::extension(F);
1598  // then, remove it.
1599  llvm::sys::path::replace_extension(F, "");
1600  // attach -<arch> to it.
1601  F += "-";
1602  F += Triple.getArchName();
1603  // put back the extension.
1604  llvm::sys::path::replace_extension(F, OldExtension);
1605  }
1606 
1607  SmallString<32> Extension;
1608  Extension += "opt.";
1609  Extension += Format;
1610 
1611  llvm::sys::path::replace_extension(F, Extension);
1612  CmdArgs.push_back(Args.MakeArgString(F));
1613  }
1614 
1615  if (const Arg *A =
1616  Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1617  CmdArgs.push_back("-opt-record-passes");
1618  CmdArgs.push_back(A->getValue());
1619  }
1620 
1621  if (!Format.empty()) {
1622  CmdArgs.push_back("-opt-record-format");
1623  CmdArgs.push_back(Format.data());
1624  }
1625 }
1626 
1627 void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1628  if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1629  options::OPT_fno_aapcs_bitfield_width, true))
1630  CmdArgs.push_back("-fno-aapcs-bitfield-width");
1631 
1632  if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1633  CmdArgs.push_back("-faapcs-bitfield-load");
1634 }
1635 
1636 namespace {
1637 void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1638  const ArgList &Args, ArgStringList &CmdArgs) {
1639  // Select the ABI to use.
1640  // FIXME: Support -meabi.
1641  // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1642  const char *ABIName = nullptr;
1643  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1644  ABIName = A->getValue();
1645  } else {
1646  std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1647  ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1648  }
1649 
1650  CmdArgs.push_back("-target-abi");
1651  CmdArgs.push_back(ABIName);
1652 }
1653 
1654 void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1655  auto StrictAlignIter =
1656  std::find_if(CmdArgs.rbegin(), CmdArgs.rend(), [](StringRef Arg) {
1657  return Arg == "+strict-align" || Arg == "-strict-align";
1658  });
1659  if (StrictAlignIter != CmdArgs.rend() &&
1660  StringRef(*StrictAlignIter) == "+strict-align")
1661  CmdArgs.push_back("-Wunaligned-access");
1662 }
1663 }
1664 
1665 static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1666  ArgStringList &CmdArgs, bool isAArch64) {
1667  const Arg *A = isAArch64
1668  ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1669  options::OPT_mbranch_protection_EQ)
1670  : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1671  if (!A)
1672  return;
1673 
1674  const Driver &D = TC.getDriver();
1675  const llvm::Triple &Triple = TC.getEffectiveTriple();
1676  if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1677  D.Diag(diag::warn_incompatible_branch_protection_option)
1678  << Triple.getArchName();
1679 
1680  StringRef Scope, Key;
1681  bool IndirectBranches;
1682 
1683  if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1684  Scope = A->getValue();
1685  if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1686  D.Diag(diag::err_drv_unsupported_option_argument)
1687  << A->getOption().getName() << Scope;
1688  Key = "a_key";
1689  IndirectBranches = false;
1690  } else {
1691  StringRef DiagMsg;
1692  llvm::ARM::ParsedBranchProtection PBP;
1693  if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
1694  D.Diag(diag::err_drv_unsupported_option_argument)
1695  << A->getOption().getName() << DiagMsg;
1696  if (!isAArch64 && PBP.Key == "b_key")
1697  D.Diag(diag::warn_unsupported_branch_protection)
1698  << "b-key" << A->getAsString(Args);
1699  Scope = PBP.Scope;
1700  Key = PBP.Key;
1701  IndirectBranches = PBP.BranchTargetEnforcement;
1702  }
1703 
1704  CmdArgs.push_back(
1705  Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1706  if (!Scope.equals("none"))
1707  CmdArgs.push_back(
1708  Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1709  if (IndirectBranches)
1710  CmdArgs.push_back("-mbranch-target-enforce");
1711 }
1712 
1713 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1714  ArgStringList &CmdArgs, bool KernelOrKext) const {
1715  RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1716 
1717  // Determine floating point ABI from the options & target defaults.
1718  arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1719  if (ABI == arm::FloatABI::Soft) {
1720  // Floating point operations and argument passing are soft.
1721  // FIXME: This changes CPP defines, we need -target-soft-float.
1722  CmdArgs.push_back("-msoft-float");
1723  CmdArgs.push_back("-mfloat-abi");
1724  CmdArgs.push_back("soft");
1725  } else if (ABI == arm::FloatABI::SoftFP) {
1726  // Floating point operations are hard, but argument passing is soft.
1727  CmdArgs.push_back("-mfloat-abi");
1728  CmdArgs.push_back("soft");
1729  } else {
1730  // Floating point operations and argument passing are hard.
1731  assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1732  CmdArgs.push_back("-mfloat-abi");
1733  CmdArgs.push_back("hard");
1734  }
1735 
1736  // Forward the -mglobal-merge option for explicit control over the pass.
1737  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1738  options::OPT_mno_global_merge)) {
1739  CmdArgs.push_back("-mllvm");
1740  if (A->getOption().matches(options::OPT_mno_global_merge))
1741  CmdArgs.push_back("-arm-global-merge=false");
1742  else
1743  CmdArgs.push_back("-arm-global-merge=true");
1744  }
1745 
1746  if (!Args.hasFlag(options::OPT_mimplicit_float,
1747  options::OPT_mno_implicit_float, true))
1748  CmdArgs.push_back("-no-implicit-float");
1749 
1750  if (Args.getLastArg(options::OPT_mcmse))
1751  CmdArgs.push_back("-mcmse");
1752 
1753  AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1754 
1755  // Enable/disable return address signing and indirect branch targets.
1756  CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1757 
1758  AddUnalignedAccessWarning(CmdArgs);
1759 }
1760 
1761 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1762  const ArgList &Args, bool KernelOrKext,
1763  ArgStringList &CmdArgs) const {
1764  const ToolChain &TC = getToolChain();
1765 
1766  // Add the target features
1767  getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1768 
1769  // Add target specific flags.
1770  switch (TC.getArch()) {
1771  default:
1772  break;
1773 
1774  case llvm::Triple::arm:
1775  case llvm::Triple::armeb:
1776  case llvm::Triple::thumb:
1777  case llvm::Triple::thumbeb:
1778  // Use the effective triple, which takes into account the deployment target.
1779  AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1780  break;
1781 
1782  case llvm::Triple::aarch64:
1783  case llvm::Triple::aarch64_32:
1784  case llvm::Triple::aarch64_be:
1785  AddAArch64TargetArgs(Args, CmdArgs);
1786  break;
1787 
1788  case llvm::Triple::loongarch32:
1789  case llvm::Triple::loongarch64:
1790  AddLoongArchTargetArgs(Args, CmdArgs);
1791  break;
1792 
1793  case llvm::Triple::mips:
1794  case llvm::Triple::mipsel:
1795  case llvm::Triple::mips64:
1796  case llvm::Triple::mips64el:
1797  AddMIPSTargetArgs(Args, CmdArgs);
1798  break;
1799 
1800  case llvm::Triple::ppc:
1801  case llvm::Triple::ppcle:
1802  case llvm::Triple::ppc64:
1803  case llvm::Triple::ppc64le:
1804  AddPPCTargetArgs(Args, CmdArgs);
1805  break;
1806 
1807  case llvm::Triple::riscv32:
1808  case llvm::Triple::riscv64:
1809  AddRISCVTargetArgs(Args, CmdArgs);
1810  break;
1811 
1812  case llvm::Triple::sparc:
1813  case llvm::Triple::sparcel:
1814  case llvm::Triple::sparcv9:
1815  AddSparcTargetArgs(Args, CmdArgs);
1816  break;
1817 
1818  case llvm::Triple::systemz:
1819  AddSystemZTargetArgs(Args, CmdArgs);
1820  break;
1821 
1822  case llvm::Triple::x86:
1823  case llvm::Triple::x86_64:
1824  AddX86TargetArgs(Args, CmdArgs);
1825  break;
1826 
1827  case llvm::Triple::lanai:
1828  AddLanaiTargetArgs(Args, CmdArgs);
1829  break;
1830 
1831  case llvm::Triple::hexagon:
1832  AddHexagonTargetArgs(Args, CmdArgs);
1833  break;
1834 
1835  case llvm::Triple::wasm32:
1836  case llvm::Triple::wasm64:
1837  AddWebAssemblyTargetArgs(Args, CmdArgs);
1838  break;
1839 
1840  case llvm::Triple::ve:
1841  AddVETargetArgs(Args, CmdArgs);
1842  break;
1843  }
1844 }
1845 
1846 namespace {
1847 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1848  ArgStringList &CmdArgs) {
1849  const char *ABIName = nullptr;
1850  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1851  ABIName = A->getValue();
1852  else if (Triple.isOSDarwin())
1853  ABIName = "darwinpcs";
1854  else
1855  ABIName = "aapcs";
1856 
1857  CmdArgs.push_back("-target-abi");
1858  CmdArgs.push_back(ABIName);
1859 }
1860 }
1861 
1862 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1863  ArgStringList &CmdArgs) const {
1864  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1865 
1866  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1867  Args.hasArg(options::OPT_mkernel) ||
1868  Args.hasArg(options::OPT_fapple_kext))
1869  CmdArgs.push_back("-disable-red-zone");
1870 
1871  if (!Args.hasFlag(options::OPT_mimplicit_float,
1872  options::OPT_mno_implicit_float, true))
1873  CmdArgs.push_back("-no-implicit-float");
1874 
1875  RenderAArch64ABI(Triple, Args, CmdArgs);
1876 
1877  // Forward the -mglobal-merge option for explicit control over the pass.
1878  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1879  options::OPT_mno_global_merge)) {
1880  CmdArgs.push_back("-mllvm");
1881  if (A->getOption().matches(options::OPT_mno_global_merge))
1882  CmdArgs.push_back("-aarch64-enable-global-merge=false");
1883  else
1884  CmdArgs.push_back("-aarch64-enable-global-merge=true");
1885  }
1886 
1887  // Enable/disable return address signing and indirect branch targets.
1888  CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1889 
1890  // Handle -msve_vector_bits=<bits>
1891  if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1892  StringRef Val = A->getValue();
1893  const Driver &D = getToolChain().getDriver();
1894  if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1895  Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
1896  Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
1897  Val.equals("2048+")) {
1898  unsigned Bits = 0;
1899  if (Val.endswith("+"))
1900  Val = Val.substr(0, Val.size() - 1);
1901  else {
1902  bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1903  assert(!Invalid && "Failed to parse value");
1904  CmdArgs.push_back(
1905  Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1906  }
1907 
1908  bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1909  assert(!Invalid && "Failed to parse value");
1910  CmdArgs.push_back(
1911  Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1912  // Silently drop requests for vector-length agnostic code as it's implied.
1913  } else if (!Val.equals("scalable"))
1914  // Handle the unsupported values passed to msve-vector-bits.
1915  D.Diag(diag::err_drv_unsupported_option_argument)
1916  << A->getOption().getName() << Val;
1917  }
1918 
1919  AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1920 
1921  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1922  CmdArgs.push_back("-tune-cpu");
1923  if (strcmp(A->getValue(), "native") == 0)
1924  CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1925  else
1926  CmdArgs.push_back(A->getValue());
1927  }
1928 
1929  AddUnalignedAccessWarning(CmdArgs);
1930 }
1931 
1932 void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1933  ArgStringList &CmdArgs) const {
1934  CmdArgs.push_back("-target-abi");
1935  CmdArgs.push_back(
1936  loongarch::getLoongArchABI(Args, getToolChain().getTriple()).data());
1937 }
1938 
1939 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1940  ArgStringList &CmdArgs) const {
1941  const Driver &D = getToolChain().getDriver();
1942  StringRef CPUName;
1943  StringRef ABIName;
1944  const llvm::Triple &Triple = getToolChain().getTriple();
1945  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1946 
1947  CmdArgs.push_back("-target-abi");
1948  CmdArgs.push_back(ABIName.data());
1949 
1950  mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1951  if (ABI == mips::FloatABI::Soft) {
1952  // Floating point operations and argument passing are soft.
1953  CmdArgs.push_back("-msoft-float");
1954  CmdArgs.push_back("-mfloat-abi");
1955  CmdArgs.push_back("soft");
1956  } else {
1957  // Floating point operations and argument passing are hard.
1958  assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1959  CmdArgs.push_back("-mfloat-abi");
1960  CmdArgs.push_back("hard");
1961  }
1962 
1963  if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1964  options::OPT_mno_ldc1_sdc1)) {
1965  if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1966  CmdArgs.push_back("-mllvm");
1967  CmdArgs.push_back("-mno-ldc1-sdc1");
1968  }
1969  }
1970 
1971  if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1972  options::OPT_mno_check_zero_division)) {
1973  if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1974  CmdArgs.push_back("-mllvm");
1975  CmdArgs.push_back("-mno-check-zero-division");
1976  }
1977  }
1978 
1979  if (Args.getLastArg(options::OPT_mfix4300)) {
1980  CmdArgs.push_back("-mllvm");
1981  CmdArgs.push_back("-mfix4300");
1982  }
1983 
1984  if (Arg *A = Args.getLastArg(options::OPT_G)) {
1985  StringRef v = A->getValue();
1986  CmdArgs.push_back("-mllvm");
1987  CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1988  A->claim();
1989  }
1990 
1991  Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1992  Arg *ABICalls =
1993  Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1994 
1995  // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1996  // -mgpopt is the default for static, -fno-pic environments but these two
1997  // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1998  // the only case where -mllvm -mgpopt is passed.
1999  // NOTE: We need a warning here or in the backend to warn when -mgpopt is
2000  // passed explicitly when compiling something with -mabicalls
2001  // (implictly) in affect. Currently the warning is in the backend.
2002  //
2003  // When the ABI in use is N64, we also need to determine the PIC mode that
2004  // is in use, as -fno-pic for N64 implies -mno-abicalls.
2005  bool NoABICalls =
2006  ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
2007 
2008  llvm::Reloc::Model RelocationModel;
2009  unsigned PICLevel;
2010  bool IsPIE;
2011  std::tie(RelocationModel, PICLevel, IsPIE) =
2012  ParsePICArgs(getToolChain(), Args);
2013 
2014  NoABICalls = NoABICalls ||
2015  (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
2016 
2017  bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
2018  // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
2019  if (NoABICalls && (!GPOpt || WantGPOpt)) {
2020  CmdArgs.push_back("-mllvm");
2021  CmdArgs.push_back("-mgpopt");
2022 
2023  Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
2024  options::OPT_mno_local_sdata);
2025  Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
2026  options::OPT_mno_extern_sdata);
2027  Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
2028  options::OPT_mno_embedded_data);
2029  if (LocalSData) {
2030  CmdArgs.push_back("-mllvm");
2031  if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
2032  CmdArgs.push_back("-mlocal-sdata=1");
2033  } else {
2034  CmdArgs.push_back("-mlocal-sdata=0");
2035  }
2036  LocalSData->claim();
2037  }
2038 
2039  if (ExternSData) {
2040  CmdArgs.push_back("-mllvm");
2041  if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
2042  CmdArgs.push_back("-mextern-sdata=1");
2043  } else {
2044  CmdArgs.push_back("-mextern-sdata=0");
2045  }
2046  ExternSData->claim();
2047  }
2048 
2049  if (EmbeddedData) {
2050  CmdArgs.push_back("-mllvm");
2051  if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
2052  CmdArgs.push_back("-membedded-data=1");
2053  } else {
2054  CmdArgs.push_back("-membedded-data=0");
2055  }
2056  EmbeddedData->claim();
2057  }
2058 
2059  } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
2060  D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
2061 
2062  if (GPOpt)
2063  GPOpt->claim();
2064 
2065  if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
2066  StringRef Val = StringRef(A->getValue());
2067  if (mips::hasCompactBranches(CPUName)) {
2068  if (Val == "never" || Val == "always" || Val == "optimal") {
2069  CmdArgs.push_back("-mllvm");
2070  CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
2071  } else
2072  D.Diag(diag::err_drv_unsupported_option_argument)
2073  << A->getOption().getName() << Val;
2074  } else
2075  D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
2076  }
2077 
2078  if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
2079  options::OPT_mno_relax_pic_calls)) {
2080  if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
2081  CmdArgs.push_back("-mllvm");
2082  CmdArgs.push_back("-mips-jalr-reloc=0");
2083  }
2084  }
2085 }
2086 
2087 void Clang::AddPPCTargetArgs(const ArgList &Args,
2088  ArgStringList &CmdArgs) const {
2089  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2090  CmdArgs.push_back("-tune-cpu");
2091  if (strcmp(A->getValue(), "native") == 0)
2092  CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2093  else
2094  CmdArgs.push_back(A->getValue());
2095  }
2096 
2097  // Select the ABI to use.
2098  const char *ABIName = nullptr;
2099  const llvm::Triple &T = getToolChain().getTriple();
2100  if (T.isOSBinFormatELF()) {
2101  switch (getToolChain().getArch()) {
2102  case llvm::Triple::ppc64: {
2103  if ((T.isOSFreeBSD() && T.getOSMajorVersion() >= 13) ||
2104  T.isOSOpenBSD() || T.isMusl())
2105  ABIName = "elfv2";
2106  else
2107  ABIName = "elfv1";
2108  break;
2109  }
2110  case llvm::Triple::ppc64le:
2111  ABIName = "elfv2";
2112  break;
2113  default:
2114  break;
2115  }
2116  }
2117 
2118  bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2119  for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2120  StringRef V = A->getValue();
2121  if (V == "ieeelongdouble")
2122  IEEELongDouble = true;
2123  else if (V == "ibmlongdouble")
2124  IEEELongDouble = false;
2125  else if (V != "altivec")
2126  // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2127  // the option if given as we don't have backend support for any targets
2128  // that don't use the altivec abi.
2129  ABIName = A->getValue();
2130  }
2131  if (IEEELongDouble)
2132  CmdArgs.push_back("-mabi=ieeelongdouble");
2133 
2135  ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
2136 
2137  if (FloatABI == ppc::FloatABI::Soft) {
2138  // Floating point operations and argument passing are soft.
2139  CmdArgs.push_back("-msoft-float");
2140  CmdArgs.push_back("-mfloat-abi");
2141  CmdArgs.push_back("soft");
2142  } else {
2143  // Floating point operations and argument passing are hard.
2144  assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2145  CmdArgs.push_back("-mfloat-abi");
2146  CmdArgs.push_back("hard");
2147  }
2148 
2149  if (ABIName) {
2150  CmdArgs.push_back("-target-abi");
2151  CmdArgs.push_back(ABIName);
2152  }
2153 }
2154 
2155 static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2156  ArgStringList &CmdArgs) {
2157  const Driver &D = TC.getDriver();
2158  const llvm::Triple &Triple = TC.getTriple();
2159  // Default small data limitation is eight.
2160  const char *SmallDataLimit = "8";
2161  // Get small data limitation.
2162  if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2163  options::OPT_fPIC)) {
2164  // Not support linker relaxation for PIC.
2165  SmallDataLimit = "0";
2166  if (Args.hasArg(options::OPT_G)) {
2167  D.Diag(diag::warn_drv_unsupported_sdata);
2168  }
2169  } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2170  .equals_insensitive("large") &&
2171  (Triple.getArch() == llvm::Triple::riscv64)) {
2172  // Not support linker relaxation for RV64 with large code model.
2173  SmallDataLimit = "0";
2174  if (Args.hasArg(options::OPT_G)) {
2175  D.Diag(diag::warn_drv_unsupported_sdata);
2176  }
2177  } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2178  SmallDataLimit = A->getValue();
2179  }
2180  // Forward the -msmall-data-limit= option.
2181  CmdArgs.push_back("-msmall-data-limit");
2182  CmdArgs.push_back(SmallDataLimit);
2183 }
2184 
2185 void Clang::AddRISCVTargetArgs(const ArgList &Args,
2186  ArgStringList &CmdArgs) const {
2187  const llvm::Triple &Triple = getToolChain().getTriple();
2188  StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2189 
2190  CmdArgs.push_back("-target-abi");
2191  CmdArgs.push_back(ABIName.data());
2192 
2193  SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2194 
2195  if (!Args.hasFlag(options::OPT_mimplicit_float,
2196  options::OPT_mno_implicit_float, true))
2197  CmdArgs.push_back("-no-implicit-float");
2198 
2199  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2200  CmdArgs.push_back("-tune-cpu");
2201  CmdArgs.push_back(A->getValue());
2202  }
2203 }
2204 
2205 void Clang::AddSparcTargetArgs(const ArgList &Args,
2206  ArgStringList &CmdArgs) const {
2208  sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2209 
2211  // Floating point operations and argument passing are soft.
2212  CmdArgs.push_back("-msoft-float");
2213  CmdArgs.push_back("-mfloat-abi");
2214  CmdArgs.push_back("soft");
2215  } else {
2216  // Floating point operations and argument passing are hard.
2217  assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2218  CmdArgs.push_back("-mfloat-abi");
2219  CmdArgs.push_back("hard");
2220  }
2221 
2222  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2223  StringRef Name = A->getValue();
2224  std::string TuneCPU;
2225  if (Name == "native")
2226  TuneCPU = std::string(llvm::sys::getHostCPUName());
2227  else
2228  TuneCPU = std::string(Name);
2229 
2230  CmdArgs.push_back("-tune-cpu");
2231  CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2232  }
2233 }
2234 
2235 void Clang::AddSystemZTargetArgs(const ArgList &Args,
2236  ArgStringList &CmdArgs) const {
2237  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2238  CmdArgs.push_back("-tune-cpu");
2239  if (strcmp(A->getValue(), "native") == 0)
2240  CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2241  else
2242  CmdArgs.push_back(A->getValue());
2243  }
2244 
2245  bool HasBackchain =
2246  Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2247  bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2248  options::OPT_mno_packed_stack, false);
2250  systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2251  bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2252  if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2253  const Driver &D = getToolChain().getDriver();
2254  D.Diag(diag::err_drv_unsupported_opt)
2255  << "-mpacked-stack -mbackchain -mhard-float";
2256  }
2257  if (HasBackchain)
2258  CmdArgs.push_back("-mbackchain");
2259  if (HasPackedStack)
2260  CmdArgs.push_back("-mpacked-stack");
2261  if (HasSoftFloat) {
2262  // Floating point operations and argument passing are soft.
2263  CmdArgs.push_back("-msoft-float");
2264  CmdArgs.push_back("-mfloat-abi");
2265  CmdArgs.push_back("soft");
2266  }
2267 }
2268 
2269 void Clang::AddX86TargetArgs(const ArgList &Args,
2270  ArgStringList &CmdArgs) const {
2271  const Driver &D = getToolChain().getDriver();
2272  addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2273 
2274  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2275  Args.hasArg(options::OPT_mkernel) ||
2276  Args.hasArg(options::OPT_fapple_kext))
2277  CmdArgs.push_back("-disable-red-zone");
2278 
2279  if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2280  options::OPT_mno_tls_direct_seg_refs, true))
2281  CmdArgs.push_back("-mno-tls-direct-seg-refs");
2282 
2283  // Default to avoid implicit floating-point for kernel/kext code, but allow
2284  // that to be overridden with -mno-soft-float.
2285  bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2286  Args.hasArg(options::OPT_fapple_kext));
2287  if (Arg *A = Args.getLastArg(
2288  options::OPT_msoft_float, options::OPT_mno_soft_float,
2289  options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2290  const Option &O = A->getOption();
2291  NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2292  O.matches(options::OPT_msoft_float));
2293  }
2294  if (NoImplicitFloat)
2295  CmdArgs.push_back("-no-implicit-float");
2296 
2297  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2298  StringRef Value = A->getValue();
2299  if (Value == "intel" || Value == "att") {
2300  CmdArgs.push_back("-mllvm");
2301  CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2302  CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2303  } else {
2304  D.Diag(diag::err_drv_unsupported_option_argument)
2305  << A->getOption().getName() << Value;
2306  }
2307  } else if (D.IsCLMode()) {
2308  CmdArgs.push_back("-mllvm");
2309  CmdArgs.push_back("-x86-asm-syntax=intel");
2310  }
2311 
2312  if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2313  options::OPT_mno_skip_rax_setup))
2314  if (A->getOption().matches(options::OPT_mskip_rax_setup))
2315  CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2316 
2317  // Set flags to support MCU ABI.
2318  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2319  CmdArgs.push_back("-mfloat-abi");
2320  CmdArgs.push_back("soft");
2321  CmdArgs.push_back("-mstack-alignment=4");
2322  }
2323 
2324  // Handle -mtune.
2325 
2326  // Default to "generic" unless -march is present or targetting the PS4/PS5.
2327  std::string TuneCPU;
2328  if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2329  !getToolChain().getTriple().isPS())
2330  TuneCPU = "generic";
2331 
2332  // Override based on -mtune.
2333  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2334  StringRef Name = A->getValue();
2335 
2336  if (Name == "native") {
2337  Name = llvm::sys::getHostCPUName();
2338  if (!Name.empty())
2339  TuneCPU = std::string(Name);
2340  } else
2341  TuneCPU = std::string(Name);
2342  }
2343 
2344  if (!TuneCPU.empty()) {
2345  CmdArgs.push_back("-tune-cpu");
2346  CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2347  }
2348 }
2349 
2350 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2351  ArgStringList &CmdArgs) const {
2352  CmdArgs.push_back("-mqdsp6-compat");
2353  CmdArgs.push_back("-Wreturn-type");
2354 
2356  CmdArgs.push_back("-mllvm");
2357  CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
2358  Twine(G.value())));
2359  }
2360 
2361  if (!Args.hasArg(options::OPT_fno_short_enums))
2362  CmdArgs.push_back("-fshort-enums");
2363  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2364  CmdArgs.push_back("-mllvm");
2365  CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2366  }
2367  CmdArgs.push_back("-mllvm");
2368  CmdArgs.push_back("-machine-sink-split=0");
2369 }
2370 
2371 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2372  ArgStringList &CmdArgs) const {
2373  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2374  StringRef CPUName = A->getValue();
2375 
2376  CmdArgs.push_back("-target-cpu");
2377  CmdArgs.push_back(Args.MakeArgString(CPUName));
2378  }
2379  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2380  StringRef Value = A->getValue();
2381  // Only support mregparm=4 to support old usage. Report error for all other
2382  // cases.
2383  int Mregparm;
2384  if (Value.getAsInteger(10, Mregparm)) {
2385  if (Mregparm != 4) {
2386  getToolChain().getDriver().Diag(
2387  diag::err_drv_unsupported_option_argument)
2388  << A->getOption().getName() << Value;
2389  }
2390  }
2391  }
2392 }
2393 
2394 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2395  ArgStringList &CmdArgs) const {
2396  // Default to "hidden" visibility.
2397  if (!Args.hasArg(options::OPT_fvisibility_EQ,
2398  options::OPT_fvisibility_ms_compat))
2399  CmdArgs.push_back("-fvisibility=hidden");
2400 }
2401 
2402 void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2403  // Floating point operations and argument passing are hard.
2404  CmdArgs.push_back("-mfloat-abi");
2405  CmdArgs.push_back("hard");
2406 }
2407 
2408 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2409  StringRef Target, const InputInfo &Output,
2410  const InputInfo &Input, const ArgList &Args) const {
2411  // If this is a dry run, do not create the compilation database file.
2412  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2413  return;
2414 
2415  using llvm::yaml::escape;
2416  const Driver &D = getToolChain().getDriver();
2417 
2418  if (!CompilationDatabase) {
2419  std::error_code EC;
2420  auto File = std::make_unique<llvm::raw_fd_ostream>(
2421  Filename, EC,
2422  llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2423  if (EC) {
2424  D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2425  << EC.message();
2426  return;
2427  }
2428  CompilationDatabase = std::move(File);
2429  }
2430  auto &CDB = *CompilationDatabase;
2431  auto CWD = D.getVFS().getCurrentWorkingDirectory();
2432  if (!CWD)
2433  CWD = ".";
2434  CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2435  CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2436  CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2437  CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2438  SmallString<128> Buf;
2439  Buf = "-x";
2440  Buf += types::getTypeName(Input.getType());
2441  CDB << ", \"" << escape(Buf) << "\"";
2442  if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2443  Buf = "--sysroot=";
2444  Buf += D.SysRoot;
2445  CDB << ", \"" << escape(Buf) << "\"";
2446  }
2447  CDB << ", \"" << escape(Input.getFilename()) << "\"";
2448  CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2449  for (auto &A: Args) {
2450  auto &O = A->getOption();
2451  // Skip language selection, which is positional.
2452  if (O.getID() == options::OPT_x)
2453  continue;
2454  // Skip writing dependency output and the compilation database itself.
2455  if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2456  continue;
2457  if (O.getID() == options::OPT_gen_cdb_fragment_path)
2458  continue;
2459  // Skip inputs.
2460  if (O.getKind() == Option::InputClass)
2461  continue;
2462  // Skip output.
2463  if (O.getID() == options::OPT_o)
2464  continue;
2465  // All other arguments are quoted and appended.
2466  ArgStringList ASL;
2467  A->render(Args, ASL);
2468  for (auto &it: ASL)
2469  CDB << ", \"" << escape(it) << "\"";
2470  }
2471  Buf = "--target=";
2472  Buf += Target;
2473  CDB << ", \"" << escape(Buf) << "\"]},\n";
2474 }
2475 
2476 void Clang::DumpCompilationDatabaseFragmentToDir(
2477  StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2478  const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2479  // If this is a dry run, do not create the compilation database file.
2480  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2481  return;
2482 
2483  if (CompilationDatabase)
2484  DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2485 
2486  SmallString<256> Path = Dir;
2487  const auto &Driver = C.getDriver();
2488  Driver.getVFS().makeAbsolute(Path);
2489  auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2490  if (Err) {
2491  Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2492  return;
2493  }
2494 
2495  llvm::sys::path::append(
2496  Path,
2497  Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2498  int FD;
2499  SmallString<256> TempPath;
2500  Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2501  llvm::sys::fs::OF_Text);
2502  if (Err) {
2503  Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2504  return;
2505  }
2506  CompilationDatabase =
2507  std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2508  DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2509 }
2510 
2511 static bool CheckARMImplicitITArg(StringRef Value) {
2512  return Value == "always" || Value == "never" || Value == "arm" ||
2513  Value == "thumb";
2514 }
2515 
2516 static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2517  StringRef Value) {
2518  CmdArgs.push_back("-mllvm");
2519  CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2520 }
2521 
2523  const ArgList &Args,
2524  ArgStringList &CmdArgs,
2525  const Driver &D) {
2526  if (UseRelaxAll(C, Args))
2527  CmdArgs.push_back("-mrelax-all");
2528 
2529  // Only default to -mincremental-linker-compatible if we think we are
2530  // targeting the MSVC linker.
2531  bool DefaultIncrementalLinkerCompatible =
2532  C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2533  if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2534  options::OPT_mno_incremental_linker_compatible,
2535  DefaultIncrementalLinkerCompatible))
2536  CmdArgs.push_back("-mincremental-linker-compatible");
2537 
2538  Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2539 
2540  // If you add more args here, also add them to the block below that
2541  // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2542 
2543  // When passing -I arguments to the assembler we sometimes need to
2544  // unconditionally take the next argument. For example, when parsing
2545  // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2546  // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2547  // arg after parsing the '-I' arg.
2548  bool TakeNextArg = false;
2549 
2550  bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2551  bool UseNoExecStack = false;
2552  const char *MipsTargetFeature = nullptr;
2553  StringRef ImplicitIt;
2554  for (const Arg *A :
2555  Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2556  options::OPT_mimplicit_it_EQ)) {
2557  A->claim();
2558 
2559  if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2560  switch (C.getDefaultToolChain().getArch()) {
2561  case llvm::Triple::arm:
2562  case llvm::Triple::armeb:
2563  case llvm::Triple::thumb:
2564  case llvm::Triple::thumbeb:
2565  // Only store the value; the last value set takes effect.
2566  ImplicitIt = A->getValue();
2567  if (!CheckARMImplicitITArg(ImplicitIt))
2568  D.Diag(diag::err_drv_unsupported_option_argument)
2569  << A->getOption().getName() << ImplicitIt;
2570  continue;
2571  default:
2572  break;
2573  }
2574  }
2575 
2576  for (StringRef Value : A->getValues()) {
2577  if (TakeNextArg) {
2578  CmdArgs.push_back(Value.data());
2579  TakeNextArg = false;
2580  continue;
2581  }
2582 
2583  if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2584  Value == "-mbig-obj")
2585  continue; // LLVM handles bigobj automatically
2586 
2587  switch (C.getDefaultToolChain().getArch()) {
2588  default:
2589  break;
2590  case llvm::Triple::wasm32:
2591  case llvm::Triple::wasm64:
2592  if (Value == "--no-type-check") {
2593  CmdArgs.push_back("-mno-type-check");
2594  continue;
2595  }
2596  break;
2597  case llvm::Triple::thumb:
2598  case llvm::Triple::thumbeb:
2599  case llvm::Triple::arm:
2600  case llvm::Triple::armeb:
2601  if (Value.startswith("-mimplicit-it=")) {
2602  // Only store the value; the last value set takes effect.
2603  ImplicitIt = Value.split("=").second;
2604  if (CheckARMImplicitITArg(ImplicitIt))
2605  continue;
2606  }
2607  if (Value == "-mthumb")
2608  // -mthumb has already been processed in ComputeLLVMTriple()
2609  // recognize but skip over here.
2610  continue;
2611  break;
2612  case llvm::Triple::mips:
2613  case llvm::Triple::mipsel:
2614  case llvm::Triple::mips64:
2615  case llvm::Triple::mips64el:
2616  if (Value == "--trap") {
2617  CmdArgs.push_back("-target-feature");
2618  CmdArgs.push_back("+use-tcc-in-div");
2619  continue;
2620  }
2621  if (Value == "--break") {
2622  CmdArgs.push_back("-target-feature");
2623  CmdArgs.push_back("-use-tcc-in-div");
2624  continue;
2625  }
2626  if (Value.startswith("-msoft-float")) {
2627  CmdArgs.push_back("-target-feature");
2628  CmdArgs.push_back("+soft-float");
2629  continue;
2630  }
2631  if (Value.startswith("-mhard-float")) {
2632  CmdArgs.push_back("-target-feature");
2633  CmdArgs.push_back("-soft-float");
2634  continue;
2635  }
2636 
2637  MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2638  .Case("-mips1", "+mips1")
2639  .Case("-mips2", "+mips2")
2640  .Case("-mips3", "+mips3")
2641  .Case("-mips4", "+mips4")
2642  .Case("-mips5", "+mips5")
2643  .Case("-mips32", "+mips32")
2644  .Case("-mips32r2", "+mips32r2")
2645  .Case("-mips32r3", "+mips32r3")
2646  .Case("-mips32r5", "+mips32r5")
2647  .Case("-mips32r6", "+mips32r6")
2648  .Case("-mips64", "+mips64")
2649  .Case("-mips64r2", "+mips64r2")
2650  .Case("-mips64r3", "+mips64r3")
2651  .Case("-mips64r5", "+mips64r5")
2652  .Case("-mips64r6", "+mips64r6")
2653  .Default(nullptr);
2654  if (MipsTargetFeature)
2655  continue;
2656  }
2657 
2658  if (Value == "-force_cpusubtype_ALL") {
2659  // Do nothing, this is the default and we don't support anything else.
2660  } else if (Value == "-L") {
2661  CmdArgs.push_back("-msave-temp-labels");
2662  } else if (Value == "--fatal-warnings") {
2663  CmdArgs.push_back("-massembler-fatal-warnings");
2664  } else if (Value == "--no-warn" || Value == "-W") {
2665  CmdArgs.push_back("-massembler-no-warn");
2666  } else if (Value == "--noexecstack") {
2667  UseNoExecStack = true;
2668  } else if (Value.startswith("-compress-debug-sections") ||
2669  Value.startswith("--compress-debug-sections") ||
2670  Value == "-nocompress-debug-sections" ||
2671  Value == "--nocompress-debug-sections") {
2672  CmdArgs.push_back(Value.data());
2673  } else if (Value == "-mrelax-relocations=yes" ||
2674  Value == "--mrelax-relocations=yes") {
2675  UseRelaxRelocations = true;
2676  } else if (Value == "-mrelax-relocations=no" ||
2677  Value == "--mrelax-relocations=no") {
2678  UseRelaxRelocations = false;
2679  } else if (Value.startswith("-I")) {
2680  CmdArgs.push_back(Value.data());
2681  // We need to consume the next argument if the current arg is a plain
2682  // -I. The next arg will be the include directory.
2683  if (Value == "-I")
2684  TakeNextArg = true;
2685  } else if (Value.startswith("-gdwarf-")) {
2686  // "-gdwarf-N" options are not cc1as options.
2687  unsigned DwarfVersion = DwarfVersionNum(Value);
2688  if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2689  CmdArgs.push_back(Value.data());
2690  } else {
2691  RenderDebugEnablingArgs(Args, CmdArgs,
2693  DwarfVersion, llvm::DebuggerKind::Default);
2694  }
2695  } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2696  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2697  // Do nothing, we'll validate it later.
2698  } else if (Value == "-defsym") {
2699  if (A->getNumValues() != 2) {
2700  D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2701  break;
2702  }
2703  const char *S = A->getValue(1);
2704  auto Pair = StringRef(S).split('=');
2705  auto Sym = Pair.first;
2706  auto SVal = Pair.second;
2707 
2708  if (Sym.empty() || SVal.empty()) {
2709  D.Diag(diag::err_drv_defsym_invalid_format) << S;
2710  break;
2711  }
2712  int64_t IVal;
2713  if (SVal.getAsInteger(0, IVal)) {
2714  D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2715  break;
2716  }
2717  CmdArgs.push_back(Value.data());
2718  TakeNextArg = true;
2719  } else if (Value == "-fdebug-compilation-dir") {
2720  CmdArgs.push_back("-fdebug-compilation-dir");
2721  TakeNextArg = true;
2722  } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2723  // The flag is a -Wa / -Xassembler argument and Options doesn't
2724  // parse the argument, so this isn't automatically aliased to
2725  // -fdebug-compilation-dir (without '=') here.
2726  CmdArgs.push_back("-fdebug-compilation-dir");
2727  CmdArgs.push_back(Value.data());
2728  } else if (Value == "--version") {
2729  D.PrintVersion(C, llvm::outs());
2730  } else {
2731  D.Diag(diag::err_drv_unsupported_option_argument)
2732  << A->getOption().getName() << Value;
2733  }
2734  }
2735  }
2736  if (ImplicitIt.size())
2737  AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2738  if (UseRelaxRelocations)
2739  CmdArgs.push_back("--mrelax-relocations");
2740  if (UseNoExecStack)
2741  CmdArgs.push_back("-mnoexecstack");
2742  if (MipsTargetFeature != nullptr) {
2743  CmdArgs.push_back("-target-feature");
2744  CmdArgs.push_back(MipsTargetFeature);
2745  }
2746 
2747  // forward -fembed-bitcode to assmebler
2748  if (C.getDriver().embedBitcodeEnabled() ||
2749  C.getDriver().embedBitcodeMarkerOnly())
2750  Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2751 }
2752 
2753 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2754  bool OFastEnabled, const ArgList &Args,
2755  ArgStringList &CmdArgs,
2756  const JobAction &JA) {
2757  // Handle various floating point optimization flags, mapping them to the
2758  // appropriate LLVM code generation flags. This is complicated by several
2759  // "umbrella" flags, so we do this by stepping through the flags incrementally
2760  // adjusting what we think is enabled/disabled, then at the end setting the
2761  // LLVM flags based on the final state.
2762  bool HonorINFs = true;
2763  bool HonorNaNs = true;
2764  bool ApproxFunc = false;
2765  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2766  bool MathErrno = TC.IsMathErrnoDefault();
2767  bool AssociativeMath = false;
2768  bool ReciprocalMath = false;
2769  bool SignedZeros = true;
2770  bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2771  bool TrappingMathPresent = false; // Is trapping-math in args, and not
2772  // overriden by ffp-exception-behavior?
2773  bool RoundingFPMath = false;
2774  bool RoundingMathPresent = false; // Is rounding-math in args?
2775  // -ffp-model values: strict, fast, precise
2776  StringRef FPModel = "";
2777  // -ffp-exception-behavior options: strict, maytrap, ignore
2778  StringRef FPExceptionBehavior = "";
2779  // -ffp-eval-method options: double, extended, source
2780  StringRef FPEvalMethod = "";
2781  const llvm::DenormalMode DefaultDenormalFPMath =
2782  TC.getDefaultDenormalModeForType(Args, JA);
2783  const llvm::DenormalMode DefaultDenormalFP32Math =
2784  TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2785 
2786  llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2787  llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2788  // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2789  // If one wasn't given by the user, don't pass it here.
2790  StringRef FPContract;
2791  StringRef LastSeenFfpContractOption;
2792  bool SeenFfastMathOption = false;
2795  FPContract = "on";
2796  bool StrictFPModel = false;
2797 
2798  if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2799  CmdArgs.push_back("-mlimit-float-precision");
2800  CmdArgs.push_back(A->getValue());
2801  }
2802 
2803  for (const Arg *A : Args) {
2804  auto optID = A->getOption().getID();
2805  bool PreciseFPModel = false;
2806  switch (optID) {
2807  default:
2808  break;
2809  case options::OPT_ffp_model_EQ: {
2810  // If -ffp-model= is seen, reset to fno-fast-math
2811  HonorINFs = true;
2812  HonorNaNs = true;
2813  // Turning *off* -ffast-math restores the toolchain default.
2814  MathErrno = TC.IsMathErrnoDefault();
2815  AssociativeMath = false;
2816  ReciprocalMath = false;
2817  SignedZeros = true;
2818  // -fno_fast_math restores default denormal and fpcontract handling
2819  FPContract = "on";
2820  DenormalFPMath = llvm::DenormalMode::getIEEE();
2821 
2822  // FIXME: The target may have picked a non-IEEE default mode here based on
2823  // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2824  DenormalFP32Math = llvm::DenormalMode::getIEEE();
2825 
2826  StringRef Val = A->getValue();
2827  if (OFastEnabled && !Val.equals("fast")) {
2828  // Only -ffp-model=fast is compatible with OFast, ignore.
2829  D.Diag(clang::diag::warn_drv_overriding_flag_option)
2830  << Args.MakeArgString("-ffp-model=" + Val)
2831  << "-Ofast";
2832  break;
2833  }
2834  StrictFPModel = false;
2835  PreciseFPModel = true;
2836  // ffp-model= is a Driver option, it is entirely rewritten into more
2837  // granular options before being passed into cc1.
2838  // Use the gcc option in the switch below.
2839  if (!FPModel.empty() && !FPModel.equals(Val))
2840  D.Diag(clang::diag::warn_drv_overriding_flag_option)
2841  << Args.MakeArgString("-ffp-model=" + FPModel)
2842  << Args.MakeArgString("-ffp-model=" + Val);
2843  if (Val.equals("fast")) {
2844  optID = options::OPT_ffast_math;
2845  FPModel = Val;
2846  FPContract = "fast";
2847  } else if (Val.equals("precise")) {
2848  optID = options::OPT_ffp_contract;
2849  FPModel = Val;
2850  FPContract = "on";
2851  PreciseFPModel = true;
2852  } else if (Val.equals("strict")) {
2853  StrictFPModel = true;
2854  optID = options::OPT_frounding_math;
2855  FPExceptionBehavior = "strict";
2856  FPModel = Val;
2857  FPContract = "off";
2858  TrappingMath = true;
2859  } else
2860  D.Diag(diag::err_drv_unsupported_option_argument)
2861  << A->getOption().getName() << Val;
2862  break;
2863  }
2864  }
2865 
2866  switch (optID) {
2867  // If this isn't an FP option skip the claim below
2868  default: continue;
2869 
2870  // Options controlling individual features
2871  case options::OPT_fhonor_infinities: HonorINFs = true; break;
2872  case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2873  case options::OPT_fhonor_nans: HonorNaNs = true; break;
2874  case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2875  case options::OPT_fapprox_func: ApproxFunc = true; break;
2876  case options::OPT_fno_approx_func: ApproxFunc = false; break;
2877  case options::OPT_fmath_errno: MathErrno = true; break;
2878  case options::OPT_fno_math_errno: MathErrno = false; break;
2879  case options::OPT_fassociative_math: AssociativeMath = true; break;
2880  case options::OPT_fno_associative_math: AssociativeMath = false; break;
2881  case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2882  case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2883  case options::OPT_fsigned_zeros: SignedZeros = true; break;
2884  case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2885  case options::OPT_ftrapping_math:
2886  if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2887  !FPExceptionBehavior.equals("strict"))
2888  // Warn that previous value of option is overridden.
2889  D.Diag(clang::diag::warn_drv_overriding_flag_option)
2890  << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2891  << "-ftrapping-math";
2892  TrappingMath = true;
2893  TrappingMathPresent = true;
2894  FPExceptionBehavior = "strict";
2895  break;
2896  case options::OPT_fno_trapping_math:
2897  if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2898  !FPExceptionBehavior.equals("ignore"))
2899  // Warn that previous value of option is overridden.
2900  D.Diag(clang::diag::warn_drv_overriding_flag_option)
2901  << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2902  << "-fno-trapping-math";
2903  TrappingMath = false;
2904  TrappingMathPresent = true;
2905  FPExceptionBehavior = "ignore";
2906  break;
2907 
2908  case options::OPT_frounding_math:
2909  RoundingFPMath = true;
2910  RoundingMathPresent = true;
2911  break;
2912 
2913  case options::OPT_fno_rounding_math:
2914  RoundingFPMath = false;
2915  RoundingMathPresent = false;
2916  break;
2917 
2918  case options::OPT_fdenormal_fp_math_EQ:
2919  DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2920  DenormalFP32Math = DenormalFPMath;
2921  if (!DenormalFPMath.isValid()) {
2922  D.Diag(diag::err_drv_invalid_value)
2923  << A->getAsString(Args) << A->getValue();
2924  }
2925  break;
2926 
2927  case options::OPT_fdenormal_fp_math_f32_EQ:
2928  DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2929  if (!DenormalFP32Math.isValid()) {
2930  D.Diag(diag::err_drv_invalid_value)
2931  << A->getAsString(Args) << A->getValue();
2932  }
2933  break;
2934 
2935  // Validate and pass through -ffp-contract option.
2936  case options::OPT_ffp_contract: {
2937  StringRef Val = A->getValue();
2938  if (PreciseFPModel) {
2939  // -ffp-model=precise enables ffp-contract=on.
2940  // -ffp-model=precise sets PreciseFPModel to on and Val to
2941  // "precise". FPContract is set.
2942  ;
2943  } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off")) {
2944  FPContract = Val;
2945  LastSeenFfpContractOption = Val;
2946  } else
2947  D.Diag(diag::err_drv_unsupported_option_argument)
2948  << A->getOption().getName() << Val;
2949  break;
2950  }
2951 
2952  // Validate and pass through -ffp-model option.
2953  case options::OPT_ffp_model_EQ:
2954  // This should only occur in the error case
2955  // since the optID has been replaced by a more granular
2956  // floating point option.
2957  break;
2958 
2959  // Validate and pass through -ffp-exception-behavior option.
2960  case options::OPT_ffp_exception_behavior_EQ: {
2961  StringRef Val = A->getValue();
2962  if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2963  !FPExceptionBehavior.equals(Val))
2964  // Warn that previous value of option is overridden.
2965  D.Diag(clang::diag::warn_drv_overriding_flag_option)
2966  << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2967  << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2968  TrappingMath = TrappingMathPresent = false;
2969  if (Val.equals("ignore") || Val.equals("maytrap"))
2970  FPExceptionBehavior = Val;
2971  else if (Val.equals("strict")) {
2972  FPExceptionBehavior = Val;
2973  TrappingMath = TrappingMathPresent = true;
2974  } else
2975  D.Diag(diag::err_drv_unsupported_option_argument)
2976  << A->getOption().getName() << Val;
2977  break;
2978  }
2979 
2980  // Validate and pass through -ffp-eval-method option.
2981  case options::OPT_ffp_eval_method_EQ: {
2982  StringRef Val = A->getValue();
2983  if (Val.equals("double") || Val.equals("extended") ||
2984  Val.equals("source"))
2985  FPEvalMethod = Val;
2986  else
2987  D.Diag(diag::err_drv_unsupported_option_argument)
2988  << A->getOption().getName() << Val;
2989  break;
2990  }
2991 
2992  case options::OPT_ffinite_math_only:
2993  HonorINFs = false;
2994  HonorNaNs = false;
2995  break;
2996  case options::OPT_fno_finite_math_only:
2997  HonorINFs = true;
2998  HonorNaNs = true;
2999  break;
3000 
3001  case options::OPT_funsafe_math_optimizations:
3002  AssociativeMath = true;
3003  ReciprocalMath = true;
3004  SignedZeros = false;
3005  ApproxFunc = true;
3006  TrappingMath = false;
3007  FPExceptionBehavior = "";
3008  break;
3009  case options::OPT_fno_unsafe_math_optimizations:
3010  AssociativeMath = false;
3011  ReciprocalMath = false;
3012  SignedZeros = true;
3013  ApproxFunc = false;
3014  TrappingMath = true;
3015  FPExceptionBehavior = "strict";
3016 
3017  // The target may have opted to flush by default, so force IEEE.
3018  DenormalFPMath = llvm::DenormalMode::getIEEE();
3019  DenormalFP32Math = llvm::DenormalMode::getIEEE();
3020  break;
3021 
3022  case options::OPT_Ofast:
3023  // If -Ofast is the optimization level, then -ffast-math should be enabled
3024  if (!OFastEnabled)
3025  continue;
3026  [[fallthrough]];
3027  case options::OPT_ffast_math:
3028  HonorINFs = false;
3029  HonorNaNs = false;
3030  MathErrno = false;
3031  AssociativeMath = true;
3032  ReciprocalMath = true;
3033  ApproxFunc = true;
3034  SignedZeros = false;
3035  TrappingMath = false;
3036  RoundingFPMath = false;
3037  // If fast-math is set then set the fp-contract mode to fast.
3038  FPContract = "fast";
3039  SeenFfastMathOption = true;
3040  break;
3041  case options::OPT_fno_fast_math:
3042  HonorINFs = true;
3043  HonorNaNs = true;
3044  // Turning on -ffast-math (with either flag) removes the need for
3045  // MathErrno. However, turning *off* -ffast-math merely restores the
3046  // toolchain default (which may be false).
3047  MathErrno = TC.IsMathErrnoDefault();
3048  AssociativeMath = false;
3049  ReciprocalMath = false;
3050  ApproxFunc = false;
3051  SignedZeros = true;
3052  // -fno_fast_math restores default denormal and fpcontract handling
3053  DenormalFPMath = DefaultDenormalFPMath;
3054  DenormalFP32Math = llvm::DenormalMode::getIEEE();
3057  if (LastSeenFfpContractOption != "") {
3058  FPContract = LastSeenFfpContractOption;
3059  } else if (SeenFfastMathOption)
3060  FPContract = "on";
3061  }
3062  break;
3063  }
3064  if (StrictFPModel) {
3065  // If -ffp-model=strict has been specified on command line but
3066  // subsequent options conflict then emit warning diagnostic.
3067  if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3068  SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3069  DenormalFPMath == llvm::DenormalMode::getIEEE() &&
3070  DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
3071  FPContract.equals("off"))
3072  // OK: Current Arg doesn't conflict with -ffp-model=strict
3073  ;
3074  else {
3075  StrictFPModel = false;
3076  FPModel = "";
3077  D.Diag(clang::diag::warn_drv_overriding_flag_option)
3078  << "-ffp-model=strict" <<
3079  ((A->getNumValues() == 0) ? A->getSpelling()
3080  : Args.MakeArgString(A->getSpelling() + A->getValue()));
3081  }
3082  }
3083 
3084  // If we handled this option claim it
3085  A->claim();
3086  }
3087 
3088  if (!HonorINFs)
3089  CmdArgs.push_back("-menable-no-infs");
3090 
3091  if (!HonorNaNs)
3092  CmdArgs.push_back("-menable-no-nans");
3093 
3094  if (ApproxFunc)
3095  CmdArgs.push_back("-fapprox-func");
3096 
3097  if (MathErrno)
3098  CmdArgs.push_back("-fmath-errno");
3099 
3100  if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3101  ApproxFunc && !TrappingMath)
3102  CmdArgs.push_back("-menable-unsafe-fp-math");
3103 
3104  if (!SignedZeros)
3105  CmdArgs.push_back("-fno-signed-zeros");
3106 
3107  if (AssociativeMath && !SignedZeros && !TrappingMath)
3108  CmdArgs.push_back("-mreassociate");
3109 
3110  if (ReciprocalMath)
3111  CmdArgs.push_back("-freciprocal-math");
3112 
3113  if (TrappingMath) {
3114  // FP Exception Behavior is also set to strict
3115  assert(FPExceptionBehavior.equals("strict"));
3116  }
3117 
3118  // The default is IEEE.
3119  if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3120  llvm::SmallString<64> DenormFlag;
3121  llvm::raw_svector_ostream ArgStr(DenormFlag);
3122  ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3123  CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3124  }
3125 
3126  // Add f32 specific denormal mode flag if it's different.
3127  if (DenormalFP32Math != DenormalFPMath) {
3128  llvm::SmallString<64> DenormFlag;
3129  llvm::raw_svector_ostream ArgStr(DenormFlag);
3130  ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3131  CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3132  }
3133 
3134  if (!FPContract.empty())
3135  CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3136 
3137  if (!RoundingFPMath)
3138  CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3139 
3140  if (RoundingFPMath && RoundingMathPresent)
3141  CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3142 
3143  if (!FPExceptionBehavior.empty())
3144  CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3145  FPExceptionBehavior));
3146 
3147  if (!FPEvalMethod.empty())
3148  CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3149 
3150  ParseMRecip(D, Args, CmdArgs);
3151 
3152  // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3153  // individual features enabled by -ffast-math instead of the option itself as
3154  // that's consistent with gcc's behaviour.
3155  if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3156  ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
3157  CmdArgs.push_back("-ffast-math");
3158  if (FPModel.equals("fast")) {
3159  if (FPContract.equals("fast"))
3160  // All set, do nothing.
3161  ;
3162  else if (FPContract.empty())
3163  // Enable -ffp-contract=fast
3164  CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3165  else
3166  D.Diag(clang::diag::warn_drv_overriding_flag_option)
3167  << "-ffp-model=fast"
3168  << Args.MakeArgString("-ffp-contract=" + FPContract);
3169  }
3170  }
3171 
3172  // Handle __FINITE_MATH_ONLY__ similarly.
3173  if (!HonorINFs && !HonorNaNs)
3174  CmdArgs.push_back("-ffinite-math-only");
3175 
3176  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3177  CmdArgs.push_back("-mfpmath");
3178  CmdArgs.push_back(A->getValue());
3179  }
3180 
3181  // Disable a codegen optimization for floating-point casts.
3182  if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3183  options::OPT_fstrict_float_cast_overflow, false))
3184  CmdArgs.push_back("-fno-strict-float-cast-overflow");
3185 }
3186 
3187 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3188  const llvm::Triple &Triple,
3189  const InputInfo &Input) {
3190  // Add default argument set.
3191  if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3192  CmdArgs.push_back("-analyzer-checker=core");
3193  CmdArgs.push_back("-analyzer-checker=apiModeling");
3194 
3195  if (!Triple.isWindowsMSVCEnvironment()) {
3196  CmdArgs.push_back("-analyzer-checker=unix");
3197  } else {
3198  // Enable "unix" checkers that also work on Windows.
3199  CmdArgs.push_back("-analyzer-checker=unix.API");
3200  CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3201  CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3202  CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3203  CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3204  CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3205  }
3206 
3207  // Disable some unix checkers for PS4/PS5.
3208  if (Triple.isPS()) {
3209  CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3210  CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3211  }
3212 
3213  if (Triple.isOSDarwin()) {
3214  CmdArgs.push_back("-analyzer-checker=osx");
3215  CmdArgs.push_back(
3216  "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3217  }
3218  else if (Triple.isOSFuchsia())
3219  CmdArgs.push_back("-analyzer-checker=fuchsia");
3220 
3221  CmdArgs.push_back("-analyzer-checker=deadcode");
3222 
3223  if (types::isCXX(Input.getType()))
3224  CmdArgs.push_back("-analyzer-checker=cplusplus");
3225 
3226  if (!Triple.isPS()) {
3227  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3228  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3229  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3230  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3231  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3232  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3233  }
3234 
3235  // Default nullability checks.
3236  CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3237  CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3238  }
3239 
3240  // Set the output format. The default is plist, for (lame) historical reasons.
3241  CmdArgs.push_back("-analyzer-output");
3242  if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3243  CmdArgs.push_back(A->getValue());
3244  else
3245  CmdArgs.push_back("plist");
3246 
3247  // Disable the presentation of standard compiler warnings when using
3248  // --analyze. We only want to show static analyzer diagnostics or frontend
3249  // errors.
3250  CmdArgs.push_back("-w");
3251 
3252  // Add -Xanalyzer arguments when running as analyzer.
3253  Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3254 }
3255 
3256 static bool isValidSymbolName(StringRef S) {
3257  if (S.empty())
3258  return false;
3259 
3260  if (std::isdigit(S[0]))
3261  return false;
3262 
3263  return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3264 }
3265 
3266 static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3267  const ArgList &Args, ArgStringList &CmdArgs,
3268  bool KernelOrKext) {
3269  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3270 
3271  // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3272  // doesn't even have a stack!
3273  if (EffectiveTriple.isNVPTX())
3274  return;
3275 
3276  // -stack-protector=0 is default.
3278  LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3279  TC.GetDefaultStackProtectorLevel(KernelOrKext);
3280 
3281  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3282  options::OPT_fstack_protector_all,
3283  options::OPT_fstack_protector_strong,
3284  options::OPT_fstack_protector)) {
3285  if (A->getOption().matches(options::OPT_fstack_protector))
3286  StackProtectorLevel =
3287  std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3288  else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3289  StackProtectorLevel = LangOptions::SSPStrong;
3290  else if (A->getOption().matches(options::OPT_fstack_protector_all))
3291  StackProtectorLevel = LangOptions::SSPReq;
3292  } else {
3293  StackProtectorLevel = DefaultStackProtectorLevel;
3294  }
3295 
3296  if (StackProtectorLevel) {
3297  CmdArgs.push_back("-stack-protector");
3298  CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3299  }
3300 
3301  // --param ssp-buffer-size=
3302  for (const Arg *A : Args.filtered(options::OPT__param)) {
3303  StringRef Str(A->getValue());
3304  if (Str.startswith("ssp-buffer-size=")) {
3305  if (StackProtectorLevel) {
3306  CmdArgs.push_back("-stack-protector-buffer-size");
3307  // FIXME: Verify the argument is a valid integer.
3308  CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3309  }
3310  A->claim();
3311  }
3312  }
3313 
3314  const std::string &TripleStr = EffectiveTriple.getTriple();
3315  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3316  StringRef Value = A->getValue();
3317  if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3318  !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3319  D.Diag(diag::err_drv_unsupported_opt_for_target)
3320  << A->getAsString(Args) << TripleStr;
3321  if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3322  EffectiveTriple.isThumb()) &&
3323  Value != "tls" && Value != "global") {
3324  D.Diag(diag::err_drv_invalid_value_with_suggestion)
3325  << A->getOption().getName() << Value << "tls global";
3326  return;
3327  }
3328  if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3329  Value == "tls") {
3330  if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3331  D.Diag(diag::err_drv_ssp_missing_offset_argument)
3332  << A->getAsString(Args);
3333  return;
3334  }
3335  // Check whether the target subarch supports the hardware TLS register
3336  if (!arm::isHardTPSupported(EffectiveTriple)) {
3337  D.Diag(diag::err_target_unsupported_tp_hard)
3338  << EffectiveTriple.getArchName();
3339  return;
3340  }
3341  // Check whether the user asked for something other than -mtp=cp15
3342  if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3343  StringRef Value = A->getValue();
3344  if (Value != "cp15") {
3345  D.Diag(diag::err_drv_argument_not_allowed_with)
3346  << A->getAsString(Args) << "-mstack-protector-guard=tls";
3347  return;
3348  }
3349  }
3350  CmdArgs.push_back("-target-feature");
3351  CmdArgs.push_back("+read-tp-hard");
3352  }
3353  if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3354  D.Diag(diag::err_drv_invalid_value_with_suggestion)
3355  << A->getOption().getName() << Value << "sysreg global";
3356  return;
3357  }
3358  A->render(Args, CmdArgs);
3359  }
3360 
3361  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3362  StringRef Value = A->getValue();
3363  if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3364  !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3365  D.Diag(diag::err_drv_unsupported_opt_for_target)
3366  << A->getAsString(Args) << TripleStr;
3367  int Offset;
3368  if (Value.getAsInteger(10, Offset)) {
3369  D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3370  return;
3371  }
3372  if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3373  (Offset < 0 || Offset > 0xfffff)) {
3374  D.Diag(diag::err_drv_invalid_int_value)
3375  << A->getOption().getName() << Value;
3376  return;
3377  }
3378  A->render(Args, CmdArgs);
3379  }
3380 
3381  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3382  StringRef Value = A->getValue();
3383  if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3384  D.Diag(diag::err_drv_unsupported_opt_for_target)
3385  << A->getAsString(Args) << TripleStr;
3386  if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3387  D.Diag(diag::err_drv_invalid_value_with_suggestion)
3388  << A->getOption().getName() << Value << "fs gs";
3389  return;
3390  }
3391  if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3392  D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3393  return;
3394  }
3395  A->render(Args, CmdArgs);
3396  }
3397 
3398  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3399  StringRef Value = A->getValue();
3400  if (!isValidSymbolName(Value)) {
3401  D.Diag(diag::err_drv_argument_only_allowed_with)
3402  << A->getOption().getName() << "legal symbol name";
3403  return;
3404  }
3405  A->render(Args, CmdArgs);
3406  }
3407 }
3408 
3409 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3410  ArgStringList &CmdArgs) {
3411  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3412 
3413  if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3414  return;
3415 
3416  if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3417  !EffectiveTriple.isPPC64())
3418  return;
3419 
3420  Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3421  options::OPT_fno_stack_clash_protection);
3422 }
3423 
3425  const ToolChain &TC,
3426  const ArgList &Args,
3427  ArgStringList &CmdArgs) {
3428  auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3429  StringRef TrivialAutoVarInit = "";
3430 
3431  for (const Arg *A : Args) {
3432  switch (A->getOption().getID()) {
3433  default:
3434  continue;
3435  case options::OPT_ftrivial_auto_var_init: {
3436  A->claim();
3437  StringRef Val = A->getValue();
3438  if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3439  TrivialAutoVarInit = Val;
3440  else
3441  D.Diag(diag::err_drv_unsupported_option_argument)
3442  << A->getOption().getName() << Val;
3443  break;
3444  }
3445  }
3446  }
3447 
3448  if (TrivialAutoVarInit.empty())
3449  switch (DefaultTrivialAutoVarInit) {
3451  break;
3453  TrivialAutoVarInit = "pattern";
3454  break;
3456  TrivialAutoVarInit = "zero";
3457  break;
3458  }
3459 
3460  if (!TrivialAutoVarInit.empty()) {
3461  CmdArgs.push_back(
3462  Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3463  }
3464 
3465  if (Arg *A =
3466  Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3467  if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3468  StringRef(
3469  Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3470  "uninitialized")
3471  D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3472  A->claim();
3473  StringRef Val = A->getValue();
3474  if (std::stoi(Val.str()) <= 0)
3475  D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3476  CmdArgs.push_back(
3477  Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3478  }
3479 }
3480 
3481 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3482  types::ID InputType) {
3483  // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3484  // for denormal flushing handling based on the target.
3485  const unsigned ForwardedArguments[] = {
3486  options::OPT_cl_opt_disable,
3487  options::OPT_cl_strict_aliasing,
3488  options::OPT_cl_single_precision_constant,
3489  options::OPT_cl_finite_math_only,
3490  options::OPT_cl_kernel_arg_info,
3491  options::OPT_cl_unsafe_math_optimizations,
3492  options::OPT_cl_fast_relaxed_math,
3493  options::OPT_cl_mad_enable,
3494  options::OPT_cl_no_signed_zeros,
3495  options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3496  options::OPT_cl_uniform_work_group_size
3497  };
3498 
3499  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3500  std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3501  CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3502  } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3503  std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3504  CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3505  }
3506 
3507  for (const auto &Arg : ForwardedArguments)
3508  if (const auto *A = Args.getLastArg(Arg))
3509  CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3510 
3511  // Only add the default headers if we are compiling OpenCL sources.
3512  if ((types::isOpenCL(InputType) ||
3513  (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3514  !Args.hasArg(options::OPT_cl_no_stdinc)) {
3515  CmdArgs.push_back("-finclude-default-header");
3516  CmdArgs.push_back("-fdeclare-opencl-builtins");
3517  }
3518 }
3519 
3520 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3521  types::ID InputType) {
3522  const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3523  options::OPT_D,
3524  options::OPT_I,
3525  options::OPT_S,
3526  options::OPT_O,
3527  options::OPT_emit_llvm,
3528  options::OPT_emit_obj,
3529  options::OPT_disable_llvm_passes,
3530  options::OPT_fnative_half_type,
3531  options::OPT_hlsl_entrypoint};
3532  if (!types::isHLSL(InputType))
3533  return;
3534  for (const auto &Arg : ForwardedArguments)
3535  if (const auto *A = Args.getLastArg(Arg))
3536  A->renderAsInput(Args, CmdArgs);
3537  // Add the default headers if dxc_no_stdinc is not set.
3538  if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3539  !Args.hasArg(options::OPT_nostdinc))
3540  CmdArgs.push_back("-finclude-default-header");
3541 }
3542 
3543 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3544  ArgStringList &CmdArgs) {
3545  bool ARCMTEnabled = false;
3546  if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3547  if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3548  options::OPT_ccc_arcmt_modify,
3549  options::OPT_ccc_arcmt_migrate)) {
3550  ARCMTEnabled = true;
3551  switch (A->getOption().getID()) {
3552  default: llvm_unreachable("missed a case");
3553  case options::OPT_ccc_arcmt_check:
3554  CmdArgs.push_back("-arcmt-action=check");
3555  break;
3556  case options::OPT_ccc_arcmt_modify:
3557  CmdArgs.push_back("-arcmt-action=modify");
3558  break;
3559  case options::OPT_ccc_arcmt_migrate:
3560  CmdArgs.push_back("-arcmt-action=migrate");
3561  CmdArgs.push_back("-mt-migrate-directory");
3562  CmdArgs.push_back(A->getValue());
3563 
3564  Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3565  Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3566  break;
3567  }
3568  }
3569  } else {
3570  Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3571  Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3572  Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3573  }
3574 
3575  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3576  if (ARCMTEnabled)
3577  D.Diag(diag::err_drv_argument_not_allowed_with)
3578  << A->getAsString(Args) << "-ccc-arcmt-migrate";
3579 
3580  CmdArgs.push_back("-mt-migrate-directory");
3581  CmdArgs.push_back(A->getValue());
3582 
3583  if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3584  options::OPT_objcmt_migrate_subscripting,
3585  options::OPT_objcmt_migrate_property)) {
3586  // None specified, means enable them all.
3587  CmdArgs.push_back("-objcmt-migrate-literals");
3588  CmdArgs.push_back("-objcmt-migrate-subscripting");
3589  CmdArgs.push_back("-objcmt-migrate-property");
3590  } else {
3591  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3592  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3593  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3594  }
3595  } else {
3596  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3597  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3598  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3599  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3600  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3601  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3602  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3603  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3604  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3605  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3606  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3607  Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3608  Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3609  Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3610  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3611  Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3612  }
3613 }
3614 
3615 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3616  const ArgList &Args, ArgStringList &CmdArgs) {
3617  // -fbuiltin is default unless -mkernel is used.
3618  bool UseBuiltins =
3619  Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3620  !Args.hasArg(options::OPT_mkernel));
3621  if (!UseBuiltins)
3622  CmdArgs.push_back("-fno-builtin");
3623 
3624  // -ffreestanding implies -fno-builtin.
3625  if (Args.hasArg(options::OPT_ffreestanding))
3626  UseBuiltins = false;
3627 
3628  // Process the -fno-builtin-* options.
3629  for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3630  A->claim();
3631 
3632  // If -fno-builtin is specified, then there's no need to pass the option to
3633  // the frontend.
3634  if (UseBuiltins)
3635  A->render(Args, CmdArgs);
3636  }
3637 
3638  // le32-specific flags:
3639  // -fno-math-builtin: clang should not convert math builtins to intrinsics
3640  // by default.
3641  if (TC.getArch() == llvm::Triple::le32)
3642  CmdArgs.push_back("-fno-math-builtin");
3643 }
3644 
3646  if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3647  Twine Path{Str};
3648  Path.toVector(Result);
3649  return Path.getSingleStringRef() != "";
3650  }
3651  if (llvm::sys::path::cache_directory(Result)) {
3652  llvm::sys::path::append(Result, "clang");
3653  llvm::sys::path::append(Result, "ModuleCache");
3654  return true;
3655  }
3656  return false;
3657 }
3658 
3659 static void RenderModulesOptions(Compilation &C, const Driver &D,
3660  const ArgList &Args, const InputInfo &Input,
3661  const InputInfo &Output,
3662  ArgStringList &CmdArgs, bool &HaveModules) {
3663  // -fmodules enables the use of precompiled modules (off by default).
3664  // Users can pass -fno-cxx-modules to turn off modules support for
3665  // C++/Objective-C++ programs.
3666  bool HaveClangModules = false;
3667  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3668  bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3669  options::OPT_fno_cxx_modules, true);
3670  if (AllowedInCXX || !types::isCXX(Input.getType())) {
3671  CmdArgs.push_back("-fmodules");
3672  HaveClangModules = true;
3673  }
3674  }
3675 
3676  HaveModules |= HaveClangModules;
3677  if (Args.hasArg(options::OPT_fmodules_ts)) {
3678  CmdArgs.push_back("-fmodules-ts");
3679  HaveModules = true;
3680  }
3681 
3682  // -fmodule-maps enables implicit reading of module map files. By default,
3683  // this is enabled if we are using Clang's flavor of precompiled modules.
3684  if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3685  options::OPT_fno_implicit_module_maps, HaveClangModules))
3686  CmdArgs.push_back("-fimplicit-module-maps");
3687 
3688  // -fmodules-decluse checks that modules used are declared so (off by default)
3689  Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3690  options::OPT_fno_modules_decluse);
3691 
3692  // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3693  // all #included headers are part of modules.
3694  if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3695  options::OPT_fno_modules_strict_decluse, false))
3696  CmdArgs.push_back("-fmodules-strict-decluse");
3697 
3698  // -fno-implicit-modules turns off implicitly compiling modules on demand.
3699  bool ImplicitModules = false;
3700  if (!Args.hasFlag(options::OPT_fimplicit_modules,
3701  options::OPT_fno_implicit_modules, HaveClangModules)) {
3702  if (HaveModules)
3703  CmdArgs.push_back("-fno-implicit-modules");
3704  } else if (HaveModules) {
3705  ImplicitModules = true;
3706  // -fmodule-cache-path specifies where our implicitly-built module files
3707  // should be written.
3708  SmallString<128> Path;
3709  if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3710  Path = A->getValue();
3711 
3712  bool HasPath = true;
3713  if (C.isForDiagnostics()) {
3714  // When generating crash reports, we want to emit the modules along with
3715  // the reproduction sources, so we ignore any provided module path.
3716  Path = Output.getFilename();
3717  llvm::sys::path::replace_extension(Path, ".cache");
3718  llvm::sys::path::append(Path, "modules");
3719  } else if (Path.empty()) {
3720  // No module path was provided: use the default.
3721  HasPath = Driver::getDefaultModuleCachePath(Path);
3722  }
3723 
3724  // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3725  // That being said, that failure is unlikely and not caching is harmless.
3726  if (HasPath) {
3727  const char Arg[] = "-fmodules-cache-path=";
3728  Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3729  CmdArgs.push_back(Args.MakeArgString(Path));
3730  }
3731  }
3732 
3733  if (HaveModules) {
3734  // -fprebuilt-module-path specifies where to load the prebuilt module files.
3735  for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3736  CmdArgs.push_back(Args.MakeArgString(
3737  std::string("-fprebuilt-module-path=") + A->getValue()));
3738  A->claim();
3739  }
3740  if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3741  options::OPT_fno_prebuilt_implicit_modules, false))
3742  CmdArgs.push_back("-fprebuilt-implicit-modules");
3743  if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3744  options::OPT_fno_modules_validate_input_files_content,
3745  false))
3746  CmdArgs.push_back("-fvalidate-ast-input-files-content");
3747  }
3748 
3749  // -fmodule-name specifies the module that is currently being built (or
3750  // used for header checking by -fmodule-maps).
3751  Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3752 
3753  // -fmodule-map-file can be used to specify files containing module
3754  // definitions.
3755  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3756 
3757  // -fbuiltin-module-map can be used to load the clang
3758  // builtin headers modulemap file.
3759  if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3760  SmallString<128> BuiltinModuleMap(D.ResourceDir);
3761  llvm::sys::path::append(BuiltinModuleMap, "include");
3762  llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3763  if (llvm::sys::fs::exists(BuiltinModuleMap))
3764  CmdArgs.push_back(
3765  Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3766  }
3767 
3768  // The -fmodule-file=<name>=<file> form specifies the mapping of module
3769  // names to precompiled module files (the module is loaded only if used).
3770  // The -fmodule-file=<file> form can be used to unconditionally load
3771  // precompiled module files (whether used or not).
3772  if (HaveModules)
3773  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3774  else
3775  Args.ClaimAllArgs(options::OPT_fmodule_file);
3776 
3777  // When building modules and generating crashdumps, we need to dump a module
3778  // dependency VFS alongside the output.
3779  if (HaveClangModules && C.isForDiagnostics()) {
3780  SmallString<128> VFSDir(Output.getFilename());
3781  llvm::sys::path::replace_extension(VFSDir, ".cache");
3782  // Add the cache directory as a temp so the crash diagnostics pick it up.
3783  C.addTempFile(Args.MakeArgString(VFSDir));
3784 
3785  llvm::sys::path::append(VFSDir, "vfs");
3786  CmdArgs.push_back("-module-dependency-dir");
3787  CmdArgs.push_back(Args.MakeArgString(VFSDir));
3788  }
3789 
3790  if (HaveClangModules)
3791  Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3792 
3793  // Pass through all -fmodules-ignore-macro arguments.
3794  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3795  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3796  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3797 
3798  if (HaveClangModules) {
3799  Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3800 
3801  if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3802  if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3803  D.Diag(diag::err_drv_argument_not_allowed_with)
3804  << A->getAsString(Args) << "-fbuild-session-timestamp";
3805 
3806  llvm::sys::fs::file_status Status;
3807  if (llvm::sys::fs::status(A->getValue(), Status))
3808  D.Diag(diag::err_drv_no_such_file) << A->getValue();
3809  CmdArgs.push_back(Args.MakeArgString(
3810  "-fbuild-session-timestamp=" +
3811  Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3812  Status.getLastModificationTime().time_since_epoch())
3813  .count())));
3814  }
3815 
3816  if (Args.getLastArg(
3817  options::OPT_fmodules_validate_once_per_build_session)) {
3818  if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3819  options::OPT_fbuild_session_file))
3820  D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3821 
3822  Args.AddLastArg(CmdArgs,
3823  options::OPT_fmodules_validate_once_per_build_session);
3824  }
3825 
3826  if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3827  options::OPT_fno_modules_validate_system_headers,
3828  ImplicitModules))
3829  CmdArgs.push_back("-fmodules-validate-system-headers");
3830 
3831  Args.AddLastArg(CmdArgs,
3832  options::OPT_fmodules_disable_diagnostic_validation);
3833  } else {
3834  Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
3835  Args.ClaimAllArgs(options::OPT_fbuild_session_file);
3836  Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
3837  Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
3838  Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
3839  Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
3840  }
3841 }
3842 
3843 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3844  ArgStringList &CmdArgs) {
3845  // -fsigned-char is default.
3846  if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3847  options::OPT_fno_signed_char,
3848  options::OPT_funsigned_char,
3849  options::OPT_fno_unsigned_char)) {
3850  if (A->getOption().matches(options::OPT_funsigned_char) ||
3851  A->getOption().matches(options::OPT_fno_signed_char)) {
3852  CmdArgs.push_back("-fno-signed-char");
3853  }
3854  } else if (!isSignedCharDefault(T)) {
3855  CmdArgs.push_back("-fno-signed-char");
3856  }
3857 
3858  // The default depends on the language standard.
3859  Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3860 
3861  if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3862  options::OPT_fno_short_wchar)) {
3863  if (A->getOption().matches(options::OPT_fshort_wchar)) {
3864  CmdArgs.push_back("-fwchar-type=short");
3865  CmdArgs.push_back("-fno-signed-wchar");
3866  } else {
3867  bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3868  CmdArgs.push_back("-fwchar-type=int");
3869  if (T.isOSzOS() ||
3870  (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3871  CmdArgs.push_back("-fno-signed-wchar");
3872  else
3873  CmdArgs.push_back("-fsigned-wchar");
3874  }
3875  }
3876 }
3877 
3878 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3879  const llvm::Triple &T, const ArgList &Args,
3880  ObjCRuntime &Runtime, bool InferCovariantReturns,
3881  const InputInfo &Input, ArgStringList &CmdArgs) {
3882  const llvm::Triple::ArchType Arch = TC.getArch();
3883 
3884  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3885  // is the default. Except for deployment target of 10.5, next runtime is
3886  // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3887  if (Runtime.isNonFragile()) {
3888  if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3889  options::OPT_fno_objc_legacy_dispatch,
3890  Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3891  if (TC.UseObjCMixedDispatch())
3892  CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3893  else
3894  CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3895  }
3896  }
3897 
3898  // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3899  // to do Array/Dictionary subscripting by default.
3900  if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
3901  Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3902  CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3903 
3904  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3905  // NOTE: This logic is duplicated in ToolChains.cpp.
3906  if (isObjCAutoRefCount(Args)) {
3907  TC.CheckObjCARC();
3908 
3909  CmdArgs.push_back("-fobjc-arc");
3910 
3911  // FIXME: It seems like this entire block, and several around it should be
3912  // wrapped in isObjC, but for now we just use it here as this is where it
3913  // was being used previously.
3914  if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3915  if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3916  CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3917  else
3918  CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3919  }
3920 
3921  // Allow the user to enable full exceptions code emission.
3922  // We default off for Objective-C, on for Objective-C++.
3923  if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3924  options::OPT_fno_objc_arc_exceptions,
3925  /*Default=*/types::isCXX(Input.getType())))
3926  CmdArgs.push_back("-fobjc-arc-exceptions");
3927  }
3928 
3929  // Silence warning for full exception code emission options when explicitly
3930  // set to use no ARC.
3931  if (Args.hasArg(options::OPT_fno_objc_arc)) {
3932  Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3933  Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3934  }
3935 
3936  // Allow the user to control whether messages can be converted to runtime
3937  // functions.
3938  if (types::isObjC(Input.getType())) {
3939  auto *Arg = Args.getLastArg(
3940  options::OPT_fobjc_convert_messages_to_runtime_calls,
3941  options::OPT_fno_objc_convert_messages_to_runtime_calls);
3942  if (Arg &&
3943  Arg->getOption().matches(
3944  options::OPT_fno_objc_convert_messages_to_runtime_calls))
3945  CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3946  }
3947 
3948  // -fobjc-infer-related-result-type is the default, except in the Objective-C
3949  // rewriter.
3950  if (InferCovariantReturns)
3951  CmdArgs.push_back("-fno-objc-infer-related-result-type");
3952 
3953  // Pass down -fobjc-weak or -fno-objc-weak if present.
3954  if (types::isObjC(Input.getType())) {
3955  auto WeakArg =
3956  Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3957  if (!WeakArg) {
3958  // nothing to do
3959  } else if (!Runtime.allowsWeak()) {
3960  if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3961  D.Diag(diag::err_objc_weak_unsupported);
3962  } else {
3963  WeakArg->render(Args, CmdArgs);
3964  }
3965  }
3966 
3967  if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
3968  CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
3969 }
3970 
3971 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3972  ArgStringList &CmdArgs) {
3973  bool CaretDefault = true;
3974  bool ColumnDefault = true;
3975 
3976  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3977  options::OPT__SLASH_diagnostics_column,
3978  options::OPT__SLASH_diagnostics_caret)) {
3979  switch (A->getOption().getID()) {
3980  case options::OPT__SLASH_diagnostics_caret:
3981  CaretDefault = true;
3982  ColumnDefault = true;
3983  break;
3984  case options::OPT__SLASH_diagnostics_column:
3985  CaretDefault = false;
3986  ColumnDefault = true;
3987  break;
3988  case options::OPT__SLASH_diagnostics_classic:
3989  CaretDefault = false;
3990  ColumnDefault = false;
3991  break;
3992  }
3993  }
3994 
3995  // -fcaret-diagnostics is default.
3996  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3997  options::OPT_fno_caret_diagnostics, CaretDefault))
3998  CmdArgs.push_back("-fno-caret-diagnostics");
3999 
4000  Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4001  options::OPT_fno_diagnostics_fixit_info);
4002  Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4003  options::OPT_fno_diagnostics_show_option);
4004 
4005  if (const Arg *A =
4006  Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4007  CmdArgs.push_back("-fdiagnostics-show-category");
4008  CmdArgs.push_back(A->getValue());
4009  }
4010 
4011  Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4012  options::OPT_fno_diagnostics_show_hotness);
4013 
4014  if (const Arg *A =
4015  Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4016  std::string Opt =
4017  std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4018  CmdArgs.push_back(Args.MakeArgString(Opt));
4019  }
4020 
4021  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4022  CmdArgs.push_back("-fdiagnostics-format");
4023  CmdArgs.push_back(A->getValue());
4024  if (StringRef(A->getValue()) == "sarif" ||
4025  StringRef(A->getValue()) == "SARIF")
4026  D.Diag(diag::warn_drv_sarif_format_unstable);
4027  }
4028 
4029  if (const Arg *A = Args.getLastArg(
4030  options::OPT_fdiagnostics_show_note_include_stack,
4031  options::OPT_fno_diagnostics_show_note_include_stack)) {
4032  const Option &O = A->getOption();
4033  if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4034  CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4035  else
4036  CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4037  }
4038 
4039  // Color diagnostics are parsed by the driver directly from argv and later
4040  // re-parsed to construct this job; claim any possible color diagnostic here
4041  // to avoid warn_drv_unused_argument and diagnose bad
4042  // OPT_fdiagnostics_color_EQ values.
4043  Args.getLastArg(options::OPT_fcolor_diagnostics,
4044  options::OPT_fno_color_diagnostics);
4045  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4046  StringRef Value(A->getValue());
4047  if (Value != "always" && Value != "never" && Value != "auto")
4048  D.Diag(diag::err_drv_invalid_argument_to_option)
4049  << Value << A->getOption().getName();
4050  }
4051 
4052  if (D.getDiags().getDiagnosticOptions().ShowColors)
4053  CmdArgs.push_back("-fcolor-diagnostics");
4054 
4055  if (Args.hasArg(options::OPT_fansi_escape_codes))
4056  CmdArgs.push_back("-fansi-escape-codes");
4057 
4058  Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4059  options::OPT_fno_show_source_location);
4060 
4061  if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4062  CmdArgs.push_back("-fdiagnostics-absolute-paths");
4063 
4064  if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4065  ColumnDefault))
4066  CmdArgs.push_back("-fno-show-column");
4067 
4068  Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4069  options::OPT_fno_spell_checking);
4070 }
4071 
4073  const ArgList &Args, Arg *&Arg) {
4074  Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4075  options::OPT_gno_split_dwarf);
4076  if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4077  return DwarfFissionKind::None;
4078 
4079  if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4080  return DwarfFissionKind::Split;
4081 
4082  StringRef Value = Arg->getValue();
4083  if (Value == "split")
4084  return DwarfFissionKind::Split;
4085  if (Value == "single")
4086  return DwarfFissionKind::Single;
4087 
4088  D.Diag(diag::err_drv_unsupported_option_argument)
4089  << Arg->getOption().getName() << Arg->getValue();
4090  return DwarfFissionKind::None;
4091 }
4092 
4093 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4094  const ArgList &Args, ArgStringList &CmdArgs,
4095  unsigned DwarfVersion) {
4096  auto *DwarfFormatArg =
4097  Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4098  if (!DwarfFormatArg)
4099  return;
4100 
4101  if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4102  if (DwarfVersion < 3)
4103  D.Diag(diag::err_drv_argument_only_allowed_with)
4104  << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4105  else if (!T.isArch64Bit())
4106  D.Diag(diag::err_drv_argument_only_allowed_with)
4107  << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4108  else if (!T.isOSBinFormatELF())
4109  D.Diag(diag::err_drv_argument_only_allowed_with)
4110  << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4111  }
4112 
4113  DwarfFormatArg->render(Args, CmdArgs);
4114 }
4115 
4116 static void renderDebugOptions(const ToolChain &TC, const Driver &D,
4117  const llvm::Triple &T, const ArgList &Args,
4118  bool EmitCodeView, bool IRInput,
4119  ArgStringList &CmdArgs,
4121  DwarfFissionKind &DwarfFission) {
4122  if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4123  options::OPT_fno_debug_info_for_profiling, false) &&
4125  Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4126  CmdArgs.push_back("-fdebug-info-for-profiling");
4127 
4128  // The 'g' groups options involve a somewhat intricate sequence of decisions
4129  // about what to pass from the driver to the frontend, but by the time they
4130  // reach cc1 they've been factored into three well-defined orthogonal choices:
4131  // * what level of debug info to generate
4132  // * what dwarf version to write
4133  // * what debugger tuning to use
4134  // This avoids having to monkey around further in cc1 other than to disable
4135  // codeview if not running in a Windows environment. Perhaps even that
4136  // decision should be made in the driver as well though.
4137  llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4138 
4139  bool SplitDWARFInlining =
4140  Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4141  options::OPT_fno_split_dwarf_inlining, false);
4142 
4143  // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4144  // object file generation and no IR generation, -gN should not be needed. So
4145  // allow -gsplit-dwarf with either -gN or IR input.
4146  if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4147  Arg *SplitDWARFArg;
4148  DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4149  if (DwarfFission != DwarfFissionKind::None &&
4150  !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4151  DwarfFission = DwarfFissionKind::None;
4152  SplitDWARFInlining = false;
4153  }
4154  }
4155  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4157 
4158  // If the last option explicitly specified a debug-info level, use it.
4159  if (checkDebugInfoOption(A, Args, D, TC) &&
4160  A->getOption().matches(options::OPT_gN_Group)) {
4162  // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4163  // complicated if you've disabled inline info in the skeleton CUs
4164  // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4165  // line-tables-only, so let those compose naturally in that case.
4169  SplitDWARFInlining))
4170  DwarfFission = DwarfFissionKind::None;
4171  }
4172  }
4173 
4174  // If a debugger tuning argument appeared, remember it.
4175  if (const Arg *A =
4176  Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4177  if (checkDebugInfoOption(A, Args, D, TC)) {
4178  if (A->getOption().matches(options::OPT_glldb))
4179  DebuggerTuning = llvm::DebuggerKind::LLDB;
4180  else if (A->getOption().matches(options::OPT_gsce))
4181  DebuggerTuning = llvm::DebuggerKind::SCE;
4182  else if (A->getOption().matches(options::OPT_gdbx))
4183  DebuggerTuning = llvm::DebuggerKind::DBX;
4184  else
4185  DebuggerTuning = llvm::DebuggerKind::GDB;
4186  }
4187  }
4188 
4189  // If a -gdwarf argument appeared, remember it.
4190  const Arg *GDwarfN = getDwarfNArg(Args);
4191  bool EmitDwarf = false;
4192  if (GDwarfN) {
4193  if (checkDebugInfoOption(GDwarfN, Args, D, TC))
4194  EmitDwarf = true;
4195  else
4196  GDwarfN = nullptr;
4197  }
4198 
4199  if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
4200  if (checkDebugInfoOption(A, Args, D, TC))
4201  EmitCodeView = true;
4202  }
4203 
4204  // If the user asked for debug info but did not explicitly specify -gcodeview
4205  // or -gdwarf, ask the toolchain for the default format.
4206  if (!EmitCodeView && !EmitDwarf &&
4208  switch (TC.getDefaultDebugFormat()) {
4210  EmitCodeView = true;
4211  break;
4213  EmitDwarf = true;
4214  break;
4215  }
4216  }
4217 
4218  unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4219  unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4220  // be lower than what the user wanted.
4221  unsigned DefaultDWARFVersion = ParseDebugDefaultVersion(TC, Args);
4222  if (EmitDwarf) {
4223  // Start with the platform default DWARF version
4224  RequestedDWARFVersion = TC.GetDefaultDwarfVersion();
4225  assert(RequestedDWARFVersion &&
4226  "toolchain default DWARF version must be nonzero");
4227 
4228  // If the user specified a default DWARF version, that takes precedence
4229  // over the platform default.
4230  if (DefaultDWARFVersion)
4231  RequestedDWARFVersion = DefaultDWARFVersion;
4232 
4233  // Override with a user-specified DWARF version
4234  if (GDwarfN)
4235  if (auto ExplicitVersion = DwarfVersionNum(GDwarfN->getSpelling()))
4236  RequestedDWARFVersion = ExplicitVersion;
4237  // Clamp effective DWARF version to the max supported by the toolchain.
4238  EffectiveDWARFVersion =
4239  std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4240  }
4241 
4242  // -gline-directives-only supported only for the DWARF debug info.
4243  if (RequestedDWARFVersion == 0 &&
4246 
4247  // strict DWARF is set to false by default. But for DBX, we need it to be set
4248  // as true by default.
4249  if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4250  (void)checkDebugInfoOption(A, Args, D, TC);
4251  if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4252  DebuggerTuning == llvm::DebuggerKind::DBX))
4253  CmdArgs.push_back("-gstrict-dwarf");
4254 
4255  // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4256  Args.ClaimAllArgs(options::OPT_g_flags_Group);
4257 
4258  // Column info is included by default for everything except SCE and
4259  // CodeView. Clang doesn't track end columns, just starting columns, which,
4260  // in theory, is fine for CodeView (and PDB). In practice, however, the
4261  // Microsoft debuggers don't handle missing end columns well, and the AIX
4262  // debugger DBX also doesn't handle the columns well, so it's better not to
4263  // include any column info.
4264  if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4265  (void)checkDebugInfoOption(A, Args, D, TC);
4266  if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4267  !EmitCodeView &&
4268  (DebuggerTuning != llvm::DebuggerKind::SCE &&
4269  DebuggerTuning != llvm::DebuggerKind::DBX)))
4270  CmdArgs.push_back("-gno-column-info");
4271 
4272  // FIXME: Move backend command line options to the module.
4273  // If -gline-tables-only or -gline-directives-only is the last option it wins.
4274  if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
4275  if (checkDebugInfoOption(A, Args, D, TC)) {
4279  CmdArgs.push_back("-dwarf-ext-refs");
4280  CmdArgs.push_back("-fmodule-format=obj");
4281  }
4282  }
4283 
4284  if (T.isOSBinFormatELF() && SplitDWARFInlining)
4285  CmdArgs.push_back("-fsplit-dwarf-inlining");
4286 
4287  // After we've dealt with all combinations of things that could
4288  // make DebugInfoKind be other than None or DebugLineTablesOnly,
4289  // figure out if we need to "upgrade" it to standalone debug info.
4290  // We parse these two '-f' options whether or not they will be used,
4291  // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4292  bool NeedFullDebug = Args.hasFlag(
4293  options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4294  DebuggerTuning == llvm::DebuggerKind::LLDB ||
4296  if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4297  (void)checkDebugInfoOption(A, Args, D, TC);
4298 
4301  if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4302  options::OPT_feliminate_unused_debug_types, false))
4304  else if (NeedFullDebug)
4306  }
4307 
4308  if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4309  false)) {
4310  // Source embedding is a vendor extension to DWARF v5. By now we have
4311  // checked if a DWARF version was stated explicitly, and have otherwise
4312  // fallen back to the target default, so if this is still not at least 5
4313  // we emit an error.
4314  const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4315  if (RequestedDWARFVersion < 5)
4316  D.Diag(diag::err_drv_argument_only_allowed_with)
4317  << A->getAsString(Args) << "-gdwarf-5";
4318  else if (EffectiveDWARFVersion < 5)
4319  // The toolchain has reduced allowed dwarf version, so we can't enable
4320  // -gembed-source.
4321  D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4322  << A->getAsString(Args) << TC.getTripleString() << 5
4323  << EffectiveDWARFVersion;
4324  else if (checkDebugInfoOption(A, Args, D, TC))
4325  CmdArgs.push_back("-gembed-source");
4326  }
4327 
4328  if (EmitCodeView) {
4329  CmdArgs.push_back("-gcodeview");
4330 
4331  // Emit codeview type hashes if requested.
4332  if (Args.hasFlag(options::OPT_gcodeview_ghash,
4333  options::OPT_gno_codeview_ghash, false)) {
4334  CmdArgs.push_back("-gcodeview-ghash");
4335  }
4336  }
4337 
4338  // Omit inline line tables if requested.
4339  if (Args.hasFlag(options::OPT_gno_inline_line_tables,
4340  options::OPT_ginline_line_tables, false)) {
4341  CmdArgs.push_back("-gno-inline-line-tables");
4342  }
4343 
4344  // When emitting remarks, we need at least debug lines in the output.
4345  if (willEmitRemarks(Args) &&
4348 
4349  // Adjust the debug info kind for the given toolchain.
4351 
4352  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4353  DebuggerTuning);
4354 
4355  // -fdebug-macro turns on macro debug info generation.
4356  if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4357  false))
4358  if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4359  D, TC))
4360  CmdArgs.push_back("-debug-info-macro");
4361 
4362  // -ggnu-pubnames turns on gnu style pubnames in the backend.
4363  const auto *PubnamesArg =
4364  Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4365  options::OPT_gpubnames, options::OPT_gno_pubnames);
4366  if (DwarfFission != DwarfFissionKind::None ||
4367  (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4368  if (!PubnamesArg ||
4369  (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4370  !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4371  CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4372  options::OPT_gpubnames)
4373  ? "-gpubnames"
4374  : "-ggnu-pubnames");
4375  const auto *SimpleTemplateNamesArg =
4376  Args.getLastArg(options::OPT_gsimple_template_names,
4377  options::OPT_gno_simple_template_names);
4378  bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4379  if (SimpleTemplateNamesArg &&
4380  checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4381  const auto &Opt = SimpleTemplateNamesArg->getOption();
4382  if (Opt.matches(options::OPT_gsimple_template_names)) {
4383  ForwardTemplateParams = true;
4384  CmdArgs.push_back("-gsimple-template-names=simple");
4385  }
4386  }
4387 
4388  if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4389  StringRef v = A->getValue();
4390  CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4391  }
4392 
4393  if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
4394  options::OPT_fno_debug_ranges_base_address, false)) {
4395  CmdArgs.push_back("-fdebug-ranges-base-address");
4396  }
4397 
4398  // -gdwarf-aranges turns on the emission of the aranges section in the
4399  // backend.
4400  // Always enabled for SCE tuning.
4401  bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4402  if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4403  NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4404  if (NeedAranges) {
4405  CmdArgs.push_back("-mllvm");
4406  CmdArgs.push_back("-generate-arange-section");
4407  }
4408 
4409  if (Args.hasFlag(options::OPT_fforce_dwarf_frame,
4410  options::OPT_fno_force_dwarf_frame, false))
4411  CmdArgs.push_back("-fforce-dwarf-frame");
4412 
4413  if (Args.hasFlag(options::OPT_fdebug_types_section,
4414  options::OPT_fno_debug_types_section, false)) {
4415  if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4416  D.Diag(diag::err_drv_unsupported_opt_for_target)
4417  << Args.getLastArg(options::OPT_fdebug_types_section)
4418  ->getAsString(Args)
4419  << T.getTriple();
4420  } else if (checkDebugInfoOption(
4421  Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4422  TC)) {
4423  CmdArgs.push_back("-mllvm");
4424  CmdArgs.push_back("-generate-type-units");
4425  }
4426  }
4427 
4428  // To avoid join/split of directory+filename, the integrated assembler prefers
4429  // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4430  // form before DWARF v5.
4431  if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4432  options::OPT_fno_dwarf_directory_asm,
4433  TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4434  CmdArgs.push_back("-fno-dwarf-directory-asm");
4435 
4436  // Decide how to render forward declarations of template instantiations.
4437  // SCE wants full descriptions, others just get them in the name.
4438  if (ForwardTemplateParams)
4439  CmdArgs.push_back("-debug-forward-template-params");
4440 
4441  // Do we need to explicitly import anonymous namespaces into the parent
4442  // scope?
4443  if (DebuggerTuning == llvm::DebuggerKind::SCE)
4444  CmdArgs.push_back("-dwarf-explicit-import");
4445 
4446  renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4447  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4448 }
4449 
4450 static void ProcessVSRuntimeLibrary(const ArgList &Args,
4451  ArgStringList &CmdArgs) {
4452  unsigned RTOptionID = options::OPT__SLASH_MT;
4453 
4454  if (Args.hasArg(options::OPT__SLASH_LDd))
4455  // The /LDd option implies /MTd. The dependent lib part can be overridden,
4456  // but defining _DEBUG is sticky.
4457  RTOptionID = options::OPT__SLASH_MTd;
4458 
4459  if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4460  RTOptionID = A->getOption().getID();
4461 
4462  if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4463  RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4464  .Case("static", options::OPT__SLASH_MT)
4465  .Case("static_dbg", options::OPT__SLASH_MTd)
4466  .Case("dll", options::OPT__SLASH_MD)
4467  .Case("dll_dbg", options::OPT__SLASH_MDd)
4468  .Default(options::OPT__SLASH_MT);
4469  }
4470 
4471  StringRef FlagForCRT;
4472  switch (RTOptionID) {
4473  case options::OPT__SLASH_MD:
4474  if (Args.hasArg(options::OPT__SLASH_LDd))
4475  CmdArgs.push_back("-D_DEBUG");
4476  CmdArgs.push_back("-D_MT");
4477  CmdArgs.push_back("-D_DLL");
4478  FlagForCRT = "--dependent-lib=msvcrt";
4479  break;
4480  case options::OPT__SLASH_MDd:
4481  CmdArgs.push_back("-D_DEBUG");
4482  CmdArgs.push_back("-D_MT");
4483  CmdArgs.push_back("-D_DLL");
4484  FlagForCRT = "--dependent-lib=msvcrtd";
4485  break;
4486  case options::OPT__SLASH_MT:
4487  if (Args.hasArg(options::OPT__SLASH_LDd))
4488  CmdArgs.push_back("-D_DEBUG");
4489  CmdArgs.push_back("-D_MT");
4490  CmdArgs.push_back("-flto-visibility-public-std");
4491  FlagForCRT = "--dependent-lib=libcmt";
4492  break;
4493  case options::OPT__SLASH_MTd:
4494  CmdArgs.push_back("-D_DEBUG");
4495  CmdArgs.push_back("-D_MT");
4496  CmdArgs.push_back("-flto-visibility-public-std");
4497  FlagForCRT = "--dependent-lib=libcmtd";
4498  break;
4499  default:
4500  llvm_unreachable("Unexpected option ID.");
4501  }
4502 
4503  if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4504  CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4505  } else {
4506  CmdArgs.push_back(FlagForCRT.data());
4507 
4508  // This provides POSIX compatibility (maps 'open' to '_open'), which most
4509  // users want. The /Za flag to cl.exe turns this off, but it's not
4510  // implemented in clang.
4511  CmdArgs.push_back("--dependent-lib=oldnames");
4512  }
4513 }
4514 
4516  const InputInfo &Output, const InputInfoList &Inputs,
4517  const ArgList &Args, const char *LinkingOutput) const {
4518  const auto &TC = getToolChain();
4519  const llvm::Triple &RawTriple = TC.getTriple();
4520  const llvm::Triple &Triple = TC.getEffectiveTriple();
4521  const std::string &TripleStr = Triple.getTriple();
4522 
4523  bool KernelOrKext =
4524  Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4525  const Driver &D = TC.getDriver();
4526  ArgStringList CmdArgs;
4527 
4528  assert(Inputs.size() >= 1 && "Must have at least one input.");
4529  // CUDA/HIP compilation may have multiple inputs (source file + results of
4530  // device-side compilations). OpenMP device jobs also take the host IR as a
4531  // second input. Module precompilation accepts a list of header files to
4532  // include as part of the module. API extraction accepts a list of header
4533  // files whose API information is emitted in the output. All other jobs are
4534  // expected to have exactly one input.
4535  bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4536  bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4537  bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4538  bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4539  bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4540  bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
4541  bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4542  bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4544  bool IsHostOffloadingAction =
4546  (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4547  Args.hasFlag(options::OPT_offload_new_driver,
4548  options::OPT_no_offload_new_driver, false));
4549 
4550  bool IsRDCMode =
4551  Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4552  bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4553  auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4554 
4555  // A header module compilation doesn't have a main input file, so invent a
4556  // fake one as a placeholder.
4557  const char *ModuleName = [&] {
4558  auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
4559  return ModuleNameArg ? ModuleNameArg->getValue() : "";
4560  }();
4561  InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
4562 
4563  // Extract API doesn't have a main input file, so invent a fake one as a
4564  // placeholder.
4565  InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4566  "extract-api");
4567 
4568  const InputInfo &Input = [&]() -> const InputInfo & {
4569  if (IsHeaderModulePrecompile)
4570  return HeaderModuleInput;
4571  if (IsExtractAPI)
4572  return ExtractAPIPlaceholderInput;
4573  return Inputs[0];
4574  }();
4575 
4576  InputInfoList ModuleHeaderInputs;
4577  InputInfoList ExtractAPIInputs;
4578  InputInfoList HostOffloadingInputs;
4579  const InputInfo *CudaDeviceInput = nullptr;
4580  const InputInfo *OpenMPDeviceInput = nullptr;
4581  for (const InputInfo &I : Inputs) {
4582  if (&I == &Input || I.getType() == types::TY_Nothing) {
4583  // This is the primary input or contains nothing.
4584  } else if (IsHeaderModulePrecompile &&
4585  types::getPrecompiledType(I.getType()) == types::TY_PCH) {
4586  types::ID Expected = HeaderModuleInput.getType();
4587  if (I.getType() != Expected) {
4588  D.Diag(diag::err_drv_module_header_wrong_kind)
4589  << I.getFilename() << types::getTypeName(I.getType())
4591  }
4592  ModuleHeaderInputs.push_back(I);
4593  } else if (IsExtractAPI) {
4594  auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4595  if (I.getType() != ExpectedInputType) {
4596  D.Diag(diag::err_drv_extract_api_wrong_kind)
4597  << I.getFilename() << types::getTypeName(I.getType())
4598  << types::getTypeName(ExpectedInputType);
4599  }
4600  ExtractAPIInputs.push_back(I);
4601  } else if (IsHostOffloadingAction) {
4602  HostOffloadingInputs.push_back(I);
4603  } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4604  CudaDeviceInput = &I;
4605  } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4606  OpenMPDeviceInput = &I;
4607  } else {
4608  llvm_unreachable("unexpectedly given multiple inputs");
4609  }
4610  }
4611 
4612  const llvm::Triple *AuxTriple =
4613  (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4614  bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4615  bool IsIAMCU = RawTriple.isOSIAMCU();
4616 
4617  // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
4618  // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4619  // Windows), we need to pass Windows-specific flags to cc1.
4620  if (IsCuda || IsHIP)
4621  IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4622 
4623  // C++ is not supported for IAMCU.
4624  if (IsIAMCU && types::isCXX(Input.getType()))
4625  D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4626 
4627  // Invoke ourselves in -cc1 mode.
4628  //
4629  // FIXME: Implement custom jobs for internal actions.
4630  CmdArgs.push_back("-cc1");
4631 
4632  // Add the "effective" target triple.
4633  CmdArgs.push_back("-triple");
4634  CmdArgs.push_back(Args.MakeArgString(TripleStr));
4635 
4636  if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4637  DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4638  Args.ClaimAllArgs(options::OPT_MJ);
4639  } else if (const Arg *GenCDBFragment =
4640  Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4641  DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4642  TripleStr, Output, Input, Args);
4643  Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4644  }
4645 
4646  if (IsCuda || IsHIP) {
4647  // We have to pass the triple of the host if compiling for a CUDA/HIP device
4648  // and vice-versa.
4649  std::string NormalizedTriple;
4652  NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4653  ->getTriple()
4654  .normalize();
4655  else {
4656  // Host-side compilation.
4657  NormalizedTriple =
4658  (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4659  : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4660  ->getTriple()
4661  .normalize();
4662  if (IsCuda) {
4663  // We need to figure out which CUDA version we're compiling for, as that
4664  // determines how we load and launch GPU kernels.
4665  auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4666  C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4667  assert(CTC && "Expected valid CUDA Toolchain.");
4668  if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4669  CmdArgs.push_back(Args.MakeArgString(
4670  Twine("-target-sdk-version=") +
4671  CudaVersionToString(CTC->CudaInstallation.version())));
4672  }
4673  }
4674  CmdArgs.push_back("-aux-triple");
4675  CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4676  }
4677 
4678  if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4679  CmdArgs.push_back("-fsycl-is-device");
4680 
4681  if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4682  A->render(Args, CmdArgs);
4683  } else {
4684  // Ensure the default version in SYCL mode is 2020.
4685  CmdArgs.push_back("-sycl-std=2020");
4686  }
4687  }
4688 
4689  if (IsOpenMPDevice) {
4690  // We have to pass the triple of the host if compiling for an OpenMP device.
4691  std::string NormalizedTriple =
4692  C.getSingleOffloadToolChain<Action::OFK_Host>()
4693  ->getTriple()
4694  .normalize();
4695  CmdArgs.push_back("-aux-triple");
4696  CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4697  }
4698 
4699  if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4700  Triple.getArch() == llvm::Triple::thumb)) {
4701  unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4702  unsigned Version = 0;
4703  bool Failure =
4704  Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4705  if (Failure || Version < 7)
4706  D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4707  << TripleStr;
4708  }
4709 
4710  // Push all default warning arguments that are specific to
4711  // the given target. These come before user provided warning options
4712  // are provided.
4713  TC.addClangWarningOptions(CmdArgs);
4714 
4715  // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4716  if (Triple.isSPIR() || Triple.isSPIRV())
4717  CmdArgs.push_back("-Wspir-compat");
4718 
4719  // Select the appropriate action.
4720  RewriteKind rewriteKind = RK_None;
4721 
4722  // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4723  // it claims when not running an assembler. Otherwise, clang would emit
4724  // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4725  // flags while debugging something. That'd be somewhat inconvenient, and it's
4726  // also inconsistent with most other flags -- we don't warn on
4727  // -ffunction-sections not being used in -E mode either for example, even
4728  // though it's not really used either.
4729  if (!isa<AssembleJobAction>(JA)) {
4730  // The args claimed here should match the args used in
4731  // CollectArgsForIntegratedAssembler().
4732  if (TC.useIntegratedAs()) {
4733  Args.ClaimAllArgs(options::OPT_mrelax_all);
4734  Args.ClaimAllArgs(options::OPT_mno_relax_all);
4735  Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4736  Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4737  switch (C.getDefaultToolChain().getArch()) {
4738  case llvm::Triple::arm:
4739  case llvm::Triple::armeb:
4740  case llvm::Triple::thumb:
4741  case llvm::Triple::thumbeb:
4742  Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4743  break;
4744  default:
4745  break;
4746  }
4747  }
4748  Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4749  Args.ClaimAllArgs(options::OPT_Xassembler);
4750  Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4751  }
4752 
4753  if (isa<AnalyzeJobAction>(JA)) {
4754  assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4755  CmdArgs.push_back("-analyze");
4756  } else if (isa<MigrateJobAction>(JA)) {
4757  CmdArgs.push_back("-migrate");
4758  } else if (isa<PreprocessJobAction>(JA)) {
4759  if (Output.getType() == types::TY_Dependencies)
4760  CmdArgs.push_back("-Eonly");
4761  else {
4762  CmdArgs.push_back("-E");
4763  if (Args.hasArg(options::OPT_rewrite_objc) &&
4764  !Args.hasArg(options::OPT_g_Group))
4765  CmdArgs.push_back("-P");
4766  else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
4767  CmdArgs.push_back("-fdirectives-only");
4768  }
4769  } else if (isa<AssembleJobAction>(JA)) {
4770  CmdArgs.push_back("-emit-obj");
4771 
4772  CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4773 
4774  // Also ignore explicit -force_cpusubtype_ALL option.
4775  (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4776  } else if (isa<PrecompileJobAction>(JA)) {
4777  if (JA.getType() == types::TY_Nothing)
4778  CmdArgs.push_back("-fsyntax-only");
4779  else if (JA.getType() == types::TY_ModuleFile)
4780  CmdArgs.push_back(IsHeaderModulePrecompile
4781  ? "-emit-header-module"
4782  : "-emit-module-interface");
4783  else if (JA.getType() == types::TY_HeaderUnit)
4784  CmdArgs.push_back("-emit-header-unit");
4785  else
4786  CmdArgs.push_back("-emit-pch");
4787  } else if (isa<VerifyPCHJobAction>(JA)) {
4788  CmdArgs.push_back("-verify-pch");
4789  } else if (isa<ExtractAPIJobAction>(JA)) {
4790  assert(JA.getType() == types::TY_API_INFO &&
4791  "Extract API actions must generate a API information.");
4792  CmdArgs.push_back("-extract-api");
4793  if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
4794  ProductNameArg->render(Args, CmdArgs);
4795  } else {
4796  assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4797  "Invalid action for clang tool.");
4798  if (JA.getType() == types::TY_Nothing) {
4799  CmdArgs.push_back("-fsyntax-only");
4800  } else if (JA.getType() == types::TY_LLVM_IR ||
4801  JA.getType() == types::TY_LTO_IR) {
4802  CmdArgs.push_back("-emit-llvm");
4803  } else if (JA.getType() == types::TY_LLVM_BC ||
4804  JA.getType() == types::TY_LTO_BC) {
4805  // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4806  if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4807  Args.hasArg(options::OPT_emit_llvm)) {
4808  CmdArgs.push_back("-emit-llvm");
4809  } else {
4810  CmdArgs.push_back("-emit-llvm-bc");
4811  }
4812  } else if (JA.getType() == types::TY_IFS ||
4813  JA.getType() == types::TY_IFS_CPP) {
4814  StringRef ArgStr =
4815  Args.hasArg(options::OPT_interface_stub_version_EQ)
4816  ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4817  : "ifs-v1";
4818  CmdArgs.push_back("-emit-interface-stubs");
4819  CmdArgs.push_back(
4820  Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4821  } else if (JA.getType() == types::TY_PP_Asm) {
4822  CmdArgs.push_back("-S");
4823  } else if (JA.getType() == types::TY_AST) {
4824  CmdArgs.push_back("-emit-pch");
4825  } else if (JA.getType() == types::TY_ModuleFile) {
4826  CmdArgs.push_back("-module-file-info");
4827  } else if (JA.getType() == types::TY_RewrittenObjC) {
4828  CmdArgs.push_back("-rewrite-objc");
4829  rewriteKind = RK_NonFragile;
4830  } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4831  CmdArgs.push_back("-rewrite-objc");
4832  rewriteKind = RK_Fragile;
4833  } else {
4834  assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4835  }
4836 
4837  // Preserve use-list order by default when emitting bitcode, so that
4838  // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4839  // same result as running passes here. For LTO, we don't need to preserve
4840  // the use-list order, since serialization to bitcode is part of the flow.
4841  if (JA.getType() == types::TY_LLVM_BC)
4842  CmdArgs.push_back("-emit-llvm-uselists");
4843 
4844  if (IsUsingLTO) {
4845  // Only AMDGPU supports device-side LTO.
4846  if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
4847  !Args.hasFlag(options::OPT_offload_new_driver,
4848  options::OPT_no_offload_new_driver, false) &&
4849  !Triple.isAMDGPU()) {
4850  D.Diag(diag::err_drv_unsupported_opt_for_target)
4851  << Args.getLastArg(options::OPT_foffload_lto,
4852  options::OPT_foffload_lto_EQ)
4853  ->getAsString(Args)
4854  << Triple.getTriple();
4855  } else {
4856  assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4857  CmdArgs.push_back(Args.MakeArgString(
4858  Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4859  CmdArgs.push_back("-flto-unit");
4860  }
4861  }
4862  }
4863 
4864  if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4865  if (!types::isLLVMIR(Input.getType()))
4866  D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4867  Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4868  }
4869 
4870  if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4871  Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4872 
4873  if (Args.getLastArg(options::OPT_save_temps_EQ))
4874  Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4875 
4876  auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4877  options::OPT_fmemory_profile_EQ,
4878  options::OPT_fno_memory_profile);
4879  if (MemProfArg &&
4880  !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4881  MemProfArg->render(Args, CmdArgs);
4882 
4883  // Embed-bitcode option.
4884  // Only white-listed flags below are allowed to be embedded.
4885  if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
4886  (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
4887  // Add flags implied by -fembed-bitcode.
4888  Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4889  // Disable all llvm IR level optimizations.
4890  CmdArgs.push_back("-disable-llvm-passes");
4891 
4892  // Render target options.
4893  TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4894 
4895  // reject options that shouldn't be supported in bitcode
4896  // also reject kernel/kext
4897  static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
4898  options::OPT_mkernel,
4899  options::OPT_fapple_kext,
4900  options::OPT_ffunction_sections,
4901  options::OPT_fno_function_sections,
4902  options::OPT_fdata_sections,
4903  options::OPT_fno_data_sections,
4904  options::OPT_fbasic_block_sections_EQ,
4905  options::OPT_funique_internal_linkage_names,
4906  options::OPT_fno_unique_internal_linkage_names,
4907  options::OPT_funique_section_names,
4908  options::OPT_fno_unique_section_names,
4909  options::OPT_funique_basic_block_section_names,
4910  options::OPT_fno_unique_basic_block_section_names,
4911  options::OPT_mrestrict_it,
4912  options::OPT_mno_restrict_it,
4913  options::OPT_mstackrealign,
4914  options::OPT_mno_stackrealign,
4915  options::OPT_mstack_alignment,
4916  options::OPT_mcmodel_EQ,
4917  options::OPT_mlong_calls,
4918  options::OPT_mno_long_calls,
4919  options::OPT_ggnu_pubnames,
4920  options::OPT_gdwarf_aranges,
4921  options::OPT_fdebug_types_section,
4922  options::OPT_fno_debug_types_section,
4923  options::OPT_fdwarf_directory_asm,
4924  options::OPT_fno_dwarf_directory_asm,
4925  options::OPT_mrelax_all,
4926  options::OPT_mno_relax_all,
4927  options::OPT_ftrap_function_EQ,
4928  options::OPT_ffixed_r9,
4929  options::OPT_mfix_cortex_a53_835769,
4930  options::OPT_mno_fix_cortex_a53_835769,
4931  options::OPT_ffixed_x18,
4932  options::OPT_mglobal_merge,
4933  options::OPT_mno_global_merge,
4934  options::OPT_mred_zone,
4935  options::OPT_mno_red_zone,
4936  options::OPT_Wa_COMMA,
4937  options::OPT_Xassembler,
4938  options::OPT_mllvm,
4939  };
4940  for (const auto &A : Args)
4941  if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
4942  D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
4943 
4944  // Render the CodeGen options that need to be passed.
4945  Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
4946  options::OPT_fno_optimize_sibling_calls);
4947 
4949  CmdArgs, JA);
4950 
4951  // Render ABI arguments
4952  switch (TC.getArch()) {
4953  default: break;
4954  case llvm::Triple::arm:
4955  case llvm::Triple::armeb:
4956  case llvm::Triple::thumbeb:
4957  RenderARMABI(D, Triple, Args, CmdArgs);
4958  break;
4959  case llvm::Triple::aarch64:
4960  case llvm::Triple::aarch64_32:
4961  case llvm::Triple::aarch64_be:
4962  RenderAArch64ABI(Triple, Args, CmdArgs);
4963  break;
4964  }
4965 
4966  // Optimization level for CodeGen.
4967  if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4968  if (A->getOption().matches(options::OPT_O4)) {
4969  CmdArgs.push_back("-O3");
4970  D.Diag(diag::warn_O4_is_O3);
4971  } else {
4972  A->render(Args, CmdArgs);
4973  }
4974  }
4975 
4976  // Input/Output file.
4977  if (Output.getType() == types::TY_Dependencies) {
4978  // Handled with other dependency code.
4979  } else if (Output.isFilename()) {
4980  CmdArgs.push_back("-o");
4981  CmdArgs.push_back(Output.getFilename());
4982  } else {
4983  assert(Output.isNothing() && "Input output.");
4984  }
4985 
4986  for (const auto &II : Inputs) {
4987  addDashXForInput(Args, II, CmdArgs);
4988  if (II.isFilename())
4989  CmdArgs.push_back(II.getFilename());
4990  else
4991  II.getInputArg().renderAsInput(Args, CmdArgs);
4992  }
4993 
4994  C.addCommand(std::make_unique<Command>(
4996  CmdArgs, Inputs, Output));
4997  return;
4998  }
4999 
5000  if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5001  CmdArgs.push_back("-fembed-bitcode=marker");
5002 
5003  // We normally speed up the clang process a bit by skipping destructors at
5004  // exit, but when we're generating diagnostics we can rely on some of the
5005  // cleanup.
5006  if (!C.isForDiagnostics())
5007  CmdArgs.push_back("-disable-free");
5008  CmdArgs.push_back("-clear-ast-before-backend");
5009 
5010 #ifdef NDEBUG
5011  const bool IsAssertBuild = false;
5012 #else
5013  const bool IsAssertBuild = true;
5014 #endif
5015 
5016  // Disable the verification pass in -asserts builds.
5017  if (!IsAssertBuild)
5018  CmdArgs.push_back("-disable-llvm-verifier");
5019 
5020  // Discard value names in assert builds unless otherwise specified.
5021  if (Args.hasFlag(options::OPT_fdiscard_value_names,
5022  options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5023  if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5024  llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5025  return types::isLLVMIR(II.getType());
5026  })) {
5027  D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5028  }
5029  CmdArgs.push_back("-discard-value-names");
5030  }
5031 
5032  // Set the main file name, so that debug info works even with
5033  // -save-temps.
5034  CmdArgs.push_back("-main-file-name");
5035  CmdArgs.push_back(getBaseInputName(Args, Input));
5036 
5037  // Some flags which affect the language (via preprocessor
5038  // defines).
5039  if (Args.hasArg(options::OPT_static))
5040  CmdArgs.push_back("-static-define");
5041 
5042  if (Args.hasArg(options::OPT_municode))
5043  CmdArgs.push_back("-DUNICODE");
5044 
5045  if (isa<AnalyzeJobAction>(JA))
5046  RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5047 
5048  if (isa<AnalyzeJobAction>(JA) ||
5049  (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5050  CmdArgs.push_back("-setup-static-analyzer");
5051 
5052  // Enable compatilibily mode to avoid analyzer-config related errors.
5053  // Since we can't access frontend flags through hasArg, let's manually iterate
5054  // through them.
5055  bool FoundAnalyzerConfig = false;
5056  for (auto *Arg : Args.filtered(options::OPT_Xclang))
5057  if (StringRef(Arg->getValue()) == "-analyzer-config") {
5058  FoundAnalyzerConfig = true;
5059  break;
5060  }
5061  if (!FoundAnalyzerConfig)
5062  for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5063  if (StringRef(Arg->getValue()) == "-analyzer-config") {
5064  FoundAnalyzerConfig = true;
5065  break;
5066  }
5067  if (FoundAnalyzerConfig)
5068  CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5069 
5070  CheckCodeGenerationOptions(D, Args);
5071 
5072  unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5073  assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5074  if (FunctionAlignment) {
5075  CmdArgs.push_back("-function-alignment");
5076  CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5077  }
5078 
5079  // We support -falign-loops=N where N is a power of 2. GCC supports more
5080  // forms.
5081  if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5082  unsigned Value = 0;
5083  if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5084  TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5085  << A->getAsString(Args) << A->getValue();
5086  else if (Value & (Value - 1))
5087  TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5088  << A->getAsString(Args) << A->getValue();
5089  // Treat =0 as unspecified (use the target preference).
5090  if (Value)
5091  CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5092  Twine(std::min(Value, 65536u))));
5093  }
5094 
5095  llvm::Reloc::Model RelocationModel;
5096  unsigned PICLevel;
5097  bool IsPIE;
5098  std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5099 
5100  bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5101  RelocationModel == llvm::Reloc::ROPI_RWPI;
5102  bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5103  RelocationModel == llvm::Reloc::ROPI_RWPI;
5104 
5105  if (Args.hasArg(options::OPT_mcmse) &&
5106  !Args.hasArg(options::OPT_fallow_unsupported)) {
5107  if (IsROPI)
5108  D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5109  if (IsRWPI)
5110  D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5111  }
5112 
5113  if (IsROPI && types::isCXX(Input.getType()) &&
5114  !Args.hasArg(options::OPT_fallow_unsupported))
5115  D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5116 
5117  const char *RMName = RelocationModelName(RelocationModel);
5118  if (RMName) {
5119  CmdArgs.push_back("-mrelocation-model");
5120  CmdArgs.push_back(RMName);
5121  }
5122  if (PICLevel > 0) {
5123  CmdArgs.push_back("-pic-level");
5124  CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5125  if (IsPIE)
5126  CmdArgs.push_back("-pic-is-pie");
5127  }
5128 
5129  if (RelocationModel == llvm::Reloc::ROPI ||
5130  RelocationModel == llvm::Reloc::ROPI_RWPI)
5131  CmdArgs.push_back("-fropi");
5132  if (RelocationModel == llvm::Reloc::RWPI ||
5133  RelocationModel == llvm::Reloc::ROPI_RWPI)
5134  CmdArgs.push_back("-frwpi");
5135 
5136  if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5137  CmdArgs.push_back("-meabi");
5138  CmdArgs.push_back(A->getValue());
5139  }
5140 
5141  // -fsemantic-interposition is forwarded to CC1: set the
5142  // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5143  // make default visibility external linkage definitions dso_preemptable.
5144  //
5145  // -fno-semantic-interposition: if the target supports .Lfoo$local local
5146  // aliases (make default visibility external linkage definitions dso_local).
5147  // This is the CC1 default for ELF to match COFF/Mach-O.
5148  //
5149  // Otherwise use Clang's traditional behavior: like
5150  // -fno-semantic-interposition but local aliases are not used. So references
5151  // can be interposed if not optimized out.
5152  if (Triple.isOSBinFormatELF()) {
5153  Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5154  options::OPT_fno_semantic_interposition);
5155  if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5156  // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5157  bool SupportsLocalAlias =
5158  Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5159  if (!A)
5160  CmdArgs.push_back("-fhalf-no-semantic-interposition");
5161  else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5162  A->render(Args, CmdArgs);
5163  else if (!SupportsLocalAlias)
5164  CmdArgs.push_back("-fhalf-no-semantic-interposition");
5165  }
5166  }
5167 
5168  {
5169  std::string Model;
5170  if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5171  if (!TC.isThreadModelSupported(A->getValue()))
5172  D.Diag(diag::err_drv_invalid_thread_model_for_target)
5173  << A->getValue() << A->getAsString(Args);
5174  Model = A->getValue();
5175  } else
5176  Model = TC.getThreadModel();
5177  if (Model != "posix") {
5178  CmdArgs.push_back("-mthread-model");
5179  CmdArgs.push_back(Args.MakeArgString(Model));
5180  }
5181  }
5182 
5183  Args.AddLastArg(CmdArgs, options::OPT_fveclib);
5184 
5185  if (Args.hasFlag(options::OPT_fmerge_all_constants,
5186  options::OPT_fno_merge_all_constants, false))
5187  CmdArgs.push_back("-fmerge-all-constants");
5188 
5189  if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
5190  options::OPT_fdelete_null_pointer_checks, false))
5191  CmdArgs.push_back("-fno-delete-null-pointer-checks");
5192 
5193  // LLVM Code Generator Options.
5194 
5195  for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) {
5196  StringRef Map = A->getValue();
5197  if (!llvm::sys::fs::exists(Map)) {
5198  D.Diag(diag::err_drv_no_such_file) << Map;
5199  } else {
5200  A->render(Args, CmdArgs);
5201  A->claim();
5202  }
5203  }
5204 
5205  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi,
5206  options::OPT_mabi_EQ_vec_default)) {
5207  if (!Triple.isOSAIX())
5208  D.Diag(diag::err_drv_unsupported_opt_for_target)
5209  << A->getSpelling() << RawTriple.str();
5210  if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi)
5211  CmdArgs.push_back("-mabi=vec-extabi");
5212  else
5213  CmdArgs.push_back("-mabi=vec-default");
5214  }
5215 
5216  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5217  if (!Triple.isOSAIX() || Triple.isPPC32())
5218  D.Diag(diag::err_drv_unsupported_opt_for_target)
5219  << A->getSpelling() << RawTriple.str();
5220  CmdArgs.push_back("-mabi=quadword-atomics");
5221  }
5222 
5223  if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5224  // Emit the unsupported option error until the Clang's library integration
5225  // support for 128-bit long double is available for AIX.
5226  if (Triple.isOSAIX())
5227  D.Diag(diag::err_drv_unsupported_opt_for_target)
5228  << A->getSpelling() << RawTriple.str();
5229  }
5230 
5231  if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5232  StringRef v = A->getValue();
5233  // FIXME: Validate the argument here so we don't produce meaningless errors
5234  // about -fwarn-stack-size=.
5235  if (v.empty())
5236  D.Diag(diag::err_drv_missing_argument) << A->getSpelling() << 1;
5237  else
5238  CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + v));
5239  A->claim();
5240  }
5241 
5242  Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5243  options::OPT_fno_jump_tables);
5244  Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5245  options::OPT_fno_profile_sample_accurate);
5246  Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5247  options::OPT_fno_preserve_as_comments);
5248 
5249  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5250  CmdArgs.push_back("-mregparm");
5251  CmdArgs.push_back(A->getValue());
5252  }
5253 
5254  if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5255  options::OPT_msvr4_struct_return)) {
5256  if (!TC.getTriple().isPPC32()) {
5257  D.Diag(diag::err_drv_unsupported_opt_for_target)
5258  << A->getSpelling() << RawTriple.str();
5259  } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5260  CmdArgs.push_back("-maix-struct-return");
5261  } else {
5262  assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5263  CmdArgs.push_back("-msvr4-struct-return");
5264  }
5265  }
5266 
5267  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5268  options::OPT_freg_struct_return)) {
5269  if (TC.getArch() != llvm::Triple::x86) {
5270  D.Diag(diag::err_drv_unsupported_opt_for_target)
5271  << A->getSpelling() << RawTriple.str();
5272  } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5273  CmdArgs.push_back("-fpcc-struct-return");
5274  } else {
5275  assert(A->getOption().matches(options::OPT_freg_struct_return));
5276  CmdArgs.push_back("-freg-struct-return");
5277  }
5278  }
5279 
5280  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
5281  CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5282 
5283  if (Args.hasArg(options::OPT_fenable_matrix)) {
5284  // enable-matrix is needed by both the LangOpts and by LLVM.
5285  CmdArgs.push_back("-fenable-matrix");
5286  CmdArgs.push_back("-mllvm");
5287  CmdArgs.push_back("-enable-matrix");
5288  }
5289 
5291  getFramePointerKind(Args, RawTriple);
5292  const char *FPKeepKindStr = nullptr;
5293  switch (FPKeepKind) {
5295  FPKeepKindStr = "-mframe-pointer=none";
5296  break;
5298  FPKeepKindStr = "-mframe-pointer=non-leaf";
5299  break;
5301  FPKeepKindStr = "-mframe-pointer=all";
5302  break;
5303  }
5304  assert(FPKeepKindStr && "unknown FramePointerKind");
5305  CmdArgs.push_back(FPKeepKindStr);
5306 
5307  Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5308  options::OPT_fno_zero_initialized_in_bss);
5309 
5310  bool OFastEnabled = isOptimizationLevelFast(Args);
5311  // If -Ofast is the optimization level, then -fstrict-aliasing should be
5312  // enabled. This alias option is being used to simplify the hasFlag logic.
5313  OptSpecifier StrictAliasingAliasOption =
5314  OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5315  // We turn strict aliasing off by default if we're in CL mode, since MSVC
5316  // doesn't do any TBAA.
5317  bool TBAAOnByDefault = !D.IsCLMode();
5318  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5319  options::OPT_fno_strict_aliasing, TBAAOnByDefault))
5320  CmdArgs.push_back("-relaxed-aliasing");
5321  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5322  options::OPT_fno_struct_path_tbaa, true))
5323  CmdArgs.push_back("-no-struct-path-tbaa");
5324  Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5325  options::OPT_fno_strict_enums);
5326  Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5327  options::OPT_fno_strict_return);
5328  Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5329  options::OPT_fno_allow_editor_placeholders);
5330  Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5331  options::OPT_fno_strict_vtable_pointers);
5332  Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5333  options::OPT_fno_force_emit_vtables);
5334  Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5335  options::OPT_fno_optimize_sibling_calls);
5336  Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5337  options::OPT_fno_escaping_block_tail_calls);
5338 
5339  Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5340  options::OPT_fno_fine_grained_bitfield_accesses);
5341 
5342  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5343  options::OPT_fno_experimental_relative_cxx_abi_vtables);
5344 
5345  // Handle segmented stacks.
5346  if (Args.hasFlag(options::OPT_fsplit_stack, options::OPT_fno_split_stack,
5347  false))
5348  CmdArgs.push_back("-fsplit-stack");
5349 
5350  // -fprotect-parens=0 is default.
5351  if (Args.hasFlag(options::OPT_fprotect_parens,
5352  options::OPT_fno_protect_parens, false))
5353  CmdArgs.push_back("-fprotect-parens");
5354 
5355  RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5356 
5357  if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5358  const llvm::Triple::ArchType Arch = TC.getArch();
5359  if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5360  StringRef V = A->getValue();
5361  if (V == "64")
5362  CmdArgs.push_back("-fextend-arguments=64");
5363  else if (V != "32")
5364  D.Diag(diag::err_drv_invalid_argument_to_option)
5365  << A->getValue() << A->getOption().getName();
5366  } else
5367  D.Diag(diag::err_drv_unsupported_opt_for_target)
5368  << A->getOption().getName() << TripleStr;
5369  }
5370 
5371  if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5372  if (TC.getArch() == llvm::Triple::avr)
5373  A->render(Args, CmdArgs);
5374  else
5375  D.Diag(diag::err_drv_unsupported_opt_for_target)
5376  << A->getAsString(Args) << TripleStr;
5377  }
5378 
5379  if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5380  if (TC.getTriple().isX86())
5381  A->render(Args, CmdArgs);
5382  else if (TC.getTriple().isPPC() &&
5383  (A->getOption().getID() != options::OPT_mlong_double_80))
5384  A->render(Args, CmdArgs);
5385  else
5386  D.Diag(diag::err_drv_unsupported_opt_for_target)
5387  << A->getAsString(Args) << TripleStr;
5388  }
5389 
5390  // Decide whether to use verbose asm. Verbose assembly is the default on
5391  // toolchains which have the integrated assembler on by default.
5392  bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5393  if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5394  IsIntegratedAssemblerDefault))
5395  CmdArgs.push_back("-fno-verbose-asm");
5396 
5397  // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5398  // use that to indicate the MC default in the backend.
5399  if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5400  StringRef V = A->getValue();
5401  unsigned Num;
5402  if (V == "none")
5403  A->render(Args, CmdArgs);
5404  else if (!V.consumeInteger(10, Num) && Num > 0 &&
5405  (V.empty() || (V.consume_front(".") &&
5406  !V.consumeInteger(10, Num) && V.empty())))
5407  A->render(Args, CmdArgs);
5408  else
5409  D.Diag(diag::err_drv_invalid_argument_to_option)
5410  << A->getValue() << A->getOption().getName();
5411  }
5412 
5413  // If toolchain choose to use MCAsmParser for inline asm don't pass the
5414  // option to disable integrated-as explictly.
5415  if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5416  CmdArgs.push_back("-no-integrated-as");
5417 
5418  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5419  CmdArgs.push_back("-mdebug-pass");
5420  CmdArgs.push_back("Structure");
5421  }
5422  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5423  CmdArgs.push_back("-mdebug-pass");
5424  CmdArgs.push_back("Arguments");
5425  }
5426 
5427  // Enable -mconstructor-aliases except on darwin, where we have to work around
5428  // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
5429  // aliases aren't supported.
5430  if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5431  CmdArgs.push_back("-mconstructor-aliases");
5432 
5433  // Darwin's kernel doesn't support guard variables; just die if we
5434  // try to use them.
5435  if (KernelOrKext && RawTriple.isOSDarwin())
5436  CmdArgs.push_back("-fforbid-guard-variables");
5437 
5438  if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5439  Triple.isWindowsGNUEnvironment())) {
5440  CmdArgs.push_back("-mms-bitfields");
5441  }
5442 
5443  // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5444  // defaults to -fno-direct-access-external-data. Pass the option if different
5445  // from the default.
5446  if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5447  options::OPT_fno_direct_access_external_data))
5448  if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5449  (PICLevel == 0))
5450  A->render(Args, CmdArgs);
5451 
5452  if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5453  CmdArgs.push_back("-fno-plt");
5454  }
5455 
5456  // -fhosted is default.
5457  // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5458  // use Freestanding.
5459  bool Freestanding =
5460  Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5461  KernelOrKext;
5462  if (Freestanding)
5463  CmdArgs.push_back("-ffreestanding");
5464 
5465  Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
5466 
5467  // This is a coarse approximation of what llvm-gcc actually does, both
5468  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5469  // complicated ways.
5470  auto SanitizeArgs = TC.getSanitizerArgs(Args);
5471 
5472  bool IsAsyncUnwindTablesDefault =
5474  bool IsSyncUnwindTablesDefault =
5476 
5477  bool AsyncUnwindTables = Args.hasFlag(
5478  options::OPT_fasynchronous_unwind_tables,
5479  options::OPT_fno_asynchronous_unwind_tables,
5480  (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
5481  !Freestanding);
5482  bool UnwindTables =
5483  Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5484  IsSyncUnwindTablesDefault && !Freestanding);
5485  if (AsyncUnwindTables)
5486  CmdArgs.push_back("-funwind-tables=2");
5487  else if (UnwindTables)
5488  CmdArgs.push_back("-funwind-tables=1");
5489 
5490  // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5491  // `--gpu-use-aux-triple-only` is specified.
5492  if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5493  (IsCudaDevice || IsHIPDevice)) {
5494  const ArgList &HostArgs =
5495  C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5496  std::string HostCPU =
5497  getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5498  if (!HostCPU.empty()) {
5499  CmdArgs.push_back("-aux-target-cpu");
5500  CmdArgs.push_back(Args.MakeArgString(HostCPU));
5501  }
5502  getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5503  /*ForAS*/ false, /*IsAux*/ true);
5504  }
5505 
5506  TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5507 
5508  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5509  StringRef CM = A->getValue();
5510  if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" ||
5511  CM == "tiny") {
5512  if (Triple.isOSAIX() && CM == "medium")
5513  CmdArgs.push_back("-mcmodel=large");
5514  else if (Triple.isAArch64() && (CM == "kernel" || CM == "medium"))
5515  D.Diag(diag::err_drv_invalid_argument_to_option)
5516  << CM << A->getOption().getName();
5517  else
5518  A->render(Args, CmdArgs);
5519  } else {
5520  D.Diag(diag::err_drv_invalid_argument_to_option)
5521  << CM << A->getOption().getName();
5522  }
5523  }
5524 
5525  if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5526  StringRef Value = A->getValue();
5527  unsigned TLSSize = 0;
5528  Value.getAsInteger(10, TLSSize);
5529  if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5530  D.Diag(diag::err_drv_unsupported_opt_for_target)
5531  << A->getOption().getName() << TripleStr;
5532  if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5533  D.Diag(diag::err_drv_invalid_int_value)
5534  << A->getOption().getName() << Value;
5535  Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5536  }
5537 
5538  // Add the target cpu
5539  std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
5540  if (!CPU.empty()) {
5541  CmdArgs.push_back("-target-cpu");
5542  CmdArgs.push_back(Args.MakeArgString(CPU));
5543  }
5544 
5545  RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5546 
5547  // FIXME: For now we want to demote any errors to warnings, when they have
5548  // been raised for asking the wrong question of scalable vectors, such as
5549  // asking for the fixed number of elements. This may happen because code that
5550  // is not yet ported to work for scalable vectors uses the wrong interfaces,
5551  // whereas the behaviour is actually correct. Emitting a warning helps bring
5552  // up scalable vector support in an incremental way. When scalable vector
5553  // support is stable enough, all uses of wrong interfaces should be considered
5554  // as errors, but until then, we can live with a warning being emitted by the
5555  // compiler. This way, Clang can be used to compile code with scalable vectors
5556  // and identify possible issues.
5557  if (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5558  isa<BackendJobAction>(JA)) {
5559  CmdArgs.push_back("-mllvm");
5560  CmdArgs.push_back("-treat-scalable-fixed-error-as-warning");
5561  }
5562 
5563  // These two are potentially updated by AddClangCLArgs.
5565  bool EmitCodeView = false;
5566 
5567  // Add clang-cl arguments.
5568  types::ID InputType = Input.getType();
5569  if (D.IsCLMode())
5570  AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
5571 
5573  renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
5574  types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
5575  DwarfFission);
5576 
5577  // This controls whether or not we perform JustMyCode instrumentation.
5578  if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5579  if (TC.getTriple().isOSBinFormatELF()) {
5581  CmdArgs.push_back("-fjmc");
5582  else
5583  D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5584  << "-g";
5585  } else {
5586  D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5587  }
5588  }
5589 
5590  // Add the split debug info name to the command lines here so we
5591  // can propagate it to the backend.
5592  bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5593  (TC.getTriple().isOSBinFormatELF() ||
5594  TC.getTriple().isOSBinFormatWasm()) &&
5595  (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5596  isa<BackendJobAction>(JA));
5597  if (SplitDWARF) {
5598  const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5599  CmdArgs.push_back("-split-dwarf-file");
5600  CmdArgs.push_back(SplitDWARFOut);
5601  if (DwarfFission == DwarfFissionKind::Split) {
5602  CmdArgs.push_back("-split-dwarf-output");
5603  CmdArgs.push_back(SplitDWARFOut);
5604  }
5605  }
5606 
5607  // Pass the linker version in use.
5608  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5609  CmdArgs.push_back("-target-linker-version");
5610  CmdArgs.push_back(A->getValue());
5611  }
5612 
5613  // Explicitly error on some things we know we don't support and can't just
5614  // ignore.
5615  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5616  Arg *Unsupported;
5617  if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5618  TC.getArch() == llvm::Triple::x86) {
5619  if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5620  (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5621  D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5622  << Unsupported->getOption().getName();
5623  }
5624  // The faltivec option has been superseded by the maltivec option.
5625  if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5626  D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5627  << Unsupported->getOption().getName()
5628  << "please use -maltivec and include altivec.h explicitly";
5629  if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5630  D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5631  << Unsupported->getOption().getName() << "please use -mno-altivec";
5632  }
5633 
5634  Args.AddAllArgs(CmdArgs, options::OPT_v);
5635 
5636  if (Args.getLastArg(options::OPT_H)) {
5637  CmdArgs.push_back("-H");
5638  CmdArgs.push_back("-sys-header-deps");
5639  }
5640  Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5641 
5642  if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
5643  CmdArgs.push_back("-header-include-file");
5644  CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5645  ? D.CCPrintHeadersFilename.c_str()
5646  : "-");
5647  CmdArgs.push_back("-sys-header-deps");
5648  }
5649  Args.AddLastArg(CmdArgs, options::OPT_P);
5650  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5651 
5652  if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5653  CmdArgs.push_back("-diagnostic-log-file");
5654  CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5655  ? D.CCLogDiagnosticsFilename.c_str()
5656  : "-");
5657  }
5658 
5659  // Give the gen diagnostics more chances to succeed, by avoiding intentional
5660  // crashes.
5661  if (D.CCGenDiagnostics)
5662  CmdArgs.push_back("-disable-pragma-debug-crash");
5663 
5664  // Allow backend to put its diagnostic files in the same place as frontend
5665  // crash diagnostics files.
5666  if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5667  StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5668  CmdArgs.push_back("-mllvm");
5669  CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5670  }
5671 
5672  bool UseSeparateSections = isUseSeparateSections(Triple);
5673 
5674  if (Args.hasFlag(options::OPT_ffunction_sections,
5675  options::OPT_fno_function_sections, UseSeparateSections)) {
5676  CmdArgs.push_back("-ffunction-sections");
5677  }
5678 
5679  if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5680  StringRef Val = A->getValue();
5681  if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5682  if (Val != "all" && Val != "labels" && Val != "none" &&
5683  !Val.startswith("list="))
5684  D.Diag(diag::err_drv_invalid_value)
5685  << A->getAsString(Args) << A->getValue();
5686  else
5687  A->render(Args, CmdArgs);
5688  } else if (Triple.isNVPTX()) {
5689  // Do not pass the option to the GPU compilation. We still want it enabled
5690  // for the host-side compilation, so seeing it here is not an error.
5691  } else if (Val != "none") {
5692  // =none is allowed everywhere. It's useful for overriding the option
5693  // and is the same as not specifying the option.
5694  D.Diag(diag::err_drv_unsupported_opt_for_target)
5695  << A->getAsString(Args) << TripleStr;
5696  }
5697  }
5698 
5699  bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5700  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5701  UseSeparateSections || HasDefaultDataSections)) {
5702  CmdArgs.push_back("-fdata-sections");
5703  }
5704 
5705  Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
5706  options::OPT_fno_unique_section_names);
5707  Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
5708  options::OPT_fno_unique_internal_linkage_names);
5709  Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
5710  options::OPT_fno_unique_basic_block_section_names);
5711 
5712  if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5713  options::OPT_fno_split_machine_functions)) {
5714  // This codegen pass is only available on x86-elf targets.
5715  if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5716  if (A->getOption().matches(options::OPT_fsplit_machine_functions))
5717  A->render(Args, CmdArgs);
5718  } else {
5719  D.Diag(diag::err_drv_unsupported_opt_for_target)
5720  << A->getAsString(Args) << TripleStr;
5721  }
5722  }
5723 
5724  Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5725  options::OPT_finstrument_functions_after_inlining,
5726  options::OPT_finstrument_function_entry_bare);
5727 
5728  // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5729  // for sampling, overhead of call arc collection is way too high and there's
5730  // no way to collect the output.
5731  if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5732  addPGOAndCoverageFlags(TC, C, D, Output, Args, SanitizeArgs, CmdArgs);
5733 
5734  Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5735 
5736  // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
5737  if (RawTriple.isPS() &&
5738  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5739  PScpu::addProfileRTArgs(TC, Args, CmdArgs);
5740  PScpu::addSanitizerArgs(TC, Args, CmdArgs);
5741  }
5742 
5743  // Pass options for controlling the default header search paths.
5744  if (Args.hasArg(options::OPT_nostdinc)) {
5745  CmdArgs.push_back("-nostdsysteminc");
5746  CmdArgs.push_back("-nobuiltininc");
5747  } else {
5748  if (Args.hasArg(options::OPT_nostdlibinc))
5749  CmdArgs.push_back("-nostdsysteminc");
5750  Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5751  Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5752  }
5753 
5754  // Pass the path to compiler resource files.
5755  CmdArgs.push_back("-resource-dir");
5756  CmdArgs.push_back(D.ResourceDir.c_str());
5757 
5758  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5759 
5760  RenderARCMigrateToolOptions(D, Args, CmdArgs);
5761 
5762  // Add preprocessing options like -I, -D, etc. if we are using the
5763  // preprocessor.
5764  //
5765  // FIXME: Support -fpreprocessed
5767  AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5768 
5769  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5770  // that "The compiler can only warn and ignore the option if not recognized".
5771  // When building with ccache, it will pass -D options to clang even on
5772  // preprocessed inputs and configure concludes that -fPIC is not supported.
5773  Args.ClaimAllArgs(options::OPT_D);
5774 
5775  // Manually translate -O4 to -O3; let clang reject others.
5776  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5777  if (A->getOption().matches(options::OPT_O4)) {
5778  CmdArgs.push_back("-O3");
5779  D.Diag(diag::warn_O4_is_O3);
5780  } else {
5781  A->render(Args, CmdArgs);
5782  }
5783  }
5784 
5785  // Warn about ignored options to clang.
5786  for (const Arg *A :
5787  Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
5788  D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
5789  A->claim();
5790  }
5791 
5792  for (const Arg *A :
5793  Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
5794  D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
5795  A->claim();
5796  }
5797 
5798  claimNoWarnArgs(Args);
5799 
5800  Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
5801 
5802  for (const Arg *A :
5803  Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
5804  A->claim();
5805  if (A->getOption().getID() == options::OPT__SLASH_wd) {
5806  unsigned WarningNumber;
5807  if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
5808  D.Diag(diag::err_drv_invalid_int_value)
5809  << A->getAsString(Args) << A->getValue();
5810  continue;
5811  }
5812 
5813  if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
5814  CmdArgs.push_back(Args.MakeArgString(
5816  }
5817  continue;
5818  }
5819  A->render(Args, CmdArgs);
5820  }
5821 
5822  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
5823  CmdArgs.push_back("-pedantic");
5824  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
5825  Args.AddLastArg(CmdArgs, options::OPT_w);
5826 
5827  // Fixed point flags
5828  if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
5829  /*Default=*/false))
5830  Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
5831 
5832  if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
5833  A->render(Args, CmdArgs);
5834 
5835  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5836  options::OPT_fno_experimental_relative_cxx_abi_vtables);
5837 
5838  if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
5839  A->render(Args, CmdArgs);
5840 
5841  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5842  // (-ansi is equivalent to -std=c89 or -std=c++98).
5843  //
5844  // If a std is supplied, only add -trigraphs if it follows the
5845  // option.
5846  bool ImplyVCPPCVer = false;
5847  bool ImplyVCPPCXXVer = false;
5848  const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
5849  if (Std) {
5850  if (Std->getOption().matches(options::OPT_ansi))
5851  if (types::isCXX(InputType))
5852  CmdArgs.push_back("-std=c++98");
5853  else
5854  CmdArgs.push_back("-std=c89");
5855  else
5856  Std->render(Args, CmdArgs);
5857 
5858  // If -f(no-)trigraphs appears after the language standard flag, honor it.
5859  if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
5860  options::OPT_ftrigraphs,
5861  options::OPT_fno_trigraphs))
5862  if (A != Std)
5863  A->render(Args, CmdArgs);
5864  } else {
5865  // Honor -std-default.
5866  //
5867  // FIXME: Clang doesn't correctly handle -std= when the input language
5868  // doesn't match. For the time being just ignore this for C++ inputs;
5869  // eventually we want to do all the standard defaulting here instead of
5870  // splitting it between the driver and clang -cc1.
5871  if (!types::isCXX(InputType)) {
5872  if (!Args.hasArg(options::OPT__SLASH_std)) {
5873  Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
5874  /*Joined=*/true);
5875  } else
5876  ImplyVCPPCVer = true;
5877  }
5878  else if (IsWindowsMSVC)
5879  ImplyVCPPCXXVer = true;
5880 
5881  Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
5882  options::OPT_fno_trigraphs);
5883  }
5884 
5885  // GCC's behavior for -Wwrite-strings is a bit strange:
5886  // * In C, this "warning flag" changes the types of string literals from
5887  // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
5888  // for the discarded qualifier.
5889  // * In C++, this is just a normal warning flag.
5890  //
5891  // Implementing this warning correctly in C is hard, so we follow GCC's
5892  // behavior for now. FIXME: Directly diagnose uses of a string literal as
5893  // a non-const char* in C, rather than using this crude hack.
5894  if (!types::isCXX(InputType)) {
5895  // FIXME: This should behave just like a warning flag, and thus should also
5896  // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
5897  Arg *WriteStrings =
5898  Args.getLastArg(options::OPT_Wwrite_strings,
5899  options::OPT_Wno_write_strings, options::OPT_w);
5900  if (WriteStrings &&
5901  WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
5902  CmdArgs.push_back("-fconst-strings");
5903  }
5904 
5905  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
5906  // during C++ compilation, which it is by default. GCC keeps this define even
5907  // in the presence of '-w', match this behavior bug-for-bug.
5908  if (types::isCXX(InputType) &&
5909  Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
5910  true)) {
5911  CmdArgs.push_back("-fdeprecated-macro");
5912  }
5913 
5914  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
5915  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
5916  if (Asm->getOption().matches(options::OPT_fasm))
5917  CmdArgs.push_back("-fgnu-keywords");
5918  else
5919  CmdArgs.push_back("-fno-gnu-keywords");
5920  }
5921 
5922  if (!ShouldEnableAutolink(Args, TC, JA))
5923  CmdArgs.push_back("-fno-autolink");
5924 
5925  // Add in -fdebug-compilation-dir if necessary.
5926  const char *DebugCompilationDir =
5927  addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5928 
5929  addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5930 
5931  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
5932  options::OPT_ftemplate_depth_EQ)) {
5933  CmdArgs.push_back("-ftemplate-depth");
5934  CmdArgs.push_back(A->getValue());
5935  }
5936 
5937  if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
5938  CmdArgs.push_back("-foperator-arrow-depth");
5939  CmdArgs.push_back(A->getValue());
5940  }
5941 
5942  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
5943  CmdArgs.push_back("-fconstexpr-depth");
5944  CmdArgs.push_back(A->getValue());
5945  }
5946 
5947  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
5948  CmdArgs.push_back("-fconstexpr-steps");
5949  CmdArgs.push_back(A->getValue());
5950  }
5951 
5952  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
5953 
5954  if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
5955  CmdArgs.push_back("-fexperimental-new-constant-interpreter");
5956 
5957  if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
5958  CmdArgs.push_back("-fbracket-depth");
5959  CmdArgs.push_back(A->getValue());
5960  }
5961 
5962  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
5963  options::OPT_Wlarge_by_value_copy_def)) {
5964  if (A->getNumValues()) {
5965  StringRef bytes = A->getValue();
5966  CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
5967  } else
5968  CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
5969  }
5970 
5971  if (Args.hasArg(options::OPT_relocatable_pch))
5972  CmdArgs.push_back("-relocatable-pch");
5973 
5974  if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
5975  static const char *kCFABIs[] = {
5976  "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
5977  };
5978 
5979  if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
5980  D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
5981  else
5982  A->render(Args, CmdArgs);
5983  }
5984 
5985  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
5986  CmdArgs.push_back("-fconstant-string-class");
5987  CmdArgs.push_back(A->getValue());
5988  }
5989 
5990  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
5991  CmdArgs.push_back("-ftabstop");
5992  CmdArgs.push_back(A->getValue());
5993  }
5994 
5995  Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
5996  options::OPT_fno_stack_size_section);
5997 
5998  if (Args.hasArg(options::OPT_fstack_usage)) {
5999  CmdArgs.push_back("-stack-usage-file");
6000 
6001  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6002  SmallString<128> OutputFilename(OutputOpt->getValue());
6003  llvm::sys::path::replace_extension(OutputFilename, "su");
6004  CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6005  } else
6006  CmdArgs.push_back(
6007  Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6008  }
6009 
6010  CmdArgs.push_back("-ferror-limit");
6011  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6012  CmdArgs.push_back(A->getValue());
6013  else
6014  CmdArgs.push_back("19");
6015 
6016  if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
6017  CmdArgs.push_back("-fmacro-backtrace-limit");
6018  CmdArgs.push_back(A->getValue());
6019  }
6020 
6021  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
6022  CmdArgs.push_back("-ftemplate-backtrace-limit");
6023  CmdArgs.push_back(A->getValue());
6024  }
6025 
6026  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
6027  CmdArgs.push_back("-fconstexpr-backtrace-limit");
6028  CmdArgs.push_back(A->getValue());
6029  }
6030 
6031  if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
6032  CmdArgs.push_back("-fspell-checking-limit");
6033  CmdArgs.push_back(A->getValue());
6034  }
6035 
6036  // Pass -fmessage-length=.
6037  unsigned MessageLength = 0;
6038  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6039  StringRef V(A->getValue());
6040  if (V.getAsInteger(0, MessageLength))
6041  D.Diag(diag::err_drv_invalid_argument_to_option)
6042  << V << A->getOption().getName();
6043  } else {
6044  // If -fmessage-length=N was not specified, determine whether this is a
6045  // terminal and, if so, implicitly define -fmessage-length appropriately.
6046  MessageLength = llvm::sys::Process::StandardErrColumns();
6047  }
6048  if (MessageLength != 0)
6049  CmdArgs.push_back(
6050  Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6051 
6052  if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6053  CmdArgs.push_back(
6054  Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6055 
6056  if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6057  CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6058  Twine(A->getValue(0))));
6059 
6060  // -fvisibility= and -fvisibility-ms-compat are of a piece.
6061  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6062  options::OPT_fvisibility_ms_compat)) {
6063  if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6064  A->render(Args, CmdArgs);
6065  } else {
6066  assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6067  CmdArgs.push_back("-fvisibility=hidden");
6068  CmdArgs.push_back("-ftype-visibility=default");
6069  }
6070  } else if (IsOpenMPDevice) {
6071  // When compiling for the OpenMP device we want protected visibility by
6072  // default. This prevents the device from accidentally preempting code on
6073  // the host, makes the system more robust, and improves performance.
6074  CmdArgs.push_back("-fvisibility=protected");
6075  }
6076 
6077  if (!RawTriple.isPS4())
6078  if (const Arg *A =
6079  Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6080  options::OPT_fno_visibility_from_dllstorageclass)) {
6081  if (A->getOption().matches(
6082  options::OPT_fvisibility_from_dllstorageclass)) {
6083  CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6084  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6085  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6086  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6087  Args.AddLastArg(CmdArgs,
6088  options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6089  }
6090  }
6091 
6092  if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) {
6093  if (Triple.isOSAIX())
6094  CmdArgs.push_back("-mignore-xcoff-visibility");
6095  else
6096  D.Diag(diag::err_drv_unsupported_opt_for_target)
6097  << A->getAsString(Args) << TripleStr;
6098  }
6099 
6100  if (const Arg *A =
6101  Args.getLastArg(options::OPT_mdefault_visibility_export_mapping_EQ)) {
6102  if (Triple.isOSAIX())
6103  A->render(Args, CmdArgs);
6104  else
6105  D.Diag(diag::err_drv_unsupported_opt_for_target)
6106  << A->getAsString(Args) << TripleStr;
6107  }
6108 
6109  if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6110  options::OPT_fno_visibility_inlines_hidden, false))
6111  CmdArgs.push_back("-fvisibility-inlines-hidden");
6112 
6113  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6114  options::OPT_fno_visibility_inlines_hidden_static_local_var);
6115  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
6116  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6117 
6118  if (Args.hasFlag(options::OPT_fnew_infallible,
6119  options::OPT_fno_new_infallible, false))
6120  CmdArgs.push_back("-fnew-infallible");
6121 
6122  if (Args.hasFlag(options::OPT_fno_operator_names,
6123  options::OPT_foperator_names, false))
6124  CmdArgs.push_back("-fno-operator-names");
6125 
6126  // Forward -f (flag) options which we can pass directly.
6127  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6128  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6129  Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6130  Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
6131  options::OPT_fno_emulated_tls);
6132  Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6133 
6134  if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6135  // FIXME: There's no reason for this to be restricted to X86. The backend
6136  // code needs to be changed to include the appropriate function calls
6137  // automatically.
6138  if (!Triple.isX86() && !Triple.isAArch64())
6139  D.Diag(diag::err_drv_unsupported_opt_for_target)
6140  << A->getAsString(Args) << TripleStr;
6141  }
6142 
6143  // AltiVec-like language extensions aren't relevant for assembling.
6144  if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6145  Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6146 
6147  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6148  Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6149 
6150  // Forward flags for OpenMP. We don't do this if the current action is an
6151  // device offloading action other than OpenMP.
6152  if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6153  options::OPT_fno_openmp, false) &&
6156  switch (D.getOpenMPRuntime(Args)) {
6157  case Driver::OMPRT_OMP:
6158  case Driver::OMPRT_IOMP5:
6159  // Clang can generate useful OpenMP code for these two runtime libraries.
6160  CmdArgs.push_back("-fopenmp");
6161 
6162  // If no option regarding the use of TLS in OpenMP codegeneration is
6163  // given, decide a default based on the target. Otherwise rely on the
6164  // options and pass the right information to the frontend.
6165  if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6166  options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6167  CmdArgs.push_back("-fnoopenmp-use-tls");
6168  Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6169  options::OPT_fno_openmp_simd);
6170  Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6171  Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6172  if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6173  options::OPT_fno_openmp_extensions, /*Default=*/true))
6174  CmdArgs.push_back("-fno-openmp-extensions");
6175  Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6176  Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6177  Args.AddAllArgs(CmdArgs,
6178  options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6179  if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6180  options::OPT_fno_openmp_optimistic_collapse,
6181  /*Default=*/false))
6182  CmdArgs.push_back("-fopenmp-optimistic-collapse");
6183 
6184  // When in OpenMP offloading mode with NVPTX target, forward
6185  // cuda-mode flag
6186  if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6187  options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6188  CmdArgs.push_back("-fopenmp-cuda-mode");
6189 
6190  // When in OpenMP offloading mode, enable debugging on the device.
6191  Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6192  if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6193  options::OPT_fno_openmp_target_debug, /*Default=*/false))
6194  CmdArgs.push_back("-fopenmp-target-debug");
6195 
6196  // When in OpenMP offloading mode, forward assumptions information about
6197  // thread and team counts in the device.
6198  if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6199  options::OPT_fno_openmp_assume_teams_oversubscription,
6200  /*Default=*/false))
6201  CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6202  if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6203  options::OPT_fno_openmp_assume_threads_oversubscription,
6204  /*Default=*/false))
6205  CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6206  if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6207  CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6208  if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6209  CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6210  if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6211  CmdArgs.push_back("-fopenmp-offload-mandatory");
6212  break;
6213  default:
6214  // By default, if Clang doesn't know how to generate useful OpenMP code
6215  // for a specific runtime library, we just don't pass the '-fopenmp' flag
6216  // down to the actual compilation.
6217  // FIXME: It would be better to have a mode which *only* omits IR
6218  // generation based on the OpenMP support so that we get consistent
6219  // semantic analysis, etc.
6220  break;
6221  }
6222  } else {
6223  Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6224  options::OPT_fno_openmp_simd);
6225  Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6226  Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6227  options::OPT_fno_openmp_extensions);
6228  }
6229 
6230  // Forward the new driver to change offloading code generation.
6231  if (Args.hasArg(options::OPT_offload_new_driver))
6232  CmdArgs.push_back("--offload-new-driver");
6233 
6234  SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
6235 
6236  const XRayArgs &XRay = TC.getXRayArgs();
6237  XRay.addArgs(TC, Args, CmdArgs, InputType);
6238 
6239  for (const auto &Filename :
6240  Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6241  if (D.getVFS().exists(Filename))
6242  CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6243  else
6244  D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6245  }
6246 
6247  if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6248  StringRef S0 = A->getValue(), S = S0;
6249  unsigned Size, Offset = 0;
6250  if (!Triple.isAArch64() && !Triple.isRISCV() && !Triple.isX86())
6251  D.Diag(diag::err_drv_unsupported_opt_for_target)
6252  << A->getAsString(Args) << TripleStr;
6253  else if (S.consumeInteger(10, Size) ||
6254  (!S.empty() && (!S.consume_front(",") ||
6255  S.consumeInteger(10, Offset) || !S.empty())))
6256  D.Diag(diag::err_drv_invalid_argument_to_option)
6257  << S0 << A->getOption().getName();
6258  else if (Size < Offset)
6259  D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6260  else {
6261  CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6262  CmdArgs.push_back(Args.MakeArgString(
6263  "-fpatchable-function-entry-offset=" + Twine(Offset)));
6264  }
6265  }
6266 
6267  Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);