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