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