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