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