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