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