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