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