1 //===--- LLVM.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "Arch/AArch64.h"
13 #include "Arch/Mips.h"
15 #include "Arch/Sparc.h"
16 #include "Arch/SystemZ.h"
18 #include "CommonArgs.h"
20 #include "InputInfo.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"
41 #include <unistd.h> // For getuid().
44 using namespace clang::driver;
45 using namespace clang::driver::tools;
46 using namespace clang;
47 using namespace llvm::opt;
49 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
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");
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))
65 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
66 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
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) {
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) {
95 // Escape the preceding backslashes
96 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
99 // Escape the space/tab
112 Res.push_back(Target[i]);
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.
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);
125 // Apply Work on all the offloading tool chains associated with the current
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>());
133 // TODO: Add support for other offloading programming models here.
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;
159 char RefStepChar = RefStep[0];
160 if (RefStepChar < '0' || RefStepChar > '9') {
161 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
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=";
176 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
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"));
187 // Pass through "all", "none", or "default" with an optional refinement step.
188 if (NumOptions == 1) {
189 StringRef Val = A->getValue(0);
191 if (!getRefinementStep(Val, D, *A, RefStepLoc))
193 StringRef ValBase = Val.slice(0, RefStepLoc);
194 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
195 OutStrings.push_back(Args.MakeArgString(Out + Val));
200 // Each reciprocal type may be enabled or disabled individually.
201 // Check each input value for validity, concatenate them all back together,
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));
214 for (unsigned i = 0; i != NumOptions; ++i) {
215 StringRef Val = A->getValue(i);
217 bool IsDisabled = Val.startswith(DisabledPrefixIn);
218 // Ignore the disablement token for string matching.
223 if (!getRefinementStep(Val, D, *A, RefStep))
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;
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;
245 if (OptionIter->second == true) {
246 // Duplicate option specified.
247 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
251 // Mark the matched option as found. Do not allow duplicate specifiers.
252 OptionIter->second = true;
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;
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 + ",");
265 OutStrings.push_back(Args.MakeArgString(Out));
268 static void getHexagonTargetFeatures(const ArgList &Args,
269 std::vector<StringRef> &Features) {
270 handleTargetFeaturesGroup(Args, Features,
271 options::OPT_m_hexagon_Features_Group);
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))
280 Features.push_back(UseLongCalls ? "+long-calls" : "-long-calls");
283 static void getWebAssemblyTargetFeatures(const ArgList &Args,
284 std::vector<StringRef> &Features) {
285 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
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");
297 D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
301 handleTargetFeaturesGroup(
302 Args, Features, options::OPT_m_amdgpu_Features_Group);
305 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
306 const ArgList &Args, ArgStringList &CmdArgs,
308 const Driver &D = TC.getDriver();
309 std::vector<StringRef> Features;
310 switch (Triple.getArch()) {
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);
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);
327 case llvm::Triple::ppc:
328 case llvm::Triple::ppc64:
329 case llvm::Triple::ppc64le:
330 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
332 case llvm::Triple::systemz:
333 systemz::getSystemZTargetFeatures(Args, Features);
335 case llvm::Triple::aarch64:
336 case llvm::Triple::aarch64_be:
337 aarch64::getAArch64TargetFeatures(D, Args, Features);
339 case llvm::Triple::x86:
340 case llvm::Triple::x86_64:
341 x86::getX86TargetFeatures(D, Triple, Args, Features);
343 case llvm::Triple::hexagon:
344 getHexagonTargetFeatures(Args, Features);
346 case llvm::Triple::wasm32:
347 case llvm::Triple::wasm64:
348 getWebAssemblyTargetFeatures(Args, Features);
350 case llvm::Triple::sparc:
351 case llvm::Triple::sparcel:
352 case llvm::Triple::sparcv9:
353 sparc::getSparcTargetFeatures(D, Args, Features);
355 case llvm::Triple::r600:
356 case llvm::Triple::amdgcn:
357 getAMDGPUTargetFeatures(D, Args, Features);
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;
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;
378 CmdArgs.push_back("-target-feature");
379 CmdArgs.push_back(Name.data());
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
389 if (runtime.isNonFragile())
392 if (!Triple.isMacOSX())
395 return (!Triple.isMacOSXVersionLT(10, 5) &&
396 (Triple.getArch() == llvm::Triple::x86_64 ||
397 Triple.getArch() == llvm::Triple::arm));
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();
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);
423 // See if the user explicitly enabled exceptions.
424 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
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");
434 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
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);
445 CXXExceptionsEnabled =
446 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
447 ExceptionArg->getOption().matches(options::OPT_fexceptions);
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 "
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);
463 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
465 CmdArgs.push_back("-fcxx-exceptions");
472 CmdArgs.push_back("-fexceptions");
475 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
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();
482 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
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;
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;
508 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
509 switch (Triple.getArch()){
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();
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.
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);
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
563 // All other supported Windows ISAs use xdata unwind information, so frame
564 // pointers are not generally useful.
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);
579 if (Args.hasArg(options::OPT_pg))
582 return useFramePointerForTargetByDefault(Args, Triple);
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);
591 if (Args.hasArg(options::OPT_pg))
594 if (Triple.isPS4CPU())
597 return useFramePointerForTargetByDefault(Args, Triple);
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));
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))
617 if (A->getOption().matches(options::OPT_O0))
620 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
623 StringRef S(A->getValue());
627 // Don't vectorize -Oz, unless it's the slp vectorizer.
631 unsigned OptLevel = 0;
632 if (S.getAsInteger(10, OptLevel))
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)
649 CmdArgs.push_back("-x");
650 if (Args.hasArg(options::OPT_rewrite_objc))
651 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
653 CmdArgs.push_back(types::getTypeName(Input.getType()));
656 static void appendUserToPath(SmallVectorImpl<char> &Result) {
658 const char *Username = getenv("LOGNAME");
660 const char *Username = getenv("USERNAME");
663 // Validate that LoginName can be used in a path, and get its length.
665 for (const char *P = Username; *P; ++P, ++Len) {
666 if (!clang::isAlphanumeric(*P) && *P != '_') {
672 if (Username && Len > 0) {
673 Result.append(Username, Username + Len);
678 // Fallback to user id.
680 std::string UID = llvm::utostr(getuid());
682 // FIXME: Windows seems to have an 'SID' that might work.
683 std::string UID = "9999";
685 Result.append(UID.begin(), UID.end());
688 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
689 const InputInfo &Output, const ArgList &Args,
690 ArgStringList &CmdArgs) {
692 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
693 options::OPT_fprofile_generate_EQ,
694 options::OPT_fno_profile_generate);
695 if (PGOGenerateArg &&
696 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
697 PGOGenerateArg = nullptr;
699 auto *ProfileGenerateArg = Args.getLastArg(
700 options::OPT_fprofile_instr_generate,
701 options::OPT_fprofile_instr_generate_EQ,
702 options::OPT_fno_profile_instr_generate);
703 if (ProfileGenerateArg &&
704 ProfileGenerateArg->getOption().matches(
705 options::OPT_fno_profile_instr_generate))
706 ProfileGenerateArg = nullptr;
708 if (PGOGenerateArg && ProfileGenerateArg)
709 D.Diag(diag::err_drv_argument_not_allowed_with)
710 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
712 auto *ProfileUseArg = getLastProfileUseArg(Args);
714 if (PGOGenerateArg && ProfileUseArg)
715 D.Diag(diag::err_drv_argument_not_allowed_with)
716 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
718 if (ProfileGenerateArg && ProfileUseArg)
719 D.Diag(diag::err_drv_argument_not_allowed_with)
720 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
722 if (ProfileGenerateArg) {
723 if (ProfileGenerateArg->getOption().matches(
724 options::OPT_fprofile_instr_generate_EQ))
725 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
726 ProfileGenerateArg->getValue()));
727 // The default is to use Clang Instrumentation.
728 CmdArgs.push_back("-fprofile-instrument=clang");
731 if (PGOGenerateArg) {
732 CmdArgs.push_back("-fprofile-instrument=llvm");
733 if (PGOGenerateArg->getOption().matches(
734 options::OPT_fprofile_generate_EQ)) {
735 SmallString<128> Path(PGOGenerateArg->getValue());
736 llvm::sys::path::append(Path, "default_%m.profraw");
738 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
743 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
744 CmdArgs.push_back(Args.MakeArgString(
745 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
746 else if ((ProfileUseArg->getOption().matches(
747 options::OPT_fprofile_use_EQ) ||
748 ProfileUseArg->getOption().matches(
749 options::OPT_fprofile_instr_use))) {
750 SmallString<128> Path(
751 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
752 if (Path.empty() || llvm::sys::fs::is_directory(Path))
753 llvm::sys::path::append(Path, "default.profdata");
755 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
759 if (Args.hasArg(options::OPT_ftest_coverage) ||
760 Args.hasArg(options::OPT_coverage))
761 CmdArgs.push_back("-femit-coverage-notes");
762 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
764 Args.hasArg(options::OPT_coverage))
765 CmdArgs.push_back("-femit-coverage-data");
767 if (Args.hasFlag(options::OPT_fcoverage_mapping,
768 options::OPT_fno_coverage_mapping, false) &&
770 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
771 << "-fcoverage-mapping"
772 << "-fprofile-instr-generate";
774 if (Args.hasFlag(options::OPT_fcoverage_mapping,
775 options::OPT_fno_coverage_mapping, false))
776 CmdArgs.push_back("-fcoverage-mapping");
778 if (C.getArgs().hasArg(options::OPT_c) ||
779 C.getArgs().hasArg(options::OPT_S)) {
780 if (Output.isFilename()) {
781 CmdArgs.push_back("-coverage-notes-file");
782 SmallString<128> OutputFilename;
783 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
784 OutputFilename = FinalOutput->getValue();
786 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
787 SmallString<128> CoverageFilename = OutputFilename;
788 if (llvm::sys::path::is_relative(CoverageFilename)) {
789 SmallString<128> Pwd;
790 if (!llvm::sys::fs::current_path(Pwd)) {
791 llvm::sys::path::append(Pwd, CoverageFilename);
792 CoverageFilename.swap(Pwd);
795 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
796 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
798 // Leave -fprofile-dir= an unused argument unless .gcda emission is
799 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
800 // the flag used. There is no -fno-profile-dir, so the user has no
801 // targeted way to suppress the warning.
802 if (Args.hasArg(options::OPT_fprofile_arcs) ||
803 Args.hasArg(options::OPT_coverage)) {
804 CmdArgs.push_back("-coverage-data-file");
805 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
806 CoverageFilename = FProfileDir->getValue();
807 llvm::sys::path::append(CoverageFilename, OutputFilename);
809 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
810 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
816 /// \brief Check whether the given input tree contains any compilation actions.
817 static bool ContainsCompileAction(const Action *A) {
818 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
821 for (const auto &AI : A->inputs())
822 if (ContainsCompileAction(AI))
828 /// \brief Check if -relax-all should be passed to the internal assembler.
829 /// This is done by default when compiling non-assembler source with -O0.
830 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
831 bool RelaxDefault = true;
833 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
834 RelaxDefault = A->getOption().matches(options::OPT_O0);
837 RelaxDefault = false;
838 for (const auto &Act : C.getActions()) {
839 if (ContainsCompileAction(Act)) {
846 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
850 // Extract the integer N from a string spelled "-dwarf-N", returning 0
851 // on mismatch. The StringRef input (rather than an Arg) allows
852 // for use by the "-Xassembler" option parser.
853 static unsigned DwarfVersionNum(StringRef ArgValue) {
854 return llvm::StringSwitch<unsigned>(ArgValue)
855 .Case("-gdwarf-2", 2)
856 .Case("-gdwarf-3", 3)
857 .Case("-gdwarf-4", 4)
858 .Case("-gdwarf-5", 5)
862 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
863 codegenoptions::DebugInfoKind DebugInfoKind,
864 unsigned DwarfVersion,
865 llvm::DebuggerKind DebuggerTuning) {
866 switch (DebugInfoKind) {
867 case codegenoptions::DebugLineTablesOnly:
868 CmdArgs.push_back("-debug-info-kind=line-tables-only");
870 case codegenoptions::LimitedDebugInfo:
871 CmdArgs.push_back("-debug-info-kind=limited");
873 case codegenoptions::FullDebugInfo:
874 CmdArgs.push_back("-debug-info-kind=standalone");
879 if (DwarfVersion > 0)
881 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
882 switch (DebuggerTuning) {
883 case llvm::DebuggerKind::GDB:
884 CmdArgs.push_back("-debugger-tuning=gdb");
886 case llvm::DebuggerKind::LLDB:
887 CmdArgs.push_back("-debugger-tuning=lldb");
889 case llvm::DebuggerKind::SCE:
890 CmdArgs.push_back("-debugger-tuning=sce");
897 static const char *RelocationModelName(llvm::Reloc::Model Model) {
899 case llvm::Reloc::Static:
901 case llvm::Reloc::PIC_:
903 case llvm::Reloc::DynamicNoPIC:
904 return "dynamic-no-pic";
905 case llvm::Reloc::ROPI:
907 case llvm::Reloc::RWPI:
909 case llvm::Reloc::ROPI_RWPI:
912 llvm_unreachable("Unknown Reloc::Model kind");
915 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
916 const Driver &D, const ArgList &Args,
917 ArgStringList &CmdArgs,
918 const InputInfo &Output,
919 const InputInfoList &Inputs) const {
921 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
923 CheckPreprocessingOptions(D, Args);
925 Args.AddLastArg(CmdArgs, options::OPT_C);
926 Args.AddLastArg(CmdArgs, options::OPT_CC);
928 // Handle dependency file generation.
929 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
930 (A = Args.getLastArg(options::OPT_MD)) ||
931 (A = Args.getLastArg(options::OPT_MMD))) {
932 // Determine the output location.
934 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
935 DepFile = MF->getValue();
936 C.addFailureResultFile(DepFile, &JA);
937 } else if (Output.getType() == types::TY_Dependencies) {
938 DepFile = Output.getFilename();
939 } else if (A->getOption().matches(options::OPT_M) ||
940 A->getOption().matches(options::OPT_MM)) {
943 DepFile = getDependencyFileName(Args, Inputs);
944 C.addFailureResultFile(DepFile, &JA);
946 CmdArgs.push_back("-dependency-file");
947 CmdArgs.push_back(DepFile);
949 // Add a default target if one wasn't specified.
950 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
951 const char *DepTarget;
953 // If user provided -o, that is the dependency target, except
954 // when we are only generating a dependency file.
955 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
956 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
957 DepTarget = OutputOpt->getValue();
959 // Otherwise derive from the base input.
961 // FIXME: This should use the computed output file location.
962 SmallString<128> P(Inputs[0].getBaseInput());
963 llvm::sys::path::replace_extension(P, "o");
964 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
967 CmdArgs.push_back("-MT");
968 SmallString<128> Quoted;
969 QuoteTarget(DepTarget, Quoted);
970 CmdArgs.push_back(Args.MakeArgString(Quoted));
973 if (A->getOption().matches(options::OPT_M) ||
974 A->getOption().matches(options::OPT_MD))
975 CmdArgs.push_back("-sys-header-deps");
976 if ((isa<PrecompileJobAction>(JA) &&
977 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
978 Args.hasArg(options::OPT_fmodule_file_deps))
979 CmdArgs.push_back("-module-file-deps");
982 if (Args.hasArg(options::OPT_MG)) {
983 if (!A || A->getOption().matches(options::OPT_MD) ||
984 A->getOption().matches(options::OPT_MMD))
985 D.Diag(diag::err_drv_mg_requires_m_or_mm);
986 CmdArgs.push_back("-MG");
989 Args.AddLastArg(CmdArgs, options::OPT_MP);
990 Args.AddLastArg(CmdArgs, options::OPT_MV);
992 // Convert all -MQ <target> args to -MT <quoted target>
993 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
996 if (A->getOption().matches(options::OPT_MQ)) {
997 CmdArgs.push_back("-MT");
998 SmallString<128> Quoted;
999 QuoteTarget(A->getValue(), Quoted);
1000 CmdArgs.push_back(Args.MakeArgString(Quoted));
1002 // -MT flag - no change
1004 A->render(Args, CmdArgs);
1008 // Add offload include arguments specific for CUDA. This must happen before
1009 // we -I or -include anything else, because we must pick up the CUDA headers
1010 // from the particular CUDA installation, rather than from e.g.
1011 // /usr/local/include.
1012 if (JA.isOffloading(Action::OFK_Cuda))
1013 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1015 // Add -i* options, and automatically translate to
1016 // -include-pch/-include-pth for transparent PCH support. It's
1017 // wonky, but we include looking for .gch so we can support seamless
1018 // replacement into a build system already set up to be generating
1020 int YcIndex = -1, YuIndex = -1;
1023 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1024 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1025 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1026 // Walk the whole i_Group and skip non "-include" flags so that the index
1027 // here matches the index in the next loop below.
1029 if (!A->getOption().matches(options::OPT_include))
1031 if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
1033 if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
1037 if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
1038 Driver::InputList Inputs;
1039 D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
1040 assert(Inputs.size() == 1 && "Need one input when building pch");
1041 CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
1042 Inputs[0].second->getValue()));
1045 bool RenderedImplicitInclude = false;
1047 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1050 if (getToolChain().getDriver().IsCLMode() &&
1051 A->getOption().matches(options::OPT_include)) {
1052 // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
1053 // include is compiled into foo.h, and everything after goes into
1054 // the .obj file. /Yufoo.h means that all includes prior to and including
1055 // foo.h are completely skipped and replaced with a use of the pch file
1056 // for foo.h. (Each flag can have at most one value, multiple /Yc flags
1057 // just mean that the last one wins.) If /Yc and /Yu are both present
1058 // and refer to the same file, /Yc wins.
1059 // Note that OPT__SLASH_FI gets mapped to OPT_include.
1060 // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
1061 // cl.exe seems to support both flags with different values, but that
1062 // seems strange (which flag does /Fp now refer to?), so don't implement
1063 // that until someone needs it.
1064 int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
1065 if (PchIndex != -1) {
1066 if (isa<PrecompileJobAction>(JA)) {
1067 // When building the pch, skip all includes after the pch.
1068 assert(YcIndex != -1 && PchIndex == YcIndex);
1072 // When using the pch, skip all includes prior to the pch.
1073 if (AI < PchIndex) {
1077 if (AI == PchIndex) {
1079 CmdArgs.push_back("-include-pch");
1081 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
1086 } else if (A->getOption().matches(options::OPT_include)) {
1087 // Handling of gcc-style gch precompiled headers.
1088 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1089 RenderedImplicitInclude = true;
1091 // Use PCH if the user requested it.
1092 bool UsePCH = D.CCCUsePCH;
1094 bool FoundPTH = false;
1095 bool FoundPCH = false;
1096 SmallString<128> P(A->getValue());
1097 // We want the files to have a name like foo.h.pch. Add a dummy extension
1098 // so that replace_extension does the right thing.
1101 llvm::sys::path::replace_extension(P, "pch");
1102 if (llvm::sys::fs::exists(P))
1107 llvm::sys::path::replace_extension(P, "pth");
1108 if (llvm::sys::fs::exists(P))
1112 if (!FoundPCH && !FoundPTH) {
1113 llvm::sys::path::replace_extension(P, "gch");
1114 if (llvm::sys::fs::exists(P)) {
1120 if (FoundPCH || FoundPTH) {
1121 if (IsFirstImplicitInclude) {
1124 CmdArgs.push_back("-include-pch");
1126 CmdArgs.push_back("-include-pth");
1127 CmdArgs.push_back(Args.MakeArgString(P));
1130 // Ignore the PCH if not first on command line and emit warning.
1131 D.Diag(diag::warn_drv_pch_not_first_include) << P
1132 << A->getAsString(Args);
1135 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1136 // Handling of paths which must come late. These entries are handled by
1137 // the toolchain itself after the resource dir is inserted in the right
1139 // Do not claim the argument so that the use of the argument does not
1140 // silently go unnoticed on toolchains which do not honour the option.
1144 // Not translated, render as usual.
1146 A->render(Args, CmdArgs);
1149 Args.AddAllArgs(CmdArgs,
1150 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1151 options::OPT_F, options::OPT_index_header_map});
1153 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1155 // FIXME: There is a very unfortunate problem here, some troubled
1156 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1157 // really support that we would have to parse and then translate
1158 // those options. :(
1159 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1160 options::OPT_Xpreprocessor);
1162 // -I- is a deprecated GCC feature, reject it.
1163 if (Arg *A = Args.getLastArg(options::OPT_I_))
1164 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1166 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1167 // -isysroot to the CC1 invocation.
1168 StringRef sysroot = C.getSysRoot();
1169 if (sysroot != "") {
1170 if (!Args.hasArg(options::OPT_isysroot)) {
1171 CmdArgs.push_back("-isysroot");
1172 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1176 // Parse additional include paths from environment variables.
1177 // FIXME: We should probably sink the logic for handling these from the
1178 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1179 // CPATH - included following the user specified includes (but prior to
1180 // builtin and standard includes).
1181 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1182 // C_INCLUDE_PATH - system includes enabled when compiling C.
1183 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1184 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1185 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1186 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1187 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1188 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1189 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1191 // While adding the include arguments, we also attempt to retrieve the
1192 // arguments of related offloading toolchains or arguments that are specific
1193 // of an offloading programming model.
1195 // Add C++ include arguments, if needed.
1196 if (types::isCXX(Inputs[0].getType()))
1197 forAllAssociatedToolChains(C, JA, getToolChain(),
1198 [&Args, &CmdArgs](const ToolChain &TC) {
1199 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1202 // Add system include arguments for all targets but IAMCU.
1204 forAllAssociatedToolChains(C, JA, getToolChain(),
1205 [&Args, &CmdArgs](const ToolChain &TC) {
1206 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1209 // For IAMCU add special include arguments.
1210 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1214 // FIXME: Move to target hook.
1215 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1216 switch (Triple.getArch()) {
1220 case llvm::Triple::aarch64:
1221 case llvm::Triple::aarch64_be:
1222 case llvm::Triple::arm:
1223 case llvm::Triple::armeb:
1224 case llvm::Triple::thumb:
1225 case llvm::Triple::thumbeb:
1226 if (Triple.isOSDarwin() || Triple.isOSWindows())
1230 case llvm::Triple::ppc:
1231 case llvm::Triple::ppc64:
1232 if (Triple.isOSDarwin())
1236 case llvm::Triple::hexagon:
1237 case llvm::Triple::ppc64le:
1238 case llvm::Triple::systemz:
1239 case llvm::Triple::xcore:
1244 static bool isNoCommonDefault(const llvm::Triple &Triple) {
1245 switch (Triple.getArch()) {
1249 case llvm::Triple::xcore:
1250 case llvm::Triple::wasm32:
1251 case llvm::Triple::wasm64:
1256 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1257 ArgStringList &CmdArgs, bool KernelOrKext) const {
1258 // Select the ABI to use.
1259 // FIXME: Support -meabi.
1260 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1261 const char *ABIName = nullptr;
1262 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1263 ABIName = A->getValue();
1264 } else if (Triple.isOSBinFormatMachO()) {
1265 if (arm::useAAPCSForMachO(Triple)) {
1267 } else if (Triple.isWatchABI()) {
1268 ABIName = "aapcs16";
1270 ABIName = "apcs-gnu";
1272 } else if (Triple.isOSWindows()) {
1273 // FIXME: this is invalid for WindowsCE
1276 // Select the default based on the platform.
1277 switch (Triple.getEnvironment()) {
1278 case llvm::Triple::Android:
1279 case llvm::Triple::GNUEABI:
1280 case llvm::Triple::GNUEABIHF:
1281 case llvm::Triple::MuslEABI:
1282 case llvm::Triple::MuslEABIHF:
1283 ABIName = "aapcs-linux";
1285 case llvm::Triple::EABIHF:
1286 case llvm::Triple::EABI:
1290 if (Triple.getOS() == llvm::Triple::NetBSD)
1291 ABIName = "apcs-gnu";
1292 else if (Triple.getOS() == llvm::Triple::OpenBSD)
1293 ABIName = "aapcs-linux";
1299 CmdArgs.push_back("-target-abi");
1300 CmdArgs.push_back(ABIName);
1302 // Determine floating point ABI from the options & target defaults.
1303 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1304 if (ABI == arm::FloatABI::Soft) {
1305 // Floating point operations and argument passing are soft.
1306 // FIXME: This changes CPP defines, we need -target-soft-float.
1307 CmdArgs.push_back("-msoft-float");
1308 CmdArgs.push_back("-mfloat-abi");
1309 CmdArgs.push_back("soft");
1310 } else if (ABI == arm::FloatABI::SoftFP) {
1311 // Floating point operations are hard, but argument passing is soft.
1312 CmdArgs.push_back("-mfloat-abi");
1313 CmdArgs.push_back("soft");
1315 // Floating point operations and argument passing are hard.
1316 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1317 CmdArgs.push_back("-mfloat-abi");
1318 CmdArgs.push_back("hard");
1321 // Forward the -mglobal-merge option for explicit control over the pass.
1322 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1323 options::OPT_mno_global_merge)) {
1324 CmdArgs.push_back("-backend-option");
1325 if (A->getOption().matches(options::OPT_mno_global_merge))
1326 CmdArgs.push_back("-arm-global-merge=false");
1328 CmdArgs.push_back("-arm-global-merge=true");
1331 if (!Args.hasFlag(options::OPT_mimplicit_float,
1332 options::OPT_mno_implicit_float, true))
1333 CmdArgs.push_back("-no-implicit-float");
1336 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1337 ArgStringList &CmdArgs) const {
1338 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1340 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1341 Args.hasArg(options::OPT_mkernel) ||
1342 Args.hasArg(options::OPT_fapple_kext))
1343 CmdArgs.push_back("-disable-red-zone");
1345 if (!Args.hasFlag(options::OPT_mimplicit_float,
1346 options::OPT_mno_implicit_float, true))
1347 CmdArgs.push_back("-no-implicit-float");
1349 const char *ABIName = nullptr;
1350 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1351 ABIName = A->getValue();
1352 else if (Triple.isOSDarwin())
1353 ABIName = "darwinpcs";
1357 CmdArgs.push_back("-target-abi");
1358 CmdArgs.push_back(ABIName);
1360 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1361 options::OPT_mno_fix_cortex_a53_835769)) {
1362 CmdArgs.push_back("-backend-option");
1363 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1364 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1366 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1367 } else if (Triple.isAndroid()) {
1368 // Enabled A53 errata (835769) workaround by default on android
1369 CmdArgs.push_back("-backend-option");
1370 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1373 // Forward the -mglobal-merge option for explicit control over the pass.
1374 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1375 options::OPT_mno_global_merge)) {
1376 CmdArgs.push_back("-backend-option");
1377 if (A->getOption().matches(options::OPT_mno_global_merge))
1378 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1380 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1384 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1385 ArgStringList &CmdArgs) const {
1386 const Driver &D = getToolChain().getDriver();
1389 const llvm::Triple &Triple = getToolChain().getTriple();
1390 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1392 CmdArgs.push_back("-target-abi");
1393 CmdArgs.push_back(ABIName.data());
1395 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1396 if (ABI == mips::FloatABI::Soft) {
1397 // Floating point operations and argument passing are soft.
1398 CmdArgs.push_back("-msoft-float");
1399 CmdArgs.push_back("-mfloat-abi");
1400 CmdArgs.push_back("soft");
1402 // Floating point operations and argument passing are hard.
1403 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1404 CmdArgs.push_back("-mfloat-abi");
1405 CmdArgs.push_back("hard");
1408 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1409 if (A->getOption().matches(options::OPT_mxgot)) {
1410 CmdArgs.push_back("-mllvm");
1411 CmdArgs.push_back("-mxgot");
1415 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1416 options::OPT_mno_ldc1_sdc1)) {
1417 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1418 CmdArgs.push_back("-mllvm");
1419 CmdArgs.push_back("-mno-ldc1-sdc1");
1423 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1424 options::OPT_mno_check_zero_division)) {
1425 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1426 CmdArgs.push_back("-mllvm");
1427 CmdArgs.push_back("-mno-check-zero-division");
1431 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1432 StringRef v = A->getValue();
1433 CmdArgs.push_back("-mllvm");
1434 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1438 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1439 StringRef Val = StringRef(A->getValue());
1440 if (mips::hasCompactBranches(CPUName)) {
1441 if (Val == "never" || Val == "always" || Val == "optimal") {
1442 CmdArgs.push_back("-mllvm");
1443 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1445 D.Diag(diag::err_drv_unsupported_option_argument)
1446 << A->getOption().getName() << Val;
1448 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1452 void Clang::AddPPCTargetArgs(const ArgList &Args,
1453 ArgStringList &CmdArgs) const {
1454 // Select the ABI to use.
1455 const char *ABIName = nullptr;
1456 if (getToolChain().getTriple().isOSLinux())
1457 switch (getToolChain().getArch()) {
1458 case llvm::Triple::ppc64: {
1459 // When targeting a processor that supports QPX, or if QPX is
1460 // specifically enabled, default to using the ABI that supports QPX (so
1461 // long as it is not specifically disabled).
1462 bool HasQPX = false;
1463 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1464 HasQPX = A->getValue() == StringRef("a2q");
1465 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1467 ABIName = "elfv1-qpx";
1474 case llvm::Triple::ppc64le:
1481 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1482 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1483 // the option if given as we don't have backend support for any targets
1484 // that don't use the altivec abi.
1485 if (StringRef(A->getValue()) != "altivec")
1486 ABIName = A->getValue();
1488 ppc::FloatABI FloatABI =
1489 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1491 if (FloatABI == ppc::FloatABI::Soft) {
1492 // Floating point operations and argument passing are soft.
1493 CmdArgs.push_back("-msoft-float");
1494 CmdArgs.push_back("-mfloat-abi");
1495 CmdArgs.push_back("soft");
1497 // Floating point operations and argument passing are hard.
1498 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1499 CmdArgs.push_back("-mfloat-abi");
1500 CmdArgs.push_back("hard");
1504 CmdArgs.push_back("-target-abi");
1505 CmdArgs.push_back(ABIName);
1509 void Clang::AddSparcTargetArgs(const ArgList &Args,
1510 ArgStringList &CmdArgs) const {
1511 sparc::FloatABI FloatABI =
1512 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1514 if (FloatABI == sparc::FloatABI::Soft) {
1515 // Floating point operations and argument passing are soft.
1516 CmdArgs.push_back("-msoft-float");
1517 CmdArgs.push_back("-mfloat-abi");
1518 CmdArgs.push_back("soft");
1520 // Floating point operations and argument passing are hard.
1521 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1522 CmdArgs.push_back("-mfloat-abi");
1523 CmdArgs.push_back("hard");
1527 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1528 ArgStringList &CmdArgs) const {
1529 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1530 CmdArgs.push_back("-mbackchain");
1533 void Clang::AddX86TargetArgs(const ArgList &Args,
1534 ArgStringList &CmdArgs) const {
1535 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1536 Args.hasArg(options::OPT_mkernel) ||
1537 Args.hasArg(options::OPT_fapple_kext))
1538 CmdArgs.push_back("-disable-red-zone");
1540 // Default to avoid implicit floating-point for kernel/kext code, but allow
1541 // that to be overridden with -mno-soft-float.
1542 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1543 Args.hasArg(options::OPT_fapple_kext));
1544 if (Arg *A = Args.getLastArg(
1545 options::OPT_msoft_float, options::OPT_mno_soft_float,
1546 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1547 const Option &O = A->getOption();
1548 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1549 O.matches(options::OPT_msoft_float));
1551 if (NoImplicitFloat)
1552 CmdArgs.push_back("-no-implicit-float");
1554 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1555 StringRef Value = A->getValue();
1556 if (Value == "intel" || Value == "att") {
1557 CmdArgs.push_back("-mllvm");
1558 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1560 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1561 << A->getOption().getName() << Value;
1565 // Set flags to support MCU ABI.
1566 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1567 CmdArgs.push_back("-mfloat-abi");
1568 CmdArgs.push_back("soft");
1569 CmdArgs.push_back("-mstack-alignment=4");
1573 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1574 ArgStringList &CmdArgs) const {
1575 CmdArgs.push_back("-mqdsp6-compat");
1576 CmdArgs.push_back("-Wreturn-type");
1578 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1579 std::string N = llvm::utostr(G.getValue());
1580 std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
1581 CmdArgs.push_back("-mllvm");
1582 CmdArgs.push_back(Args.MakeArgString(Opt));
1585 if (!Args.hasArg(options::OPT_fno_short_enums))
1586 CmdArgs.push_back("-fshort-enums");
1587 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1588 CmdArgs.push_back("-mllvm");
1589 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1591 CmdArgs.push_back("-mllvm");
1592 CmdArgs.push_back("-machine-sink-split=0");
1595 void Clang::AddLanaiTargetArgs(const ArgList &Args,
1596 ArgStringList &CmdArgs) const {
1597 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1598 StringRef CPUName = A->getValue();
1600 CmdArgs.push_back("-target-cpu");
1601 CmdArgs.push_back(Args.MakeArgString(CPUName));
1603 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1604 StringRef Value = A->getValue();
1605 // Only support mregparm=4 to support old usage. Report error for all other
1608 if (Value.getAsInteger(10, Mregparm)) {
1609 if (Mregparm != 4) {
1610 getToolChain().getDriver().Diag(
1611 diag::err_drv_unsupported_option_argument)
1612 << A->getOption().getName() << Value;
1618 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1619 ArgStringList &CmdArgs) const {
1620 // Default to "hidden" visibility.
1621 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1622 options::OPT_fvisibility_ms_compat)) {
1623 CmdArgs.push_back("-fvisibility");
1624 CmdArgs.push_back("hidden");
1628 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1629 StringRef Target, const InputInfo &Output,
1630 const InputInfo &Input, const ArgList &Args) const {
1631 // If this is a dry run, do not create the compilation database file.
1632 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1635 using llvm::yaml::escape;
1636 const Driver &D = getToolChain().getDriver();
1638 if (!CompilationDatabase) {
1640 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1642 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1646 CompilationDatabase = std::move(File);
1648 auto &CDB = *CompilationDatabase;
1649 SmallString<128> Buf;
1650 if (llvm::sys::fs::current_path(Buf))
1652 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1653 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1654 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1655 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1657 Buf += types::getTypeName(Input.getType());
1658 CDB << ", \"" << escape(Buf) << "\"";
1659 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1662 CDB << ", \"" << escape(Buf) << "\"";
1664 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1665 for (auto &A: Args) {
1666 auto &O = A->getOption();
1667 // Skip language selection, which is positional.
1668 if (O.getID() == options::OPT_x)
1670 // Skip writing dependency output and the compilation database itself.
1671 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1674 if (O.getKind() == Option::InputClass)
1676 // All other arguments are quoted and appended.
1678 A->render(Args, ASL);
1680 CDB << ", \"" << escape(it) << "\"";
1684 CDB << ", \"" << escape(Buf) << "\"]},\n";
1687 static void CollectArgsForIntegratedAssembler(Compilation &C,
1688 const ArgList &Args,
1689 ArgStringList &CmdArgs,
1691 if (UseRelaxAll(C, Args))
1692 CmdArgs.push_back("-mrelax-all");
1694 // Only default to -mincremental-linker-compatible if we think we are
1695 // targeting the MSVC linker.
1696 bool DefaultIncrementalLinkerCompatible =
1697 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1698 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1699 options::OPT_mno_incremental_linker_compatible,
1700 DefaultIncrementalLinkerCompatible))
1701 CmdArgs.push_back("-mincremental-linker-compatible");
1703 switch (C.getDefaultToolChain().getArch()) {
1704 case llvm::Triple::arm:
1705 case llvm::Triple::armeb:
1706 case llvm::Triple::thumb:
1707 case llvm::Triple::thumbeb:
1708 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1709 StringRef Value = A->getValue();
1710 if (Value == "always" || Value == "never" || Value == "arm" ||
1712 CmdArgs.push_back("-mllvm");
1713 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1715 D.Diag(diag::err_drv_unsupported_option_argument)
1716 << A->getOption().getName() << Value;
1724 // When passing -I arguments to the assembler we sometimes need to
1725 // unconditionally take the next argument. For example, when parsing
1726 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1727 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1728 // arg after parsing the '-I' arg.
1729 bool TakeNextArg = false;
1731 // When using an integrated assembler, translate -Wa, and -Xassembler
1733 bool CompressDebugSections = false;
1735 bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
1736 const char *MipsTargetFeature = nullptr;
1738 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1741 for (StringRef Value : A->getValues()) {
1743 CmdArgs.push_back(Value.data());
1744 TakeNextArg = false;
1748 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1749 Value == "-mbig-obj")
1750 continue; // LLVM handles bigobj automatically
1752 switch (C.getDefaultToolChain().getArch()) {
1755 case llvm::Triple::mips:
1756 case llvm::Triple::mipsel:
1757 case llvm::Triple::mips64:
1758 case llvm::Triple::mips64el:
1759 if (Value == "--trap") {
1760 CmdArgs.push_back("-target-feature");
1761 CmdArgs.push_back("+use-tcc-in-div");
1764 if (Value == "--break") {
1765 CmdArgs.push_back("-target-feature");
1766 CmdArgs.push_back("-use-tcc-in-div");
1769 if (Value.startswith("-msoft-float")) {
1770 CmdArgs.push_back("-target-feature");
1771 CmdArgs.push_back("+soft-float");
1774 if (Value.startswith("-mhard-float")) {
1775 CmdArgs.push_back("-target-feature");
1776 CmdArgs.push_back("-soft-float");
1780 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1781 .Case("-mips1", "+mips1")
1782 .Case("-mips2", "+mips2")
1783 .Case("-mips3", "+mips3")
1784 .Case("-mips4", "+mips4")
1785 .Case("-mips5", "+mips5")
1786 .Case("-mips32", "+mips32")
1787 .Case("-mips32r2", "+mips32r2")
1788 .Case("-mips32r3", "+mips32r3")
1789 .Case("-mips32r5", "+mips32r5")
1790 .Case("-mips32r6", "+mips32r6")
1791 .Case("-mips64", "+mips64")
1792 .Case("-mips64r2", "+mips64r2")
1793 .Case("-mips64r3", "+mips64r3")
1794 .Case("-mips64r5", "+mips64r5")
1795 .Case("-mips64r6", "+mips64r6")
1797 if (MipsTargetFeature)
1801 if (Value == "-force_cpusubtype_ALL") {
1802 // Do nothing, this is the default and we don't support anything else.
1803 } else if (Value == "-L") {
1804 CmdArgs.push_back("-msave-temp-labels");
1805 } else if (Value == "--fatal-warnings") {
1806 CmdArgs.push_back("-massembler-fatal-warnings");
1807 } else if (Value == "--noexecstack") {
1808 CmdArgs.push_back("-mnoexecstack");
1809 } else if (Value == "-compress-debug-sections" ||
1810 Value == "--compress-debug-sections") {
1811 CompressDebugSections = true;
1812 } else if (Value == "-nocompress-debug-sections" ||
1813 Value == "--nocompress-debug-sections") {
1814 CompressDebugSections = false;
1815 } else if (Value == "-mrelax-relocations=yes" ||
1816 Value == "--mrelax-relocations=yes") {
1817 UseRelaxRelocations = true;
1818 } else if (Value == "-mrelax-relocations=no" ||
1819 Value == "--mrelax-relocations=no") {
1820 UseRelaxRelocations = false;
1821 } else if (Value.startswith("-I")) {
1822 CmdArgs.push_back(Value.data());
1823 // We need to consume the next argument if the current arg is a plain
1824 // -I. The next arg will be the include directory.
1827 } else if (Value.startswith("-gdwarf-")) {
1828 // "-gdwarf-N" options are not cc1as options.
1829 unsigned DwarfVersion = DwarfVersionNum(Value);
1830 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
1831 CmdArgs.push_back(Value.data());
1833 RenderDebugEnablingArgs(Args, CmdArgs,
1834 codegenoptions::LimitedDebugInfo,
1835 DwarfVersion, llvm::DebuggerKind::Default);
1837 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
1838 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
1839 // Do nothing, we'll validate it later.
1840 } else if (Value == "-defsym") {
1841 if (A->getNumValues() != 2) {
1842 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
1845 const char *S = A->getValue(1);
1846 auto Pair = StringRef(S).split('=');
1847 auto Sym = Pair.first;
1848 auto SVal = Pair.second;
1850 if (Sym.empty() || SVal.empty()) {
1851 D.Diag(diag::err_drv_defsym_invalid_format) << S;
1855 if (SVal.getAsInteger(0, IVal)) {
1856 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
1859 CmdArgs.push_back(Value.data());
1862 D.Diag(diag::err_drv_unsupported_option_argument)
1863 << A->getOption().getName() << Value;
1867 if (CompressDebugSections) {
1868 if (llvm::zlib::isAvailable())
1869 CmdArgs.push_back("-compress-debug-sections");
1871 D.Diag(diag::warn_debug_compression_unavailable);
1873 if (UseRelaxRelocations)
1874 CmdArgs.push_back("--mrelax-relocations");
1875 if (MipsTargetFeature != nullptr) {
1876 CmdArgs.push_back("-target-feature");
1877 CmdArgs.push_back(MipsTargetFeature);
1881 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
1882 const InputInfo &Output, const InputInfoList &Inputs,
1883 const ArgList &Args, const char *LinkingOutput) const {
1884 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1885 const std::string &TripleStr = Triple.getTriple();
1888 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1889 const Driver &D = getToolChain().getDriver();
1890 ArgStringList CmdArgs;
1892 // Check number of inputs for sanity. We need at least one input.
1893 assert(Inputs.size() >= 1 && "Must have at least one input.");
1894 const InputInfo &Input = Inputs[0];
1895 // CUDA compilation may have multiple inputs (source file + results of
1896 // device-side compilations). OpenMP device jobs also take the host IR as a
1897 // second input. All other jobs are expected to have exactly one
1899 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
1900 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
1901 assert((IsCuda || (IsOpenMPDevice && Inputs.size() == 2) ||
1902 Inputs.size() == 1) &&
1903 "Unable to handle multiple inputs.");
1905 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
1906 bool IsWindowsCygnus =
1907 getToolChain().getTriple().isWindowsCygwinEnvironment();
1908 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
1909 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
1910 bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1912 // Adjust IsWindowsXYZ for CUDA compilations. Even when compiling in device
1913 // mode (i.e., getToolchain().getTriple() is NVPTX, not Windows), we need to
1914 // pass Windows-specific flags to cc1.
1916 const llvm::Triple *AuxTriple = getToolChain().getAuxTriple();
1917 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
1918 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
1919 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
1922 // C++ is not supported for IAMCU.
1923 if (IsIAMCU && types::isCXX(Input.getType()))
1924 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
1926 // Invoke ourselves in -cc1 mode.
1928 // FIXME: Implement custom jobs for internal actions.
1929 CmdArgs.push_back("-cc1");
1931 // Add the "effective" target triple.
1932 CmdArgs.push_back("-triple");
1933 CmdArgs.push_back(Args.MakeArgString(TripleStr));
1935 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
1936 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
1937 Args.ClaimAllArgs(options::OPT_MJ);
1941 // We have to pass the triple of the host if compiling for a CUDA device and
1943 std::string NormalizedTriple;
1944 if (JA.isDeviceOffloading(Action::OFK_Cuda))
1945 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
1949 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
1953 CmdArgs.push_back("-aux-triple");
1954 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
1957 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
1958 Triple.getArch() == llvm::Triple::thumb)) {
1959 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
1961 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
1963 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
1967 // Push all default warning arguments that are specific to
1968 // the given target. These come before user provided warning options
1970 getToolChain().addClangWarningOptions(CmdArgs);
1972 // Select the appropriate action.
1973 RewriteKind rewriteKind = RK_None;
1975 if (isa<AnalyzeJobAction>(JA)) {
1976 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
1977 CmdArgs.push_back("-analyze");
1978 } else if (isa<MigrateJobAction>(JA)) {
1979 CmdArgs.push_back("-migrate");
1980 } else if (isa<PreprocessJobAction>(JA)) {
1981 if (Output.getType() == types::TY_Dependencies)
1982 CmdArgs.push_back("-Eonly");
1984 CmdArgs.push_back("-E");
1985 if (Args.hasArg(options::OPT_rewrite_objc) &&
1986 !Args.hasArg(options::OPT_g_Group))
1987 CmdArgs.push_back("-P");
1989 } else if (isa<AssembleJobAction>(JA)) {
1990 CmdArgs.push_back("-emit-obj");
1992 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
1994 // Also ignore explicit -force_cpusubtype_ALL option.
1995 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
1996 } else if (isa<PrecompileJobAction>(JA)) {
1997 // Use PCH if the user requested it.
1998 bool UsePCH = D.CCCUsePCH;
2000 if (JA.getType() == types::TY_Nothing)
2001 CmdArgs.push_back("-fsyntax-only");
2002 else if (JA.getType() == types::TY_ModuleFile)
2003 CmdArgs.push_back("-emit-module-interface");
2005 CmdArgs.push_back("-emit-pch");
2007 CmdArgs.push_back("-emit-pth");
2008 } else if (isa<VerifyPCHJobAction>(JA)) {
2009 CmdArgs.push_back("-verify-pch");
2011 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
2012 "Invalid action for clang tool.");
2013 if (JA.getType() == types::TY_Nothing) {
2014 CmdArgs.push_back("-fsyntax-only");
2015 } else if (JA.getType() == types::TY_LLVM_IR ||
2016 JA.getType() == types::TY_LTO_IR) {
2017 CmdArgs.push_back("-emit-llvm");
2018 } else if (JA.getType() == types::TY_LLVM_BC ||
2019 JA.getType() == types::TY_LTO_BC) {
2020 CmdArgs.push_back("-emit-llvm-bc");
2021 } else if (JA.getType() == types::TY_PP_Asm) {
2022 CmdArgs.push_back("-S");
2023 } else if (JA.getType() == types::TY_AST) {
2024 CmdArgs.push_back("-emit-pch");
2025 } else if (JA.getType() == types::TY_ModuleFile) {
2026 CmdArgs.push_back("-module-file-info");
2027 } else if (JA.getType() == types::TY_RewrittenObjC) {
2028 CmdArgs.push_back("-rewrite-objc");
2029 rewriteKind = RK_NonFragile;
2030 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2031 CmdArgs.push_back("-rewrite-objc");
2032 rewriteKind = RK_Fragile;
2034 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
2037 // Preserve use-list order by default when emitting bitcode, so that
2038 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
2039 // same result as running passes here. For LTO, we don't need to preserve
2040 // the use-list order, since serialization to bitcode is part of the flow.
2041 if (JA.getType() == types::TY_LLVM_BC)
2042 CmdArgs.push_back("-emit-llvm-uselists");
2044 if (D.isUsingLTO()) {
2045 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
2047 // The Darwin linker currently uses the legacy LTO API, which does not
2048 // support LTO unit features (CFI, whole program vtable opt) under
2050 if (!getToolChain().getTriple().isOSDarwin() ||
2051 D.getLTOMode() == LTOK_Full)
2052 CmdArgs.push_back("-flto-unit");
2056 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
2057 if (!types::isLLVMIR(Input.getType()))
2058 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
2060 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
2063 // Embed-bitcode option.
2064 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
2065 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
2066 // Add flags implied by -fembed-bitcode.
2067 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2068 // Disable all llvm IR level optimizations.
2069 CmdArgs.push_back("-disable-llvm-passes");
2071 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
2072 CmdArgs.push_back("-fembed-bitcode=marker");
2074 // We normally speed up the clang process a bit by skipping destructors at
2075 // exit, but when we're generating diagnostics we can rely on some of the
2077 if (!C.isForDiagnostics())
2078 CmdArgs.push_back("-disable-free");
2080 // Disable the verification pass in -asserts builds.
2082 CmdArgs.push_back("-disable-llvm-verifier");
2083 // Discard LLVM value names in -asserts builds.
2084 CmdArgs.push_back("-discard-value-names");
2087 // Set the main file name, so that debug info works even with
2089 CmdArgs.push_back("-main-file-name");
2090 CmdArgs.push_back(getBaseInputName(Args, Input));
2092 // Some flags which affect the language (via preprocessor
2094 if (Args.hasArg(options::OPT_static))
2095 CmdArgs.push_back("-static-define");
2097 if (isa<AnalyzeJobAction>(JA)) {
2098 // Enable region store model by default.
2099 CmdArgs.push_back("-analyzer-store=region");
2101 // Treat blocks as analysis entry points.
2102 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2104 CmdArgs.push_back("-analyzer-eagerly-assume");
2106 // Add default argument set.
2107 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2108 CmdArgs.push_back("-analyzer-checker=core");
2109 CmdArgs.push_back("-analyzer-checker=apiModeling");
2111 if (!IsWindowsMSVC) {
2112 CmdArgs.push_back("-analyzer-checker=unix");
2114 // Enable "unix" checkers that also work on Windows.
2115 CmdArgs.push_back("-analyzer-checker=unix.API");
2116 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2117 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2118 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2119 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2120 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2123 // Disable some unix checkers for PS4.
2125 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2126 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2129 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2130 CmdArgs.push_back("-analyzer-checker=osx");
2132 CmdArgs.push_back("-analyzer-checker=deadcode");
2134 if (types::isCXX(Input.getType()))
2135 CmdArgs.push_back("-analyzer-checker=cplusplus");
2139 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
2140 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2141 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2142 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2143 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2144 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2147 // Default nullability checks.
2148 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2150 "-analyzer-checker=nullability.NullReturnedFromNonnull");
2153 // Set the output format. The default is plist, for (lame) historical
2155 CmdArgs.push_back("-analyzer-output");
2156 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2157 CmdArgs.push_back(A->getValue());
2159 CmdArgs.push_back("plist");
2161 // Disable the presentation of standard compiler warnings when
2162 // using --analyze. We only want to show static analyzer diagnostics
2163 // or frontend errors.
2164 CmdArgs.push_back("-w");
2166 // Add -Xanalyzer arguments when running as analyzer.
2167 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2170 CheckCodeGenerationOptions(D, Args);
2172 llvm::Reloc::Model RelocationModel;
2175 std::tie(RelocationModel, PICLevel, IsPIE) =
2176 ParsePICArgs(getToolChain(), Args);
2178 const char *RMName = RelocationModelName(RelocationModel);
2180 if ((RelocationModel == llvm::Reloc::ROPI ||
2181 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
2182 types::isCXX(Input.getType()) &&
2183 !Args.hasArg(options::OPT_fallow_unsupported))
2184 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
2187 CmdArgs.push_back("-mrelocation-model");
2188 CmdArgs.push_back(RMName);
2191 CmdArgs.push_back("-pic-level");
2192 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
2194 CmdArgs.push_back("-pic-is-pie");
2197 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
2198 CmdArgs.push_back("-meabi");
2199 CmdArgs.push_back(A->getValue());
2202 CmdArgs.push_back("-mthread-model");
2203 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
2204 CmdArgs.push_back(A->getValue());
2206 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
2208 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
2210 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
2211 options::OPT_fno_merge_all_constants))
2212 CmdArgs.push_back("-fno-merge-all-constants");
2214 // LLVM Code Generator Options.
2216 if (Args.hasArg(options::OPT_frewrite_map_file) ||
2217 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
2218 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
2219 options::OPT_frewrite_map_file_EQ)) {
2220 StringRef Map = A->getValue();
2221 if (!llvm::sys::fs::exists(Map)) {
2222 D.Diag(diag::err_drv_no_such_file) << Map;
2224 CmdArgs.push_back("-frewrite-map-file");
2225 CmdArgs.push_back(A->getValue());
2231 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
2232 StringRef v = A->getValue();
2233 CmdArgs.push_back("-mllvm");
2234 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
2238 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
2240 CmdArgs.push_back("-fno-jump-tables");
2242 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
2243 options::OPT_fno_preserve_as_comments, true))
2244 CmdArgs.push_back("-fno-preserve-as-comments");
2246 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2247 CmdArgs.push_back("-mregparm");
2248 CmdArgs.push_back(A->getValue());
2251 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
2252 options::OPT_freg_struct_return)) {
2253 if (getToolChain().getArch() != llvm::Triple::x86) {
2254 D.Diag(diag::err_drv_unsupported_opt_for_target)
2255 << A->getSpelling() << getToolChain().getTriple().str();
2256 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
2257 CmdArgs.push_back("-fpcc-struct-return");
2259 assert(A->getOption().matches(options::OPT_freg_struct_return));
2260 CmdArgs.push_back("-freg-struct-return");
2264 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
2265 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
2267 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
2268 CmdArgs.push_back("-mdisable-fp-elim");
2269 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
2270 options::OPT_fno_zero_initialized_in_bss))
2271 CmdArgs.push_back("-mno-zero-initialized-in-bss");
2273 bool OFastEnabled = isOptimizationLevelFast(Args);
2274 // If -Ofast is the optimization level, then -fstrict-aliasing should be
2275 // enabled. This alias option is being used to simplify the hasFlag logic.
2276 OptSpecifier StrictAliasingAliasOption =
2277 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
2278 // We turn strict aliasing off by default if we're in CL mode, since MSVC
2279 // doesn't do any TBAA.
2280 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
2281 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
2282 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
2283 CmdArgs.push_back("-relaxed-aliasing");
2284 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
2285 options::OPT_fno_struct_path_tbaa))
2286 CmdArgs.push_back("-no-struct-path-tbaa");
2287 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
2289 CmdArgs.push_back("-fstrict-enums");
2290 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
2292 CmdArgs.push_back("-fno-strict-return");
2293 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
2294 options::OPT_fno_strict_vtable_pointers,
2296 CmdArgs.push_back("-fstrict-vtable-pointers");
2297 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
2298 options::OPT_fno_optimize_sibling_calls))
2299 CmdArgs.push_back("-mdisable-tail-calls");
2301 // Handle segmented stacks.
2302 if (Args.hasArg(options::OPT_fsplit_stack))
2303 CmdArgs.push_back("-split-stacks");
2305 // Handle various floating point optimization flags, mapping them to the
2306 // appropriate LLVM code generation flags. This is complicated by several
2307 // "umbrella" flags, so we do this by stepping through the flags incrementally
2308 // adjusting what we think is enabled/disabled, then at the end settting the
2309 // LLVM flags based on the final state.
2310 bool HonorInfs = true;
2311 bool HonorNans = true;
2312 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2313 bool MathErrno = getToolChain().IsMathErrnoDefault();
2314 bool AssociativeMath = false;
2315 bool ReciprocalMath = false;
2316 bool SignedZeros = true;
2317 bool TrappingMath = true;
2318 StringRef DenormalFpMath = "";
2319 StringRef FpContract = "";
2321 for (Arg *A : Args) {
2322 switch (A->getOption().getID()) {
2323 // If this isn't an FP option skip the claim below
2327 // Options controlling individual features
2328 case options::OPT_fhonor_infinities: HonorInfs = true; break;
2329 case options::OPT_fno_honor_infinities: HonorInfs = false; break;
2330 case options::OPT_fhonor_nans: HonorNans = true; break;
2331 case options::OPT_fno_honor_nans: HonorNans = false; break;
2332 case options::OPT_fmath_errno: MathErrno = true; break;
2333 case options::OPT_fno_math_errno: MathErrno = false; break;
2334 case options::OPT_fassociative_math: AssociativeMath = true; break;
2335 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2336 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2337 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2338 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2339 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2340 case options::OPT_ftrapping_math: TrappingMath = true; break;
2341 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2343 case options::OPT_fdenormal_fp_math_EQ:
2344 DenormalFpMath = A->getValue();
2347 // Validate and pass through -fp-contract option.
2348 case options::OPT_ffp_contract: {
2349 StringRef Val = A->getValue();
2350 if (Val == "fast" || Val == "on" || Val == "off") {
2353 D.Diag(diag::err_drv_unsupported_option_argument)
2354 << A->getOption().getName() << Val;
2359 case options::OPT_ffinite_math_only:
2363 case options::OPT_fno_finite_math_only:
2368 case options::OPT_funsafe_math_optimizations:
2369 AssociativeMath = true;
2370 ReciprocalMath = true;
2371 SignedZeros = false;
2372 TrappingMath = false;
2374 case options::OPT_fno_unsafe_math_optimizations:
2375 AssociativeMath = false;
2376 ReciprocalMath = false;
2378 TrappingMath = true;
2379 // -fno_unsafe_math_optimizations restores default denormal handling
2380 DenormalFpMath = "";
2383 case options::OPT_Ofast:
2384 // If -Ofast is the optimization level, then -ffast-math should be enabled
2388 case options::OPT_ffast_math:
2392 AssociativeMath = true;
2393 ReciprocalMath = true;
2394 SignedZeros = false;
2395 TrappingMath = false;
2396 // If fast-math is set then set the fp-contract mode to fast.
2397 FpContract = "fast";
2399 case options::OPT_fno_fast_math:
2402 // Turning on -ffast-math (with either flag) removes the need for
2403 // MathErrno. However, turning *off* -ffast-math merely restores the
2404 // toolchain default (which may be false).
2405 MathErrno = getToolChain().IsMathErrnoDefault();
2406 AssociativeMath = false;
2407 ReciprocalMath = false;
2409 TrappingMath = true;
2410 // -fno_fast_math restores default denormal and fpcontract handling
2411 DenormalFpMath = "";
2415 // If we handled this option claim it
2420 CmdArgs.push_back("-menable-no-infs");
2423 CmdArgs.push_back("-menable-no-nans");
2426 CmdArgs.push_back("-fmath-errno");
2428 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2430 CmdArgs.push_back("-menable-unsafe-fp-math");
2433 CmdArgs.push_back("-fno-signed-zeros");
2436 CmdArgs.push_back("-freciprocal-math");
2439 CmdArgs.push_back("-fno-trapping-math");
2441 if (!DenormalFpMath.empty())
2442 CmdArgs.push_back(Args.MakeArgString("-fdenormal-fp-math="+DenormalFpMath));
2444 if (!FpContract.empty())
2445 CmdArgs.push_back(Args.MakeArgString("-ffp-contract="+FpContract));
2447 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
2449 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2450 // individual features enabled by -ffast-math instead of the option itself as
2451 // that's consistent with gcc's behaviour.
2452 if (!HonorInfs && !HonorNans && !MathErrno && AssociativeMath &&
2453 ReciprocalMath && !SignedZeros && !TrappingMath)
2454 CmdArgs.push_back("-ffast-math");
2456 // Handle __FINITE_MATH_ONLY__ similarly.
2457 if (!HonorInfs && !HonorNans)
2458 CmdArgs.push_back("-ffinite-math-only");
2460 // Decide whether to use verbose asm. Verbose assembly is the default on
2461 // toolchains which have the integrated assembler on by default.
2462 bool IsIntegratedAssemblerDefault =
2463 getToolChain().IsIntegratedAssemblerDefault();
2464 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2465 IsIntegratedAssemblerDefault) ||
2466 Args.hasArg(options::OPT_dA))
2467 CmdArgs.push_back("-masm-verbose");
2469 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
2470 IsIntegratedAssemblerDefault))
2471 CmdArgs.push_back("-no-integrated-as");
2473 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2474 CmdArgs.push_back("-mdebug-pass");
2475 CmdArgs.push_back("Structure");
2477 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2478 CmdArgs.push_back("-mdebug-pass");
2479 CmdArgs.push_back("Arguments");
2482 // Enable -mconstructor-aliases except on darwin, where we have to work around
2483 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
2484 // aliases aren't supported.
2485 if (!getToolChain().getTriple().isOSDarwin() &&
2486 !getToolChain().getTriple().isNVPTX())
2487 CmdArgs.push_back("-mconstructor-aliases");
2489 // Darwin's kernel doesn't support guard variables; just die if we
2491 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2492 CmdArgs.push_back("-fforbid-guard-variables");
2494 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
2496 CmdArgs.push_back("-mms-bitfields");
2499 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
2500 options::OPT_mno_pie_copy_relocations,
2502 CmdArgs.push_back("-mpie-copy-relocations");
2505 // This is a coarse approximation of what llvm-gcc actually does, both
2506 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2507 // complicated ways.
2508 bool AsynchronousUnwindTables =
2509 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2510 options::OPT_fno_asynchronous_unwind_tables,
2511 (getToolChain().IsUnwindTablesDefault() ||
2512 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
2514 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2515 AsynchronousUnwindTables))
2516 CmdArgs.push_back("-munwind-tables");
2518 getToolChain().addClangTargetOptions(Args, CmdArgs);
2520 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2521 CmdArgs.push_back("-mlimit-float-precision");
2522 CmdArgs.push_back(A->getValue());
2525 // FIXME: Handle -mtune=.
2526 (void)Args.hasArg(options::OPT_mtune_EQ);
2528 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2529 CmdArgs.push_back("-mcode-model");
2530 CmdArgs.push_back(A->getValue());
2533 // Add the target cpu
2534 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
2536 CmdArgs.push_back("-target-cpu");
2537 CmdArgs.push_back(Args.MakeArgString(CPU));
2540 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2541 CmdArgs.push_back("-mfpmath");
2542 CmdArgs.push_back(A->getValue());
2545 // Add the target features
2546 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
2548 // Add target specific flags.
2549 switch (getToolChain().getArch()) {
2553 case llvm::Triple::arm:
2554 case llvm::Triple::armeb:
2555 case llvm::Triple::thumb:
2556 case llvm::Triple::thumbeb:
2557 // Use the effective triple, which takes into account the deployment target.
2558 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
2561 case llvm::Triple::aarch64:
2562 case llvm::Triple::aarch64_be:
2563 AddAArch64TargetArgs(Args, CmdArgs);
2566 case llvm::Triple::mips:
2567 case llvm::Triple::mipsel:
2568 case llvm::Triple::mips64:
2569 case llvm::Triple::mips64el:
2570 AddMIPSTargetArgs(Args, CmdArgs);
2573 case llvm::Triple::ppc:
2574 case llvm::Triple::ppc64:
2575 case llvm::Triple::ppc64le:
2576 AddPPCTargetArgs(Args, CmdArgs);
2579 case llvm::Triple::sparc:
2580 case llvm::Triple::sparcel:
2581 case llvm::Triple::sparcv9:
2582 AddSparcTargetArgs(Args, CmdArgs);
2585 case llvm::Triple::systemz:
2586 AddSystemZTargetArgs(Args, CmdArgs);
2589 case llvm::Triple::x86:
2590 case llvm::Triple::x86_64:
2591 AddX86TargetArgs(Args, CmdArgs);
2594 case llvm::Triple::lanai:
2595 AddLanaiTargetArgs(Args, CmdArgs);
2598 case llvm::Triple::hexagon:
2599 AddHexagonTargetArgs(Args, CmdArgs);
2602 case llvm::Triple::wasm32:
2603 case llvm::Triple::wasm64:
2604 AddWebAssemblyTargetArgs(Args, CmdArgs);
2608 // The 'g' groups options involve a somewhat intricate sequence of decisions
2609 // about what to pass from the driver to the frontend, but by the time they
2610 // reach cc1 they've been factored into three well-defined orthogonal choices:
2611 // * what level of debug info to generate
2612 // * what dwarf version to write
2613 // * what debugger tuning to use
2614 // This avoids having to monkey around further in cc1 other than to disable
2615 // codeview if not running in a Windows environment. Perhaps even that
2616 // decision should be made in the driver as well though.
2617 unsigned DwarfVersion = 0;
2618 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
2619 // These two are potentially updated by AddClangCLArgs.
2620 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
2621 bool EmitCodeView = false;
2623 // Add clang-cl arguments.
2624 types::ID InputType = Input.getType();
2625 if (getToolChain().getDriver().IsCLMode())
2626 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
2628 // Pass the linker version in use.
2629 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2630 CmdArgs.push_back("-target-linker-version");
2631 CmdArgs.push_back(A->getValue());
2634 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
2635 CmdArgs.push_back("-momit-leaf-frame-pointer");
2637 // Explicitly error on some things we know we don't support and can't just
2639 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
2641 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
2642 getToolChain().getArch() == llvm::Triple::x86) {
2643 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
2644 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
2645 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
2646 << Unsupported->getOption().getName();
2648 // The faltivec option has been superseded by the maltivec option.
2649 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
2650 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
2651 << Unsupported->getOption().getName()
2652 << "please use -maltivec and include altivec.h explicitly";
2653 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
2654 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
2655 << Unsupported->getOption().getName() << "please use -mno-altivec";
2658 Args.AddAllArgs(CmdArgs, options::OPT_v);
2659 Args.AddLastArg(CmdArgs, options::OPT_H);
2660 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
2661 CmdArgs.push_back("-header-include-file");
2662 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
2665 Args.AddLastArg(CmdArgs, options::OPT_P);
2666 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
2668 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
2669 CmdArgs.push_back("-diagnostic-log-file");
2670 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
2674 bool splitDwarfInlining =
2675 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2676 options::OPT_fno_split_dwarf_inlining, true);
2678 Args.ClaimAllArgs(options::OPT_g_Group);
2679 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2680 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2681 // If the last option explicitly specified a debug-info level, use it.
2682 if (A->getOption().matches(options::OPT_gN_Group)) {
2683 DebugInfoKind = DebugLevelToInfoKind(*A);
2684 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2685 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2686 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
2687 // This gets a bit more complicated if you've disabled inline info in the
2688 // skeleton CUs (splitDwarfInlining) - then there's value in composing
2689 // split-dwarf and line-tables-only, so let those compose naturally in
2691 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2692 if (SplitDwarfArg) {
2693 if (A->getIndex() > SplitDwarfArg->getIndex()) {
2694 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2695 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2696 splitDwarfInlining))
2697 SplitDwarfArg = nullptr;
2698 } else if (splitDwarfInlining)
2699 DebugInfoKind = codegenoptions::NoDebugInfo;
2702 // For any other 'g' option, use Limited.
2703 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2706 // If a debugger tuning argument appeared, remember it.
2707 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2708 options::OPT_ggdbN_Group)) {
2709 if (A->getOption().matches(options::OPT_glldb))
2710 DebuggerTuning = llvm::DebuggerKind::LLDB;
2711 else if (A->getOption().matches(options::OPT_gsce))
2712 DebuggerTuning = llvm::DebuggerKind::SCE;
2714 DebuggerTuning = llvm::DebuggerKind::GDB;
2717 // If a -gdwarf argument appeared, remember it.
2718 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2719 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2720 DwarfVersion = DwarfVersionNum(A->getSpelling());
2722 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2723 // argument parsing.
2724 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
2725 // DwarfVersion remains at 0 if no explicit choice was made.
2726 CmdArgs.push_back("-gcodeview");
2727 } else if (DwarfVersion == 0 &&
2728 DebugInfoKind != codegenoptions::NoDebugInfo) {
2729 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
2732 // We ignore flag -gstrict-dwarf for now.
2733 // And we handle flag -grecord-gcc-switches later with DwarfDebugFlags.
2734 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2736 // Column info is included by default for everything except PS4 and CodeView.
2737 // Clang doesn't track end columns, just starting columns, which, in theory,
2738 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2739 // debuggers don't handle missing end columns well, so it's better not to
2740 // include any column info.
2741 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
2742 /*Default=*/ !IsPS4CPU && !(IsWindowsMSVC && EmitCodeView)))
2743 CmdArgs.push_back("-dwarf-column-info");
2745 // FIXME: Move backend command line options to the module.
2746 // If -gline-tables-only is the last option it wins.
2747 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2748 Args.hasArg(options::OPT_gmodules)) {
2749 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2750 CmdArgs.push_back("-dwarf-ext-refs");
2751 CmdArgs.push_back("-fmodule-format=obj");
2754 // -gsplit-dwarf should turn on -g and enable the backend dwarf
2755 // splitting and extraction.
2756 // FIXME: Currently only works on Linux.
2757 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
2758 if (!splitDwarfInlining)
2759 CmdArgs.push_back("-fno-split-dwarf-inlining");
2760 if (DebugInfoKind == codegenoptions::NoDebugInfo)
2761 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2762 CmdArgs.push_back("-backend-option");
2763 CmdArgs.push_back("-split-dwarf=Enable");
2766 // After we've dealt with all combinations of things that could
2767 // make DebugInfoKind be other than None or DebugLineTablesOnly,
2768 // figure out if we need to "upgrade" it to standalone debug info.
2769 // We parse these two '-f' options whether or not they will be used,
2770 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
2771 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
2772 options::OPT_fno_standalone_debug,
2773 getToolChain().GetDefaultStandaloneDebug());
2774 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
2775 DebugInfoKind = codegenoptions::FullDebugInfo;
2776 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
2779 // -fdebug-macro turns on macro debug info generation.
2780 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
2782 CmdArgs.push_back("-debug-info-macro");
2784 // -ggnu-pubnames turns on gnu style pubnames in the backend.
2785 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
2786 CmdArgs.push_back("-backend-option");
2787 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
2790 // -gdwarf-aranges turns on the emission of the aranges section in the
2792 // Always enabled on the PS4.
2793 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
2794 CmdArgs.push_back("-backend-option");
2795 CmdArgs.push_back("-generate-arange-section");
2798 if (Args.hasFlag(options::OPT_fdebug_types_section,
2799 options::OPT_fno_debug_types_section, false)) {
2800 CmdArgs.push_back("-backend-option");
2801 CmdArgs.push_back("-generate-type-units");
2804 bool UseSeparateSections = isUseSeparateSections(Triple);
2806 if (Args.hasFlag(options::OPT_ffunction_sections,
2807 options::OPT_fno_function_sections, UseSeparateSections)) {
2808 CmdArgs.push_back("-ffunction-sections");
2811 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
2812 UseSeparateSections)) {
2813 CmdArgs.push_back("-fdata-sections");
2816 if (!Args.hasFlag(options::OPT_funique_section_names,
2817 options::OPT_fno_unique_section_names, true))
2818 CmdArgs.push_back("-fno-unique-section-names");
2820 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2822 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
2824 // Add runtime flag for PS4 when PGO or Coverage are enabled.
2825 if (getToolChain().getTriple().isPS4CPU())
2826 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
2828 // Pass options for controlling the default header search paths.
2829 if (Args.hasArg(options::OPT_nostdinc)) {
2830 CmdArgs.push_back("-nostdsysteminc");
2831 CmdArgs.push_back("-nobuiltininc");
2833 if (Args.hasArg(options::OPT_nostdlibinc))
2834 CmdArgs.push_back("-nostdsysteminc");
2835 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2836 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2839 // Pass the path to compiler resource files.
2840 CmdArgs.push_back("-resource-dir");
2841 CmdArgs.push_back(D.ResourceDir.c_str());
2843 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2845 bool ARCMTEnabled = false;
2846 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2847 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2848 options::OPT_ccc_arcmt_modify,
2849 options::OPT_ccc_arcmt_migrate)) {
2850 ARCMTEnabled = true;
2851 switch (A->getOption().getID()) {
2853 llvm_unreachable("missed a case");
2854 case options::OPT_ccc_arcmt_check:
2855 CmdArgs.push_back("-arcmt-check");
2857 case options::OPT_ccc_arcmt_modify:
2858 CmdArgs.push_back("-arcmt-modify");
2860 case options::OPT_ccc_arcmt_migrate:
2861 CmdArgs.push_back("-arcmt-migrate");
2862 CmdArgs.push_back("-mt-migrate-directory");
2863 CmdArgs.push_back(A->getValue());
2865 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2866 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2871 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2872 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2873 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2876 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2878 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
2879 << "-ccc-arcmt-migrate";
2881 CmdArgs.push_back("-mt-migrate-directory");
2882 CmdArgs.push_back(A->getValue());
2884 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2885 options::OPT_objcmt_migrate_subscripting,
2886 options::OPT_objcmt_migrate_property)) {
2887 // None specified, means enable them all.
2888 CmdArgs.push_back("-objcmt-migrate-literals");
2889 CmdArgs.push_back("-objcmt-migrate-subscripting");
2890 CmdArgs.push_back("-objcmt-migrate-property");
2892 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2893 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2894 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2897 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2898 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2899 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2900 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2901 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2902 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2903 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2904 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2905 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2906 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2907 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2908 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2909 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2910 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2911 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2912 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2915 // Add preprocessing options like -I, -D, etc. if we are using the
2918 // FIXME: Support -fpreprocessed
2919 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2920 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
2922 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2923 // that "The compiler can only warn and ignore the option if not recognized".
2924 // When building with ccache, it will pass -D options to clang even on
2925 // preprocessed inputs and configure concludes that -fPIC is not supported.
2926 Args.ClaimAllArgs(options::OPT_D);
2928 // Manually translate -O4 to -O3; let clang reject others.
2929 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2930 if (A->getOption().matches(options::OPT_O4)) {
2931 CmdArgs.push_back("-O3");
2932 D.Diag(diag::warn_O4_is_O3);
2934 A->render(Args, CmdArgs);
2938 // Warn about ignored options to clang.
2940 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
2941 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
2945 claimNoWarnArgs(Args);
2947 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
2949 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
2950 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
2951 CmdArgs.push_back("-pedantic");
2952 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
2953 Args.AddLastArg(CmdArgs, options::OPT_w);
2955 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
2956 // (-ansi is equivalent to -std=c89 or -std=c++98).
2958 // If a std is supplied, only add -trigraphs if it follows the
2960 bool ImplyVCPPCXXVer = false;
2961 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2962 if (Std->getOption().matches(options::OPT_ansi))
2963 if (types::isCXX(InputType))
2964 CmdArgs.push_back("-std=c++98");
2966 CmdArgs.push_back("-std=c89");
2968 Std->render(Args, CmdArgs);
2970 // If -f(no-)trigraphs appears after the language standard flag, honor it.
2971 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
2972 options::OPT_ftrigraphs,
2973 options::OPT_fno_trigraphs))
2975 A->render(Args, CmdArgs);
2977 // Honor -std-default.
2979 // FIXME: Clang doesn't correctly handle -std= when the input language
2980 // doesn't match. For the time being just ignore this for C++ inputs;
2981 // eventually we want to do all the standard defaulting here instead of
2982 // splitting it between the driver and clang -cc1.
2983 if (!types::isCXX(InputType))
2984 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
2986 else if (IsWindowsMSVC)
2987 ImplyVCPPCXXVer = true;
2989 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
2990 options::OPT_fno_trigraphs);
2993 // GCC's behavior for -Wwrite-strings is a bit strange:
2994 // * In C, this "warning flag" changes the types of string literals from
2995 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
2996 // for the discarded qualifier.
2997 // * In C++, this is just a normal warning flag.
2999 // Implementing this warning correctly in C is hard, so we follow GCC's
3000 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3001 // a non-const char* in C, rather than using this crude hack.
3002 if (!types::isCXX(InputType)) {
3003 // FIXME: This should behave just like a warning flag, and thus should also
3004 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3006 Args.getLastArg(options::OPT_Wwrite_strings,
3007 options::OPT_Wno_write_strings, options::OPT_w);
3009 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3010 CmdArgs.push_back("-fconst-strings");
3013 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3014 // during C++ compilation, which it is by default. GCC keeps this define even
3015 // in the presence of '-w', match this behavior bug-for-bug.
3016 if (types::isCXX(InputType) &&
3017 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3019 CmdArgs.push_back("-fdeprecated-macro");
3022 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3023 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3024 if (Asm->getOption().matches(options::OPT_fasm))
3025 CmdArgs.push_back("-fgnu-keywords");
3027 CmdArgs.push_back("-fno-gnu-keywords");
3030 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3031 CmdArgs.push_back("-fno-dwarf-directory-asm");
3033 if (ShouldDisableAutolink(Args, getToolChain()))
3034 CmdArgs.push_back("-fno-autolink");
3036 // Add in -fdebug-compilation-dir if necessary.
3037 addDebugCompDirArg(Args, CmdArgs);
3039 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3040 StringRef Map = A->getValue();
3041 if (Map.find('=') == StringRef::npos)
3042 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3044 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3048 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3049 options::OPT_ftemplate_depth_EQ)) {
3050 CmdArgs.push_back("-ftemplate-depth");
3051 CmdArgs.push_back(A->getValue());
3054 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3055 CmdArgs.push_back("-foperator-arrow-depth");
3056 CmdArgs.push_back(A->getValue());
3059 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3060 CmdArgs.push_back("-fconstexpr-depth");
3061 CmdArgs.push_back(A->getValue());
3064 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3065 CmdArgs.push_back("-fconstexpr-steps");
3066 CmdArgs.push_back(A->getValue());
3069 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3070 CmdArgs.push_back("-fbracket-depth");
3071 CmdArgs.push_back(A->getValue());
3074 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3075 options::OPT_Wlarge_by_value_copy_def)) {
3076 if (A->getNumValues()) {
3077 StringRef bytes = A->getValue();
3078 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3080 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3083 if (Args.hasArg(options::OPT_relocatable_pch))
3084 CmdArgs.push_back("-relocatable-pch");
3086 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3087 CmdArgs.push_back("-fconstant-string-class");
3088 CmdArgs.push_back(A->getValue());
3091 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3092 CmdArgs.push_back("-ftabstop");
3093 CmdArgs.push_back(A->getValue());
3096 CmdArgs.push_back("-ferror-limit");
3097 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3098 CmdArgs.push_back(A->getValue());
3100 CmdArgs.push_back("19");
3102 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3103 CmdArgs.push_back("-fmacro-backtrace-limit");
3104 CmdArgs.push_back(A->getValue());
3107 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3108 CmdArgs.push_back("-ftemplate-backtrace-limit");
3109 CmdArgs.push_back(A->getValue());
3112 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3113 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3114 CmdArgs.push_back(A->getValue());
3117 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3118 CmdArgs.push_back("-fspell-checking-limit");
3119 CmdArgs.push_back(A->getValue());
3122 // Pass -fmessage-length=.
3123 CmdArgs.push_back("-fmessage-length");
3124 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3125 CmdArgs.push_back(A->getValue());
3127 // If -fmessage-length=N was not specified, determine whether this is a
3128 // terminal and, if so, implicitly define -fmessage-length appropriately.
3129 unsigned N = llvm::sys::Process::StandardErrColumns();
3130 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3133 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3134 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3135 options::OPT_fvisibility_ms_compat)) {
3136 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3137 CmdArgs.push_back("-fvisibility");
3138 CmdArgs.push_back(A->getValue());
3140 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3141 CmdArgs.push_back("-fvisibility");
3142 CmdArgs.push_back("hidden");
3143 CmdArgs.push_back("-ftype-visibility");
3144 CmdArgs.push_back("default");
3148 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3150 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3152 // -fhosted is default.
3153 bool IsHosted = true;
3154 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3156 CmdArgs.push_back("-ffreestanding");
3160 // Forward -f (flag) options which we can pass directly.
3161 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3162 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3163 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3164 // Emulated TLS is enabled by default on Android, and can be enabled manually
3165 // with -femulated-tls.
3166 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
3167 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
3168 EmulatedTLSDefault))
3169 CmdArgs.push_back("-femulated-tls");
3170 // AltiVec-like language extensions aren't relevant for assembling.
3171 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
3172 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
3174 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3175 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3177 // Forward flags for OpenMP. We don't do this if the current action is an
3178 // device offloading action other than OpenMP.
3179 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3180 options::OPT_fno_openmp, false) &&
3181 (JA.isDeviceOffloading(Action::OFK_None) ||
3182 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
3183 switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
3184 case Driver::OMPRT_OMP:
3185 case Driver::OMPRT_IOMP5:
3186 // Clang can generate useful OpenMP code for these two runtime libraries.
3187 CmdArgs.push_back("-fopenmp");
3189 // If no option regarding the use of TLS in OpenMP codegeneration is
3190 // given, decide a default based on the target. Otherwise rely on the
3191 // options and pass the right information to the frontend.
3192 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3193 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3194 CmdArgs.push_back("-fnoopenmp-use-tls");
3195 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
3198 // By default, if Clang doesn't know how to generate useful OpenMP code
3199 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3200 // down to the actual compilation.
3201 // FIXME: It would be better to have a mode which *only* omits IR
3202 // generation based on the OpenMP support so that we get consistent
3203 // semantic analysis, etc.
3208 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3209 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3211 const XRayArgs &XRay = getToolChain().getXRayArgs();
3212 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
3214 if (getToolChain().SupportsProfiling())
3215 Args.AddLastArg(CmdArgs, options::OPT_pg);
3217 if (getToolChain().SupportsProfiling())
3218 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
3220 // -flax-vector-conversions is default.
3221 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3222 options::OPT_fno_lax_vector_conversions))
3223 CmdArgs.push_back("-fno-lax-vector-conversions");
3225 if (Args.getLastArg(options::OPT_fapple_kext) ||
3226 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
3227 CmdArgs.push_back("-fapple-kext");
3229 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3230 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3231 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3232 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3233 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3235 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3236 CmdArgs.push_back("-ftrapv-handler");
3237 CmdArgs.push_back(A->getValue());
3240 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3242 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3243 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3244 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3245 if (A->getOption().matches(options::OPT_fwrapv))
3246 CmdArgs.push_back("-fwrapv");
3247 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3248 options::OPT_fno_strict_overflow)) {
3249 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3250 CmdArgs.push_back("-fwrapv");
3253 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3254 options::OPT_fno_reroll_loops))
3255 if (A->getOption().matches(options::OPT_freroll_loops))
3256 CmdArgs.push_back("-freroll-loops");
3258 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3259 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3260 options::OPT_fno_unroll_loops);
3262 Args.AddLastArg(CmdArgs, options::OPT_pthread);
3264 // -stack-protector=0 is default.
3265 unsigned StackProtectorLevel = 0;
3266 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3267 // doesn't even have a stack!
3268 if (!Triple.isNVPTX()) {
3269 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3270 options::OPT_fstack_protector_all,
3271 options::OPT_fstack_protector_strong,
3272 options::OPT_fstack_protector)) {
3273 if (A->getOption().matches(options::OPT_fstack_protector)) {
3274 StackProtectorLevel = std::max<unsigned>(
3276 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
3277 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3278 StackProtectorLevel = LangOptions::SSPStrong;
3279 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3280 StackProtectorLevel = LangOptions::SSPReq;
3282 StackProtectorLevel =
3283 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3284 // Only use a default stack protector on Darwin in case -ffreestanding
3285 // is not specified.
3286 if (Triple.isOSDarwin() && !IsHosted)
3287 StackProtectorLevel = 0;
3290 if (StackProtectorLevel) {
3291 CmdArgs.push_back("-stack-protector");
3292 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3295 // --param ssp-buffer-size=
3296 for (const Arg *A : Args.filtered(options::OPT__param)) {
3297 StringRef Str(A->getValue());
3298 if (Str.startswith("ssp-buffer-size=")) {
3299 if (StackProtectorLevel) {
3300 CmdArgs.push_back("-stack-protector-buffer-size");
3301 // FIXME: Verify the argument is a valid integer.
3302 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3308 // Translate -mstackrealign
3309 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3311 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3313 if (Args.hasArg(options::OPT_mstack_alignment)) {
3314 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3315 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3318 if (Args.hasArg(options::OPT_mstack_probe_size)) {
3319 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
3322 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
3324 CmdArgs.push_back("-mstack-probe-size=0");
3327 switch (getToolChain().getArch()) {
3328 case llvm::Triple::aarch64:
3329 case llvm::Triple::aarch64_be:
3330 case llvm::Triple::arm:
3331 case llvm::Triple::armeb:
3332 case llvm::Triple::thumb:
3333 case llvm::Triple::thumbeb:
3334 CmdArgs.push_back("-fallow-half-arguments-and-returns");
3341 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3342 options::OPT_mno_restrict_it)) {
3343 if (A->getOption().matches(options::OPT_mrestrict_it)) {
3344 CmdArgs.push_back("-backend-option");
3345 CmdArgs.push_back("-arm-restrict-it");
3347 CmdArgs.push_back("-backend-option");
3348 CmdArgs.push_back("-arm-no-restrict-it");
3350 } else if (Triple.isOSWindows() &&
3351 (Triple.getArch() == llvm::Triple::arm ||
3352 Triple.getArch() == llvm::Triple::thumb)) {
3353 // Windows on ARM expects restricted IT blocks
3354 CmdArgs.push_back("-backend-option");
3355 CmdArgs.push_back("-arm-restrict-it");
3358 // Forward -cl options to -cc1
3359 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
3360 CmdArgs.push_back("-cl-opt-disable");
3362 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
3363 CmdArgs.push_back("-cl-strict-aliasing");
3365 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
3366 CmdArgs.push_back("-cl-single-precision-constant");
3368 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
3369 CmdArgs.push_back("-cl-finite-math-only");
3371 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
3372 CmdArgs.push_back("-cl-kernel-arg-info");
3374 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
3375 CmdArgs.push_back("-cl-unsafe-math-optimizations");
3377 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
3378 CmdArgs.push_back("-cl-fast-relaxed-math");
3380 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
3381 CmdArgs.push_back("-cl-mad-enable");
3383 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
3384 CmdArgs.push_back("-cl-no-signed-zeros");
3386 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3387 std::string CLStdStr = "-cl-std=";
3388 CLStdStr += A->getValue();
3389 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3391 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
3392 CmdArgs.push_back("-cl-denorms-are-zero");
3394 if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
3395 CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
3398 // Forward -f options with positive and negative forms; we translate
3400 if (Arg *A = getLastProfileSampleUseArg(Args)) {
3401 StringRef fname = A->getValue();
3402 if (!llvm::sys::fs::exists(fname))
3403 D.Diag(diag::err_drv_no_such_file) << fname;
3405 A->render(Args, CmdArgs);
3408 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3409 options::OPT_fno_debug_info_for_profiling, false))
3410 CmdArgs.push_back("-fdebug-info-for-profiling");
3412 // -fbuiltin is default unless -mkernel is used.
3414 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3415 !Args.hasArg(options::OPT_mkernel));
3417 CmdArgs.push_back("-fno-builtin");
3419 // -ffreestanding implies -fno-builtin.
3420 if (Args.hasArg(options::OPT_ffreestanding))
3421 UseBuiltins = false;
3423 // Process the -fno-builtin-* options.
3424 for (const auto &Arg : Args) {
3425 const Option &O = Arg->getOption();
3426 if (!O.matches(options::OPT_fno_builtin_))
3430 // If -fno-builtin is specified, then there's no need to pass the option to
3435 StringRef FuncName = Arg->getValue();
3436 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3439 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3440 options::OPT_fno_assume_sane_operator_new))
3441 CmdArgs.push_back("-fno-assume-sane-operator-new");
3443 // -fblocks=0 is default.
3444 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3445 getToolChain().IsBlocksDefault()) ||
3446 (Args.hasArg(options::OPT_fgnu_runtime) &&
3447 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3448 !Args.hasArg(options::OPT_fno_blocks))) {
3449 CmdArgs.push_back("-fblocks");
3451 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
3452 !getToolChain().hasBlocksRuntime())
3453 CmdArgs.push_back("-fblocks-runtime-optional");
3456 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
3458 types::isCXX(InputType)) {
3459 CmdArgs.push_back("-fcoroutines-ts");
3462 // -fmodules enables the use of precompiled modules (off by default).
3463 // Users can pass -fno-cxx-modules to turn off modules support for
3464 // C++/Objective-C++ programs.
3465 bool HaveClangModules = false;
3466 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3467 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3468 options::OPT_fno_cxx_modules, true);
3469 if (AllowedInCXX || !types::isCXX(InputType)) {
3470 CmdArgs.push_back("-fmodules");
3471 HaveClangModules = true;
3475 bool HaveAnyModules = HaveClangModules;
3476 if (Args.hasArg(options::OPT_fmodules_ts)) {
3477 CmdArgs.push_back("-fmodules-ts");
3478 HaveAnyModules = true;
3481 // -fmodule-maps enables implicit reading of module map files. By default,
3482 // this is enabled if we are using Clang's flavor of precompiled modules.
3483 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3484 options::OPT_fno_implicit_module_maps, HaveClangModules)) {
3485 CmdArgs.push_back("-fimplicit-module-maps");
3488 // -fmodules-decluse checks that modules used are declared so (off by
3490 if (Args.hasFlag(options::OPT_fmodules_decluse,
3491 options::OPT_fno_modules_decluse, false)) {
3492 CmdArgs.push_back("-fmodules-decluse");
3495 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3496 // all #included headers are part of modules.
3497 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3498 options::OPT_fno_modules_strict_decluse, false)) {
3499 CmdArgs.push_back("-fmodules-strict-decluse");
3502 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3503 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3504 options::OPT_fno_implicit_modules, HaveClangModules)) {
3506 CmdArgs.push_back("-fno-implicit-modules");
3507 } else if (HaveAnyModules) {
3508 // -fmodule-cache-path specifies where our implicitly-built module files
3509 // should be written.
3510 SmallString<128> Path;
3511 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3512 Path = A->getValue();
3513 if (C.isForDiagnostics()) {
3514 // When generating crash reports, we want to emit the modules along with
3515 // the reproduction sources, so we ignore any provided module path.
3516 Path = Output.getFilename();
3517 llvm::sys::path::replace_extension(Path, ".cache");
3518 llvm::sys::path::append(Path, "modules");
3519 } else if (Path.empty()) {
3520 // No module path was provided: use the default.
3521 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
3522 llvm::sys::path::append(Path, "org.llvm.clang.");
3523 appendUserToPath(Path);
3524 llvm::sys::path::append(Path, "ModuleCache");
3526 const char Arg[] = "-fmodules-cache-path=";
3527 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3528 CmdArgs.push_back(Args.MakeArgString(Path));
3531 if (HaveAnyModules) {
3532 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3533 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path))
3534 CmdArgs.push_back(Args.MakeArgString(
3535 std::string("-fprebuilt-module-path=") + A->getValue()));
3538 // -fmodule-name specifies the module that is currently being built (or
3539 // used for header checking by -fmodule-maps).
3540 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3542 // -fmodule-map-file can be used to specify files containing module
3544 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3546 // -fbuiltin-module-map can be used to load the clang
3547 // builtin headers modulemap file.
3548 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3549 SmallString<128> BuiltinModuleMap(getToolChain().getDriver().ResourceDir);
3550 llvm::sys::path::append(BuiltinModuleMap, "include");
3551 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3552 if (llvm::sys::fs::exists(BuiltinModuleMap)) {
3553 CmdArgs.push_back(Args.MakeArgString("-fmodule-map-file=" +
3558 // -fmodule-file can be used to specify files containing precompiled modules.
3560 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3562 Args.ClaimAllArgs(options::OPT_fmodule_file);
3564 // When building modules and generating crashdumps, we need to dump a module
3565 // dependency VFS alongside the output.
3566 if (HaveClangModules && C.isForDiagnostics()) {
3567 SmallString<128> VFSDir(Output.getFilename());
3568 llvm::sys::path::replace_extension(VFSDir, ".cache");
3569 // Add the cache directory as a temp so the crash diagnostics pick it up.
3570 C.addTempFile(Args.MakeArgString(VFSDir));
3572 llvm::sys::path::append(VFSDir, "vfs");
3573 CmdArgs.push_back("-module-dependency-dir");
3574 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3577 if (HaveClangModules)
3578 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3580 // Pass through all -fmodules-ignore-macro arguments.
3581 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3582 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3583 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3585 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3587 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3588 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3589 D.Diag(diag::err_drv_argument_not_allowed_with)
3590 << A->getAsString(Args) << "-fbuild-session-timestamp";
3592 llvm::sys::fs::file_status Status;
3593 if (llvm::sys::fs::status(A->getValue(), Status))
3594 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3596 Args.MakeArgString("-fbuild-session-timestamp=" +
3597 Twine((uint64_t)Status.getLastModificationTime()
3602 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3603 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3604 options::OPT_fbuild_session_file))
3605 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3607 Args.AddLastArg(CmdArgs,
3608 options::OPT_fmodules_validate_once_per_build_session);
3611 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
3612 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3614 // -faccess-control is default.
3615 if (Args.hasFlag(options::OPT_fno_access_control,
3616 options::OPT_faccess_control, false))
3617 CmdArgs.push_back("-fno-access-control");
3619 // -felide-constructors is the default.
3620 if (Args.hasFlag(options::OPT_fno_elide_constructors,
3621 options::OPT_felide_constructors, false))
3622 CmdArgs.push_back("-fno-elide-constructors");
3624 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
3626 if (KernelOrKext || (types::isCXX(InputType) &&
3627 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
3628 RTTIMode == ToolChain::RM_DisabledImplicitly)))
3629 CmdArgs.push_back("-fno-rtti");
3631 // -fshort-enums=0 is default for all architectures except Hexagon.
3632 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
3633 getToolChain().getArch() == llvm::Triple::hexagon))
3634 CmdArgs.push_back("-fshort-enums");
3636 // -fsigned-char is default.
3637 if (Arg *A = Args.getLastArg(
3638 options::OPT_fsigned_char, options::OPT_fno_signed_char,
3639 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
3640 if (A->getOption().matches(options::OPT_funsigned_char) ||
3641 A->getOption().matches(options::OPT_fno_signed_char)) {
3642 CmdArgs.push_back("-fno-signed-char");
3644 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
3645 CmdArgs.push_back("-fno-signed-char");
3648 // -fuse-cxa-atexit is default.
3650 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
3651 !IsWindowsCygnus && !IsWindowsGNU &&
3652 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
3653 getToolChain().getArch() != llvm::Triple::hexagon &&
3654 getToolChain().getArch() != llvm::Triple::xcore &&
3655 ((getToolChain().getTriple().getVendor() !=
3656 llvm::Triple::MipsTechnologies) ||
3657 getToolChain().getTriple().hasEnvironment())) ||
3659 CmdArgs.push_back("-fno-use-cxa-atexit");
3661 // -fms-extensions=0 is default.
3662 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3664 CmdArgs.push_back("-fms-extensions");
3666 // -fno-use-line-directives is default.
3667 if (Args.hasFlag(options::OPT_fuse_line_directives,
3668 options::OPT_fno_use_line_directives, false))
3669 CmdArgs.push_back("-fuse-line-directives");
3671 // -fms-compatibility=0 is default.
3672 if (Args.hasFlag(options::OPT_fms_compatibility,
3673 options::OPT_fno_ms_compatibility,
3675 Args.hasFlag(options::OPT_fms_extensions,
3676 options::OPT_fno_ms_extensions, true))))
3677 CmdArgs.push_back("-fms-compatibility");
3680 getToolChain().computeMSVCVersion(&getToolChain().getDriver(), Args);
3683 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
3685 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
3686 if (ImplyVCPPCXXVer) {
3687 StringRef LanguageStandard;
3688 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
3689 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
3690 .Case("c++14", "-std=c++14")
3691 .Case("c++latest", "-std=c++1z")
3693 if (LanguageStandard.empty())
3694 D.Diag(clang::diag::warn_drv_unused_argument)
3695 << StdArg->getAsString(Args);
3698 if (LanguageStandard.empty()) {
3699 if (IsMSVC2015Compatible)
3700 LanguageStandard = "-std=c++14";
3702 LanguageStandard = "-std=c++11";
3705 CmdArgs.push_back(LanguageStandard.data());
3708 // -fno-borland-extensions is default.
3709 if (Args.hasFlag(options::OPT_fborland_extensions,
3710 options::OPT_fno_borland_extensions, false))
3711 CmdArgs.push_back("-fborland-extensions");
3713 // -fno-declspec is default, except for PS4.
3714 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
3715 getToolChain().getTriple().isPS4()))
3716 CmdArgs.push_back("-fdeclspec");
3717 else if (Args.hasArg(options::OPT_fno_declspec))
3718 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
3720 // -fthreadsafe-static is default, except for MSVC compatibility versions less
3722 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3723 options::OPT_fno_threadsafe_statics,
3724 !IsWindowsMSVC || IsMSVC2015Compatible))
3725 CmdArgs.push_back("-fno-threadsafe-statics");
3727 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
3729 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
3730 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
3731 CmdArgs.push_back("-fdelayed-template-parsing");
3733 // -fgnu-keywords default varies depending on language; only pass if
3735 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3736 options::OPT_fno_gnu_keywords))
3737 A->render(Args, CmdArgs);
3739 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
3741 CmdArgs.push_back("-fgnu89-inline");
3743 if (Args.hasArg(options::OPT_fno_inline))
3744 CmdArgs.push_back("-fno-inline");
3746 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
3747 options::OPT_finline_hint_functions,
3748 options::OPT_fno_inline_functions))
3749 InlineArg->render(Args, CmdArgs);
3751 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
3752 options::OPT_fno_experimental_new_pass_manager);
3754 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3756 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3757 // legacy is the default. Except for deployment target of 10.5,
3758 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
3759 // gets ignored silently.
3760 if (objcRuntime.isNonFragile()) {
3761 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3762 options::OPT_fno_objc_legacy_dispatch,
3763 objcRuntime.isLegacyDispatchDefaultForArch(
3764 getToolChain().getArch()))) {
3765 if (getToolChain().UseObjCMixedDispatch())
3766 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3768 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3772 // When ObjectiveC legacy runtime is in effect on MacOSX,
3773 // turn on the option to do Array/Dictionary subscripting
3775 if (getToolChain().getArch() == llvm::Triple::x86 &&
3776 getToolChain().getTriple().isMacOSX() &&
3777 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
3778 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
3779 objcRuntime.isNeXTFamily())
3780 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3782 // -fencode-extended-block-signature=1 is default.
3783 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3784 CmdArgs.push_back("-fencode-extended-block-signature");
3787 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3788 // NOTE: This logic is duplicated in ToolChains.cpp.
3789 bool ARC = isObjCAutoRefCount(Args);
3791 getToolChain().CheckObjCARC();
3793 CmdArgs.push_back("-fobjc-arc");
3795 // FIXME: It seems like this entire block, and several around it should be
3796 // wrapped in isObjC, but for now we just use it here as this is where it
3797 // was being used previously.
3798 if (types::isCXX(InputType) && types::isObjC(InputType)) {
3799 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3800 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3802 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3805 // Allow the user to enable full exceptions code emission.
3806 // We define off for Objective-CC, on for Objective-C++.
3807 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3808 options::OPT_fno_objc_arc_exceptions,
3809 /*default*/ types::isCXX(InputType)))
3810 CmdArgs.push_back("-fobjc-arc-exceptions");
3813 // Silence warning for full exception code emission options when explicitly
3814 // set to use no ARC.
3815 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3816 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3817 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3820 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3822 if (rewriteKind != RK_None)
3823 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3825 // Pass down -fobjc-weak or -fno-objc-weak if present.
3826 if (types::isObjC(InputType)) {
3827 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
3828 options::OPT_fno_objc_weak);
3831 } else if (!objcRuntime.allowsWeak()) {
3832 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3833 D.Diag(diag::err_objc_weak_unsupported);
3835 WeakArg->render(Args, CmdArgs);
3839 if (Args.hasFlag(options::OPT_fapplication_extension,
3840 options::OPT_fno_application_extension, false))
3841 CmdArgs.push_back("-fapplication-extension");
3843 // Handle GCC-style exception args.
3844 if (!C.getDriver().IsCLMode())
3845 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
3848 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
3849 getToolChain().UseSjLjExceptions(Args))
3850 CmdArgs.push_back("-fsjlj-exceptions");
3852 // C++ "sane" operator new.
3853 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3854 options::OPT_fno_assume_sane_operator_new))
3855 CmdArgs.push_back("-fno-assume-sane-operator-new");
3857 // -frelaxed-template-template-args is off by default, as it is a severe
3858 // breaking change until a corresponding change to template partial ordering
3860 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
3861 options::OPT_fno_relaxed_template_template_args, false))
3862 CmdArgs.push_back("-frelaxed-template-template-args");
3864 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
3866 if (Args.hasFlag(options::OPT_fsized_deallocation,
3867 options::OPT_fno_sized_deallocation, false))
3868 CmdArgs.push_back("-fsized-deallocation");
3870 // -faligned-allocation is on by default in C++17 onwards and otherwise off
3872 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
3873 options::OPT_fno_aligned_allocation,
3874 options::OPT_faligned_new_EQ)) {
3875 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
3876 CmdArgs.push_back("-fno-aligned-allocation");
3878 CmdArgs.push_back("-faligned-allocation");
3881 // The default new alignment can be specified using a dedicated option or via
3882 // a GCC-compatible option that also turns on aligned allocation.
3883 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
3884 options::OPT_faligned_new_EQ))
3886 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
3888 // -fconstant-cfstrings is default, and may be subject to argument translation
3890 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
3891 options::OPT_fno_constant_cfstrings) ||
3892 !Args.hasFlag(options::OPT_mconstant_cfstrings,
3893 options::OPT_mno_constant_cfstrings))
3894 CmdArgs.push_back("-fno-constant-cfstrings");
3896 // -fshort-wchar default varies depending on platform; only
3897 // pass if specified.
3898 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3899 options::OPT_fno_short_wchar))
3900 A->render(Args, CmdArgs);
3902 // -fno-pascal-strings is default, only pass non-default.
3903 if (Args.hasFlag(options::OPT_fpascal_strings,
3904 options::OPT_fno_pascal_strings, false))
3905 CmdArgs.push_back("-fpascal-strings");
3907 // Honor -fpack-struct= and -fpack-struct, if given. Note that
3908 // -fno-pack-struct doesn't apply to -fpack-struct=.
3909 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
3910 std::string PackStructStr = "-fpack-struct=";
3911 PackStructStr += A->getValue();
3912 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
3913 } else if (Args.hasFlag(options::OPT_fpack_struct,
3914 options::OPT_fno_pack_struct, false)) {
3915 CmdArgs.push_back("-fpack-struct=1");
3918 // Handle -fmax-type-align=N and -fno-type-align
3919 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
3920 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
3921 if (!SkipMaxTypeAlign) {
3922 std::string MaxTypeAlignStr = "-fmax-type-align=";
3923 MaxTypeAlignStr += A->getValue();
3924 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
3926 } else if (getToolChain().getTriple().isOSDarwin()) {
3927 if (!SkipMaxTypeAlign) {
3928 std::string MaxTypeAlignStr = "-fmax-type-align=16";
3929 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
3933 // -fcommon is the default unless compiling kernel code or the target says so
3934 bool NoCommonDefault =
3935 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
3936 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
3938 CmdArgs.push_back("-fno-common");
3940 // -fsigned-bitfields is default, and clang doesn't yet support
3941 // -funsigned-bitfields.
3942 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
3943 options::OPT_funsigned_bitfields))
3944 D.Diag(diag::warn_drv_clang_unsupported)
3945 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
3947 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
3948 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
3949 D.Diag(diag::err_drv_clang_unsupported)
3950 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
3952 // -finput_charset=UTF-8 is default. Reject others
3953 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
3954 StringRef value = inputCharset->getValue();
3955 if (!value.equals_lower("utf-8"))
3956 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
3960 // -fexec_charset=UTF-8 is default. Reject others
3961 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
3962 StringRef value = execCharset->getValue();
3963 if (!value.equals_lower("utf-8"))
3964 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
3968 // -fcaret-diagnostics is default.
3969 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3970 options::OPT_fno_caret_diagnostics, true))
3971 CmdArgs.push_back("-fno-caret-diagnostics");
3973 // -fdiagnostics-fixit-info is default, only pass non-default.
3974 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3975 options::OPT_fno_diagnostics_fixit_info))
3976 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3978 // Enable -fdiagnostics-show-option by default.
3979 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3980 options::OPT_fno_diagnostics_show_option))
3981 CmdArgs.push_back("-fdiagnostics-show-option");
3984 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3985 CmdArgs.push_back("-fdiagnostics-show-category");
3986 CmdArgs.push_back(A->getValue());
3989 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3990 options::OPT_fno_diagnostics_show_hotness, false))
3991 CmdArgs.push_back("-fdiagnostics-show-hotness");
3993 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3994 CmdArgs.push_back("-fdiagnostics-format");
3995 CmdArgs.push_back(A->getValue());
3998 if (Arg *A = Args.getLastArg(
3999 options::OPT_fdiagnostics_show_note_include_stack,
4000 options::OPT_fno_diagnostics_show_note_include_stack)) {
4001 if (A->getOption().matches(
4002 options::OPT_fdiagnostics_show_note_include_stack))
4003 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4005 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4008 // Color diagnostics are parsed by the driver directly from argv
4009 // and later re-parsed to construct this job; claim any possible
4010 // color diagnostic here to avoid warn_drv_unused_argument and
4011 // diagnose bad OPT_fdiagnostics_color_EQ values.
4012 for (Arg *A : Args) {
4013 const Option &O = A->getOption();
4014 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4015 !O.matches(options::OPT_fdiagnostics_color) &&
4016 !O.matches(options::OPT_fno_color_diagnostics) &&
4017 !O.matches(options::OPT_fno_diagnostics_color) &&
4018 !O.matches(options::OPT_fdiagnostics_color_EQ))
4020 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
4021 StringRef Value(A->getValue());
4022 if (Value != "always" && Value != "never" && Value != "auto")
4023 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4024 << ("-fdiagnostics-color=" + Value).str();
4028 if (D.getDiags().getDiagnosticOptions().ShowColors)
4029 CmdArgs.push_back("-fcolor-diagnostics");
4031 if (Args.hasArg(options::OPT_fansi_escape_codes))
4032 CmdArgs.push_back("-fansi-escape-codes");
4034 if (!Args.hasFlag(options::OPT_fshow_source_location,
4035 options::OPT_fno_show_source_location))
4036 CmdArgs.push_back("-fno-show-source-location");
4038 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4039 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4041 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4043 CmdArgs.push_back("-fno-show-column");
4045 if (!Args.hasFlag(options::OPT_fspell_checking,
4046 options::OPT_fno_spell_checking))
4047 CmdArgs.push_back("-fno-spell-checking");
4049 // -fno-asm-blocks is default.
4050 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4052 CmdArgs.push_back("-fasm-blocks");
4054 // -fgnu-inline-asm is default.
4055 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4056 options::OPT_fno_gnu_inline_asm, true))
4057 CmdArgs.push_back("-fno-gnu-inline-asm");
4059 // Enable vectorization per default according to the optimization level
4060 // selected. For optimization levels that want vectorization we use the alias
4061 // option to simplify the hasFlag logic.
4062 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4063 OptSpecifier VectorizeAliasOption =
4064 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4065 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4066 options::OPT_fno_vectorize, EnableVec))
4067 CmdArgs.push_back("-vectorize-loops");
4069 // -fslp-vectorize is enabled based on the optimization level selected.
4070 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4071 OptSpecifier SLPVectAliasOption =
4072 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4073 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4074 options::OPT_fno_slp_vectorize, EnableSLPVec))
4075 CmdArgs.push_back("-vectorize-slp");
4077 // -fno-slp-vectorize-aggressive is default.
4078 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4079 options::OPT_fno_slp_vectorize_aggressive, false))
4080 CmdArgs.push_back("-vectorize-slp-aggressive");
4082 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4083 A->render(Args, CmdArgs);
4085 if (Arg *A = Args.getLastArg(
4086 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4087 A->render(Args, CmdArgs);
4089 // -fdollars-in-identifiers default varies depending on platform and
4090 // language; only pass if specified.
4091 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4092 options::OPT_fno_dollars_in_identifiers)) {
4093 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4094 CmdArgs.push_back("-fdollars-in-identifiers");
4096 CmdArgs.push_back("-fno-dollars-in-identifiers");
4099 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4100 // practical purposes.
4101 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4102 options::OPT_fno_unit_at_a_time)) {
4103 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4104 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4107 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4108 options::OPT_fno_apple_pragma_pack, false))
4109 CmdArgs.push_back("-fapple-pragma-pack");
4111 // le32-specific flags:
4112 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4114 if (getToolChain().getArch() == llvm::Triple::le32) {
4115 CmdArgs.push_back("-fno-math-builtin");
4118 if (Args.hasFlag(options::OPT_fsave_optimization_record,
4119 options::OPT_fno_save_optimization_record, false)) {
4120 CmdArgs.push_back("-opt-record-file");
4122 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4124 CmdArgs.push_back(A->getValue());
4127 if (Output.isFilename() && (Args.hasArg(options::OPT_c) ||
4128 Args.hasArg(options::OPT_S))) {
4129 F = Output.getFilename();
4131 // Use the input filename.
4132 F = llvm::sys::path::stem(Input.getBaseInput());
4134 // If we're compiling for an offload architecture (i.e. a CUDA device),
4135 // we need to make the file name for the device compilation different
4136 // from the host compilation.
4137 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4138 !JA.isDeviceOffloading(Action::OFK_Host)) {
4139 llvm::sys::path::replace_extension(F, "");
4140 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4141 Triple.normalize());
4143 F += JA.getOffloadingArch();
4147 llvm::sys::path::replace_extension(F, "opt.yaml");
4148 CmdArgs.push_back(Args.MakeArgString(F));
4152 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4154 // FIXME: Now that PR4941 has been fixed this can be enabled.
4156 if (getToolChain().getTriple().isOSDarwin() &&
4157 (getToolChain().getArch() == llvm::Triple::arm ||
4158 getToolChain().getArch() == llvm::Triple::thumb)) {
4159 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4160 CmdArgs.push_back("-fno-builtin-strcat");
4161 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4162 CmdArgs.push_back("-fno-builtin-strcpy");
4166 // Enable rewrite includes if the user's asked for it or if we're generating
4168 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4169 // nice to enable this when doing a crashdump for modules as well.
4170 if (Args.hasFlag(options::OPT_frewrite_includes,
4171 options::OPT_fno_rewrite_includes, false) ||
4172 (C.isForDiagnostics() && !HaveAnyModules))
4173 CmdArgs.push_back("-frewrite-includes");
4175 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4176 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4177 options::OPT_traditional_cpp)) {
4178 if (isa<PreprocessJobAction>(JA))
4179 CmdArgs.push_back("-traditional-cpp");
4181 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4184 Args.AddLastArg(CmdArgs, options::OPT_dM);
4185 Args.AddLastArg(CmdArgs, options::OPT_dD);
4187 // Handle serialized diagnostics.
4188 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4189 CmdArgs.push_back("-serialize-diagnostic-file");
4190 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4193 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4194 CmdArgs.push_back("-fretain-comments-from-system-headers");
4196 // Forward -fcomment-block-commands to -cc1.
4197 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4198 // Forward -fparse-all-comments to -cc1.
4199 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4201 // Turn -fplugin=name.so into -load name.so
4202 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4203 CmdArgs.push_back("-load");
4204 CmdArgs.push_back(A->getValue());
4208 // Setup statistics file output.
4209 if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
4210 StringRef SaveStats = A->getValue();
4212 SmallString<128> StatsFile;
4213 bool DoSaveStats = false;
4214 if (SaveStats == "obj") {
4215 if (Output.isFilename()) {
4216 StatsFile.assign(Output.getFilename());
4217 llvm::sys::path::remove_filename(StatsFile);
4220 } else if (SaveStats == "cwd") {
4223 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
4227 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
4228 llvm::sys::path::append(StatsFile, BaseName);
4229 llvm::sys::path::replace_extension(StatsFile, "stats");
4230 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
4235 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4237 // -finclude-default-header flag is for preprocessor,
4238 // do not pass it to other cc1 commands when save-temps is enabled
4239 if (C.getDriver().isSaveTempsEnabled() &&
4240 !isa<PreprocessJobAction>(JA)) {
4241 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4243 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4244 CmdArgs.push_back(Arg->getValue());
4248 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4250 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4253 // We translate this by hand to the -cc1 argument, since nightly test uses
4254 // it and developers have been trained to spell it with -mllvm. Both
4255 // spellings are now deprecated and should be removed.
4256 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4257 CmdArgs.push_back("-disable-llvm-optzns");
4259 A->render(Args, CmdArgs);
4263 // With -save-temps, we want to save the unoptimized bitcode output from the
4264 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4266 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4267 // has slightly different breakdown between stages.
4268 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4269 // pristine IR generated by the frontend. Ideally, a new compile action should
4270 // be added so both IR can be captured.
4271 if (C.getDriver().isSaveTempsEnabled() &&
4272 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4273 isa<CompileJobAction>(JA))
4274 CmdArgs.push_back("-disable-llvm-passes");
4276 if (Output.getType() == types::TY_Dependencies) {
4277 // Handled with other dependency code.
4278 } else if (Output.isFilename()) {
4279 CmdArgs.push_back("-o");
4280 CmdArgs.push_back(Output.getFilename());
4282 assert(Output.isNothing() && "Invalid output.");
4285 addDashXForInput(Args, Input, CmdArgs);
4287 if (Input.isFilename())
4288 CmdArgs.push_back(Input.getFilename());
4290 Input.getInputArg().renderAsInput(Args, CmdArgs);
4292 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4294 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4296 // Optionally embed the -cc1 level arguments into the debug info, for build
4298 // Also record command line arguments into the debug info if
4299 // -grecord-gcc-switches options is set on.
4300 // By default, -gno-record-gcc-switches is set on and no recording.
4301 if (getToolChain().UseDwarfDebugFlags() ||
4302 Args.hasFlag(options::OPT_grecord_gcc_switches,
4303 options::OPT_gno_record_gcc_switches, false)) {
4304 ArgStringList OriginalArgs;
4305 for (const auto &Arg : Args)
4306 Arg->render(Args, OriginalArgs);
4308 SmallString<256> Flags;
4310 for (const char *OriginalArg : OriginalArgs) {
4311 SmallString<128> EscapedArg;
4312 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4314 Flags += EscapedArg;
4316 CmdArgs.push_back("-dwarf-debug-flags");
4317 CmdArgs.push_back(Args.MakeArgString(Flags));
4320 // Add the split debug info name to the command lines here so we
4321 // can propagate it to the backend.
4322 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
4323 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4324 isa<BackendJobAction>(JA));
4325 const char *SplitDwarfOut;
4327 CmdArgs.push_back("-split-dwarf-file");
4328 SplitDwarfOut = SplitDebugName(Args, Input);
4329 CmdArgs.push_back(SplitDwarfOut);
4332 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4333 // Include them with -fcuda-include-gpubinary.
4334 if (IsCuda && Inputs.size() > 1)
4335 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
4336 CmdArgs.push_back("-fcuda-include-gpubinary");
4337 CmdArgs.push_back(I->getFilename());
4340 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4341 // to specify the result of the compile phase on the host, so the meaningful
4342 // device declarations can be identified. Also, -fopenmp-is-device is passed
4343 // along to tell the frontend that it is generating code for a device, so that
4344 // only the relevant declarations are emitted.
4345 if (IsOpenMPDevice && Inputs.size() == 2) {
4346 CmdArgs.push_back("-fopenmp-is-device");
4347 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4348 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4351 // For all the host OpenMP offloading compile jobs we need to pass the targets
4352 // information using -fopenmp-targets= option.
4353 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4354 SmallString<128> TargetInfo("-fopenmp-targets=");
4356 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4357 assert(Tgts && Tgts->getNumValues() &&
4358 "OpenMP offloading has to have targets specified.");
4359 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4362 // We need to get the string from the triple because it may be not exactly
4363 // the same as the one we get directly from the arguments.
4364 llvm::Triple T(Tgts->getValue(i));
4365 TargetInfo += T.getTriple();
4367 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4370 bool WholeProgramVTables =
4371 Args.hasFlag(options::OPT_fwhole_program_vtables,
4372 options::OPT_fno_whole_program_vtables, false);
4373 if (WholeProgramVTables) {
4374 if (!D.isUsingLTO())
4375 D.Diag(diag::err_drv_argument_only_allowed_with)
4376 << "-fwhole-program-vtables"
4378 CmdArgs.push_back("-fwhole-program-vtables");
4381 // Finally add the compile command to the compilation.
4382 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4383 Output.getType() == types::TY_Object &&
4384 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4386 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4387 C.addCommand(llvm::make_unique<FallbackCommand>(
4388 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4389 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4390 isa<PrecompileJobAction>(JA)) {
4391 // In /fallback builds, run the main compilation even if the pch generation
4392 // fails, so that the main compilation's fallback to cl.exe runs.
4393 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4396 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4399 // Handle the debug info splitting at object creation time if we're
4400 // creating an object.
4401 // TODO: Currently only works on linux with newer objcopy.
4402 if (SplitDwarf && Output.getType() == types::TY_Object)
4403 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4405 if (Arg *A = Args.getLastArg(options::OPT_pg))
4406 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4407 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4408 << A->getAsString(Args);
4410 // Claim some arguments which clang supports automatically.
4412 // -fpch-preprocess is used with gcc to add a special marker in the output to
4413 // include the PCH file. Clang's PTH solution is completely transparent, so we
4414 // do not need to deal with it at all.
4415 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4417 // Claim some arguments which clang doesn't support, but we don't
4418 // care to warn the user about.
4419 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4420 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4422 // Disable warnings for clang -E -emit-llvm foo.c
4423 Args.ClaimAllArgs(options::OPT_emit_llvm);
4426 Clang::Clang(const ToolChain &TC)
4427 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4428 // as it is for other tools. Some operations on a Tool actually test
4429 // whether that tool is Clang based on the Tool's Name as a string.
4430 : Tool("clang", "clang frontend", TC, RF_Full) {}
4434 /// Add options related to the Objective-C runtime/ABI.
4436 /// Returns true if the runtime is non-fragile.
4437 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4438 ArgStringList &cmdArgs,
4439 RewriteKind rewriteKind) const {
4440 // Look for the controlling runtime option.
4442 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4443 options::OPT_fobjc_runtime_EQ);
4445 // Just forward -fobjc-runtime= to the frontend. This supercedes
4446 // options about fragility.
4448 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4449 ObjCRuntime runtime;
4450 StringRef value = runtimeArg->getValue();
4451 if (runtime.tryParse(value)) {
4452 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4456 runtimeArg->render(args, cmdArgs);
4460 // Otherwise, we'll need the ABI "version". Version numbers are
4461 // slightly confusing for historical reasons:
4462 // 1 - Traditional "fragile" ABI
4463 // 2 - Non-fragile ABI, version 1
4464 // 3 - Non-fragile ABI, version 2
4465 unsigned objcABIVersion = 1;
4466 // If -fobjc-abi-version= is present, use that to set the version.
4467 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4468 StringRef value = abiArg->getValue();
4471 else if (value == "2")
4473 else if (value == "3")
4476 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4478 // Otherwise, determine if we are using the non-fragile ABI.
4479 bool nonFragileABIIsDefault =
4480 (rewriteKind == RK_NonFragile ||
4481 (rewriteKind == RK_None &&
4482 getToolChain().IsObjCNonFragileABIDefault()));
4483 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4484 options::OPT_fno_objc_nonfragile_abi,
4485 nonFragileABIIsDefault)) {
4486 // Determine the non-fragile ABI version to use.
4487 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4488 unsigned nonFragileABIVersion = 1;
4490 unsigned nonFragileABIVersion = 2;
4494 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4495 StringRef value = abiArg->getValue();
4497 nonFragileABIVersion = 1;
4498 else if (value == "2")
4499 nonFragileABIVersion = 2;
4501 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4505 objcABIVersion = 1 + nonFragileABIVersion;
4511 // We don't actually care about the ABI version other than whether
4512 // it's non-fragile.
4513 bool isNonFragile = objcABIVersion != 1;
4515 // If we have no runtime argument, ask the toolchain for its default runtime.
4516 // However, the rewriter only really supports the Mac runtime, so assume that.
4517 ObjCRuntime runtime;
4519 switch (rewriteKind) {
4521 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4524 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4527 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4532 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4533 // On Darwin, make this use the default behavior for the toolchain.
4534 if (getToolChain().getTriple().isOSDarwin()) {
4535 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4537 // Otherwise, build for a generic macosx port.
4539 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4544 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4545 // Legacy behaviour is to target the gnustep runtime if we are in
4546 // non-fragile mode or the GCC runtime in fragile mode.
4548 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4550 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4554 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4558 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4559 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4567 bool Asynch = false;
4568 bool NoUnwindC = false;
4570 } // end anonymous namespace
4572 /// /EH controls whether to run destructor cleanups when exceptions are
4573 /// thrown. There are three modifiers:
4574 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4575 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4576 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4577 /// - c: Assume that extern "C" functions are implicitly nounwind.
4578 /// The default is /EHs-c-, meaning cleanups are disabled.
4579 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4582 std::vector<std::string> EHArgs =
4583 Args.getAllArgValues(options::OPT__SLASH_EH);
4584 for (auto EHVal : EHArgs) {
4585 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4588 EH.Asynch = maybeConsumeDash(EHVal, I);
4593 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
4596 EH.Synch = maybeConsumeDash(EHVal, I);
4603 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4607 // The /GX, /GX- flags are only processed if there are not /EH flags.
4608 // The default is that /GX is not specified.
4609 if (EHArgs.empty() &&
4610 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
4611 /*default=*/false)) {
4613 EH.NoUnwindC = true;
4619 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
4620 ArgStringList &CmdArgs,
4621 codegenoptions::DebugInfoKind *DebugInfoKind,
4622 bool *EmitCodeView) const {
4623 unsigned RTOptionID = options::OPT__SLASH_MT;
4625 if (Args.hasArg(options::OPT__SLASH_LDd))
4626 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4627 // but defining _DEBUG is sticky.
4628 RTOptionID = options::OPT__SLASH_MTd;
4630 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4631 RTOptionID = A->getOption().getID();
4633 StringRef FlagForCRT;
4634 switch (RTOptionID) {
4635 case options::OPT__SLASH_MD:
4636 if (Args.hasArg(options::OPT__SLASH_LDd))
4637 CmdArgs.push_back("-D_DEBUG");
4638 CmdArgs.push_back("-D_MT");
4639 CmdArgs.push_back("-D_DLL");
4640 FlagForCRT = "--dependent-lib=msvcrt";
4642 case options::OPT__SLASH_MDd:
4643 CmdArgs.push_back("-D_DEBUG");
4644 CmdArgs.push_back("-D_MT");
4645 CmdArgs.push_back("-D_DLL");
4646 FlagForCRT = "--dependent-lib=msvcrtd";
4648 case options::OPT__SLASH_MT:
4649 if (Args.hasArg(options::OPT__SLASH_LDd))
4650 CmdArgs.push_back("-D_DEBUG");
4651 CmdArgs.push_back("-D_MT");
4652 CmdArgs.push_back("-flto-visibility-public-std");
4653 FlagForCRT = "--dependent-lib=libcmt";
4655 case options::OPT__SLASH_MTd:
4656 CmdArgs.push_back("-D_DEBUG");
4657 CmdArgs.push_back("-D_MT");
4658 CmdArgs.push_back("-flto-visibility-public-std");
4659 FlagForCRT = "--dependent-lib=libcmtd";
4662 llvm_unreachable("Unexpected option ID.");
4665 if (Args.hasArg(options::OPT__SLASH_Zl)) {
4666 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4668 CmdArgs.push_back(FlagForCRT.data());
4670 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4671 // users want. The /Za flag to cl.exe turns this off, but it's not
4672 // implemented in clang.
4673 CmdArgs.push_back("--dependent-lib=oldnames");
4676 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4677 // would produce interleaved output, so ignore /showIncludes in such cases.
4678 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
4679 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4680 A->render(Args, CmdArgs);
4682 // This controls whether or not we emit RTTI data for polymorphic types.
4683 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4685 CmdArgs.push_back("-fno-rtti-data");
4687 // This controls whether or not we emit stack-protector instrumentation.
4688 // In MSVC, Buffer Security Check (/GS) is on by default.
4689 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
4690 /*default=*/true)) {
4691 CmdArgs.push_back("-stack-protector");
4692 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
4695 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
4696 if (Arg *DebugInfoArg =
4697 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
4698 options::OPT_gline_tables_only)) {
4699 *EmitCodeView = true;
4700 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
4701 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
4703 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4704 CmdArgs.push_back("-gcodeview");
4706 *EmitCodeView = false;
4709 const Driver &D = getToolChain().getDriver();
4710 EHFlags EH = parseClangCLEHFlags(D, Args);
4711 if (EH.Synch || EH.Asynch) {
4712 if (types::isCXX(InputType))
4713 CmdArgs.push_back("-fcxx-exceptions");
4714 CmdArgs.push_back("-fexceptions");
4716 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
4717 CmdArgs.push_back("-fexternc-nounwind");
4719 // /EP should expand to -E -P.
4720 if (Args.hasArg(options::OPT__SLASH_EP)) {
4721 CmdArgs.push_back("-E");
4722 CmdArgs.push_back("-P");
4725 unsigned VolatileOptionID;
4726 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
4727 getToolChain().getArch() == llvm::Triple::x86)
4728 VolatileOptionID = options::OPT__SLASH_volatile_ms;
4730 VolatileOptionID = options::OPT__SLASH_volatile_iso;
4732 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
4733 VolatileOptionID = A->getOption().getID();
4735 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
4736 CmdArgs.push_back("-fms-volatile");
4738 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
4739 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
4740 if (MostGeneralArg && BestCaseArg)
4741 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4742 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
4744 if (MostGeneralArg) {
4745 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
4746 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
4747 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
4749 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
4750 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
4751 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
4752 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4753 << FirstConflict->getAsString(Args)
4754 << SecondConflict->getAsString(Args);
4757 CmdArgs.push_back("-fms-memptr-rep=single");
4758 else if (MultipleArg)
4759 CmdArgs.push_back("-fms-memptr-rep=multiple");
4761 CmdArgs.push_back("-fms-memptr-rep=virtual");
4764 if (Args.getLastArg(options::OPT__SLASH_Gd))
4765 CmdArgs.push_back("-fdefault-calling-conv=cdecl");
4766 else if (Args.getLastArg(options::OPT__SLASH_Gr))
4767 CmdArgs.push_back("-fdefault-calling-conv=fastcall");
4768 else if (Args.getLastArg(options::OPT__SLASH_Gz))
4769 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4770 else if (Args.getLastArg(options::OPT__SLASH_Gv))
4771 CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
4773 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
4774 A->render(Args, CmdArgs);
4776 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
4777 CmdArgs.push_back("-fdiagnostics-format");
4778 if (Args.hasArg(options::OPT__SLASH_fallback))
4779 CmdArgs.push_back("msvc-fallback");
4781 CmdArgs.push_back("msvc");
4785 visualstudio::Compiler *Clang::getCLFallback() const {
4787 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
4788 return CLFallback.get();
4792 const char *Clang::getBaseInputName(const ArgList &Args,
4793 const InputInfo &Input) {
4794 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
4797 const char *Clang::getBaseInputStem(const ArgList &Args,
4798 const InputInfoList &Inputs) {
4799 const char *Str = getBaseInputName(Args, Inputs[0]);
4801 if (const char *End = strrchr(Str, '.'))
4802 return Args.MakeArgString(std::string(Str, End));
4807 const char *Clang::getDependencyFileName(const ArgList &Args,
4808 const InputInfoList &Inputs) {
4809 // FIXME: Think about this more.
4812 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4813 std::string Str(OutputOpt->getValue());
4814 Res = Str.substr(0, Str.rfind('.'));
4816 Res = getBaseInputStem(Args, Inputs);
4818 return Args.MakeArgString(Res + ".d");
4823 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
4824 ArgStringList &CmdArgs) const {
4827 const llvm::Triple &Triple = getToolChain().getTriple();
4828 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
4830 CmdArgs.push_back("-target-abi");
4831 CmdArgs.push_back(ABIName.data());
4834 void ClangAs::AddX86TargetArgs(const ArgList &Args,
4835 ArgStringList &CmdArgs) const {
4836 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
4837 StringRef Value = A->getValue();
4838 if (Value == "intel" || Value == "att") {
4839 CmdArgs.push_back("-mllvm");
4840 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
4842 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
4843 << A->getOption().getName() << Value;
4848 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
4849 const InputInfo &Output, const InputInfoList &Inputs,
4850 const ArgList &Args,
4851 const char *LinkingOutput) const {
4852 ArgStringList CmdArgs;
4854 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4855 const InputInfo &Input = Inputs[0];
4857 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
4858 const std::string &TripleStr = Triple.getTriple();
4860 // Don't warn about "clang -w -c foo.s"
4861 Args.ClaimAllArgs(options::OPT_w);
4862 // and "clang -emit-llvm -c foo.s"
4863 Args.ClaimAllArgs(options::OPT_emit_llvm);
4865 claimNoWarnArgs(Args);
4867 // Invoke ourselves in -cc1as mode.
4869 // FIXME: Implement custom jobs for internal actions.
4870 CmdArgs.push_back("-cc1as");
4872 // Add the "effective" target triple.
4873 CmdArgs.push_back("-triple");
4874 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4876 // Set the output mode, we currently only expect to be used as a real
4878 CmdArgs.push_back("-filetype");
4879 CmdArgs.push_back("obj");
4881 // Set the main file name, so that debug info works even with
4882 // -save-temps or preprocessed assembly.
4883 CmdArgs.push_back("-main-file-name");
4884 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
4886 // Add the target cpu
4887 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
4889 CmdArgs.push_back("-target-cpu");
4890 CmdArgs.push_back(Args.MakeArgString(CPU));
4893 // Add the target features
4894 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
4896 // Ignore explicit -force_cpusubtype_ALL option.
4897 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4899 // Pass along any -I options so we get proper .include search paths.
4900 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
4902 // Determine the original source input.
4903 const Action *SourceAction = &JA;
4904 while (SourceAction->getKind() != Action::InputClass) {
4905 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4906 SourceAction = SourceAction->getInputs()[0];
4909 // Forward -g and handle debug info related flags, assuming we are dealing
4910 // with an actual assembly file.
4911 bool WantDebug = false;
4912 unsigned DwarfVersion = 0;
4913 Args.ClaimAllArgs(options::OPT_g_Group);
4914 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4915 WantDebug = !A->getOption().matches(options::OPT_g0) &&
4916 !A->getOption().matches(options::OPT_ggdb0);
4918 DwarfVersion = DwarfVersionNum(A->getSpelling());
4920 if (DwarfVersion == 0)
4921 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4923 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4925 if (SourceAction->getType() == types::TY_Asm ||
4926 SourceAction->getType() == types::TY_PP_Asm) {
4927 // You might think that it would be ok to set DebugInfoKind outside of
4928 // the guard for source type, however there is a test which asserts
4929 // that some assembler invocation receives no -debug-info-kind,
4930 // and it's not clear whether that test is just overly restrictive.
4931 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
4932 : codegenoptions::NoDebugInfo);
4933 // Add the -fdebug-compilation-dir flag if needed.
4934 addDebugCompDirArg(Args, CmdArgs);
4936 // Set the AT_producer to the clang version when using the integrated
4937 // assembler on assembly source files.
4938 CmdArgs.push_back("-dwarf-debug-producer");
4939 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
4941 // And pass along -I options
4942 Args.AddAllArgs(CmdArgs, options::OPT_I);
4944 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4945 llvm::DebuggerKind::Default);
4947 // Handle -fPIC et al -- the relocation-model affects the assembler
4948 // for some targets.
4949 llvm::Reloc::Model RelocationModel;
4952 std::tie(RelocationModel, PICLevel, IsPIE) =
4953 ParsePICArgs(getToolChain(), Args);
4955 const char *RMName = RelocationModelName(RelocationModel);
4957 CmdArgs.push_back("-mrelocation-model");
4958 CmdArgs.push_back(RMName);
4961 // Optionally embed the -cc1as level arguments into the debug info, for build
4963 if (getToolChain().UseDwarfDebugFlags()) {
4964 ArgStringList OriginalArgs;
4965 for (const auto &Arg : Args)
4966 Arg->render(Args, OriginalArgs);
4968 SmallString<256> Flags;
4969 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4971 for (const char *OriginalArg : OriginalArgs) {
4972 SmallString<128> EscapedArg;
4973 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4975 Flags += EscapedArg;
4977 CmdArgs.push_back("-dwarf-debug-flags");
4978 CmdArgs.push_back(Args.MakeArgString(Flags));
4981 // FIXME: Add -static support, once we have it.
4983 // Add target specific flags.
4984 switch (getToolChain().getArch()) {
4988 case llvm::Triple::mips:
4989 case llvm::Triple::mipsel:
4990 case llvm::Triple::mips64:
4991 case llvm::Triple::mips64el:
4992 AddMIPSTargetArgs(Args, CmdArgs);
4995 case llvm::Triple::x86:
4996 case llvm::Triple::x86_64:
4997 AddX86TargetArgs(Args, CmdArgs);
5001 // Consume all the warning flags. Usually this would be handled more
5002 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5003 // doesn't handle that so rather than warning about unused flags that are
5004 // actually used, we'll lie by omission instead.
5005 // FIXME: Stop lying and consume only the appropriate driver flags
5006 Args.ClaimAllArgs(options::OPT_W_Group);
5008 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5009 getToolChain().getDriver());
5011 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5013 assert(Output.isFilename() && "Unexpected lipo output.");
5014 CmdArgs.push_back("-o");
5015 CmdArgs.push_back(Output.getFilename());
5017 assert(Input.isFilename() && "Invalid input.");
5018 CmdArgs.push_back(Input.getFilename());
5020 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5021 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5023 // Handle the debug info splitting at object creation time if we're
5024 // creating an object.
5025 // TODO: Currently only works on linux with newer objcopy.
5026 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5027 getToolChain().getTriple().isOSLinux())
5028 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5029 SplitDebugName(Args, Input));
5032 // Begin OffloadBundler
5034 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5035 const InputInfo &Output,
5036 const InputInfoList &Inputs,
5037 const llvm::opt::ArgList &TCArgs,
5038 const char *LinkingOutput) const {
5039 // The version with only one output is expected to refer to a bundling job.
5040 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5042 // The bundling command looks like this:
5043 // clang-offload-bundler -type=bc
5044 // -targets=host-triple,openmp-triple1,openmp-triple2
5045 // -outputs=input_file
5046 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5048 ArgStringList CmdArgs;
5051 CmdArgs.push_back(TCArgs.MakeArgString(
5052 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5054 assert(JA.getInputs().size() == Inputs.size() &&
5055 "Not have inputs for all dependence actions??");
5058 SmallString<128> Triples;
5059 Triples += "-targets=";
5060 for (unsigned I = 0; I < Inputs.size(); ++I) {
5064 Action::OffloadKind CurKind = Action::OFK_Host;
5065 const ToolChain *CurTC = &getToolChain();
5066 const Action *CurDep = JA.getInputs()[I];
5068 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
5069 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
5070 CurKind = A->getOffloadingDeviceKind();
5074 Triples += Action::GetOffloadKindName(CurKind);
5076 Triples += CurTC->getTriple().normalize();
5078 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5080 // Get bundled file command.
5082 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5084 // Get unbundled files command.
5085 SmallString<128> UB;
5087 for (unsigned I = 0; I < Inputs.size(); ++I) {
5090 UB += Inputs[I].getFilename();
5092 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5094 // All the inputs are encoded as commands.
5095 C.addCommand(llvm::make_unique<Command>(
5097 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5101 void OffloadBundler::ConstructJobMultipleOutputs(
5102 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5103 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5104 const char *LinkingOutput) const {
5105 // The version with multiple outputs is expected to refer to a unbundling job.
5106 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5108 // The unbundling command looks like this:
5109 // clang-offload-bundler -type=bc
5110 // -targets=host-triple,openmp-triple1,openmp-triple2
5111 // -inputs=input_file
5112 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5115 ArgStringList CmdArgs;
5117 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5118 InputInfo Input = Inputs.front();
5121 CmdArgs.push_back(TCArgs.MakeArgString(
5122 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5125 SmallString<128> Triples;
5126 Triples += "-targets=";
5127 auto DepInfo = UA.getDependentActionsInfo();
5128 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5132 auto &Dep = DepInfo[I];
5133 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5135 Triples += Dep.DependentToolChain->getTriple().normalize();
5138 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5140 // Get bundled file command.
5142 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5144 // Get unbundled files command.
5145 SmallString<128> UB;
5147 for (unsigned I = 0; I < Outputs.size(); ++I) {
5150 UB += Outputs[I].getFilename();
5152 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5153 CmdArgs.push_back("-unbundle");
5155 // All the inputs are encoded as commands.
5156 C.addCommand(llvm::make_unique<Command>(
5158 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),