Clang.cpp revision 328753
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"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/ObjCRuntime.h"
26#include "clang/Basic/Version.h"
27#include "clang/Config/config.h"
28#include "clang/Driver/DriverDiagnostic.h"
29#include "clang/Driver/Options.h"
30#include "clang/Driver/SanitizerArgs.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
46using namespace clang::driver;
47using namespace clang::driver::tools;
48using namespace clang;
49using namespace llvm::opt;
50
51static 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
63static 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.
75static 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.
92static 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.
120static void
121forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
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.
129  if (JA.isHostOffloading(Action::OFK_Cuda))
130    Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
131  else if (JA.isDeviceOffloading(Action::OFK_Cuda))
132    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
133
134  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
135    auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
136    for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
137      Work(*II->second);
138  } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
139    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
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.
150static 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.
178static 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".
279static 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
298static void getWebAssemblyTargetFeatures(const ArgList &Args,
299                                         std::vector<StringRef> &Features) {
300  handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
301}
302
303static 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
381static bool
382shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
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.
402static 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
461        assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
462
463      CmdArgs.push_back("-fcxx-exceptions");
464
465      EH = true;
466    }
467  }
468
469  if (EH)
470    CmdArgs.push_back("-fexceptions");
471}
472
473static 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
484static 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.
494static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
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))
499    return codegenoptions::NoDebugInfo;
500  if (A.getOption().matches(options::OPT_gline_tables_only) ||
501      A.getOption().matches(options::OPT_ggdb1))
502    return codegenoptions::DebugLineTablesOnly;
503  return codegenoptions::LimitedDebugInfo;
504}
505
506static 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
518static 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
570static 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) ||
575           mustUseNonLeafFramePointerForTarget(Triple);
576
577  if (Args.hasArg(options::OPT_pg))
578    return true;
579
580  return useFramePointerForTargetByDefault(Args, Triple);
581}
582
583static 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.
599static 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.
609static 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.
640static 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
670static void appendUserToPath(SmallVectorImpl<char> &Result) {
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
702static 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.
830static 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.
843static 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.
866static 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
875static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
876                                    codegenoptions::DebugInfoKind DebugInfoKind,
877                                    unsigned DwarfVersion,
878                                    llvm::DebuggerKind DebuggerTuning) {
879  switch (DebugInfoKind) {
880  case codegenoptions::DebugLineTablesOnly:
881    CmdArgs.push_back("-debug-info-kind=line-tables-only");
882    break;
883  case codegenoptions::LimitedDebugInfo:
884    CmdArgs.push_back("-debug-info-kind=limited");
885    break;
886  case codegenoptions::FullDebugInfo:
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
910static 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
941static 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
959void 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");
1015      SmallString<128> Quoted;
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");
1045      SmallString<128> Quoted;
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.
1059  if (JA.isOffloading(Action::OFK_Cuda))
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.
1262static 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
1291static 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
1303void 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
1353void 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
1424void 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
1472void 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
1614void 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
1650  ppc::FloatABI FloatABI =
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
1671void Clang::AddSparcTargetArgs(const ArgList &Args,
1672                               ArgStringList &CmdArgs) const {
1673  sparc::FloatABI FloatABI =
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
1689void 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
1695void 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
1735void Clang::AddHexagonTargetArgs(const ArgList &Args,
1736                                 ArgStringList &CmdArgs) const {
1737  CmdArgs.push_back("-mqdsp6-compat");
1738  CmdArgs.push_back("-Wreturn-type");
1739
1740  if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1741    CmdArgs.push_back("-mllvm");
1742    CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1743                                         Twine(G.getValue())));
1744  }
1745
1746  if (!Args.hasArg(options::OPT_fno_short_enums))
1747    CmdArgs.push_back("-fshort-enums");
1748  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1749    CmdArgs.push_back("-mllvm");
1750    CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1751  }
1752  CmdArgs.push_back("-mllvm");
1753  CmdArgs.push_back("-machine-sink-split=0");
1754}
1755
1756void Clang::AddLanaiTargetArgs(const ArgList &Args,
1757                               ArgStringList &CmdArgs) const {
1758  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1759    StringRef CPUName = A->getValue();
1760
1761    CmdArgs.push_back("-target-cpu");
1762    CmdArgs.push_back(Args.MakeArgString(CPUName));
1763  }
1764  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1765    StringRef Value = A->getValue();
1766    // Only support mregparm=4 to support old usage. Report error for all other
1767    // cases.
1768    int Mregparm;
1769    if (Value.getAsInteger(10, Mregparm)) {
1770      if (Mregparm != 4) {
1771        getToolChain().getDriver().Diag(
1772            diag::err_drv_unsupported_option_argument)
1773            << A->getOption().getName() << Value;
1774      }
1775    }
1776  }
1777}
1778
1779void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1780                                     ArgStringList &CmdArgs) const {
1781  // Default to "hidden" visibility.
1782  if (!Args.hasArg(options::OPT_fvisibility_EQ,
1783                   options::OPT_fvisibility_ms_compat)) {
1784    CmdArgs.push_back("-fvisibility");
1785    CmdArgs.push_back("hidden");
1786  }
1787}
1788
1789void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1790                                    StringRef Target, const InputInfo &Output,
1791                                    const InputInfo &Input, const ArgList &Args) const {
1792  // If this is a dry run, do not create the compilation database file.
1793  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1794    return;
1795
1796  using llvm::yaml::escape;
1797  const Driver &D = getToolChain().getDriver();
1798
1799  if (!CompilationDatabase) {
1800    std::error_code EC;
1801    auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1802    if (EC) {
1803      D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1804                                                       << EC.message();
1805      return;
1806    }
1807    CompilationDatabase = std::move(File);
1808  }
1809  auto &CDB = *CompilationDatabase;
1810  SmallString<128> Buf;
1811  if (llvm::sys::fs::current_path(Buf))
1812    Buf = ".";
1813  CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1814  CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1815  CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1816  CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1817  Buf = "-x";
1818  Buf += types::getTypeName(Input.getType());
1819  CDB << ", \"" << escape(Buf) << "\"";
1820  if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1821    Buf = "--sysroot=";
1822    Buf += D.SysRoot;
1823    CDB << ", \"" << escape(Buf) << "\"";
1824  }
1825  CDB << ", \"" << escape(Input.getFilename()) << "\"";
1826  for (auto &A: Args) {
1827    auto &O = A->getOption();
1828    // Skip language selection, which is positional.
1829    if (O.getID() == options::OPT_x)
1830      continue;
1831    // Skip writing dependency output and the compilation database itself.
1832    if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1833      continue;
1834    // Skip inputs.
1835    if (O.getKind() == Option::InputClass)
1836      continue;
1837    // All other arguments are quoted and appended.
1838    ArgStringList ASL;
1839    A->render(Args, ASL);
1840    for (auto &it: ASL)
1841      CDB << ", \"" << escape(it) << "\"";
1842  }
1843  Buf = "--target=";
1844  Buf += Target;
1845  CDB << ", \"" << escape(Buf) << "\"]},\n";
1846}
1847
1848static void CollectArgsForIntegratedAssembler(Compilation &C,
1849                                              const ArgList &Args,
1850                                              ArgStringList &CmdArgs,
1851                                              const Driver &D) {
1852  if (UseRelaxAll(C, Args))
1853    CmdArgs.push_back("-mrelax-all");
1854
1855  // Only default to -mincremental-linker-compatible if we think we are
1856  // targeting the MSVC linker.
1857  bool DefaultIncrementalLinkerCompatible =
1858      C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1859  if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1860                   options::OPT_mno_incremental_linker_compatible,
1861                   DefaultIncrementalLinkerCompatible))
1862    CmdArgs.push_back("-mincremental-linker-compatible");
1863
1864  switch (C.getDefaultToolChain().getArch()) {
1865  case llvm::Triple::arm:
1866  case llvm::Triple::armeb:
1867  case llvm::Triple::thumb:
1868  case llvm::Triple::thumbeb:
1869    if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1870      StringRef Value = A->getValue();
1871      if (Value == "always" || Value == "never" || Value == "arm" ||
1872          Value == "thumb") {
1873        CmdArgs.push_back("-mllvm");
1874        CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1875      } else {
1876        D.Diag(diag::err_drv_unsupported_option_argument)
1877            << A->getOption().getName() << Value;
1878      }
1879    }
1880    break;
1881  default:
1882    break;
1883  }
1884
1885  // When passing -I arguments to the assembler we sometimes need to
1886  // unconditionally take the next argument.  For example, when parsing
1887  // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1888  // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1889  // arg after parsing the '-I' arg.
1890  bool TakeNextArg = false;
1891
1892  bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
1893  const char *MipsTargetFeature = nullptr;
1894  for (const Arg *A :
1895       Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1896    A->claim();
1897
1898    for (StringRef Value : A->getValues()) {
1899      if (TakeNextArg) {
1900        CmdArgs.push_back(Value.data());
1901        TakeNextArg = false;
1902        continue;
1903      }
1904
1905      if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1906          Value == "-mbig-obj")
1907        continue; // LLVM handles bigobj automatically
1908
1909      switch (C.getDefaultToolChain().getArch()) {
1910      default:
1911        break;
1912      case llvm::Triple::thumb:
1913      case llvm::Triple::thumbeb:
1914      case llvm::Triple::arm:
1915      case llvm::Triple::armeb:
1916        if (Value == "-mthumb")
1917          // -mthumb has already been processed in ComputeLLVMTriple()
1918          // recognize but skip over here.
1919          continue;
1920        break;
1921      case llvm::Triple::mips:
1922      case llvm::Triple::mipsel:
1923      case llvm::Triple::mips64:
1924      case llvm::Triple::mips64el:
1925        if (Value == "--trap") {
1926          CmdArgs.push_back("-target-feature");
1927          CmdArgs.push_back("+use-tcc-in-div");
1928          continue;
1929        }
1930        if (Value == "--break") {
1931          CmdArgs.push_back("-target-feature");
1932          CmdArgs.push_back("-use-tcc-in-div");
1933          continue;
1934        }
1935        if (Value.startswith("-msoft-float")) {
1936          CmdArgs.push_back("-target-feature");
1937          CmdArgs.push_back("+soft-float");
1938          continue;
1939        }
1940        if (Value.startswith("-mhard-float")) {
1941          CmdArgs.push_back("-target-feature");
1942          CmdArgs.push_back("-soft-float");
1943          continue;
1944        }
1945
1946        MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1947                                .Case("-mips1", "+mips1")
1948                                .Case("-mips2", "+mips2")
1949                                .Case("-mips3", "+mips3")
1950                                .Case("-mips4", "+mips4")
1951                                .Case("-mips5", "+mips5")
1952                                .Case("-mips32", "+mips32")
1953                                .Case("-mips32r2", "+mips32r2")
1954                                .Case("-mips32r3", "+mips32r3")
1955                                .Case("-mips32r5", "+mips32r5")
1956                                .Case("-mips32r6", "+mips32r6")
1957                                .Case("-mips64", "+mips64")
1958                                .Case("-mips64r2", "+mips64r2")
1959                                .Case("-mips64r3", "+mips64r3")
1960                                .Case("-mips64r5", "+mips64r5")
1961                                .Case("-mips64r6", "+mips64r6")
1962                                .Default(nullptr);
1963        if (MipsTargetFeature)
1964          continue;
1965      }
1966
1967      if (Value == "-force_cpusubtype_ALL") {
1968        // Do nothing, this is the default and we don't support anything else.
1969      } else if (Value == "-L") {
1970        CmdArgs.push_back("-msave-temp-labels");
1971      } else if (Value == "--fatal-warnings") {
1972        CmdArgs.push_back("-massembler-fatal-warnings");
1973      } else if (Value == "--noexecstack") {
1974        CmdArgs.push_back("-mnoexecstack");
1975      } else if (Value.startswith("-compress-debug-sections") ||
1976                 Value.startswith("--compress-debug-sections") ||
1977                 Value == "-nocompress-debug-sections" ||
1978                 Value == "--nocompress-debug-sections") {
1979        CmdArgs.push_back(Value.data());
1980      } else if (Value == "-mrelax-relocations=yes" ||
1981                 Value == "--mrelax-relocations=yes") {
1982        UseRelaxRelocations = true;
1983      } else if (Value == "-mrelax-relocations=no" ||
1984                 Value == "--mrelax-relocations=no") {
1985        UseRelaxRelocations = false;
1986      } else if (Value.startswith("-I")) {
1987        CmdArgs.push_back(Value.data());
1988        // We need to consume the next argument if the current arg is a plain
1989        // -I. The next arg will be the include directory.
1990        if (Value == "-I")
1991          TakeNextArg = true;
1992      } else if (Value.startswith("-gdwarf-")) {
1993        // "-gdwarf-N" options are not cc1as options.
1994        unsigned DwarfVersion = DwarfVersionNum(Value);
1995        if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
1996          CmdArgs.push_back(Value.data());
1997        } else {
1998          RenderDebugEnablingArgs(Args, CmdArgs,
1999                                  codegenoptions::LimitedDebugInfo,
2000                                  DwarfVersion, llvm::DebuggerKind::Default);
2001        }
2002      } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2003                 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2004        // Do nothing, we'll validate it later.
2005      } else if (Value == "-defsym") {
2006          if (A->getNumValues() != 2) {
2007            D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2008            break;
2009          }
2010          const char *S = A->getValue(1);
2011          auto Pair = StringRef(S).split('=');
2012          auto Sym = Pair.first;
2013          auto SVal = Pair.second;
2014
2015          if (Sym.empty() || SVal.empty()) {
2016            D.Diag(diag::err_drv_defsym_invalid_format) << S;
2017            break;
2018          }
2019          int64_t IVal;
2020          if (SVal.getAsInteger(0, IVal)) {
2021            D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2022            break;
2023          }
2024          CmdArgs.push_back(Value.data());
2025          TakeNextArg = true;
2026      } else {
2027        D.Diag(diag::err_drv_unsupported_option_argument)
2028            << A->getOption().getName() << Value;
2029      }
2030    }
2031  }
2032  if (UseRelaxRelocations)
2033    CmdArgs.push_back("--mrelax-relocations");
2034  if (MipsTargetFeature != nullptr) {
2035    CmdArgs.push_back("-target-feature");
2036    CmdArgs.push_back(MipsTargetFeature);
2037  }
2038}
2039
2040static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2041                                       bool OFastEnabled, const ArgList &Args,
2042                                       ArgStringList &CmdArgs) {
2043  // Handle various floating point optimization flags, mapping them to the
2044  // appropriate LLVM code generation flags. This is complicated by several
2045  // "umbrella" flags, so we do this by stepping through the flags incrementally
2046  // adjusting what we think is enabled/disabled, then at the end settting the
2047  // LLVM flags based on the final state.
2048  bool HonorINFs = true;
2049  bool HonorNaNs = true;
2050  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2051  bool MathErrno = TC.IsMathErrnoDefault();
2052  bool AssociativeMath = false;
2053  bool ReciprocalMath = false;
2054  bool SignedZeros = true;
2055  bool TrappingMath = true;
2056  StringRef DenormalFPMath = "";
2057  StringRef FPContract = "";
2058
2059  for (const Arg *A : Args) {
2060    switch (A->getOption().getID()) {
2061    // If this isn't an FP option skip the claim below
2062    default: continue;
2063
2064    // Options controlling individual features
2065    case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2066    case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2067    case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2068    case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2069    case options::OPT_fmath_errno:          MathErrno = true;         break;
2070    case options::OPT_fno_math_errno:       MathErrno = false;        break;
2071    case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2072    case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2073    case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2074    case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2075    case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2076    case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2077    case options::OPT_ftrapping_math:       TrappingMath = true;      break;
2078    case options::OPT_fno_trapping_math:    TrappingMath = false;     break;
2079
2080    case options::OPT_fdenormal_fp_math_EQ:
2081      DenormalFPMath = A->getValue();
2082      break;
2083
2084    // Validate and pass through -fp-contract option.
2085    case options::OPT_ffp_contract: {
2086      StringRef Val = A->getValue();
2087      if (Val == "fast" || Val == "on" || Val == "off")
2088        FPContract = Val;
2089      else
2090        D.Diag(diag::err_drv_unsupported_option_argument)
2091            << A->getOption().getName() << Val;
2092      break;
2093    }
2094
2095    case options::OPT_ffinite_math_only:
2096      HonorINFs = false;
2097      HonorNaNs = false;
2098      break;
2099    case options::OPT_fno_finite_math_only:
2100      HonorINFs = true;
2101      HonorNaNs = true;
2102      break;
2103
2104    case options::OPT_funsafe_math_optimizations:
2105      AssociativeMath = true;
2106      ReciprocalMath = true;
2107      SignedZeros = false;
2108      TrappingMath = false;
2109      break;
2110    case options::OPT_fno_unsafe_math_optimizations:
2111      AssociativeMath = false;
2112      ReciprocalMath = false;
2113      SignedZeros = true;
2114      TrappingMath = true;
2115      // -fno_unsafe_math_optimizations restores default denormal handling
2116      DenormalFPMath = "";
2117      break;
2118
2119    case options::OPT_Ofast:
2120      // If -Ofast is the optimization level, then -ffast-math should be enabled
2121      if (!OFastEnabled)
2122        continue;
2123      LLVM_FALLTHROUGH;
2124    case options::OPT_ffast_math:
2125      HonorINFs = false;
2126      HonorNaNs = false;
2127      MathErrno = false;
2128      AssociativeMath = true;
2129      ReciprocalMath = true;
2130      SignedZeros = false;
2131      TrappingMath = false;
2132      // If fast-math is set then set the fp-contract mode to fast.
2133      FPContract = "fast";
2134      break;
2135    case options::OPT_fno_fast_math:
2136      HonorINFs = true;
2137      HonorNaNs = true;
2138      // Turning on -ffast-math (with either flag) removes the need for
2139      // MathErrno. However, turning *off* -ffast-math merely restores the
2140      // toolchain default (which may be false).
2141      MathErrno = TC.IsMathErrnoDefault();
2142      AssociativeMath = false;
2143      ReciprocalMath = false;
2144      SignedZeros = true;
2145      TrappingMath = true;
2146      // -fno_fast_math restores default denormal and fpcontract handling
2147      DenormalFPMath = "";
2148      FPContract = "";
2149      break;
2150    }
2151
2152    // If we handled this option claim it
2153    A->claim();
2154  }
2155
2156  if (!HonorINFs)
2157    CmdArgs.push_back("-menable-no-infs");
2158
2159  if (!HonorNaNs)
2160    CmdArgs.push_back("-menable-no-nans");
2161
2162  if (MathErrno)
2163    CmdArgs.push_back("-fmath-errno");
2164
2165  if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2166      !TrappingMath)
2167    CmdArgs.push_back("-menable-unsafe-fp-math");
2168
2169  if (!SignedZeros)
2170    CmdArgs.push_back("-fno-signed-zeros");
2171
2172  if (AssociativeMath && !SignedZeros && !TrappingMath)
2173    CmdArgs.push_back("-mreassociate");
2174
2175  if (ReciprocalMath)
2176    CmdArgs.push_back("-freciprocal-math");
2177
2178  if (!TrappingMath)
2179    CmdArgs.push_back("-fno-trapping-math");
2180
2181  if (!DenormalFPMath.empty())
2182    CmdArgs.push_back(
2183        Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2184
2185  if (!FPContract.empty())
2186    CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2187
2188  ParseMRecip(D, Args, CmdArgs);
2189
2190  // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2191  // individual features enabled by -ffast-math instead of the option itself as
2192  // that's consistent with gcc's behaviour.
2193  if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2194      ReciprocalMath && !SignedZeros && !TrappingMath)
2195    CmdArgs.push_back("-ffast-math");
2196
2197  // Handle __FINITE_MATH_ONLY__ similarly.
2198  if (!HonorINFs && !HonorNaNs)
2199    CmdArgs.push_back("-ffinite-math-only");
2200
2201  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2202    CmdArgs.push_back("-mfpmath");
2203    CmdArgs.push_back(A->getValue());
2204  }
2205}
2206
2207static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2208                                  const llvm::Triple &Triple,
2209                                  const InputInfo &Input) {
2210  // Enable region store model by default.
2211  CmdArgs.push_back("-analyzer-store=region");
2212
2213  // Treat blocks as analysis entry points.
2214  CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2215
2216  CmdArgs.push_back("-analyzer-eagerly-assume");
2217
2218  // Add default argument set.
2219  if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2220    CmdArgs.push_back("-analyzer-checker=core");
2221    CmdArgs.push_back("-analyzer-checker=apiModeling");
2222
2223    if (!Triple.isWindowsMSVCEnvironment()) {
2224      CmdArgs.push_back("-analyzer-checker=unix");
2225    } else {
2226      // Enable "unix" checkers that also work on Windows.
2227      CmdArgs.push_back("-analyzer-checker=unix.API");
2228      CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2229      CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2230      CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2231      CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2232      CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2233    }
2234
2235    // Disable some unix checkers for PS4.
2236    if (Triple.isPS4CPU()) {
2237      CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2238      CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2239    }
2240
2241    if (Triple.isOSDarwin())
2242      CmdArgs.push_back("-analyzer-checker=osx");
2243
2244    CmdArgs.push_back("-analyzer-checker=deadcode");
2245
2246    if (types::isCXX(Input.getType()))
2247      CmdArgs.push_back("-analyzer-checker=cplusplus");
2248
2249    if (!Triple.isPS4CPU()) {
2250      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2251      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2252      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2253      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2254      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2255      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2256    }
2257
2258    // Default nullability checks.
2259    CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2260    CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2261  }
2262
2263  // Set the output format. The default is plist, for (lame) historical reasons.
2264  CmdArgs.push_back("-analyzer-output");
2265  if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2266    CmdArgs.push_back(A->getValue());
2267  else
2268    CmdArgs.push_back("plist");
2269
2270  // Disable the presentation of standard compiler warnings when using
2271  // --analyze.  We only want to show static analyzer diagnostics or frontend
2272  // errors.
2273  CmdArgs.push_back("-w");
2274
2275  // Add -Xanalyzer arguments when running as analyzer.
2276  Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2277}
2278
2279static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
2280                             ArgStringList &CmdArgs, bool KernelOrKext) {
2281  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2282
2283  // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2284  // doesn't even have a stack!
2285  if (EffectiveTriple.isNVPTX())
2286    return;
2287
2288  // -stack-protector=0 is default.
2289  unsigned StackProtectorLevel = 0;
2290  unsigned DefaultStackProtectorLevel =
2291      TC.GetDefaultStackProtectorLevel(KernelOrKext);
2292
2293  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2294                               options::OPT_fstack_protector_all,
2295                               options::OPT_fstack_protector_strong,
2296                               options::OPT_fstack_protector)) {
2297    if (A->getOption().matches(options::OPT_fstack_protector))
2298      StackProtectorLevel =
2299          std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2300    else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2301      StackProtectorLevel = LangOptions::SSPStrong;
2302    else if (A->getOption().matches(options::OPT_fstack_protector_all))
2303      StackProtectorLevel = LangOptions::SSPReq;
2304  } else {
2305    StackProtectorLevel = DefaultStackProtectorLevel;
2306  }
2307
2308  if (StackProtectorLevel) {
2309    CmdArgs.push_back("-stack-protector");
2310    CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2311  }
2312
2313  // --param ssp-buffer-size=
2314  for (const Arg *A : Args.filtered(options::OPT__param)) {
2315    StringRef Str(A->getValue());
2316    if (Str.startswith("ssp-buffer-size=")) {
2317      if (StackProtectorLevel) {
2318        CmdArgs.push_back("-stack-protector-buffer-size");
2319        // FIXME: Verify the argument is a valid integer.
2320        CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2321      }
2322      A->claim();
2323    }
2324  }
2325}
2326
2327static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2328  const unsigned ForwardedArguments[] = {
2329      options::OPT_cl_opt_disable,
2330      options::OPT_cl_strict_aliasing,
2331      options::OPT_cl_single_precision_constant,
2332      options::OPT_cl_finite_math_only,
2333      options::OPT_cl_kernel_arg_info,
2334      options::OPT_cl_unsafe_math_optimizations,
2335      options::OPT_cl_fast_relaxed_math,
2336      options::OPT_cl_mad_enable,
2337      options::OPT_cl_no_signed_zeros,
2338      options::OPT_cl_denorms_are_zero,
2339      options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2340  };
2341
2342  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2343    std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2344    CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2345  }
2346
2347  for (const auto &Arg : ForwardedArguments)
2348    if (const auto *A = Args.getLastArg(Arg))
2349      CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2350}
2351
2352static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2353                                        ArgStringList &CmdArgs) {
2354  bool ARCMTEnabled = false;
2355  if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2356    if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2357                                       options::OPT_ccc_arcmt_modify,
2358                                       options::OPT_ccc_arcmt_migrate)) {
2359      ARCMTEnabled = true;
2360      switch (A->getOption().getID()) {
2361      default: llvm_unreachable("missed a case");
2362      case options::OPT_ccc_arcmt_check:
2363        CmdArgs.push_back("-arcmt-check");
2364        break;
2365      case options::OPT_ccc_arcmt_modify:
2366        CmdArgs.push_back("-arcmt-modify");
2367        break;
2368      case options::OPT_ccc_arcmt_migrate:
2369        CmdArgs.push_back("-arcmt-migrate");
2370        CmdArgs.push_back("-mt-migrate-directory");
2371        CmdArgs.push_back(A->getValue());
2372
2373        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2374        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2375        break;
2376      }
2377    }
2378  } else {
2379    Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2380    Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2381    Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2382  }
2383
2384  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2385    if (ARCMTEnabled)
2386      D.Diag(diag::err_drv_argument_not_allowed_with)
2387          << A->getAsString(Args) << "-ccc-arcmt-migrate";
2388
2389    CmdArgs.push_back("-mt-migrate-directory");
2390    CmdArgs.push_back(A->getValue());
2391
2392    if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2393                     options::OPT_objcmt_migrate_subscripting,
2394                     options::OPT_objcmt_migrate_property)) {
2395      // None specified, means enable them all.
2396      CmdArgs.push_back("-objcmt-migrate-literals");
2397      CmdArgs.push_back("-objcmt-migrate-subscripting");
2398      CmdArgs.push_back("-objcmt-migrate-property");
2399    } else {
2400      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2401      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2402      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2403    }
2404  } else {
2405    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2406    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2407    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2408    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2409    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2410    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2411    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2412    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2413    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2414    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2415    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2416    Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2417    Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2418    Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2419    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2420    Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2421  }
2422}
2423
2424static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2425                                 const ArgList &Args, ArgStringList &CmdArgs) {
2426  // -fbuiltin is default unless -mkernel is used.
2427  bool UseBuiltins =
2428      Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2429                   !Args.hasArg(options::OPT_mkernel));
2430  if (!UseBuiltins)
2431    CmdArgs.push_back("-fno-builtin");
2432
2433  // -ffreestanding implies -fno-builtin.
2434  if (Args.hasArg(options::OPT_ffreestanding))
2435    UseBuiltins = false;
2436
2437  // Process the -fno-builtin-* options.
2438  for (const auto &Arg : Args) {
2439    const Option &O = Arg->getOption();
2440    if (!O.matches(options::OPT_fno_builtin_))
2441      continue;
2442
2443    Arg->claim();
2444
2445    // If -fno-builtin is specified, then there's no need to pass the option to
2446    // the frontend.
2447    if (!UseBuiltins)
2448      continue;
2449
2450    StringRef FuncName = Arg->getValue();
2451    CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2452  }
2453
2454  // le32-specific flags:
2455  //  -fno-math-builtin: clang should not convert math builtins to intrinsics
2456  //                     by default.
2457  if (TC.getArch() == llvm::Triple::le32)
2458    CmdArgs.push_back("-fno-math-builtin");
2459}
2460
2461static void RenderModulesOptions(Compilation &C, const Driver &D,
2462                                 const ArgList &Args, const InputInfo &Input,
2463                                 const InputInfo &Output,
2464                                 ArgStringList &CmdArgs, bool &HaveModules) {
2465  // -fmodules enables the use of precompiled modules (off by default).
2466  // Users can pass -fno-cxx-modules to turn off modules support for
2467  // C++/Objective-C++ programs.
2468  bool HaveClangModules = false;
2469  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2470    bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2471                                     options::OPT_fno_cxx_modules, true);
2472    if (AllowedInCXX || !types::isCXX(Input.getType())) {
2473      CmdArgs.push_back("-fmodules");
2474      HaveClangModules = true;
2475    }
2476  }
2477
2478  HaveModules = HaveClangModules;
2479  if (Args.hasArg(options::OPT_fmodules_ts)) {
2480    CmdArgs.push_back("-fmodules-ts");
2481    HaveModules = true;
2482  }
2483
2484  // -fmodule-maps enables implicit reading of module map files. By default,
2485  // this is enabled if we are using Clang's flavor of precompiled modules.
2486  if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2487                   options::OPT_fno_implicit_module_maps, HaveClangModules))
2488    CmdArgs.push_back("-fimplicit-module-maps");
2489
2490  // -fmodules-decluse checks that modules used are declared so (off by default)
2491  if (Args.hasFlag(options::OPT_fmodules_decluse,
2492                   options::OPT_fno_modules_decluse, false))
2493    CmdArgs.push_back("-fmodules-decluse");
2494
2495  // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2496  // all #included headers are part of modules.
2497  if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2498                   options::OPT_fno_modules_strict_decluse, false))
2499    CmdArgs.push_back("-fmodules-strict-decluse");
2500
2501  // -fno-implicit-modules turns off implicitly compiling modules on demand.
2502  if (!Args.hasFlag(options::OPT_fimplicit_modules,
2503                    options::OPT_fno_implicit_modules, HaveClangModules)) {
2504    if (HaveModules)
2505      CmdArgs.push_back("-fno-implicit-modules");
2506  } else if (HaveModules) {
2507    // -fmodule-cache-path specifies where our implicitly-built module files
2508    // should be written.
2509    SmallString<128> Path;
2510    if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2511      Path = A->getValue();
2512
2513    if (C.isForDiagnostics()) {
2514      // When generating crash reports, we want to emit the modules along with
2515      // the reproduction sources, so we ignore any provided module path.
2516      Path = Output.getFilename();
2517      llvm::sys::path::replace_extension(Path, ".cache");
2518      llvm::sys::path::append(Path, "modules");
2519    } else if (Path.empty()) {
2520      // No module path was provided: use the default.
2521      llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
2522      llvm::sys::path::append(Path, "org.llvm.clang.");
2523      appendUserToPath(Path);
2524      llvm::sys::path::append(Path, "ModuleCache");
2525    }
2526
2527    const char Arg[] = "-fmodules-cache-path=";
2528    Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2529    CmdArgs.push_back(Args.MakeArgString(Path));
2530  }
2531
2532  if (HaveModules) {
2533    // -fprebuilt-module-path specifies where to load the prebuilt module files.
2534    for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2535      CmdArgs.push_back(Args.MakeArgString(
2536          std::string("-fprebuilt-module-path=") + A->getValue()));
2537      A->claim();
2538    }
2539  }
2540
2541  // -fmodule-name specifies the module that is currently being built (or
2542  // used for header checking by -fmodule-maps).
2543  Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2544
2545  // -fmodule-map-file can be used to specify files containing module
2546  // definitions.
2547  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2548
2549  // -fbuiltin-module-map can be used to load the clang
2550  // builtin headers modulemap file.
2551  if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2552    SmallString<128> BuiltinModuleMap(D.ResourceDir);
2553    llvm::sys::path::append(BuiltinModuleMap, "include");
2554    llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2555    if (llvm::sys::fs::exists(BuiltinModuleMap))
2556      CmdArgs.push_back(
2557          Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2558  }
2559
2560  // The -fmodule-file=<name>=<file> form specifies the mapping of module
2561  // names to precompiled module files (the module is loaded only if used).
2562  // The -fmodule-file=<file> form can be used to unconditionally load
2563  // precompiled module files (whether used or not).
2564  if (HaveModules)
2565    Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2566  else
2567    Args.ClaimAllArgs(options::OPT_fmodule_file);
2568
2569  // When building modules and generating crashdumps, we need to dump a module
2570  // dependency VFS alongside the output.
2571  if (HaveClangModules && C.isForDiagnostics()) {
2572    SmallString<128> VFSDir(Output.getFilename());
2573    llvm::sys::path::replace_extension(VFSDir, ".cache");
2574    // Add the cache directory as a temp so the crash diagnostics pick it up.
2575    C.addTempFile(Args.MakeArgString(VFSDir));
2576
2577    llvm::sys::path::append(VFSDir, "vfs");
2578    CmdArgs.push_back("-module-dependency-dir");
2579    CmdArgs.push_back(Args.MakeArgString(VFSDir));
2580  }
2581
2582  if (HaveClangModules)
2583    Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2584
2585  // Pass through all -fmodules-ignore-macro arguments.
2586  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2587  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2588  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2589
2590  Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2591
2592  if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2593    if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2594      D.Diag(diag::err_drv_argument_not_allowed_with)
2595          << A->getAsString(Args) << "-fbuild-session-timestamp";
2596
2597    llvm::sys::fs::file_status Status;
2598    if (llvm::sys::fs::status(A->getValue(), Status))
2599      D.Diag(diag::err_drv_no_such_file) << A->getValue();
2600    CmdArgs.push_back(
2601        Args.MakeArgString("-fbuild-session-timestamp=" +
2602                           Twine((uint64_t)Status.getLastModificationTime()
2603                                     .time_since_epoch()
2604                                     .count())));
2605  }
2606
2607  if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2608    if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2609                         options::OPT_fbuild_session_file))
2610      D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2611
2612    Args.AddLastArg(CmdArgs,
2613                    options::OPT_fmodules_validate_once_per_build_session);
2614  }
2615
2616  Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
2617  Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2618}
2619
2620static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2621                                   ArgStringList &CmdArgs) {
2622  // -fsigned-char is default.
2623  if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2624                                     options::OPT_fno_signed_char,
2625                                     options::OPT_funsigned_char,
2626                                     options::OPT_fno_unsigned_char)) {
2627    if (A->getOption().matches(options::OPT_funsigned_char) ||
2628        A->getOption().matches(options::OPT_fno_signed_char)) {
2629      CmdArgs.push_back("-fno-signed-char");
2630    }
2631  } else if (!isSignedCharDefault(T)) {
2632    CmdArgs.push_back("-fno-signed-char");
2633  }
2634
2635  if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2636                                     options::OPT_fno_short_wchar)) {
2637    if (A->getOption().matches(options::OPT_fshort_wchar)) {
2638      CmdArgs.push_back("-fwchar-type=short");
2639      CmdArgs.push_back("-fno-signed-wchar");
2640    } else {
2641      bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
2642      CmdArgs.push_back("-fwchar-type=int");
2643      if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2644                     T.getOS() == llvm::Triple::OpenBSD))
2645        CmdArgs.push_back("-fno-signed-wchar");
2646      else
2647        CmdArgs.push_back("-fsigned-wchar");
2648    }
2649  }
2650}
2651
2652static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2653                              const llvm::Triple &T, const ArgList &Args,
2654                              ObjCRuntime &Runtime, bool InferCovariantReturns,
2655                              const InputInfo &Input, ArgStringList &CmdArgs) {
2656  const llvm::Triple::ArchType Arch = TC.getArch();
2657
2658  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2659  // is the default. Except for deployment target of 10.5, next runtime is
2660  // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2661  if (Runtime.isNonFragile()) {
2662    if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2663                      options::OPT_fno_objc_legacy_dispatch,
2664                      Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2665      if (TC.UseObjCMixedDispatch())
2666        CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2667      else
2668        CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2669    }
2670  }
2671
2672  // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2673  // to do Array/Dictionary subscripting by default.
2674  if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2675      !T.isMacOSXVersionLT(10, 7) &&
2676      Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2677    CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2678
2679  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2680  // NOTE: This logic is duplicated in ToolChains.cpp.
2681  if (isObjCAutoRefCount(Args)) {
2682    TC.CheckObjCARC();
2683
2684    CmdArgs.push_back("-fobjc-arc");
2685
2686    // FIXME: It seems like this entire block, and several around it should be
2687    // wrapped in isObjC, but for now we just use it here as this is where it
2688    // was being used previously.
2689    if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2690      if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2691        CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2692      else
2693        CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2694    }
2695
2696    // Allow the user to enable full exceptions code emission.
2697    // We default off for Objective-C, on for Objective-C++.
2698    if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2699                     options::OPT_fno_objc_arc_exceptions,
2700                     /*default=*/types::isCXX(Input.getType())))
2701      CmdArgs.push_back("-fobjc-arc-exceptions");
2702  }
2703
2704  // Silence warning for full exception code emission options when explicitly
2705  // set to use no ARC.
2706  if (Args.hasArg(options::OPT_fno_objc_arc)) {
2707    Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2708    Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2709  }
2710
2711  // -fobjc-infer-related-result-type is the default, except in the Objective-C
2712  // rewriter.
2713  if (InferCovariantReturns)
2714    CmdArgs.push_back("-fno-objc-infer-related-result-type");
2715
2716  // Pass down -fobjc-weak or -fno-objc-weak if present.
2717  if (types::isObjC(Input.getType())) {
2718    auto WeakArg =
2719        Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2720    if (!WeakArg) {
2721      // nothing to do
2722    } else if (!Runtime.allowsWeak()) {
2723      if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2724        D.Diag(diag::err_objc_weak_unsupported);
2725    } else {
2726      WeakArg->render(Args, CmdArgs);
2727    }
2728  }
2729}
2730
2731static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2732                                     ArgStringList &CmdArgs) {
2733  bool CaretDefault = true;
2734  bool ColumnDefault = true;
2735
2736  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2737                                     options::OPT__SLASH_diagnostics_column,
2738                                     options::OPT__SLASH_diagnostics_caret)) {
2739    switch (A->getOption().getID()) {
2740    case options::OPT__SLASH_diagnostics_caret:
2741      CaretDefault = true;
2742      ColumnDefault = true;
2743      break;
2744    case options::OPT__SLASH_diagnostics_column:
2745      CaretDefault = false;
2746      ColumnDefault = true;
2747      break;
2748    case options::OPT__SLASH_diagnostics_classic:
2749      CaretDefault = false;
2750      ColumnDefault = false;
2751      break;
2752    }
2753  }
2754
2755  // -fcaret-diagnostics is default.
2756  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2757                    options::OPT_fno_caret_diagnostics, CaretDefault))
2758    CmdArgs.push_back("-fno-caret-diagnostics");
2759
2760  // -fdiagnostics-fixit-info is default, only pass non-default.
2761  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2762                    options::OPT_fno_diagnostics_fixit_info))
2763    CmdArgs.push_back("-fno-diagnostics-fixit-info");
2764
2765  // Enable -fdiagnostics-show-option by default.
2766  if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2767                   options::OPT_fno_diagnostics_show_option))
2768    CmdArgs.push_back("-fdiagnostics-show-option");
2769
2770  if (const Arg *A =
2771          Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2772    CmdArgs.push_back("-fdiagnostics-show-category");
2773    CmdArgs.push_back(A->getValue());
2774  }
2775
2776  if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2777                   options::OPT_fno_diagnostics_show_hotness, false))
2778    CmdArgs.push_back("-fdiagnostics-show-hotness");
2779
2780  if (const Arg *A =
2781          Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2782    std::string Opt =
2783        std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2784    CmdArgs.push_back(Args.MakeArgString(Opt));
2785  }
2786
2787  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2788    CmdArgs.push_back("-fdiagnostics-format");
2789    CmdArgs.push_back(A->getValue());
2790  }
2791
2792  if (const Arg *A = Args.getLastArg(
2793          options::OPT_fdiagnostics_show_note_include_stack,
2794          options::OPT_fno_diagnostics_show_note_include_stack)) {
2795    const Option &O = A->getOption();
2796    if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2797      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2798    else
2799      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2800  }
2801
2802  // Color diagnostics are parsed by the driver directly from argv and later
2803  // re-parsed to construct this job; claim any possible color diagnostic here
2804  // to avoid warn_drv_unused_argument and diagnose bad
2805  // OPT_fdiagnostics_color_EQ values.
2806  for (const Arg *A : Args) {
2807    const Option &O = A->getOption();
2808    if (!O.matches(options::OPT_fcolor_diagnostics) &&
2809        !O.matches(options::OPT_fdiagnostics_color) &&
2810        !O.matches(options::OPT_fno_color_diagnostics) &&
2811        !O.matches(options::OPT_fno_diagnostics_color) &&
2812        !O.matches(options::OPT_fdiagnostics_color_EQ))
2813      continue;
2814
2815    if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2816      StringRef Value(A->getValue());
2817      if (Value != "always" && Value != "never" && Value != "auto")
2818        D.Diag(diag::err_drv_clang_unsupported)
2819            << ("-fdiagnostics-color=" + Value).str();
2820    }
2821    A->claim();
2822  }
2823
2824  if (D.getDiags().getDiagnosticOptions().ShowColors)
2825    CmdArgs.push_back("-fcolor-diagnostics");
2826
2827  if (Args.hasArg(options::OPT_fansi_escape_codes))
2828    CmdArgs.push_back("-fansi-escape-codes");
2829
2830  if (!Args.hasFlag(options::OPT_fshow_source_location,
2831                    options::OPT_fno_show_source_location))
2832    CmdArgs.push_back("-fno-show-source-location");
2833
2834  if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2835    CmdArgs.push_back("-fdiagnostics-absolute-paths");
2836
2837  if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2838                    ColumnDefault))
2839    CmdArgs.push_back("-fno-show-column");
2840
2841  if (!Args.hasFlag(options::OPT_fspell_checking,
2842                    options::OPT_fno_spell_checking))
2843    CmdArgs.push_back("-fno-spell-checking");
2844}
2845
2846static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2847                               const llvm::Triple &T, const ArgList &Args,
2848                               bool EmitCodeView, bool IsWindowsMSVC,
2849                               ArgStringList &CmdArgs,
2850                               codegenoptions::DebugInfoKind &DebugInfoKind,
2851                               const Arg *&SplitDWARFArg) {
2852  if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2853                   options::OPT_fno_debug_info_for_profiling, false))
2854    CmdArgs.push_back("-fdebug-info-for-profiling");
2855
2856  // The 'g' groups options involve a somewhat intricate sequence of decisions
2857  // about what to pass from the driver to the frontend, but by the time they
2858  // reach cc1 they've been factored into three well-defined orthogonal choices:
2859  //  * what level of debug info to generate
2860  //  * what dwarf version to write
2861  //  * what debugger tuning to use
2862  // This avoids having to monkey around further in cc1 other than to disable
2863  // codeview if not running in a Windows environment. Perhaps even that
2864  // decision should be made in the driver as well though.
2865  unsigned DWARFVersion = 0;
2866  llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2867
2868  bool SplitDWARFInlining =
2869      Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2870                   options::OPT_fno_split_dwarf_inlining, true);
2871
2872  Args.ClaimAllArgs(options::OPT_g_Group);
2873
2874  SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2875
2876  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2877    // If the last option explicitly specified a debug-info level, use it.
2878    if (A->getOption().matches(options::OPT_gN_Group)) {
2879      DebugInfoKind = DebugLevelToInfoKind(*A);
2880      // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2881      // But -gsplit-dwarf is not a g_group option, hence we have to check the
2882      // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2883      // This gets a bit more complicated if you've disabled inline info in the
2884      // skeleton CUs (SplitDWARFInlining) - then there's value in composing
2885      // split-dwarf and line-tables-only, so let those compose naturally in
2886      // that case.
2887      // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2888      if (SplitDWARFArg) {
2889        if (A->getIndex() > SplitDWARFArg->getIndex()) {
2890          if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2891              (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2892               SplitDWARFInlining))
2893            SplitDWARFArg = nullptr;
2894        } else if (SplitDWARFInlining)
2895          DebugInfoKind = codegenoptions::NoDebugInfo;
2896      }
2897    } else {
2898      // For any other 'g' option, use Limited.
2899      DebugInfoKind = codegenoptions::LimitedDebugInfo;
2900    }
2901  }
2902
2903  // If a debugger tuning argument appeared, remember it.
2904  if (const Arg *A =
2905          Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2906    if (A->getOption().matches(options::OPT_glldb))
2907      DebuggerTuning = llvm::DebuggerKind::LLDB;
2908    else if (A->getOption().matches(options::OPT_gsce))
2909      DebuggerTuning = llvm::DebuggerKind::SCE;
2910    else
2911      DebuggerTuning = llvm::DebuggerKind::GDB;
2912  }
2913
2914  // If a -gdwarf argument appeared, remember it.
2915  if (const Arg *A =
2916          Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2917                          options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2918    DWARFVersion = DwarfVersionNum(A->getSpelling());
2919
2920  // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2921  // argument parsing.
2922  if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
2923    // DWARFVersion remains at 0 if no explicit choice was made.
2924    CmdArgs.push_back("-gcodeview");
2925  } else if (DWARFVersion == 0 &&
2926             DebugInfoKind != codegenoptions::NoDebugInfo) {
2927    DWARFVersion = TC.GetDefaultDwarfVersion();
2928  }
2929
2930  // We ignore flag -gstrict-dwarf for now.
2931  // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2932  Args.ClaimAllArgs(options::OPT_g_flags_Group);
2933
2934  // Column info is included by default for everything except SCE and CodeView.
2935  // Clang doesn't track end columns, just starting columns, which, in theory,
2936  // is fine for CodeView (and PDB).  In practice, however, the Microsoft
2937  // debuggers don't handle missing end columns well, so it's better not to
2938  // include any column info.
2939  if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
2940                   /*Default=*/!(IsWindowsMSVC && EmitCodeView) &&
2941                       DebuggerTuning != llvm::DebuggerKind::SCE))
2942    CmdArgs.push_back("-dwarf-column-info");
2943
2944  // FIXME: Move backend command line options to the module.
2945  // If -gline-tables-only is the last option it wins.
2946  if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2947      Args.hasArg(options::OPT_gmodules)) {
2948    DebugInfoKind = codegenoptions::LimitedDebugInfo;
2949    CmdArgs.push_back("-dwarf-ext-refs");
2950    CmdArgs.push_back("-fmodule-format=obj");
2951  }
2952
2953  // -gsplit-dwarf should turn on -g and enable the backend dwarf
2954  // splitting and extraction.
2955  // FIXME: Currently only works on Linux.
2956  if (T.isOSLinux()) {
2957    if (!SplitDWARFInlining)
2958      CmdArgs.push_back("-fno-split-dwarf-inlining");
2959
2960    if (SplitDWARFArg) {
2961      if (DebugInfoKind == codegenoptions::NoDebugInfo)
2962        DebugInfoKind = codegenoptions::LimitedDebugInfo;
2963      CmdArgs.push_back("-enable-split-dwarf");
2964    }
2965  }
2966
2967  // After we've dealt with all combinations of things that could
2968  // make DebugInfoKind be other than None or DebugLineTablesOnly,
2969  // figure out if we need to "upgrade" it to standalone debug info.
2970  // We parse these two '-f' options whether or not they will be used,
2971  // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
2972  bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
2973                                    options::OPT_fno_standalone_debug,
2974                                    TC.GetDefaultStandaloneDebug());
2975  if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
2976    DebugInfoKind = codegenoptions::FullDebugInfo;
2977
2978  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
2979                          DebuggerTuning);
2980
2981  // -fdebug-macro turns on macro debug info generation.
2982  if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
2983                   false))
2984    CmdArgs.push_back("-debug-info-macro");
2985
2986  // -ggnu-pubnames turns on gnu style pubnames in the backend.
2987  if (Args.hasArg(options::OPT_ggnu_pubnames))
2988    CmdArgs.push_back("-ggnu-pubnames");
2989
2990  // -gdwarf-aranges turns on the emission of the aranges section in the
2991  // backend.
2992  // Always enabled for SCE tuning.
2993  if (Args.hasArg(options::OPT_gdwarf_aranges) ||
2994      DebuggerTuning == llvm::DebuggerKind::SCE) {
2995    CmdArgs.push_back("-backend-option");
2996    CmdArgs.push_back("-generate-arange-section");
2997  }
2998
2999  if (Args.hasFlag(options::OPT_fdebug_types_section,
3000                   options::OPT_fno_debug_types_section, false)) {
3001    CmdArgs.push_back("-backend-option");
3002    CmdArgs.push_back("-generate-type-units");
3003  }
3004
3005  // Decide how to render forward declarations of template instantiations.
3006  // SCE wants full descriptions, others just get them in the name.
3007  if (DebuggerTuning == llvm::DebuggerKind::SCE)
3008    CmdArgs.push_back("-debug-forward-template-params");
3009
3010  // Do we need to explicitly import anonymous namespaces into the parent scope?
3011  if (DebuggerTuning == llvm::DebuggerKind::SCE)
3012    CmdArgs.push_back("-dwarf-explicit-import");
3013
3014  RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
3015}
3016
3017void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3018                         const InputInfo &Output, const InputInfoList &Inputs,
3019                         const ArgList &Args, const char *LinkingOutput) const {
3020  const llvm::Triple &RawTriple = getToolChain().getTriple();
3021  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3022  const std::string &TripleStr = Triple.getTriple();
3023
3024  bool KernelOrKext =
3025      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3026  const Driver &D = getToolChain().getDriver();
3027  ArgStringList CmdArgs;
3028
3029  // Check number of inputs for sanity. We need at least one input.
3030  assert(Inputs.size() >= 1 && "Must have at least one input.");
3031  const InputInfo &Input = Inputs[0];
3032  // CUDA compilation may have multiple inputs (source file + results of
3033  // device-side compilations). OpenMP device jobs also take the host IR as a
3034  // second input. All other jobs are expected to have exactly one
3035  // input.
3036  bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3037  bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3038  assert((IsCuda || (IsOpenMPDevice && Inputs.size() == 2) ||
3039          Inputs.size() == 1) &&
3040         "Unable to handle multiple inputs.");
3041
3042  const llvm::Triple *AuxTriple =
3043      IsCuda ? getToolChain().getAuxTriple() : nullptr;
3044
3045  bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3046  bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3047  bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3048  bool IsIAMCU = RawTriple.isOSIAMCU();
3049
3050  // Adjust IsWindowsXYZ for CUDA compilations.  Even when compiling in device
3051  // mode (i.e., getToolchain().getTriple() is NVPTX, not Windows), we need to
3052  // pass Windows-specific flags to cc1.
3053  if (IsCuda) {
3054    IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3055    IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3056    IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3057  }
3058
3059  // C++ is not supported for IAMCU.
3060  if (IsIAMCU && types::isCXX(Input.getType()))
3061    D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3062
3063  // Invoke ourselves in -cc1 mode.
3064  //
3065  // FIXME: Implement custom jobs for internal actions.
3066  CmdArgs.push_back("-cc1");
3067
3068  // Add the "effective" target triple.
3069  CmdArgs.push_back("-triple");
3070  CmdArgs.push_back(Args.MakeArgString(TripleStr));
3071
3072  if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3073    DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3074    Args.ClaimAllArgs(options::OPT_MJ);
3075  }
3076
3077  if (IsCuda) {
3078    // We have to pass the triple of the host if compiling for a CUDA device and
3079    // vice-versa.
3080    std::string NormalizedTriple;
3081    if (JA.isDeviceOffloading(Action::OFK_Cuda))
3082      NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3083                             ->getTriple()
3084                             .normalize();
3085    else
3086      NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3087                             ->getTriple()
3088                             .normalize();
3089
3090    CmdArgs.push_back("-aux-triple");
3091    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3092  }
3093
3094  if (IsOpenMPDevice) {
3095    // We have to pass the triple of the host if compiling for an OpenMP device.
3096    std::string NormalizedTriple =
3097        C.getSingleOffloadToolChain<Action::OFK_Host>()
3098            ->getTriple()
3099            .normalize();
3100    CmdArgs.push_back("-aux-triple");
3101    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3102  }
3103
3104  if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3105                               Triple.getArch() == llvm::Triple::thumb)) {
3106    unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3107    unsigned Version;
3108    Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3109    if (Version < 7)
3110      D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3111                                                << TripleStr;
3112  }
3113
3114  // Push all default warning arguments that are specific to
3115  // the given target.  These come before user provided warning options
3116  // are provided.
3117  getToolChain().addClangWarningOptions(CmdArgs);
3118
3119  // Select the appropriate action.
3120  RewriteKind rewriteKind = RK_None;
3121
3122  if (isa<AnalyzeJobAction>(JA)) {
3123    assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3124    CmdArgs.push_back("-analyze");
3125  } else if (isa<MigrateJobAction>(JA)) {
3126    CmdArgs.push_back("-migrate");
3127  } else if (isa<PreprocessJobAction>(JA)) {
3128    if (Output.getType() == types::TY_Dependencies)
3129      CmdArgs.push_back("-Eonly");
3130    else {
3131      CmdArgs.push_back("-E");
3132      if (Args.hasArg(options::OPT_rewrite_objc) &&
3133          !Args.hasArg(options::OPT_g_Group))
3134        CmdArgs.push_back("-P");
3135    }
3136  } else if (isa<AssembleJobAction>(JA)) {
3137    CmdArgs.push_back("-emit-obj");
3138
3139    CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3140
3141    // Also ignore explicit -force_cpusubtype_ALL option.
3142    (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3143  } else if (isa<PrecompileJobAction>(JA)) {
3144    // Use PCH if the user requested it.
3145    bool UsePCH = D.CCCUsePCH;
3146
3147    if (JA.getType() == types::TY_Nothing)
3148      CmdArgs.push_back("-fsyntax-only");
3149    else if (JA.getType() == types::TY_ModuleFile)
3150      CmdArgs.push_back("-emit-module-interface");
3151    else if (UsePCH)
3152      CmdArgs.push_back("-emit-pch");
3153    else
3154      CmdArgs.push_back("-emit-pth");
3155  } else if (isa<VerifyPCHJobAction>(JA)) {
3156    CmdArgs.push_back("-verify-pch");
3157  } else {
3158    assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3159           "Invalid action for clang tool.");
3160    if (JA.getType() == types::TY_Nothing) {
3161      CmdArgs.push_back("-fsyntax-only");
3162    } else if (JA.getType() == types::TY_LLVM_IR ||
3163               JA.getType() == types::TY_LTO_IR) {
3164      CmdArgs.push_back("-emit-llvm");
3165    } else if (JA.getType() == types::TY_LLVM_BC ||
3166               JA.getType() == types::TY_LTO_BC) {
3167      CmdArgs.push_back("-emit-llvm-bc");
3168    } else if (JA.getType() == types::TY_PP_Asm) {
3169      CmdArgs.push_back("-S");
3170    } else if (JA.getType() == types::TY_AST) {
3171      CmdArgs.push_back("-emit-pch");
3172    } else if (JA.getType() == types::TY_ModuleFile) {
3173      CmdArgs.push_back("-module-file-info");
3174    } else if (JA.getType() == types::TY_RewrittenObjC) {
3175      CmdArgs.push_back("-rewrite-objc");
3176      rewriteKind = RK_NonFragile;
3177    } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3178      CmdArgs.push_back("-rewrite-objc");
3179      rewriteKind = RK_Fragile;
3180    } else {
3181      assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3182    }
3183
3184    // Preserve use-list order by default when emitting bitcode, so that
3185    // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3186    // same result as running passes here.  For LTO, we don't need to preserve
3187    // the use-list order, since serialization to bitcode is part of the flow.
3188    if (JA.getType() == types::TY_LLVM_BC)
3189      CmdArgs.push_back("-emit-llvm-uselists");
3190
3191    if (D.isUsingLTO()) {
3192      Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3193
3194      // The Darwin and PS4 linkers currently use the legacy LTO API, which
3195      // does not support LTO unit features (CFI, whole program vtable opt)
3196      // under ThinLTO.
3197      if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
3198          D.getLTOMode() == LTOK_Full)
3199        CmdArgs.push_back("-flto-unit");
3200    }
3201  }
3202
3203  if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3204    if (!types::isLLVMIR(Input.getType()))
3205      D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3206                                                       << "-x ir";
3207    Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3208  }
3209
3210  // Embed-bitcode option.
3211  if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3212      (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3213    // Add flags implied by -fembed-bitcode.
3214    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3215    // Disable all llvm IR level optimizations.
3216    CmdArgs.push_back("-disable-llvm-passes");
3217  }
3218  if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3219    CmdArgs.push_back("-fembed-bitcode=marker");
3220
3221  // We normally speed up the clang process a bit by skipping destructors at
3222  // exit, but when we're generating diagnostics we can rely on some of the
3223  // cleanup.
3224  if (!C.isForDiagnostics())
3225    CmdArgs.push_back("-disable-free");
3226
3227// Disable the verification pass in -asserts builds.
3228#ifdef NDEBUG
3229  CmdArgs.push_back("-disable-llvm-verifier");
3230  // Discard LLVM value names in -asserts builds.
3231  CmdArgs.push_back("-discard-value-names");
3232#endif
3233
3234  // Set the main file name, so that debug info works even with
3235  // -save-temps.
3236  CmdArgs.push_back("-main-file-name");
3237  CmdArgs.push_back(getBaseInputName(Args, Input));
3238
3239  // Some flags which affect the language (via preprocessor
3240  // defines).
3241  if (Args.hasArg(options::OPT_static))
3242    CmdArgs.push_back("-static-define");
3243
3244  if (isa<AnalyzeJobAction>(JA))
3245    RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
3246
3247  CheckCodeGenerationOptions(D, Args);
3248
3249  llvm::Reloc::Model RelocationModel;
3250  unsigned PICLevel;
3251  bool IsPIE;
3252  std::tie(RelocationModel, PICLevel, IsPIE) =
3253      ParsePICArgs(getToolChain(), Args);
3254
3255  const char *RMName = RelocationModelName(RelocationModel);
3256
3257  if ((RelocationModel == llvm::Reloc::ROPI ||
3258       RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3259      types::isCXX(Input.getType()) &&
3260      !Args.hasArg(options::OPT_fallow_unsupported))
3261    D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3262
3263  if (RMName) {
3264    CmdArgs.push_back("-mrelocation-model");
3265    CmdArgs.push_back(RMName);
3266  }
3267  if (PICLevel > 0) {
3268    CmdArgs.push_back("-pic-level");
3269    CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3270    if (IsPIE)
3271      CmdArgs.push_back("-pic-is-pie");
3272  }
3273
3274  if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3275    CmdArgs.push_back("-meabi");
3276    CmdArgs.push_back(A->getValue());
3277  }
3278
3279  CmdArgs.push_back("-mthread-model");
3280  if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3281    if (!getToolChain().isThreadModelSupported(A->getValue()))
3282      D.Diag(diag::err_drv_invalid_thread_model_for_target)
3283          << A->getValue() << A->getAsString(Args);
3284    CmdArgs.push_back(A->getValue());
3285  }
3286  else
3287    CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3288
3289  Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3290
3291  if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3292                    options::OPT_fno_merge_all_constants))
3293    CmdArgs.push_back("-fno-merge-all-constants");
3294
3295  // LLVM Code Generator Options.
3296
3297  if (Args.hasArg(options::OPT_frewrite_map_file) ||
3298      Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3299    for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3300                                      options::OPT_frewrite_map_file_EQ)) {
3301      StringRef Map = A->getValue();
3302      if (!llvm::sys::fs::exists(Map)) {
3303        D.Diag(diag::err_drv_no_such_file) << Map;
3304      } else {
3305        CmdArgs.push_back("-frewrite-map-file");
3306        CmdArgs.push_back(A->getValue());
3307        A->claim();
3308      }
3309    }
3310  }
3311
3312  if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3313    StringRef v = A->getValue();
3314    CmdArgs.push_back("-mllvm");
3315    CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3316    A->claim();
3317  }
3318
3319  if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3320                    true))
3321    CmdArgs.push_back("-fno-jump-tables");
3322
3323  if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3324                   options::OPT_fno_profile_sample_accurate, false))
3325    CmdArgs.push_back("-fprofile-sample-accurate");
3326
3327  if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3328                    options::OPT_fno_preserve_as_comments, true))
3329    CmdArgs.push_back("-fno-preserve-as-comments");
3330
3331  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3332    CmdArgs.push_back("-mregparm");
3333    CmdArgs.push_back(A->getValue());
3334  }
3335
3336  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3337                               options::OPT_freg_struct_return)) {
3338    if (getToolChain().getArch() != llvm::Triple::x86) {
3339      D.Diag(diag::err_drv_unsupported_opt_for_target)
3340          << A->getSpelling() << RawTriple.str();
3341    } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3342      CmdArgs.push_back("-fpcc-struct-return");
3343    } else {
3344      assert(A->getOption().matches(options::OPT_freg_struct_return));
3345      CmdArgs.push_back("-freg-struct-return");
3346    }
3347  }
3348
3349  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3350    CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3351
3352  if (shouldUseFramePointer(Args, RawTriple))
3353    CmdArgs.push_back("-mdisable-fp-elim");
3354  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3355                    options::OPT_fno_zero_initialized_in_bss))
3356    CmdArgs.push_back("-mno-zero-initialized-in-bss");
3357
3358  bool OFastEnabled = isOptimizationLevelFast(Args);
3359  // If -Ofast is the optimization level, then -fstrict-aliasing should be
3360  // enabled.  This alias option is being used to simplify the hasFlag logic.
3361  OptSpecifier StrictAliasingAliasOption =
3362      OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3363  // We turn strict aliasing off by default if we're in CL mode, since MSVC
3364  // doesn't do any TBAA.
3365  bool TBAAOnByDefault = !D.IsCLMode();
3366  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3367                    options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3368    CmdArgs.push_back("-relaxed-aliasing");
3369  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3370                    options::OPT_fno_struct_path_tbaa))
3371    CmdArgs.push_back("-no-struct-path-tbaa");
3372  if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3373                   false))
3374    CmdArgs.push_back("-fstrict-enums");
3375  if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3376                    true))
3377    CmdArgs.push_back("-fno-strict-return");
3378  if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3379                   options::OPT_fno_allow_editor_placeholders, false))
3380    CmdArgs.push_back("-fallow-editor-placeholders");
3381  if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3382                   options::OPT_fno_strict_vtable_pointers,
3383                   false))
3384    CmdArgs.push_back("-fstrict-vtable-pointers");
3385  if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3386                    options::OPT_fno_optimize_sibling_calls))
3387    CmdArgs.push_back("-mdisable-tail-calls");
3388
3389  Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3390                  options::OPT_fno_fine_grained_bitfield_accesses);
3391
3392  // Handle segmented stacks.
3393  if (Args.hasArg(options::OPT_fsplit_stack))
3394    CmdArgs.push_back("-split-stacks");
3395
3396  RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
3397
3398  // Decide whether to use verbose asm. Verbose assembly is the default on
3399  // toolchains which have the integrated assembler on by default.
3400  bool IsIntegratedAssemblerDefault =
3401      getToolChain().IsIntegratedAssemblerDefault();
3402  if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3403                   IsIntegratedAssemblerDefault) ||
3404      Args.hasArg(options::OPT_dA))
3405    CmdArgs.push_back("-masm-verbose");
3406
3407  if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3408                    IsIntegratedAssemblerDefault))
3409    CmdArgs.push_back("-no-integrated-as");
3410
3411  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3412    CmdArgs.push_back("-mdebug-pass");
3413    CmdArgs.push_back("Structure");
3414  }
3415  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3416    CmdArgs.push_back("-mdebug-pass");
3417    CmdArgs.push_back("Arguments");
3418  }
3419
3420  // Enable -mconstructor-aliases except on darwin, where we have to work around
3421  // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3422  // aliases aren't supported.
3423  if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
3424    CmdArgs.push_back("-mconstructor-aliases");
3425
3426  // Darwin's kernel doesn't support guard variables; just die if we
3427  // try to use them.
3428  if (KernelOrKext && RawTriple.isOSDarwin())
3429    CmdArgs.push_back("-fforbid-guard-variables");
3430
3431  if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3432                   false)) {
3433    CmdArgs.push_back("-mms-bitfields");
3434  }
3435
3436  if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3437                   options::OPT_mno_pie_copy_relocations,
3438                   false)) {
3439    CmdArgs.push_back("-mpie-copy-relocations");
3440  }
3441
3442  if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3443    CmdArgs.push_back("-fno-plt");
3444  }
3445
3446  // -fhosted is default.
3447  // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3448  // use Freestanding.
3449  bool Freestanding =
3450      Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3451      KernelOrKext;
3452  if (Freestanding)
3453    CmdArgs.push_back("-ffreestanding");
3454
3455  // This is a coarse approximation of what llvm-gcc actually does, both
3456  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3457  // complicated ways.
3458  bool AsynchronousUnwindTables =
3459      Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3460                   options::OPT_fno_asynchronous_unwind_tables,
3461                   (getToolChain().IsUnwindTablesDefault(Args) ||
3462                    getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3463                       !Freestanding);
3464  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3465                   AsynchronousUnwindTables))
3466    CmdArgs.push_back("-munwind-tables");
3467
3468  getToolChain().addClangTargetOptions(Args, CmdArgs,
3469                                       JA.getOffloadingDeviceKind());
3470
3471  if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3472    CmdArgs.push_back("-mlimit-float-precision");
3473    CmdArgs.push_back(A->getValue());
3474  }
3475
3476  // FIXME: Handle -mtune=.
3477  (void)Args.hasArg(options::OPT_mtune_EQ);
3478
3479  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3480    CmdArgs.push_back("-mcode-model");
3481    CmdArgs.push_back(A->getValue());
3482  }
3483
3484  // Add the target cpu
3485  std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3486  if (!CPU.empty()) {
3487    CmdArgs.push_back("-target-cpu");
3488    CmdArgs.push_back(Args.MakeArgString(CPU));
3489  }
3490
3491  RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
3492
3493  // These two are potentially updated by AddClangCLArgs.
3494  codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3495  bool EmitCodeView = false;
3496
3497  // Add clang-cl arguments.
3498  types::ID InputType = Input.getType();
3499  if (D.IsCLMode())
3500    AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
3501
3502  const Arg *SplitDWARFArg = nullptr;
3503  RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3504                     IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3505
3506  // Add the split debug info name to the command lines here so we
3507  // can propagate it to the backend.
3508  bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3509                    (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3510                     isa<BackendJobAction>(JA));
3511  const char *SplitDWARFOut;
3512  if (SplitDWARF) {
3513    CmdArgs.push_back("-split-dwarf-file");
3514    SplitDWARFOut = SplitDebugName(Args, Input);
3515    CmdArgs.push_back(SplitDWARFOut);
3516  }
3517
3518  // Pass the linker version in use.
3519  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3520    CmdArgs.push_back("-target-linker-version");
3521    CmdArgs.push_back(A->getValue());
3522  }
3523
3524  if (!shouldUseLeafFramePointer(Args, RawTriple))
3525    CmdArgs.push_back("-momit-leaf-frame-pointer");
3526
3527  // Explicitly error on some things we know we don't support and can't just
3528  // ignore.
3529  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3530    Arg *Unsupported;
3531    if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
3532        getToolChain().getArch() == llvm::Triple::x86) {
3533      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3534          (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3535        D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3536            << Unsupported->getOption().getName();
3537    }
3538    // The faltivec option has been superseded by the maltivec option.
3539    if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3540      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3541          << Unsupported->getOption().getName()
3542          << "please use -maltivec and include altivec.h explicitly";
3543    if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3544      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3545          << Unsupported->getOption().getName() << "please use -mno-altivec";
3546  }
3547
3548  Args.AddAllArgs(CmdArgs, options::OPT_v);
3549  Args.AddLastArg(CmdArgs, options::OPT_H);
3550  if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3551    CmdArgs.push_back("-header-include-file");
3552    CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3553                                               : "-");
3554  }
3555  Args.AddLastArg(CmdArgs, options::OPT_P);
3556  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3557
3558  if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3559    CmdArgs.push_back("-diagnostic-log-file");
3560    CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3561                                                 : "-");
3562  }
3563
3564  bool UseSeparateSections = isUseSeparateSections(Triple);
3565
3566  if (Args.hasFlag(options::OPT_ffunction_sections,
3567                   options::OPT_fno_function_sections, UseSeparateSections)) {
3568    CmdArgs.push_back("-ffunction-sections");
3569  }
3570
3571  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3572                   UseSeparateSections)) {
3573    CmdArgs.push_back("-fdata-sections");
3574  }
3575
3576  if (!Args.hasFlag(options::OPT_funique_section_names,
3577                    options::OPT_fno_unique_section_names, true))
3578    CmdArgs.push_back("-fno-unique-section-names");
3579
3580  if (auto *A = Args.getLastArg(
3581      options::OPT_finstrument_functions,
3582      options::OPT_finstrument_functions_after_inlining,
3583      options::OPT_finstrument_function_entry_bare))
3584    A->render(Args, CmdArgs);
3585
3586  addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
3587
3588  if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3589    ABICompatArg->render(Args, CmdArgs);
3590
3591  // Add runtime flag for PS4 when PGO or Coverage are enabled.
3592  if (RawTriple.isPS4CPU())
3593    PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
3594
3595  // Pass options for controlling the default header search paths.
3596  if (Args.hasArg(options::OPT_nostdinc)) {
3597    CmdArgs.push_back("-nostdsysteminc");
3598    CmdArgs.push_back("-nobuiltininc");
3599  } else {
3600    if (Args.hasArg(options::OPT_nostdlibinc))
3601      CmdArgs.push_back("-nostdsysteminc");
3602    Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3603    Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3604  }
3605
3606  // Pass the path to compiler resource files.
3607  CmdArgs.push_back("-resource-dir");
3608  CmdArgs.push_back(D.ResourceDir.c_str());
3609
3610  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3611
3612  RenderARCMigrateToolOptions(D, Args, CmdArgs);
3613
3614  // Add preprocessing options like -I, -D, etc. if we are using the
3615  // preprocessor.
3616  //
3617  // FIXME: Support -fpreprocessed
3618  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3619    AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3620
3621  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3622  // that "The compiler can only warn and ignore the option if not recognized".
3623  // When building with ccache, it will pass -D options to clang even on
3624  // preprocessed inputs and configure concludes that -fPIC is not supported.
3625  Args.ClaimAllArgs(options::OPT_D);
3626
3627  // Manually translate -O4 to -O3; let clang reject others.
3628  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3629    if (A->getOption().matches(options::OPT_O4)) {
3630      CmdArgs.push_back("-O3");
3631      D.Diag(diag::warn_O4_is_O3);
3632    } else {
3633      A->render(Args, CmdArgs);
3634    }
3635  }
3636
3637  // Warn about ignored options to clang.
3638  for (const Arg *A :
3639       Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3640    D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3641    A->claim();
3642  }
3643
3644  for (const Arg *A :
3645       Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3646    D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3647    A->claim();
3648  }
3649
3650  claimNoWarnArgs(Args);
3651
3652  Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3653
3654  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3655  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3656    CmdArgs.push_back("-pedantic");
3657  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3658  Args.AddLastArg(CmdArgs, options::OPT_w);
3659
3660  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3661  // (-ansi is equivalent to -std=c89 or -std=c++98).
3662  //
3663  // If a std is supplied, only add -trigraphs if it follows the
3664  // option.
3665  bool ImplyVCPPCXXVer = false;
3666  if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3667    if (Std->getOption().matches(options::OPT_ansi))
3668      if (types::isCXX(InputType))
3669        CmdArgs.push_back("-std=c++98");
3670      else
3671        CmdArgs.push_back("-std=c89");
3672    else
3673      Std->render(Args, CmdArgs);
3674
3675    // If -f(no-)trigraphs appears after the language standard flag, honor it.
3676    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3677                                 options::OPT_ftrigraphs,
3678                                 options::OPT_fno_trigraphs))
3679      if (A != Std)
3680        A->render(Args, CmdArgs);
3681  } else {
3682    // Honor -std-default.
3683    //
3684    // FIXME: Clang doesn't correctly handle -std= when the input language
3685    // doesn't match. For the time being just ignore this for C++ inputs;
3686    // eventually we want to do all the standard defaulting here instead of
3687    // splitting it between the driver and clang -cc1.
3688    if (!types::isCXX(InputType))
3689      Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3690                                /*Joined=*/true);
3691    else if (IsWindowsMSVC)
3692      ImplyVCPPCXXVer = true;
3693
3694    Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3695                    options::OPT_fno_trigraphs);
3696  }
3697
3698  // GCC's behavior for -Wwrite-strings is a bit strange:
3699  //  * In C, this "warning flag" changes the types of string literals from
3700  //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3701  //    for the discarded qualifier.
3702  //  * In C++, this is just a normal warning flag.
3703  //
3704  // Implementing this warning correctly in C is hard, so we follow GCC's
3705  // behavior for now. FIXME: Directly diagnose uses of a string literal as
3706  // a non-const char* in C, rather than using this crude hack.
3707  if (!types::isCXX(InputType)) {
3708    // FIXME: This should behave just like a warning flag, and thus should also
3709    // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3710    Arg *WriteStrings =
3711        Args.getLastArg(options::OPT_Wwrite_strings,
3712                        options::OPT_Wno_write_strings, options::OPT_w);
3713    if (WriteStrings &&
3714        WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3715      CmdArgs.push_back("-fconst-strings");
3716  }
3717
3718  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3719  // during C++ compilation, which it is by default. GCC keeps this define even
3720  // in the presence of '-w', match this behavior bug-for-bug.
3721  if (types::isCXX(InputType) &&
3722      Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3723                   true)) {
3724    CmdArgs.push_back("-fdeprecated-macro");
3725  }
3726
3727  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3728  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3729    if (Asm->getOption().matches(options::OPT_fasm))
3730      CmdArgs.push_back("-fgnu-keywords");
3731    else
3732      CmdArgs.push_back("-fno-gnu-keywords");
3733  }
3734
3735  if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3736    CmdArgs.push_back("-fno-dwarf-directory-asm");
3737
3738  if (ShouldDisableAutolink(Args, getToolChain()))
3739    CmdArgs.push_back("-fno-autolink");
3740
3741  // Add in -fdebug-compilation-dir if necessary.
3742  addDebugCompDirArg(Args, CmdArgs);
3743
3744  for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3745    StringRef Map = A->getValue();
3746    if (Map.find('=') == StringRef::npos)
3747      D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3748    else
3749      CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3750    A->claim();
3751  }
3752
3753  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3754                               options::OPT_ftemplate_depth_EQ)) {
3755    CmdArgs.push_back("-ftemplate-depth");
3756    CmdArgs.push_back(A->getValue());
3757  }
3758
3759  if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3760    CmdArgs.push_back("-foperator-arrow-depth");
3761    CmdArgs.push_back(A->getValue());
3762  }
3763
3764  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3765    CmdArgs.push_back("-fconstexpr-depth");
3766    CmdArgs.push_back(A->getValue());
3767  }
3768
3769  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3770    CmdArgs.push_back("-fconstexpr-steps");
3771    CmdArgs.push_back(A->getValue());
3772  }
3773
3774  if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3775    CmdArgs.push_back("-fbracket-depth");
3776    CmdArgs.push_back(A->getValue());
3777  }
3778
3779  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3780                               options::OPT_Wlarge_by_value_copy_def)) {
3781    if (A->getNumValues()) {
3782      StringRef bytes = A->getValue();
3783      CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3784    } else
3785      CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3786  }
3787
3788  if (Args.hasArg(options::OPT_relocatable_pch))
3789    CmdArgs.push_back("-relocatable-pch");
3790
3791  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3792    CmdArgs.push_back("-fconstant-string-class");
3793    CmdArgs.push_back(A->getValue());
3794  }
3795
3796  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3797    CmdArgs.push_back("-ftabstop");
3798    CmdArgs.push_back(A->getValue());
3799  }
3800
3801  CmdArgs.push_back("-ferror-limit");
3802  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3803    CmdArgs.push_back(A->getValue());
3804  else
3805    CmdArgs.push_back("19");
3806
3807  if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3808    CmdArgs.push_back("-fmacro-backtrace-limit");
3809    CmdArgs.push_back(A->getValue());
3810  }
3811
3812  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3813    CmdArgs.push_back("-ftemplate-backtrace-limit");
3814    CmdArgs.push_back(A->getValue());
3815  }
3816
3817  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3818    CmdArgs.push_back("-fconstexpr-backtrace-limit");
3819    CmdArgs.push_back(A->getValue());
3820  }
3821
3822  if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3823    CmdArgs.push_back("-fspell-checking-limit");
3824    CmdArgs.push_back(A->getValue());
3825  }
3826
3827  // Pass -fmessage-length=.
3828  CmdArgs.push_back("-fmessage-length");
3829  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3830    CmdArgs.push_back(A->getValue());
3831  } else {
3832    // If -fmessage-length=N was not specified, determine whether this is a
3833    // terminal and, if so, implicitly define -fmessage-length appropriately.
3834    unsigned N = llvm::sys::Process::StandardErrColumns();
3835    CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3836  }
3837
3838  // -fvisibility= and -fvisibility-ms-compat are of a piece.
3839  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3840                                     options::OPT_fvisibility_ms_compat)) {
3841    if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3842      CmdArgs.push_back("-fvisibility");
3843      CmdArgs.push_back(A->getValue());
3844    } else {
3845      assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3846      CmdArgs.push_back("-fvisibility");
3847      CmdArgs.push_back("hidden");
3848      CmdArgs.push_back("-ftype-visibility");
3849      CmdArgs.push_back("default");
3850    }
3851  }
3852
3853  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3854
3855  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3856
3857  // Forward -f (flag) options which we can pass directly.
3858  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3859  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3860  Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3861  // Emulated TLS is enabled by default on Android and OpenBSD, and can be enabled
3862  // manually with -femulated-tls.
3863  bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isOSOpenBSD() ||
3864                            Triple.isWindowsCygwinEnvironment();
3865  if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
3866                   EmulatedTLSDefault))
3867    CmdArgs.push_back("-femulated-tls");
3868  // AltiVec-like language extensions aren't relevant for assembling.
3869  if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
3870    Args.AddLastArg(CmdArgs, options::OPT_fzvector);
3871
3872  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3873  Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3874
3875  // Forward flags for OpenMP. We don't do this if the current action is an
3876  // device offloading action other than OpenMP.
3877  if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3878                   options::OPT_fno_openmp, false) &&
3879      (JA.isDeviceOffloading(Action::OFK_None) ||
3880       JA.isDeviceOffloading(Action::OFK_OpenMP))) {
3881    switch (D.getOpenMPRuntime(Args)) {
3882    case Driver::OMPRT_OMP:
3883    case Driver::OMPRT_IOMP5:
3884      // Clang can generate useful OpenMP code for these two runtime libraries.
3885      CmdArgs.push_back("-fopenmp");
3886
3887      // If no option regarding the use of TLS in OpenMP codegeneration is
3888      // given, decide a default based on the target. Otherwise rely on the
3889      // options and pass the right information to the frontend.
3890      if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3891                        options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3892        CmdArgs.push_back("-fnoopenmp-use-tls");
3893      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
3894      break;
3895    default:
3896      // By default, if Clang doesn't know how to generate useful OpenMP code
3897      // for a specific runtime library, we just don't pass the '-fopenmp' flag
3898      // down to the actual compilation.
3899      // FIXME: It would be better to have a mode which *only* omits IR
3900      // generation based on the OpenMP support so that we get consistent
3901      // semantic analysis, etc.
3902      break;
3903    }
3904  } else {
3905    Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
3906                    options::OPT_fno_openmp_simd);
3907    Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
3908  }
3909
3910  const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3911  Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3912
3913  const XRayArgs &XRay = getToolChain().getXRayArgs();
3914  XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
3915
3916  if (getToolChain().SupportsProfiling())
3917    Args.AddLastArg(CmdArgs, options::OPT_pg);
3918
3919  if (getToolChain().SupportsProfiling())
3920    Args.AddLastArg(CmdArgs, options::OPT_mfentry);
3921
3922  // -flax-vector-conversions is default.
3923  if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3924                    options::OPT_fno_lax_vector_conversions))
3925    CmdArgs.push_back("-fno-lax-vector-conversions");
3926
3927  if (Args.getLastArg(options::OPT_fapple_kext) ||
3928      (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
3929    CmdArgs.push_back("-fapple-kext");
3930
3931  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3932  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3933  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3934  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3935  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3936
3937  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3938    CmdArgs.push_back("-ftrapv-handler");
3939    CmdArgs.push_back(A->getValue());
3940  }
3941
3942  Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3943
3944  // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3945  // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3946  if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3947    if (A->getOption().matches(options::OPT_fwrapv))
3948      CmdArgs.push_back("-fwrapv");
3949  } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3950                                      options::OPT_fno_strict_overflow)) {
3951    if (A->getOption().matches(options::OPT_fno_strict_overflow))
3952      CmdArgs.push_back("-fwrapv");
3953  }
3954
3955  if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3956                               options::OPT_fno_reroll_loops))
3957    if (A->getOption().matches(options::OPT_freroll_loops))
3958      CmdArgs.push_back("-freroll-loops");
3959
3960  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3961  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3962                  options::OPT_fno_unroll_loops);
3963
3964  Args.AddLastArg(CmdArgs, options::OPT_pthread);
3965
3966  RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
3967
3968  // Translate -mstackrealign
3969  if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3970                   false))
3971    CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3972
3973  if (Args.hasArg(options::OPT_mstack_alignment)) {
3974    StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3975    CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3976  }
3977
3978  if (Args.hasArg(options::OPT_mstack_probe_size)) {
3979    StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
3980
3981    if (!Size.empty())
3982      CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
3983    else
3984      CmdArgs.push_back("-mstack-probe-size=0");
3985  }
3986
3987  if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3988                               options::OPT_mno_restrict_it)) {
3989    if (A->getOption().matches(options::OPT_mrestrict_it)) {
3990      CmdArgs.push_back("-backend-option");
3991      CmdArgs.push_back("-arm-restrict-it");
3992    } else {
3993      CmdArgs.push_back("-backend-option");
3994      CmdArgs.push_back("-arm-no-restrict-it");
3995    }
3996  } else if (Triple.isOSWindows() &&
3997             (Triple.getArch() == llvm::Triple::arm ||
3998              Triple.getArch() == llvm::Triple::thumb)) {
3999    // Windows on ARM expects restricted IT blocks
4000    CmdArgs.push_back("-backend-option");
4001    CmdArgs.push_back("-arm-restrict-it");
4002  }
4003
4004  // Forward -cl options to -cc1
4005  RenderOpenCLOptions(Args, CmdArgs);
4006
4007  // Forward -f options with positive and negative forms; we translate
4008  // these by hand.
4009  if (Arg *A = getLastProfileSampleUseArg(Args)) {
4010    StringRef fname = A->getValue();
4011    if (!llvm::sys::fs::exists(fname))
4012      D.Diag(diag::err_drv_no_such_file) << fname;
4013    else
4014      A->render(Args, CmdArgs);
4015  }
4016
4017  RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
4018
4019  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4020                    options::OPT_fno_assume_sane_operator_new))
4021    CmdArgs.push_back("-fno-assume-sane-operator-new");
4022
4023  // -fblocks=0 is default.
4024  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4025                   getToolChain().IsBlocksDefault()) ||
4026      (Args.hasArg(options::OPT_fgnu_runtime) &&
4027       Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4028       !Args.hasArg(options::OPT_fno_blocks))) {
4029    CmdArgs.push_back("-fblocks");
4030
4031    if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4032        !getToolChain().hasBlocksRuntime())
4033      CmdArgs.push_back("-fblocks-runtime-optional");
4034  }
4035
4036  // -fencode-extended-block-signature=1 is default.
4037  if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4038    CmdArgs.push_back("-fencode-extended-block-signature");
4039
4040  if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4041                   false) &&
4042      types::isCXX(InputType)) {
4043    CmdArgs.push_back("-fcoroutines-ts");
4044  }
4045
4046  Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4047                  options::OPT_fno_double_square_bracket_attributes);
4048
4049  bool HaveModules = false;
4050  RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4051
4052  // -faccess-control is default.
4053  if (Args.hasFlag(options::OPT_fno_access_control,
4054                   options::OPT_faccess_control, false))
4055    CmdArgs.push_back("-fno-access-control");
4056
4057  // -felide-constructors is the default.
4058  if (Args.hasFlag(options::OPT_fno_elide_constructors,
4059                   options::OPT_felide_constructors, false))
4060    CmdArgs.push_back("-fno-elide-constructors");
4061
4062  ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4063
4064  if (KernelOrKext || (types::isCXX(InputType) &&
4065                       (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4066                        RTTIMode == ToolChain::RM_DisabledImplicitly)))
4067    CmdArgs.push_back("-fno-rtti");
4068
4069  // -fshort-enums=0 is default for all architectures except Hexagon.
4070  if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4071                   getToolChain().getArch() == llvm::Triple::hexagon))
4072    CmdArgs.push_back("-fshort-enums");
4073
4074  RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
4075
4076  // -fuse-cxa-atexit is default.
4077  if (!Args.hasFlag(
4078          options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4079          !RawTriple.isOSWindows() &&
4080              RawTriple.getOS() != llvm::Triple::Solaris &&
4081              getToolChain().getArch() != llvm::Triple::hexagon &&
4082              getToolChain().getArch() != llvm::Triple::xcore &&
4083              ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4084               RawTriple.hasEnvironment())) ||
4085      KernelOrKext)
4086    CmdArgs.push_back("-fno-use-cxa-atexit");
4087
4088  // -fms-extensions=0 is default.
4089  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4090                   IsWindowsMSVC))
4091    CmdArgs.push_back("-fms-extensions");
4092
4093  // -fno-use-line-directives is default.
4094  if (Args.hasFlag(options::OPT_fuse_line_directives,
4095                   options::OPT_fno_use_line_directives, false))
4096    CmdArgs.push_back("-fuse-line-directives");
4097
4098  // -fms-compatibility=0 is default.
4099  if (Args.hasFlag(options::OPT_fms_compatibility,
4100                   options::OPT_fno_ms_compatibility,
4101                   (IsWindowsMSVC &&
4102                    Args.hasFlag(options::OPT_fms_extensions,
4103                                 options::OPT_fno_ms_extensions, true))))
4104    CmdArgs.push_back("-fms-compatibility");
4105
4106  VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
4107  if (!MSVT.empty())
4108    CmdArgs.push_back(
4109        Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4110
4111  bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4112  if (ImplyVCPPCXXVer) {
4113    StringRef LanguageStandard;
4114    if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4115      LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4116                             .Case("c++14", "-std=c++14")
4117                             .Case("c++17", "-std=c++17")
4118                             .Case("c++latest", "-std=c++2a")
4119                             .Default("");
4120      if (LanguageStandard.empty())
4121        D.Diag(clang::diag::warn_drv_unused_argument)
4122            << StdArg->getAsString(Args);
4123    }
4124
4125    if (LanguageStandard.empty()) {
4126      if (IsMSVC2015Compatible)
4127        LanguageStandard = "-std=c++14";
4128      else
4129        LanguageStandard = "-std=c++11";
4130    }
4131
4132    CmdArgs.push_back(LanguageStandard.data());
4133  }
4134
4135  // -fno-borland-extensions is default.
4136  if (Args.hasFlag(options::OPT_fborland_extensions,
4137                   options::OPT_fno_borland_extensions, false))
4138    CmdArgs.push_back("-fborland-extensions");
4139
4140  // -fno-declspec is default, except for PS4.
4141  if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4142                   RawTriple.isPS4()))
4143    CmdArgs.push_back("-fdeclspec");
4144  else if (Args.hasArg(options::OPT_fno_declspec))
4145    CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4146
4147  // -fthreadsafe-static is default, except for MSVC compatibility versions less
4148  // than 19.
4149  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4150                    options::OPT_fno_threadsafe_statics,
4151                    !IsWindowsMSVC || IsMSVC2015Compatible))
4152    CmdArgs.push_back("-fno-threadsafe-statics");
4153
4154  // -fno-delayed-template-parsing is default, except when targetting MSVC.
4155  // Many old Windows SDK versions require this to parse.
4156  // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4157  // compiler. We should be able to disable this by default at some point.
4158  if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4159                   options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4160    CmdArgs.push_back("-fdelayed-template-parsing");
4161
4162  // -fgnu-keywords default varies depending on language; only pass if
4163  // specified.
4164  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4165                               options::OPT_fno_gnu_keywords))
4166    A->render(Args, CmdArgs);
4167
4168  if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4169                   false))
4170    CmdArgs.push_back("-fgnu89-inline");
4171
4172  if (Args.hasArg(options::OPT_fno_inline))
4173    CmdArgs.push_back("-fno-inline");
4174
4175  if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4176                                       options::OPT_finline_hint_functions,
4177                                       options::OPT_fno_inline_functions))
4178    InlineArg->render(Args, CmdArgs);
4179
4180  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4181                  options::OPT_fno_experimental_new_pass_manager);
4182
4183  ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4184  RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4185                    rewriteKind != RK_None, Input, CmdArgs);
4186
4187  if (Args.hasFlag(options::OPT_fapplication_extension,
4188                   options::OPT_fno_application_extension, false))
4189    CmdArgs.push_back("-fapplication-extension");
4190
4191  // Handle GCC-style exception args.
4192  if (!C.getDriver().IsCLMode())
4193    addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
4194                     CmdArgs);
4195
4196  // Handle exception personalities
4197  Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4198                           options::OPT_fseh_exceptions,
4199                           options::OPT_fdwarf_exceptions);
4200  if (A) {
4201    const Option &Opt = A->getOption();
4202    if (Opt.matches(options::OPT_fsjlj_exceptions))
4203      CmdArgs.push_back("-fsjlj-exceptions");
4204    if (Opt.matches(options::OPT_fseh_exceptions))
4205      CmdArgs.push_back("-fseh-exceptions");
4206    if (Opt.matches(options::OPT_fdwarf_exceptions))
4207      CmdArgs.push_back("-fdwarf-exceptions");
4208  } else {
4209    switch (getToolChain().GetExceptionModel(Args)) {
4210    default:
4211      break;
4212    case llvm::ExceptionHandling::DwarfCFI:
4213      CmdArgs.push_back("-fdwarf-exceptions");
4214      break;
4215    case llvm::ExceptionHandling::SjLj:
4216      CmdArgs.push_back("-fsjlj-exceptions");
4217      break;
4218    case llvm::ExceptionHandling::WinEH:
4219      CmdArgs.push_back("-fseh-exceptions");
4220      break;
4221    }
4222  }
4223
4224  // C++ "sane" operator new.
4225  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4226                    options::OPT_fno_assume_sane_operator_new))
4227    CmdArgs.push_back("-fno-assume-sane-operator-new");
4228
4229  // -frelaxed-template-template-args is off by default, as it is a severe
4230  // breaking change until a corresponding change to template partial ordering
4231  // is provided.
4232  if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4233                   options::OPT_fno_relaxed_template_template_args, false))
4234    CmdArgs.push_back("-frelaxed-template-template-args");
4235
4236  // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4237  // most platforms.
4238  if (Args.hasFlag(options::OPT_fsized_deallocation,
4239                   options::OPT_fno_sized_deallocation, false))
4240    CmdArgs.push_back("-fsized-deallocation");
4241
4242  // -faligned-allocation is on by default in C++17 onwards and otherwise off
4243  // by default.
4244  if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4245                               options::OPT_fno_aligned_allocation,
4246                               options::OPT_faligned_new_EQ)) {
4247    if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4248      CmdArgs.push_back("-fno-aligned-allocation");
4249    else
4250      CmdArgs.push_back("-faligned-allocation");
4251  }
4252
4253  // The default new alignment can be specified using a dedicated option or via
4254  // a GCC-compatible option that also turns on aligned allocation.
4255  if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4256                               options::OPT_faligned_new_EQ))
4257    CmdArgs.push_back(
4258        Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4259
4260  // -fconstant-cfstrings is default, and may be subject to argument translation
4261  // on Darwin.
4262  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4263                    options::OPT_fno_constant_cfstrings) ||
4264      !Args.hasFlag(options::OPT_mconstant_cfstrings,
4265                    options::OPT_mno_constant_cfstrings))
4266    CmdArgs.push_back("-fno-constant-cfstrings");
4267
4268  // -fno-pascal-strings is default, only pass non-default.
4269  if (Args.hasFlag(options::OPT_fpascal_strings,
4270                   options::OPT_fno_pascal_strings, false))
4271    CmdArgs.push_back("-fpascal-strings");
4272
4273  // Honor -fpack-struct= and -fpack-struct, if given. Note that
4274  // -fno-pack-struct doesn't apply to -fpack-struct=.
4275  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4276    std::string PackStructStr = "-fpack-struct=";
4277    PackStructStr += A->getValue();
4278    CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4279  } else if (Args.hasFlag(options::OPT_fpack_struct,
4280                          options::OPT_fno_pack_struct, false)) {
4281    CmdArgs.push_back("-fpack-struct=1");
4282  }
4283
4284  // Handle -fmax-type-align=N and -fno-type-align
4285  bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4286  if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4287    if (!SkipMaxTypeAlign) {
4288      std::string MaxTypeAlignStr = "-fmax-type-align=";
4289      MaxTypeAlignStr += A->getValue();
4290      CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4291    }
4292  } else if (RawTriple.isOSDarwin()) {
4293    if (!SkipMaxTypeAlign) {
4294      std::string MaxTypeAlignStr = "-fmax-type-align=16";
4295      CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4296    }
4297  }
4298
4299  // -fcommon is the default unless compiling kernel code or the target says so
4300  bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
4301  if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4302                    !NoCommonDefault))
4303    CmdArgs.push_back("-fno-common");
4304
4305  // -fsigned-bitfields is default, and clang doesn't yet support
4306  // -funsigned-bitfields.
4307  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4308                    options::OPT_funsigned_bitfields))
4309    D.Diag(diag::warn_drv_clang_unsupported)
4310        << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4311
4312  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4313  if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4314    D.Diag(diag::err_drv_clang_unsupported)
4315        << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4316
4317  // -finput_charset=UTF-8 is default. Reject others
4318  if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4319    StringRef value = inputCharset->getValue();
4320    if (!value.equals_lower("utf-8"))
4321      D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4322                                          << value;
4323  }
4324
4325  // -fexec_charset=UTF-8 is default. Reject others
4326  if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4327    StringRef value = execCharset->getValue();
4328    if (!value.equals_lower("utf-8"))
4329      D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4330                                          << value;
4331  }
4332
4333  RenderDiagnosticsOptions(D, Args, CmdArgs);
4334
4335  // -fno-asm-blocks is default.
4336  if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4337                   false))
4338    CmdArgs.push_back("-fasm-blocks");
4339
4340  // -fgnu-inline-asm is default.
4341  if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4342                    options::OPT_fno_gnu_inline_asm, true))
4343    CmdArgs.push_back("-fno-gnu-inline-asm");
4344
4345  // Enable vectorization per default according to the optimization level
4346  // selected. For optimization levels that want vectorization we use the alias
4347  // option to simplify the hasFlag logic.
4348  bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4349  OptSpecifier VectorizeAliasOption =
4350      EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4351  if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4352                   options::OPT_fno_vectorize, EnableVec))
4353    CmdArgs.push_back("-vectorize-loops");
4354
4355  // -fslp-vectorize is enabled based on the optimization level selected.
4356  bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4357  OptSpecifier SLPVectAliasOption =
4358      EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4359  if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4360                   options::OPT_fno_slp_vectorize, EnableSLPVec))
4361    CmdArgs.push_back("-vectorize-slp");
4362
4363  ParseMPreferVectorWidth(D, Args, CmdArgs);
4364
4365  if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4366    A->render(Args, CmdArgs);
4367
4368  if (Arg *A = Args.getLastArg(
4369          options::OPT_fsanitize_undefined_strip_path_components_EQ))
4370    A->render(Args, CmdArgs);
4371
4372  // -fdollars-in-identifiers default varies depending on platform and
4373  // language; only pass if specified.
4374  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4375                               options::OPT_fno_dollars_in_identifiers)) {
4376    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4377      CmdArgs.push_back("-fdollars-in-identifiers");
4378    else
4379      CmdArgs.push_back("-fno-dollars-in-identifiers");
4380  }
4381
4382  // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4383  // practical purposes.
4384  if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4385                               options::OPT_fno_unit_at_a_time)) {
4386    if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4387      D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4388  }
4389
4390  if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4391                   options::OPT_fno_apple_pragma_pack, false))
4392    CmdArgs.push_back("-fapple-pragma-pack");
4393
4394  if (Args.hasFlag(options::OPT_fsave_optimization_record,
4395                   options::OPT_foptimization_record_file_EQ,
4396                   options::OPT_fno_save_optimization_record, false)) {
4397    CmdArgs.push_back("-opt-record-file");
4398
4399    const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4400    if (A) {
4401      CmdArgs.push_back(A->getValue());
4402    } else {
4403      SmallString<128> F;
4404
4405      if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4406        if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4407          F = FinalOutput->getValue();
4408      }
4409
4410      if (F.empty()) {
4411        // Use the input filename.
4412        F = llvm::sys::path::stem(Input.getBaseInput());
4413
4414        // If we're compiling for an offload architecture (i.e. a CUDA device),
4415        // we need to make the file name for the device compilation different
4416        // from the host compilation.
4417        if (!JA.isDeviceOffloading(Action::OFK_None) &&
4418            !JA.isDeviceOffloading(Action::OFK_Host)) {
4419          llvm::sys::path::replace_extension(F, "");
4420          F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4421                                                   Triple.normalize());
4422          F += "-";
4423          F += JA.getOffloadingArch();
4424        }
4425      }
4426
4427      llvm::sys::path::replace_extension(F, "opt.yaml");
4428      CmdArgs.push_back(Args.MakeArgString(F));
4429    }
4430  }
4431
4432  bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4433                                     options::OPT_fno_rewrite_imports, false);
4434  if (RewriteImports)
4435    CmdArgs.push_back("-frewrite-imports");
4436
4437  // Enable rewrite includes if the user's asked for it or if we're generating
4438  // diagnostics.
4439  // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4440  // nice to enable this when doing a crashdump for modules as well.
4441  if (Args.hasFlag(options::OPT_frewrite_includes,
4442                   options::OPT_fno_rewrite_includes, false) ||
4443      (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
4444    CmdArgs.push_back("-frewrite-includes");
4445
4446  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4447  if (Arg *A = Args.getLastArg(options::OPT_traditional,
4448                               options::OPT_traditional_cpp)) {
4449    if (isa<PreprocessJobAction>(JA))
4450      CmdArgs.push_back("-traditional-cpp");
4451    else
4452      D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4453  }
4454
4455  Args.AddLastArg(CmdArgs, options::OPT_dM);
4456  Args.AddLastArg(CmdArgs, options::OPT_dD);
4457
4458  // Handle serialized diagnostics.
4459  if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4460    CmdArgs.push_back("-serialize-diagnostic-file");
4461    CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4462  }
4463
4464  if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4465    CmdArgs.push_back("-fretain-comments-from-system-headers");
4466
4467  // Forward -fcomment-block-commands to -cc1.
4468  Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4469  // Forward -fparse-all-comments to -cc1.
4470  Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4471
4472  // Turn -fplugin=name.so into -load name.so
4473  for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4474    CmdArgs.push_back("-load");
4475    CmdArgs.push_back(A->getValue());
4476    A->claim();
4477  }
4478
4479  // Setup statistics file output.
4480  if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
4481    StringRef SaveStats = A->getValue();
4482
4483    SmallString<128> StatsFile;
4484    bool DoSaveStats = false;
4485    if (SaveStats == "obj") {
4486      if (Output.isFilename()) {
4487        StatsFile.assign(Output.getFilename());
4488        llvm::sys::path::remove_filename(StatsFile);
4489      }
4490      DoSaveStats = true;
4491    } else if (SaveStats == "cwd") {
4492      DoSaveStats = true;
4493    } else {
4494      D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
4495    }
4496
4497    if (DoSaveStats) {
4498      StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
4499      llvm::sys::path::append(StatsFile, BaseName);
4500      llvm::sys::path::replace_extension(StatsFile, "stats");
4501      CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
4502                                           StatsFile));
4503    }
4504  }
4505
4506  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4507  // parser.
4508  // -finclude-default-header flag is for preprocessor,
4509  // do not pass it to other cc1 commands when save-temps is enabled
4510  if (C.getDriver().isSaveTempsEnabled() &&
4511      !isa<PreprocessJobAction>(JA)) {
4512    for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4513      Arg->claim();
4514      if (StringRef(Arg->getValue()) != "-finclude-default-header")
4515        CmdArgs.push_back(Arg->getValue());
4516    }
4517  }
4518  else {
4519    Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4520  }
4521  for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4522    A->claim();
4523
4524    // We translate this by hand to the -cc1 argument, since nightly test uses
4525    // it and developers have been trained to spell it with -mllvm. Both
4526    // spellings are now deprecated and should be removed.
4527    if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4528      CmdArgs.push_back("-disable-llvm-optzns");
4529    } else {
4530      A->render(Args, CmdArgs);
4531    }
4532  }
4533
4534  // With -save-temps, we want to save the unoptimized bitcode output from the
4535  // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4536  // by the frontend.
4537  // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4538  // has slightly different breakdown between stages.
4539  // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4540  // pristine IR generated by the frontend. Ideally, a new compile action should
4541  // be added so both IR can be captured.
4542  if (C.getDriver().isSaveTempsEnabled() &&
4543      !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4544      isa<CompileJobAction>(JA))
4545    CmdArgs.push_back("-disable-llvm-passes");
4546
4547  if (Output.getType() == types::TY_Dependencies) {
4548    // Handled with other dependency code.
4549  } else if (Output.isFilename()) {
4550    CmdArgs.push_back("-o");
4551    CmdArgs.push_back(Output.getFilename());
4552  } else {
4553    assert(Output.isNothing() && "Invalid output.");
4554  }
4555
4556  addDashXForInput(Args, Input, CmdArgs);
4557
4558  if (Input.isFilename())
4559    CmdArgs.push_back(Input.getFilename());
4560  else
4561    Input.getInputArg().renderAsInput(Args, CmdArgs);
4562
4563  Args.AddAllArgs(CmdArgs, options::OPT_undef);
4564
4565  const char *Exec = D.getClangProgramPath();
4566
4567  // Optionally embed the -cc1 level arguments into the debug info, for build
4568  // analysis.
4569  // Also record command line arguments into the debug info if
4570  // -grecord-gcc-switches options is set on.
4571  // By default, -gno-record-gcc-switches is set on and no recording.
4572  if (getToolChain().UseDwarfDebugFlags() ||
4573      Args.hasFlag(options::OPT_grecord_gcc_switches,
4574                   options::OPT_gno_record_gcc_switches, false)) {
4575    ArgStringList OriginalArgs;
4576    for (const auto &Arg : Args)
4577      Arg->render(Args, OriginalArgs);
4578
4579    SmallString<256> Flags;
4580    Flags += Exec;
4581    for (const char *OriginalArg : OriginalArgs) {
4582      SmallString<128> EscapedArg;
4583      EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4584      Flags += " ";
4585      Flags += EscapedArg;
4586    }
4587    CmdArgs.push_back("-dwarf-debug-flags");
4588    CmdArgs.push_back(Args.MakeArgString(Flags));
4589  }
4590
4591  // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4592  // Include them with -fcuda-include-gpubinary.
4593  if (IsCuda && Inputs.size() > 1)
4594    for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
4595      CmdArgs.push_back("-fcuda-include-gpubinary");
4596      CmdArgs.push_back(I->getFilename());
4597    }
4598
4599  // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4600  // to specify the result of the compile phase on the host, so the meaningful
4601  // device declarations can be identified. Also, -fopenmp-is-device is passed
4602  // along to tell the frontend that it is generating code for a device, so that
4603  // only the relevant declarations are emitted.
4604  if (IsOpenMPDevice) {
4605    CmdArgs.push_back("-fopenmp-is-device");
4606    if (Inputs.size() == 2) {
4607      CmdArgs.push_back("-fopenmp-host-ir-file-path");
4608      CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4609    }
4610  }
4611
4612  // For all the host OpenMP offloading compile jobs we need to pass the targets
4613  // information using -fopenmp-targets= option.
4614  if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4615    SmallString<128> TargetInfo("-fopenmp-targets=");
4616
4617    Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4618    assert(Tgts && Tgts->getNumValues() &&
4619           "OpenMP offloading has to have targets specified.");
4620    for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4621      if (i)
4622        TargetInfo += ',';
4623      // We need to get the string from the triple because it may be not exactly
4624      // the same as the one we get directly from the arguments.
4625      llvm::Triple T(Tgts->getValue(i));
4626      TargetInfo += T.getTriple();
4627    }
4628    CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4629  }
4630
4631  bool WholeProgramVTables =
4632      Args.hasFlag(options::OPT_fwhole_program_vtables,
4633                   options::OPT_fno_whole_program_vtables, false);
4634  if (WholeProgramVTables) {
4635    if (!D.isUsingLTO())
4636      D.Diag(diag::err_drv_argument_only_allowed_with)
4637          << "-fwhole-program-vtables"
4638          << "-flto";
4639    CmdArgs.push_back("-fwhole-program-vtables");
4640  }
4641
4642  if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4643                               options::OPT_fno_experimental_isel)) {
4644    CmdArgs.push_back("-mllvm");
4645    if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4646      CmdArgs.push_back("-global-isel=1");
4647
4648      // GISel is on by default on AArch64 -O0, so don't bother adding
4649      // the fallback remarks for it. Other combinations will add a warning of
4650      // some kind.
4651      bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4652      bool IsOptLevelSupported = false;
4653
4654      Arg *A = Args.getLastArg(options::OPT_O_Group);
4655      if (Triple.getArch() == llvm::Triple::aarch64) {
4656        if (!A || A->getOption().matches(options::OPT_O0))
4657          IsOptLevelSupported = true;
4658      }
4659      if (!IsArchSupported || !IsOptLevelSupported) {
4660        CmdArgs.push_back("-mllvm");
4661        CmdArgs.push_back("-global-isel-abort=2");
4662
4663        if (!IsArchSupported)
4664          D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4665        else
4666          D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4667      }
4668    } else {
4669      CmdArgs.push_back("-global-isel=0");
4670    }
4671  }
4672
4673  // Finally add the compile command to the compilation.
4674  if (Args.hasArg(options::OPT__SLASH_fallback) &&
4675      Output.getType() == types::TY_Object &&
4676      (InputType == types::TY_C || InputType == types::TY_CXX)) {
4677    auto CLCommand =
4678        getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4679    C.addCommand(llvm::make_unique<FallbackCommand>(
4680        JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4681  } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4682             isa<PrecompileJobAction>(JA)) {
4683    // In /fallback builds, run the main compilation even if the pch generation
4684    // fails, so that the main compilation's fallback to cl.exe runs.
4685    C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4686                                                        CmdArgs, Inputs));
4687  } else {
4688    C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4689  }
4690
4691  // Handle the debug info splitting at object creation time if we're
4692  // creating an object.
4693  // TODO: Currently only works on linux with newer objcopy.
4694  if (SplitDWARF && Output.getType() == types::TY_Object)
4695    SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDWARFOut);
4696
4697  if (Arg *A = Args.getLastArg(options::OPT_pg))
4698    if (Args.hasArg(options::OPT_fomit_frame_pointer))
4699      D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4700                                                      << A->getAsString(Args);
4701
4702  // Claim some arguments which clang supports automatically.
4703
4704  // -fpch-preprocess is used with gcc to add a special marker in the output to
4705  // include the PCH file. Clang's PTH solution is completely transparent, so we
4706  // do not need to deal with it at all.
4707  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4708
4709  // Claim some arguments which clang doesn't support, but we don't
4710  // care to warn the user about.
4711  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4712  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4713
4714  // Disable warnings for clang -E -emit-llvm foo.c
4715  Args.ClaimAllArgs(options::OPT_emit_llvm);
4716}
4717
4718Clang::Clang(const ToolChain &TC)
4719    // CAUTION! The first constructor argument ("clang") is not arbitrary,
4720    // as it is for other tools. Some operations on a Tool actually test
4721    // whether that tool is Clang based on the Tool's Name as a string.
4722    : Tool("clang", "clang frontend", TC, RF_Full) {}
4723
4724Clang::~Clang() {}
4725
4726/// Add options related to the Objective-C runtime/ABI.
4727///
4728/// Returns true if the runtime is non-fragile.
4729ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4730                                      ArgStringList &cmdArgs,
4731                                      RewriteKind rewriteKind) const {
4732  // Look for the controlling runtime option.
4733  Arg *runtimeArg =
4734      args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4735                      options::OPT_fobjc_runtime_EQ);
4736
4737  // Just forward -fobjc-runtime= to the frontend.  This supercedes
4738  // options about fragility.
4739  if (runtimeArg &&
4740      runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4741    ObjCRuntime runtime;
4742    StringRef value = runtimeArg->getValue();
4743    if (runtime.tryParse(value)) {
4744      getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4745          << value;
4746    }
4747
4748    runtimeArg->render(args, cmdArgs);
4749    return runtime;
4750  }
4751
4752  // Otherwise, we'll need the ABI "version".  Version numbers are
4753  // slightly confusing for historical reasons:
4754  //   1 - Traditional "fragile" ABI
4755  //   2 - Non-fragile ABI, version 1
4756  //   3 - Non-fragile ABI, version 2
4757  unsigned objcABIVersion = 1;
4758  // If -fobjc-abi-version= is present, use that to set the version.
4759  if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4760    StringRef value = abiArg->getValue();
4761    if (value == "1")
4762      objcABIVersion = 1;
4763    else if (value == "2")
4764      objcABIVersion = 2;
4765    else if (value == "3")
4766      objcABIVersion = 3;
4767    else
4768      getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4769  } else {
4770    // Otherwise, determine if we are using the non-fragile ABI.
4771    bool nonFragileABIIsDefault =
4772        (rewriteKind == RK_NonFragile ||
4773         (rewriteKind == RK_None &&
4774          getToolChain().IsObjCNonFragileABIDefault()));
4775    if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4776                     options::OPT_fno_objc_nonfragile_abi,
4777                     nonFragileABIIsDefault)) {
4778// Determine the non-fragile ABI version to use.
4779#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4780      unsigned nonFragileABIVersion = 1;
4781#else
4782      unsigned nonFragileABIVersion = 2;
4783#endif
4784
4785      if (Arg *abiArg =
4786              args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4787        StringRef value = abiArg->getValue();
4788        if (value == "1")
4789          nonFragileABIVersion = 1;
4790        else if (value == "2")
4791          nonFragileABIVersion = 2;
4792        else
4793          getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4794              << value;
4795      }
4796
4797      objcABIVersion = 1 + nonFragileABIVersion;
4798    } else {
4799      objcABIVersion = 1;
4800    }
4801  }
4802
4803  // We don't actually care about the ABI version other than whether
4804  // it's non-fragile.
4805  bool isNonFragile = objcABIVersion != 1;
4806
4807  // If we have no runtime argument, ask the toolchain for its default runtime.
4808  // However, the rewriter only really supports the Mac runtime, so assume that.
4809  ObjCRuntime runtime;
4810  if (!runtimeArg) {
4811    switch (rewriteKind) {
4812    case RK_None:
4813      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4814      break;
4815    case RK_Fragile:
4816      runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4817      break;
4818    case RK_NonFragile:
4819      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4820      break;
4821    }
4822
4823    // -fnext-runtime
4824  } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4825    // On Darwin, make this use the default behavior for the toolchain.
4826    if (getToolChain().getTriple().isOSDarwin()) {
4827      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4828
4829      // Otherwise, build for a generic macosx port.
4830    } else {
4831      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4832    }
4833
4834    // -fgnu-runtime
4835  } else {
4836    assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4837    // Legacy behaviour is to target the gnustep runtime if we are in
4838    // non-fragile mode or the GCC runtime in fragile mode.
4839    if (isNonFragile)
4840      runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4841    else
4842      runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4843  }
4844
4845  cmdArgs.push_back(
4846      args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4847  return runtime;
4848}
4849
4850static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4851  bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4852  I += HaveDash;
4853  return !HaveDash;
4854}
4855
4856namespace {
4857struct EHFlags {
4858  bool Synch = false;
4859  bool Asynch = false;
4860  bool NoUnwindC = false;
4861};
4862} // end anonymous namespace
4863
4864/// /EH controls whether to run destructor cleanups when exceptions are
4865/// thrown.  There are three modifiers:
4866/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4867/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4868///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4869/// - c: Assume that extern "C" functions are implicitly nounwind.
4870/// The default is /EHs-c-, meaning cleanups are disabled.
4871static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4872  EHFlags EH;
4873
4874  std::vector<std::string> EHArgs =
4875      Args.getAllArgValues(options::OPT__SLASH_EH);
4876  for (auto EHVal : EHArgs) {
4877    for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4878      switch (EHVal[I]) {
4879      case 'a':
4880        EH.Asynch = maybeConsumeDash(EHVal, I);
4881        if (EH.Asynch)
4882          EH.Synch = false;
4883        continue;
4884      case 'c':
4885        EH.NoUnwindC = maybeConsumeDash(EHVal, I);
4886        continue;
4887      case 's':
4888        EH.Synch = maybeConsumeDash(EHVal, I);
4889        if (EH.Synch)
4890          EH.Asynch = false;
4891        continue;
4892      default:
4893        break;
4894      }
4895      D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4896      break;
4897    }
4898  }
4899  // The /GX, /GX- flags are only processed if there are not /EH flags.
4900  // The default is that /GX is not specified.
4901  if (EHArgs.empty() &&
4902      Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
4903                   /*default=*/false)) {
4904    EH.Synch = true;
4905    EH.NoUnwindC = true;
4906  }
4907
4908  return EH;
4909}
4910
4911void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
4912                           ArgStringList &CmdArgs,
4913                           codegenoptions::DebugInfoKind *DebugInfoKind,
4914                           bool *EmitCodeView) const {
4915  unsigned RTOptionID = options::OPT__SLASH_MT;
4916
4917  if (Args.hasArg(options::OPT__SLASH_LDd))
4918    // The /LDd option implies /MTd. The dependent lib part can be overridden,
4919    // but defining _DEBUG is sticky.
4920    RTOptionID = options::OPT__SLASH_MTd;
4921
4922  if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4923    RTOptionID = A->getOption().getID();
4924
4925  StringRef FlagForCRT;
4926  switch (RTOptionID) {
4927  case options::OPT__SLASH_MD:
4928    if (Args.hasArg(options::OPT__SLASH_LDd))
4929      CmdArgs.push_back("-D_DEBUG");
4930    CmdArgs.push_back("-D_MT");
4931    CmdArgs.push_back("-D_DLL");
4932    FlagForCRT = "--dependent-lib=msvcrt";
4933    break;
4934  case options::OPT__SLASH_MDd:
4935    CmdArgs.push_back("-D_DEBUG");
4936    CmdArgs.push_back("-D_MT");
4937    CmdArgs.push_back("-D_DLL");
4938    FlagForCRT = "--dependent-lib=msvcrtd";
4939    break;
4940  case options::OPT__SLASH_MT:
4941    if (Args.hasArg(options::OPT__SLASH_LDd))
4942      CmdArgs.push_back("-D_DEBUG");
4943    CmdArgs.push_back("-D_MT");
4944    CmdArgs.push_back("-flto-visibility-public-std");
4945    FlagForCRT = "--dependent-lib=libcmt";
4946    break;
4947  case options::OPT__SLASH_MTd:
4948    CmdArgs.push_back("-D_DEBUG");
4949    CmdArgs.push_back("-D_MT");
4950    CmdArgs.push_back("-flto-visibility-public-std");
4951    FlagForCRT = "--dependent-lib=libcmtd";
4952    break;
4953  default:
4954    llvm_unreachable("Unexpected option ID.");
4955  }
4956
4957  if (Args.hasArg(options::OPT__SLASH_Zl)) {
4958    CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4959  } else {
4960    CmdArgs.push_back(FlagForCRT.data());
4961
4962    // This provides POSIX compatibility (maps 'open' to '_open'), which most
4963    // users want.  The /Za flag to cl.exe turns this off, but it's not
4964    // implemented in clang.
4965    CmdArgs.push_back("--dependent-lib=oldnames");
4966  }
4967
4968  // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4969  // would produce interleaved output, so ignore /showIncludes in such cases.
4970  if ((!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP)) ||
4971      (Args.hasArg(options::OPT__SLASH_P) &&
4972       Args.hasArg(options::OPT__SLASH_EP) && !Args.hasArg(options::OPT_E)))
4973    if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4974      A->render(Args, CmdArgs);
4975
4976  // This controls whether or not we emit RTTI data for polymorphic types.
4977  if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4978                   /*default=*/false))
4979    CmdArgs.push_back("-fno-rtti-data");
4980
4981  // This controls whether or not we emit stack-protector instrumentation.
4982  // In MSVC, Buffer Security Check (/GS) is on by default.
4983  if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
4984                   /*default=*/true)) {
4985    CmdArgs.push_back("-stack-protector");
4986    CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
4987  }
4988
4989  // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
4990  if (Arg *DebugInfoArg =
4991          Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
4992                          options::OPT_gline_tables_only)) {
4993    *EmitCodeView = true;
4994    if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
4995      *DebugInfoKind = codegenoptions::LimitedDebugInfo;
4996    else
4997      *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4998    CmdArgs.push_back("-gcodeview");
4999  } else {
5000    *EmitCodeView = false;
5001  }
5002
5003  const Driver &D = getToolChain().getDriver();
5004  EHFlags EH = parseClangCLEHFlags(D, Args);
5005  if (EH.Synch || EH.Asynch) {
5006    if (types::isCXX(InputType))
5007      CmdArgs.push_back("-fcxx-exceptions");
5008    CmdArgs.push_back("-fexceptions");
5009  }
5010  if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5011    CmdArgs.push_back("-fexternc-nounwind");
5012
5013  // /EP should expand to -E -P.
5014  if (Args.hasArg(options::OPT__SLASH_EP)) {
5015    CmdArgs.push_back("-E");
5016    CmdArgs.push_back("-P");
5017  }
5018
5019  unsigned VolatileOptionID;
5020  if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5021      getToolChain().getArch() == llvm::Triple::x86)
5022    VolatileOptionID = options::OPT__SLASH_volatile_ms;
5023  else
5024    VolatileOptionID = options::OPT__SLASH_volatile_iso;
5025
5026  if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5027    VolatileOptionID = A->getOption().getID();
5028
5029  if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5030    CmdArgs.push_back("-fms-volatile");
5031
5032  Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5033  Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5034  if (MostGeneralArg && BestCaseArg)
5035    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5036        << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5037
5038  if (MostGeneralArg) {
5039    Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5040    Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5041    Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5042
5043    Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5044    Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5045    if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5046      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5047          << FirstConflict->getAsString(Args)
5048          << SecondConflict->getAsString(Args);
5049
5050    if (SingleArg)
5051      CmdArgs.push_back("-fms-memptr-rep=single");
5052    else if (MultipleArg)
5053      CmdArgs.push_back("-fms-memptr-rep=multiple");
5054    else
5055      CmdArgs.push_back("-fms-memptr-rep=virtual");
5056  }
5057
5058  // Parse the default calling convention options.
5059  if (Arg *CCArg =
5060          Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
5061                          options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5062                          options::OPT__SLASH_Gregcall)) {
5063    unsigned DCCOptId = CCArg->getOption().getID();
5064    const char *DCCFlag = nullptr;
5065    bool ArchSupported = true;
5066    llvm::Triple::ArchType Arch = getToolChain().getArch();
5067    switch (DCCOptId) {
5068    case options::OPT__SLASH_Gd:
5069      DCCFlag = "-fdefault-calling-conv=cdecl";
5070      break;
5071    case options::OPT__SLASH_Gr:
5072      ArchSupported = Arch == llvm::Triple::x86;
5073      DCCFlag = "-fdefault-calling-conv=fastcall";
5074      break;
5075    case options::OPT__SLASH_Gz:
5076      ArchSupported = Arch == llvm::Triple::x86;
5077      DCCFlag = "-fdefault-calling-conv=stdcall";
5078      break;
5079    case options::OPT__SLASH_Gv:
5080      ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5081      DCCFlag = "-fdefault-calling-conv=vectorcall";
5082      break;
5083    case options::OPT__SLASH_Gregcall:
5084      ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5085      DCCFlag = "-fdefault-calling-conv=regcall";
5086      break;
5087    }
5088
5089    // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5090    if (ArchSupported && DCCFlag)
5091      CmdArgs.push_back(DCCFlag);
5092  }
5093
5094  if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5095    A->render(Args, CmdArgs);
5096
5097  if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5098    CmdArgs.push_back("-fdiagnostics-format");
5099    if (Args.hasArg(options::OPT__SLASH_fallback))
5100      CmdArgs.push_back("msvc-fallback");
5101    else
5102      CmdArgs.push_back("msvc");
5103  }
5104}
5105
5106visualstudio::Compiler *Clang::getCLFallback() const {
5107  if (!CLFallback)
5108    CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5109  return CLFallback.get();
5110}
5111
5112
5113const char *Clang::getBaseInputName(const ArgList &Args,
5114                                    const InputInfo &Input) {
5115  return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5116}
5117
5118const char *Clang::getBaseInputStem(const ArgList &Args,
5119                                    const InputInfoList &Inputs) {
5120  const char *Str = getBaseInputName(Args, Inputs[0]);
5121
5122  if (const char *End = strrchr(Str, '.'))
5123    return Args.MakeArgString(std::string(Str, End));
5124
5125  return Str;
5126}
5127
5128const char *Clang::getDependencyFileName(const ArgList &Args,
5129                                         const InputInfoList &Inputs) {
5130  // FIXME: Think about this more.
5131  std::string Res;
5132
5133  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5134    std::string Str(OutputOpt->getValue());
5135    Res = Str.substr(0, Str.rfind('.'));
5136  } else {
5137    Res = getBaseInputStem(Args, Inputs);
5138  }
5139  return Args.MakeArgString(Res + ".d");
5140}
5141
5142// Begin ClangAs
5143
5144void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5145                                ArgStringList &CmdArgs) const {
5146  StringRef CPUName;
5147  StringRef ABIName;
5148  const llvm::Triple &Triple = getToolChain().getTriple();
5149  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5150
5151  CmdArgs.push_back("-target-abi");
5152  CmdArgs.push_back(ABIName.data());
5153}
5154
5155void ClangAs::AddX86TargetArgs(const ArgList &Args,
5156                               ArgStringList &CmdArgs) const {
5157  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5158    StringRef Value = A->getValue();
5159    if (Value == "intel" || Value == "att") {
5160      CmdArgs.push_back("-mllvm");
5161      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5162    } else {
5163      getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5164          << A->getOption().getName() << Value;
5165    }
5166  }
5167}
5168
5169void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5170                           const InputInfo &Output, const InputInfoList &Inputs,
5171                           const ArgList &Args,
5172                           const char *LinkingOutput) const {
5173  ArgStringList CmdArgs;
5174
5175  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5176  const InputInfo &Input = Inputs[0];
5177
5178  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5179  const std::string &TripleStr = Triple.getTriple();
5180  const auto &D = getToolChain().getDriver();
5181
5182  // Don't warn about "clang -w -c foo.s"
5183  Args.ClaimAllArgs(options::OPT_w);
5184  // and "clang -emit-llvm -c foo.s"
5185  Args.ClaimAllArgs(options::OPT_emit_llvm);
5186
5187  claimNoWarnArgs(Args);
5188
5189  // Invoke ourselves in -cc1as mode.
5190  //
5191  // FIXME: Implement custom jobs for internal actions.
5192  CmdArgs.push_back("-cc1as");
5193
5194  // Add the "effective" target triple.
5195  CmdArgs.push_back("-triple");
5196  CmdArgs.push_back(Args.MakeArgString(TripleStr));
5197
5198  // Set the output mode, we currently only expect to be used as a real
5199  // assembler.
5200  CmdArgs.push_back("-filetype");
5201  CmdArgs.push_back("obj");
5202
5203  // Set the main file name, so that debug info works even with
5204  // -save-temps or preprocessed assembly.
5205  CmdArgs.push_back("-main-file-name");
5206  CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5207
5208  // Add the target cpu
5209  std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5210  if (!CPU.empty()) {
5211    CmdArgs.push_back("-target-cpu");
5212    CmdArgs.push_back(Args.MakeArgString(CPU));
5213  }
5214
5215  // Add the target features
5216  getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5217
5218  // Ignore explicit -force_cpusubtype_ALL option.
5219  (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5220
5221  // Pass along any -I options so we get proper .include search paths.
5222  Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5223
5224  // Determine the original source input.
5225  const Action *SourceAction = &JA;
5226  while (SourceAction->getKind() != Action::InputClass) {
5227    assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5228    SourceAction = SourceAction->getInputs()[0];
5229  }
5230
5231  // Forward -g and handle debug info related flags, assuming we are dealing
5232  // with an actual assembly file.
5233  bool WantDebug = false;
5234  unsigned DwarfVersion = 0;
5235  Args.ClaimAllArgs(options::OPT_g_Group);
5236  if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5237    WantDebug = !A->getOption().matches(options::OPT_g0) &&
5238                !A->getOption().matches(options::OPT_ggdb0);
5239    if (WantDebug)
5240      DwarfVersion = DwarfVersionNum(A->getSpelling());
5241  }
5242  if (DwarfVersion == 0)
5243    DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5244
5245  codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5246
5247  if (SourceAction->getType() == types::TY_Asm ||
5248      SourceAction->getType() == types::TY_PP_Asm) {
5249    // You might think that it would be ok to set DebugInfoKind outside of
5250    // the guard for source type, however there is a test which asserts
5251    // that some assembler invocation receives no -debug-info-kind,
5252    // and it's not clear whether that test is just overly restrictive.
5253    DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5254                               : codegenoptions::NoDebugInfo);
5255    // Add the -fdebug-compilation-dir flag if needed.
5256    addDebugCompDirArg(Args, CmdArgs);
5257
5258    // Set the AT_producer to the clang version when using the integrated
5259    // assembler on assembly source files.
5260    CmdArgs.push_back("-dwarf-debug-producer");
5261    CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5262
5263    // And pass along -I options
5264    Args.AddAllArgs(CmdArgs, options::OPT_I);
5265  }
5266  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5267                          llvm::DebuggerKind::Default);
5268  RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5269
5270
5271  // Handle -fPIC et al -- the relocation-model affects the assembler
5272  // for some targets.
5273  llvm::Reloc::Model RelocationModel;
5274  unsigned PICLevel;
5275  bool IsPIE;
5276  std::tie(RelocationModel, PICLevel, IsPIE) =
5277      ParsePICArgs(getToolChain(), Args);
5278
5279  const char *RMName = RelocationModelName(RelocationModel);
5280  if (RMName) {
5281    CmdArgs.push_back("-mrelocation-model");
5282    CmdArgs.push_back(RMName);
5283  }
5284
5285  // Optionally embed the -cc1as level arguments into the debug info, for build
5286  // analysis.
5287  if (getToolChain().UseDwarfDebugFlags()) {
5288    ArgStringList OriginalArgs;
5289    for (const auto &Arg : Args)
5290      Arg->render(Args, OriginalArgs);
5291
5292    SmallString<256> Flags;
5293    const char *Exec = getToolChain().getDriver().getClangProgramPath();
5294    Flags += Exec;
5295    for (const char *OriginalArg : OriginalArgs) {
5296      SmallString<128> EscapedArg;
5297      EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5298      Flags += " ";
5299      Flags += EscapedArg;
5300    }
5301    CmdArgs.push_back("-dwarf-debug-flags");
5302    CmdArgs.push_back(Args.MakeArgString(Flags));
5303  }
5304
5305  // FIXME: Add -static support, once we have it.
5306
5307  // Add target specific flags.
5308  switch (getToolChain().getArch()) {
5309  default:
5310    break;
5311
5312  case llvm::Triple::mips:
5313  case llvm::Triple::mipsel:
5314  case llvm::Triple::mips64:
5315  case llvm::Triple::mips64el:
5316    AddMIPSTargetArgs(Args, CmdArgs);
5317    break;
5318
5319  case llvm::Triple::x86:
5320  case llvm::Triple::x86_64:
5321    AddX86TargetArgs(Args, CmdArgs);
5322    break;
5323
5324  case llvm::Triple::arm:
5325  case llvm::Triple::armeb:
5326  case llvm::Triple::thumb:
5327  case llvm::Triple::thumbeb:
5328    // This isn't in AddARMTargetArgs because we want to do this for assembly
5329    // only, not C/C++.
5330    if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5331                     options::OPT_mno_default_build_attributes, true)) {
5332        CmdArgs.push_back("-mllvm");
5333        CmdArgs.push_back("-arm-add-build-attributes");
5334    }
5335    break;
5336  }
5337
5338  // Consume all the warning flags. Usually this would be handled more
5339  // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5340  // doesn't handle that so rather than warning about unused flags that are
5341  // actually used, we'll lie by omission instead.
5342  // FIXME: Stop lying and consume only the appropriate driver flags
5343  Args.ClaimAllArgs(options::OPT_W_Group);
5344
5345  CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5346                                    getToolChain().getDriver());
5347
5348  Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5349
5350  assert(Output.isFilename() && "Unexpected lipo output.");
5351  CmdArgs.push_back("-o");
5352  CmdArgs.push_back(Output.getFilename());
5353
5354  assert(Input.isFilename() && "Invalid input.");
5355  CmdArgs.push_back(Input.getFilename());
5356
5357  const char *Exec = getToolChain().getDriver().getClangProgramPath();
5358  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5359
5360  // Handle the debug info splitting at object creation time if we're
5361  // creating an object.
5362  // TODO: Currently only works on linux with newer objcopy.
5363  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5364      getToolChain().getTriple().isOSLinux())
5365    SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5366                   SplitDebugName(Args, Input));
5367}
5368
5369// Begin OffloadBundler
5370
5371void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5372                                  const InputInfo &Output,
5373                                  const InputInfoList &Inputs,
5374                                  const llvm::opt::ArgList &TCArgs,
5375                                  const char *LinkingOutput) const {
5376  // The version with only one output is expected to refer to a bundling job.
5377  assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5378
5379  // The bundling command looks like this:
5380  // clang-offload-bundler -type=bc
5381  //   -targets=host-triple,openmp-triple1,openmp-triple2
5382  //   -outputs=input_file
5383  //   -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5384
5385  ArgStringList CmdArgs;
5386
5387  // Get the type.
5388  CmdArgs.push_back(TCArgs.MakeArgString(
5389      Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5390
5391  assert(JA.getInputs().size() == Inputs.size() &&
5392         "Not have inputs for all dependence actions??");
5393
5394  // Get the targets.
5395  SmallString<128> Triples;
5396  Triples += "-targets=";
5397  for (unsigned I = 0; I < Inputs.size(); ++I) {
5398    if (I)
5399      Triples += ',';
5400
5401    // Find ToolChain for this input.
5402    Action::OffloadKind CurKind = Action::OFK_Host;
5403    const ToolChain *CurTC = &getToolChain();
5404    const Action *CurDep = JA.getInputs()[I];
5405
5406    if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
5407      CurTC = nullptr;
5408      OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
5409        assert(CurTC == nullptr && "Expected one dependence!");
5410        CurKind = A->getOffloadingDeviceKind();
5411        CurTC = TC;
5412      });
5413    }
5414    Triples += Action::GetOffloadKindName(CurKind);
5415    Triples += '-';
5416    Triples += CurTC->getTriple().normalize();
5417  }
5418  CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5419
5420  // Get bundled file command.
5421  CmdArgs.push_back(
5422      TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5423
5424  // Get unbundled files command.
5425  SmallString<128> UB;
5426  UB += "-inputs=";
5427  for (unsigned I = 0; I < Inputs.size(); ++I) {
5428    if (I)
5429      UB += ',';
5430
5431    // Find ToolChain for this input.
5432    const ToolChain *CurTC = &getToolChain();
5433    if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5434      CurTC = nullptr;
5435      OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5436        assert(CurTC == nullptr && "Expected one dependence!");
5437        CurTC = TC;
5438      });
5439    }
5440    UB += CurTC->getInputFilename(Inputs[I]);
5441  }
5442  CmdArgs.push_back(TCArgs.MakeArgString(UB));
5443
5444  // All the inputs are encoded as commands.
5445  C.addCommand(llvm::make_unique<Command>(
5446      JA, *this,
5447      TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5448      CmdArgs, None));
5449}
5450
5451void OffloadBundler::ConstructJobMultipleOutputs(
5452    Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5453    const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5454    const char *LinkingOutput) const {
5455  // The version with multiple outputs is expected to refer to a unbundling job.
5456  auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5457
5458  // The unbundling command looks like this:
5459  // clang-offload-bundler -type=bc
5460  //   -targets=host-triple,openmp-triple1,openmp-triple2
5461  //   -inputs=input_file
5462  //   -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5463  //   -unbundle
5464
5465  ArgStringList CmdArgs;
5466
5467  assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5468  InputInfo Input = Inputs.front();
5469
5470  // Get the type.
5471  CmdArgs.push_back(TCArgs.MakeArgString(
5472      Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5473
5474  // Get the targets.
5475  SmallString<128> Triples;
5476  Triples += "-targets=";
5477  auto DepInfo = UA.getDependentActionsInfo();
5478  for (unsigned I = 0; I < DepInfo.size(); ++I) {
5479    if (I)
5480      Triples += ',';
5481
5482    auto &Dep = DepInfo[I];
5483    Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5484    Triples += '-';
5485    Triples += Dep.DependentToolChain->getTriple().normalize();
5486  }
5487
5488  CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5489
5490  // Get bundled file command.
5491  CmdArgs.push_back(
5492      TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5493
5494  // Get unbundled files command.
5495  SmallString<128> UB;
5496  UB += "-outputs=";
5497  for (unsigned I = 0; I < Outputs.size(); ++I) {
5498    if (I)
5499      UB += ',';
5500    UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
5501  }
5502  CmdArgs.push_back(TCArgs.MakeArgString(UB));
5503  CmdArgs.push_back("-unbundle");
5504
5505  // All the inputs are encoded as commands.
5506  C.addCommand(llvm::make_unique<Command>(
5507      JA, *this,
5508      TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5509      CmdArgs, None));
5510}
5511