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/RISCV.h"
16 #include "Arch/Sparc.h"
17 #include "Arch/SystemZ.h"
20 #include "CommonArgs.h"
22 #include "InputInfo.h"
24 #include "clang/Basic/CharInfo.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Basic/ObjCRuntime.h"
27 #include "clang/Basic/Version.h"
28 #include "clang/Driver/DriverDiagnostic.h"
29 #include "clang/Driver/Options.h"
30 #include "clang/Driver/SanitizerArgs.h"
31 #include "clang/Driver/XRayArgs.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Config/llvm-config.h"
34 #include "llvm/Option/ArgList.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/TargetParser.h"
41 #include "llvm/Support/YAMLParser.h"
44 #include <unistd.h> // For getuid().
47 using namespace clang::driver;
48 using namespace clang::driver::tools;
49 using namespace clang;
50 using namespace llvm::opt;
52 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
54 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
55 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
56 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
57 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
58 << A->getBaseArg().getAsString(Args)
59 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
64 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
65 // In gcc, only ARM checks this, but it seems reasonable to check universally.
66 if (Args.hasArg(options::OPT_static))
68 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
69 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
73 // Add backslashes to escape spaces and other backslashes.
74 // This is used for the space-separated argument list specified with
75 // the -dwarf-debug-flags option.
76 static void EscapeSpacesAndBackslashes(const char *Arg,
77 SmallVectorImpl<char> &Res) {
91 // Quote target names for inclusion in GNU Make dependency files.
92 // Only the characters '$', '#', ' ', '\t' are quoted.
93 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
94 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
98 // Escape the preceding backslashes
99 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
102 // Escape the space/tab
115 Res.push_back(Target[i]);
119 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
120 /// offloading tool chain that is associated with the current action \a JA.
122 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
123 const ToolChain &RegularToolChain,
124 llvm::function_ref<void(const ToolChain &)> Work) {
125 // Apply Work on the current/regular tool chain.
126 Work(RegularToolChain);
128 // Apply Work on all the offloading tool chains associated with the current
130 if (JA.isHostOffloading(Action::OFK_Cuda))
131 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
132 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
134 else if (JA.isHostOffloading(Action::OFK_HIP))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
136 else if (JA.isDeviceOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
139 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
140 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
141 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
143 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
144 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
147 // TODO: Add support for other offloading programming models here.
151 /// This is a helper function for validating the optional refinement step
152 /// parameter in reciprocal argument strings. Return false if there is an error
153 /// parsing the refinement step. Otherwise, return true and set the Position
154 /// of the refinement step in the input string.
155 static bool getRefinementStep(StringRef In, const Driver &D,
156 const Arg &A, size_t &Position) {
157 const char RefinementStepToken = ':';
158 Position = In.find(RefinementStepToken);
159 if (Position != StringRef::npos) {
160 StringRef Option = A.getOption().getName();
161 StringRef RefStep = In.substr(Position + 1);
162 // Allow exactly one numeric character for the additional refinement
163 // step parameter. This is reasonable for all currently-supported
164 // operations and architectures because we would expect that a larger value
165 // of refinement steps would cause the estimate "optimization" to
166 // under-perform the native operation. Also, if the estimate does not
167 // converge quickly, it probably will not ever converge, so further
168 // refinement steps will not produce a better answer.
169 if (RefStep.size() != 1) {
170 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
173 char RefStepChar = RefStep[0];
174 if (RefStepChar < '0' || RefStepChar > '9') {
175 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
182 /// The -mrecip flag requires processing of many optional parameters.
183 static void ParseMRecip(const Driver &D, const ArgList &Args,
184 ArgStringList &OutStrings) {
185 StringRef DisabledPrefixIn = "!";
186 StringRef DisabledPrefixOut = "!";
187 StringRef EnabledPrefixOut = "";
188 StringRef Out = "-mrecip=";
190 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
194 unsigned NumOptions = A->getNumValues();
195 if (NumOptions == 0) {
196 // No option is the same as "all".
197 OutStrings.push_back(Args.MakeArgString(Out + "all"));
201 // Pass through "all", "none", or "default" with an optional refinement step.
202 if (NumOptions == 1) {
203 StringRef Val = A->getValue(0);
205 if (!getRefinementStep(Val, D, *A, RefStepLoc))
207 StringRef ValBase = Val.slice(0, RefStepLoc);
208 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
209 OutStrings.push_back(Args.MakeArgString(Out + Val));
214 // Each reciprocal type may be enabled or disabled individually.
215 // Check each input value for validity, concatenate them all back together,
218 llvm::StringMap<bool> OptionStrings;
219 OptionStrings.insert(std::make_pair("divd", false));
220 OptionStrings.insert(std::make_pair("divf", false));
221 OptionStrings.insert(std::make_pair("vec-divd", false));
222 OptionStrings.insert(std::make_pair("vec-divf", false));
223 OptionStrings.insert(std::make_pair("sqrtd", false));
224 OptionStrings.insert(std::make_pair("sqrtf", false));
225 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
226 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
228 for (unsigned i = 0; i != NumOptions; ++i) {
229 StringRef Val = A->getValue(i);
231 bool IsDisabled = Val.startswith(DisabledPrefixIn);
232 // Ignore the disablement token for string matching.
237 if (!getRefinementStep(Val, D, *A, RefStep))
240 StringRef ValBase = Val.slice(0, RefStep);
241 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
242 if (OptionIter == OptionStrings.end()) {
243 // Try again specifying float suffix.
244 OptionIter = OptionStrings.find(ValBase.str() + 'f');
245 if (OptionIter == OptionStrings.end()) {
246 // The input name did not match any known option string.
247 D.Diag(diag::err_drv_unknown_argument) << Val;
250 // The option was specified without a float or double suffix.
251 // Make sure that the double entry was not already specified.
252 // The float entry will be checked below.
253 if (OptionStrings[ValBase.str() + 'd']) {
254 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
259 if (OptionIter->second == true) {
260 // Duplicate option specified.
261 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
265 // Mark the matched option as found. Do not allow duplicate specifiers.
266 OptionIter->second = true;
268 // If the precision was not specified, also mark the double entry as found.
269 if (ValBase.back() != 'f' && ValBase.back() != 'd')
270 OptionStrings[ValBase.str() + 'd'] = true;
272 // Build the output string.
273 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
274 Out = Args.MakeArgString(Out + Prefix + Val);
275 if (i != NumOptions - 1)
276 Out = Args.MakeArgString(Out + ",");
279 OutStrings.push_back(Args.MakeArgString(Out));
282 /// The -mprefer-vector-width option accepts either a positive integer
283 /// or the string "none".
284 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
285 ArgStringList &CmdArgs) {
286 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
290 StringRef Value = A->getValue();
291 if (Value == "none") {
292 CmdArgs.push_back("-mprefer-vector-width=none");
295 if (Value.getAsInteger(10, Width)) {
296 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
299 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
303 static void getWebAssemblyTargetFeatures(const ArgList &Args,
304 std::vector<StringRef> &Features) {
305 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
308 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
309 const ArgList &Args, ArgStringList &CmdArgs,
311 const Driver &D = TC.getDriver();
312 std::vector<StringRef> Features;
313 switch (Triple.getArch()) {
316 case llvm::Triple::mips:
317 case llvm::Triple::mipsel:
318 case llvm::Triple::mips64:
319 case llvm::Triple::mips64el:
320 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
323 case llvm::Triple::arm:
324 case llvm::Triple::armeb:
325 case llvm::Triple::thumb:
326 case llvm::Triple::thumbeb:
327 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
330 case llvm::Triple::ppc:
331 case llvm::Triple::ppc64:
332 case llvm::Triple::ppc64le:
333 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
335 case llvm::Triple::riscv32:
336 case llvm::Triple::riscv64:
337 riscv::getRISCVTargetFeatures(D, Args, Features);
339 case llvm::Triple::systemz:
340 systemz::getSystemZTargetFeatures(Args, Features);
342 case llvm::Triple::aarch64:
343 case llvm::Triple::aarch64_be:
344 aarch64::getAArch64TargetFeatures(D, Args, Features);
346 case llvm::Triple::x86:
347 case llvm::Triple::x86_64:
348 x86::getX86TargetFeatures(D, Triple, Args, Features);
350 case llvm::Triple::hexagon:
351 hexagon::getHexagonTargetFeatures(D, Args, Features);
353 case llvm::Triple::wasm32:
354 case llvm::Triple::wasm64:
355 getWebAssemblyTargetFeatures(Args, Features);
357 case llvm::Triple::sparc:
358 case llvm::Triple::sparcel:
359 case llvm::Triple::sparcv9:
360 sparc::getSparcTargetFeatures(D, Args, Features);
362 case llvm::Triple::r600:
363 case llvm::Triple::amdgcn:
364 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
368 // Find the last of each feature.
369 llvm::StringMap<unsigned> LastOpt;
370 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
371 StringRef Name = Features[I];
372 assert(Name[0] == '-' || Name[0] == '+');
373 LastOpt[Name.drop_front(1)] = I;
376 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
377 // If this feature was overridden, ignore it.
378 StringRef Name = Features[I];
379 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
380 assert(LastI != LastOpt.end());
381 unsigned Last = LastI->second;
385 CmdArgs.push_back("-target-feature");
386 CmdArgs.push_back(Name.data());
391 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
392 const llvm::Triple &Triple) {
393 // We use the zero-cost exception tables for Objective-C if the non-fragile
394 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
396 if (runtime.isNonFragile())
399 if (!Triple.isMacOSX())
402 return (!Triple.isMacOSXVersionLT(10, 5) &&
403 (Triple.getArch() == llvm::Triple::x86_64 ||
404 Triple.getArch() == llvm::Triple::arm));
407 /// Adds exception related arguments to the driver command arguments. There's a
408 /// master flag, -fexceptions and also language specific flags to enable/disable
409 /// C++ and Objective-C exceptions. This makes it possible to for example
410 /// disable C++ exceptions but enable Objective-C exceptions.
411 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
412 const ToolChain &TC, bool KernelOrKext,
413 const ObjCRuntime &objcRuntime,
414 ArgStringList &CmdArgs) {
415 const llvm::Triple &Triple = TC.getTriple();
418 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
419 // arguments now to avoid warnings about unused arguments.
420 Args.ClaimAllArgs(options::OPT_fexceptions);
421 Args.ClaimAllArgs(options::OPT_fno_exceptions);
422 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
423 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
424 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
425 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
429 // See if the user explicitly enabled exceptions.
430 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
433 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
434 // is not necessarily sensible, but follows GCC.
435 if (types::isObjC(InputType) &&
436 Args.hasFlag(options::OPT_fobjc_exceptions,
437 options::OPT_fno_objc_exceptions, true)) {
438 CmdArgs.push_back("-fobjc-exceptions");
440 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
443 if (types::isCXX(InputType)) {
444 // Disable C++ EH by default on XCore and PS4.
445 bool CXXExceptionsEnabled =
446 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
447 Arg *ExceptionArg = Args.getLastArg(
448 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
449 options::OPT_fexceptions, options::OPT_fno_exceptions);
451 CXXExceptionsEnabled =
452 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
453 ExceptionArg->getOption().matches(options::OPT_fexceptions);
455 if (CXXExceptionsEnabled) {
456 CmdArgs.push_back("-fcxx-exceptions");
463 CmdArgs.push_back("-fexceptions");
466 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
468 if (TC.getTriple().isOSDarwin()) {
469 // The native darwin assembler doesn't support the linker_option directives,
470 // so we disable them if we think the .s file will be passed to it.
471 Default = TC.useIntegratedAs();
473 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
477 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
478 const ToolChain &TC) {
479 bool UseDwarfDirectory =
480 Args.hasFlag(options::OPT_fdwarf_directory_asm,
481 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
482 return !UseDwarfDirectory;
485 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
486 // to the corresponding DebugInfoKind.
487 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
488 assert(A.getOption().matches(options::OPT_gN_Group) &&
489 "Not a -g option that specifies a debug-info level");
490 if (A.getOption().matches(options::OPT_g0) ||
491 A.getOption().matches(options::OPT_ggdb0))
492 return codegenoptions::NoDebugInfo;
493 if (A.getOption().matches(options::OPT_gline_tables_only) ||
494 A.getOption().matches(options::OPT_ggdb1))
495 return codegenoptions::DebugLineTablesOnly;
496 return codegenoptions::LimitedDebugInfo;
499 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
500 switch (Triple.getArch()){
503 case llvm::Triple::arm:
504 case llvm::Triple::thumb:
505 // ARM Darwin targets require a frame pointer to be always present to aid
506 // offline debugging via backtraces.
507 return Triple.isOSDarwin();
511 static bool useFramePointerForTargetByDefault(const ArgList &Args,
512 const llvm::Triple &Triple) {
513 switch (Triple.getArch()) {
514 case llvm::Triple::xcore:
515 case llvm::Triple::wasm32:
516 case llvm::Triple::wasm64:
517 // XCore never wants frame pointers, regardless of OS.
518 // WebAssembly never wants frame pointers.
520 case llvm::Triple::riscv32:
521 case llvm::Triple::riscv64:
522 return !areOptimizationsEnabled(Args);
527 if (Triple.getOS() == llvm::Triple::NetBSD) {
528 return !areOptimizationsEnabled(Args);
531 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
532 switch (Triple.getArch()) {
533 // Don't use a frame pointer on linux if optimizing for certain targets.
534 case llvm::Triple::mips64:
535 case llvm::Triple::mips64el:
536 case llvm::Triple::mips:
537 case llvm::Triple::mipsel:
538 case llvm::Triple::ppc:
539 case llvm::Triple::ppc64:
540 case llvm::Triple::ppc64le:
541 case llvm::Triple::systemz:
542 case llvm::Triple::x86:
543 case llvm::Triple::x86_64:
544 return !areOptimizationsEnabled(Args);
550 if (Triple.isOSWindows()) {
551 switch (Triple.getArch()) {
552 case llvm::Triple::x86:
553 return !areOptimizationsEnabled(Args);
554 case llvm::Triple::x86_64:
555 return Triple.isOSBinFormatMachO();
556 case llvm::Triple::arm:
557 case llvm::Triple::thumb:
558 // Windows on ARM builds with FPO disabled to aid fast stack walking
561 // All other supported Windows ISAs use xdata unwind information, so frame
562 // pointers are not generally useful.
570 static bool shouldUseFramePointer(const ArgList &Args,
571 const llvm::Triple &Triple) {
572 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
573 options::OPT_fomit_frame_pointer))
574 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
575 mustUseNonLeafFramePointerForTarget(Triple);
577 if (Args.hasArg(options::OPT_pg))
580 return useFramePointerForTargetByDefault(Args, Triple);
583 static bool shouldUseLeafFramePointer(const ArgList &Args,
584 const llvm::Triple &Triple) {
585 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
586 options::OPT_momit_leaf_frame_pointer))
587 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
589 if (Args.hasArg(options::OPT_pg))
592 if (Triple.isPS4CPU())
595 return useFramePointerForTargetByDefault(Args, Triple);
598 /// Add a CC1 option to specify the debug compilation directory.
599 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
600 SmallString<128> cwd;
601 if (!llvm::sys::fs::current_path(cwd)) {
602 CmdArgs.push_back("-fdebug-compilation-dir");
603 CmdArgs.push_back(Args.MakeArgString(cwd));
607 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
608 static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
609 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
610 StringRef Map = A->getValue();
611 if (Map.find('=') == StringRef::npos)
612 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
614 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
619 /// Vectorize at all optimization levels greater than 1 except for -Oz.
620 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
621 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
622 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
623 if (A->getOption().matches(options::OPT_O4) ||
624 A->getOption().matches(options::OPT_Ofast))
627 if (A->getOption().matches(options::OPT_O0))
630 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
633 StringRef S(A->getValue());
637 // Don't vectorize -Oz, unless it's the slp vectorizer.
641 unsigned OptLevel = 0;
642 if (S.getAsInteger(10, OptLevel))
651 /// Add -x lang to \p CmdArgs for \p Input.
652 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
653 ArgStringList &CmdArgs) {
654 // When using -verify-pch, we don't want to provide the type
655 // 'precompiled-header' if it was inferred from the file extension
656 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
659 CmdArgs.push_back("-x");
660 if (Args.hasArg(options::OPT_rewrite_objc))
661 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
663 // Map the driver type to the frontend type. This is mostly an identity
664 // mapping, except that the distinction between module interface units
665 // and other source files does not exist at the frontend layer.
666 const char *ClangType;
667 switch (Input.getType()) {
668 case types::TY_CXXModule:
671 case types::TY_PP_CXXModule:
672 ClangType = "c++-cpp-output";
675 ClangType = types::getTypeName(Input.getType());
678 CmdArgs.push_back(ClangType);
682 static void appendUserToPath(SmallVectorImpl<char> &Result) {
684 const char *Username = getenv("LOGNAME");
686 const char *Username = getenv("USERNAME");
689 // Validate that LoginName can be used in a path, and get its length.
691 for (const char *P = Username; *P; ++P, ++Len) {
692 if (!clang::isAlphanumeric(*P) && *P != '_') {
698 if (Username && Len > 0) {
699 Result.append(Username, Username + Len);
704 // Fallback to user id.
706 std::string UID = llvm::utostr(getuid());
708 // FIXME: Windows seems to have an 'SID' that might work.
709 std::string UID = "9999";
711 Result.append(UID.begin(), UID.end());
714 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
715 const InputInfo &Output, const ArgList &Args,
716 ArgStringList &CmdArgs) {
718 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
719 options::OPT_fprofile_generate_EQ,
720 options::OPT_fno_profile_generate);
721 if (PGOGenerateArg &&
722 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
723 PGOGenerateArg = nullptr;
725 auto *ProfileGenerateArg = Args.getLastArg(
726 options::OPT_fprofile_instr_generate,
727 options::OPT_fprofile_instr_generate_EQ,
728 options::OPT_fno_profile_instr_generate);
729 if (ProfileGenerateArg &&
730 ProfileGenerateArg->getOption().matches(
731 options::OPT_fno_profile_instr_generate))
732 ProfileGenerateArg = nullptr;
734 if (PGOGenerateArg && ProfileGenerateArg)
735 D.Diag(diag::err_drv_argument_not_allowed_with)
736 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
738 auto *ProfileUseArg = getLastProfileUseArg(Args);
740 if (PGOGenerateArg && ProfileUseArg)
741 D.Diag(diag::err_drv_argument_not_allowed_with)
742 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
744 if (ProfileGenerateArg && ProfileUseArg)
745 D.Diag(diag::err_drv_argument_not_allowed_with)
746 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
748 if (ProfileGenerateArg) {
749 if (ProfileGenerateArg->getOption().matches(
750 options::OPT_fprofile_instr_generate_EQ))
751 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
752 ProfileGenerateArg->getValue()));
753 // The default is to use Clang Instrumentation.
754 CmdArgs.push_back("-fprofile-instrument=clang");
757 if (PGOGenerateArg) {
758 CmdArgs.push_back("-fprofile-instrument=llvm");
759 if (PGOGenerateArg->getOption().matches(
760 options::OPT_fprofile_generate_EQ)) {
761 SmallString<128> Path(PGOGenerateArg->getValue());
762 llvm::sys::path::append(Path, "default_%m.profraw");
764 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
769 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
770 CmdArgs.push_back(Args.MakeArgString(
771 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
772 else if ((ProfileUseArg->getOption().matches(
773 options::OPT_fprofile_use_EQ) ||
774 ProfileUseArg->getOption().matches(
775 options::OPT_fprofile_instr_use))) {
776 SmallString<128> Path(
777 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
778 if (Path.empty() || llvm::sys::fs::is_directory(Path))
779 llvm::sys::path::append(Path, "default.profdata");
781 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
785 if (Args.hasArg(options::OPT_ftest_coverage) ||
786 Args.hasArg(options::OPT_coverage))
787 CmdArgs.push_back("-femit-coverage-notes");
788 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
790 Args.hasArg(options::OPT_coverage))
791 CmdArgs.push_back("-femit-coverage-data");
793 if (Args.hasFlag(options::OPT_fcoverage_mapping,
794 options::OPT_fno_coverage_mapping, false)) {
795 if (!ProfileGenerateArg)
796 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
797 << "-fcoverage-mapping"
798 << "-fprofile-instr-generate";
800 CmdArgs.push_back("-fcoverage-mapping");
803 if (C.getArgs().hasArg(options::OPT_c) ||
804 C.getArgs().hasArg(options::OPT_S)) {
805 if (Output.isFilename()) {
806 CmdArgs.push_back("-coverage-notes-file");
807 SmallString<128> OutputFilename;
808 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
809 OutputFilename = FinalOutput->getValue();
811 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
812 SmallString<128> CoverageFilename = OutputFilename;
813 if (llvm::sys::path::is_relative(CoverageFilename)) {
814 SmallString<128> Pwd;
815 if (!llvm::sys::fs::current_path(Pwd)) {
816 llvm::sys::path::append(Pwd, CoverageFilename);
817 CoverageFilename.swap(Pwd);
820 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
821 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
823 // Leave -fprofile-dir= an unused argument unless .gcda emission is
824 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
825 // the flag used. There is no -fno-profile-dir, so the user has no
826 // targeted way to suppress the warning.
827 if (Args.hasArg(options::OPT_fprofile_arcs) ||
828 Args.hasArg(options::OPT_coverage)) {
829 CmdArgs.push_back("-coverage-data-file");
830 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
831 CoverageFilename = FProfileDir->getValue();
832 llvm::sys::path::append(CoverageFilename, OutputFilename);
834 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
835 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
841 /// Check whether the given input tree contains any compilation actions.
842 static bool ContainsCompileAction(const Action *A) {
843 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
846 for (const auto &AI : A->inputs())
847 if (ContainsCompileAction(AI))
853 /// Check if -relax-all should be passed to the internal assembler.
854 /// This is done by default when compiling non-assembler source with -O0.
855 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
856 bool RelaxDefault = true;
858 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
859 RelaxDefault = A->getOption().matches(options::OPT_O0);
862 RelaxDefault = false;
863 for (const auto &Act : C.getActions()) {
864 if (ContainsCompileAction(Act)) {
871 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
875 // Extract the integer N from a string spelled "-dwarf-N", returning 0
876 // on mismatch. The StringRef input (rather than an Arg) allows
877 // for use by the "-Xassembler" option parser.
878 static unsigned DwarfVersionNum(StringRef ArgValue) {
879 return llvm::StringSwitch<unsigned>(ArgValue)
880 .Case("-gdwarf-2", 2)
881 .Case("-gdwarf-3", 3)
882 .Case("-gdwarf-4", 4)
883 .Case("-gdwarf-5", 5)
887 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
888 codegenoptions::DebugInfoKind DebugInfoKind,
889 unsigned DwarfVersion,
890 llvm::DebuggerKind DebuggerTuning) {
891 switch (DebugInfoKind) {
892 case codegenoptions::DebugLineTablesOnly:
893 CmdArgs.push_back("-debug-info-kind=line-tables-only");
895 case codegenoptions::LimitedDebugInfo:
896 CmdArgs.push_back("-debug-info-kind=limited");
898 case codegenoptions::FullDebugInfo:
899 CmdArgs.push_back("-debug-info-kind=standalone");
904 if (DwarfVersion > 0)
906 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
907 switch (DebuggerTuning) {
908 case llvm::DebuggerKind::GDB:
909 CmdArgs.push_back("-debugger-tuning=gdb");
911 case llvm::DebuggerKind::LLDB:
912 CmdArgs.push_back("-debugger-tuning=lldb");
914 case llvm::DebuggerKind::SCE:
915 CmdArgs.push_back("-debugger-tuning=sce");
922 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
923 const Driver &D, const ToolChain &TC) {
924 assert(A && "Expected non-nullptr argument.");
925 if (TC.supportsDebugInfoOption(A))
927 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
928 << A->getAsString(Args) << TC.getTripleString();
932 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
933 ArgStringList &CmdArgs,
935 const ToolChain &TC) {
936 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
939 if (checkDebugInfoOption(A, Args, D, TC)) {
940 if (A->getOption().getID() == options::OPT_gz) {
941 if (llvm::zlib::isAvailable())
942 CmdArgs.push_back("-compress-debug-sections");
944 D.Diag(diag::warn_debug_compression_unavailable);
948 StringRef Value = A->getValue();
949 if (Value == "none") {
950 CmdArgs.push_back("-compress-debug-sections=none");
951 } else if (Value == "zlib" || Value == "zlib-gnu") {
952 if (llvm::zlib::isAvailable()) {
954 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
956 D.Diag(diag::warn_debug_compression_unavailable);
959 D.Diag(diag::err_drv_unsupported_option_argument)
960 << A->getOption().getName() << Value;
965 static const char *RelocationModelName(llvm::Reloc::Model Model) {
967 case llvm::Reloc::Static:
969 case llvm::Reloc::PIC_:
971 case llvm::Reloc::DynamicNoPIC:
972 return "dynamic-no-pic";
973 case llvm::Reloc::ROPI:
975 case llvm::Reloc::RWPI:
977 case llvm::Reloc::ROPI_RWPI:
980 llvm_unreachable("Unknown Reloc::Model kind");
983 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
984 const Driver &D, const ArgList &Args,
985 ArgStringList &CmdArgs,
986 const InputInfo &Output,
987 const InputInfoList &Inputs) const {
989 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
991 CheckPreprocessingOptions(D, Args);
993 Args.AddLastArg(CmdArgs, options::OPT_C);
994 Args.AddLastArg(CmdArgs, options::OPT_CC);
996 // Handle dependency file generation.
997 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
998 (A = Args.getLastArg(options::OPT_MD)) ||
999 (A = Args.getLastArg(options::OPT_MMD))) {
1000 // Determine the output location.
1001 const char *DepFile;
1002 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1003 DepFile = MF->getValue();
1004 C.addFailureResultFile(DepFile, &JA);
1005 } else if (Output.getType() == types::TY_Dependencies) {
1006 DepFile = Output.getFilename();
1007 } else if (A->getOption().matches(options::OPT_M) ||
1008 A->getOption().matches(options::OPT_MM)) {
1011 DepFile = getDependencyFileName(Args, Inputs);
1012 C.addFailureResultFile(DepFile, &JA);
1014 CmdArgs.push_back("-dependency-file");
1015 CmdArgs.push_back(DepFile);
1017 // Add a default target if one wasn't specified.
1018 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1019 const char *DepTarget;
1021 // If user provided -o, that is the dependency target, except
1022 // when we are only generating a dependency file.
1023 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1024 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1025 DepTarget = OutputOpt->getValue();
1027 // Otherwise derive from the base input.
1029 // FIXME: This should use the computed output file location.
1030 SmallString<128> P(Inputs[0].getBaseInput());
1031 llvm::sys::path::replace_extension(P, "o");
1032 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1035 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1036 CmdArgs.push_back("-w");
1038 CmdArgs.push_back("-MT");
1039 SmallString<128> Quoted;
1040 QuoteTarget(DepTarget, Quoted);
1041 CmdArgs.push_back(Args.MakeArgString(Quoted));
1044 if (A->getOption().matches(options::OPT_M) ||
1045 A->getOption().matches(options::OPT_MD))
1046 CmdArgs.push_back("-sys-header-deps");
1047 if ((isa<PrecompileJobAction>(JA) &&
1048 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1049 Args.hasArg(options::OPT_fmodule_file_deps))
1050 CmdArgs.push_back("-module-file-deps");
1053 if (Args.hasArg(options::OPT_MG)) {
1054 if (!A || A->getOption().matches(options::OPT_MD) ||
1055 A->getOption().matches(options::OPT_MMD))
1056 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1057 CmdArgs.push_back("-MG");
1060 Args.AddLastArg(CmdArgs, options::OPT_MP);
1061 Args.AddLastArg(CmdArgs, options::OPT_MV);
1063 // Convert all -MQ <target> args to -MT <quoted target>
1064 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1067 if (A->getOption().matches(options::OPT_MQ)) {
1068 CmdArgs.push_back("-MT");
1069 SmallString<128> Quoted;
1070 QuoteTarget(A->getValue(), Quoted);
1071 CmdArgs.push_back(Args.MakeArgString(Quoted));
1073 // -MT flag - no change
1075 A->render(Args, CmdArgs);
1079 // Add offload include arguments specific for CUDA. This must happen before
1080 // we -I or -include anything else, because we must pick up the CUDA headers
1081 // from the particular CUDA installation, rather than from e.g.
1082 // /usr/local/include.
1083 if (JA.isOffloading(Action::OFK_Cuda))
1084 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1086 // Add -i* options, and automatically translate to
1087 // -include-pch/-include-pth for transparent PCH support. It's
1088 // wonky, but we include looking for .gch so we can support seamless
1089 // replacement into a build system already set up to be generating
1092 if (getToolChain().getDriver().IsCLMode()) {
1093 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1094 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1095 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1096 JA.getKind() <= Action::AssembleJobClass) {
1097 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1099 if (YcArg || YuArg) {
1100 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1101 if (!isa<PrecompileJobAction>(JA)) {
1102 CmdArgs.push_back("-include-pch");
1103 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(C, ThroughHeader)));
1106 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1110 bool RenderedImplicitInclude = false;
1111 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1112 if (A->getOption().matches(options::OPT_include)) {
1113 // Handling of gcc-style gch precompiled headers.
1114 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1115 RenderedImplicitInclude = true;
1117 // Use PCH if the user requested it.
1118 bool UsePCH = D.CCCUsePCH;
1120 bool FoundPTH = false;
1121 bool FoundPCH = false;
1122 SmallString<128> P(A->getValue());
1123 // We want the files to have a name like foo.h.pch. Add a dummy extension
1124 // so that replace_extension does the right thing.
1127 llvm::sys::path::replace_extension(P, "pch");
1128 if (llvm::sys::fs::exists(P))
1133 llvm::sys::path::replace_extension(P, "pth");
1134 if (llvm::sys::fs::exists(P))
1138 if (!FoundPCH && !FoundPTH) {
1139 llvm::sys::path::replace_extension(P, "gch");
1140 if (llvm::sys::fs::exists(P)) {
1146 if (FoundPCH || FoundPTH) {
1147 if (IsFirstImplicitInclude) {
1150 CmdArgs.push_back("-include-pch");
1152 CmdArgs.push_back("-include-pth");
1153 CmdArgs.push_back(Args.MakeArgString(P));
1156 // Ignore the PCH if not first on command line and emit warning.
1157 D.Diag(diag::warn_drv_pch_not_first_include) << P
1158 << A->getAsString(Args);
1161 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1162 // Handling of paths which must come late. These entries are handled by
1163 // the toolchain itself after the resource dir is inserted in the right
1165 // Do not claim the argument so that the use of the argument does not
1166 // silently go unnoticed on toolchains which do not honour the option.
1170 // Not translated, render as usual.
1172 A->render(Args, CmdArgs);
1175 Args.AddAllArgs(CmdArgs,
1176 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1177 options::OPT_F, options::OPT_index_header_map});
1179 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1181 // FIXME: There is a very unfortunate problem here, some troubled
1182 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1183 // really support that we would have to parse and then translate
1184 // those options. :(
1185 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1186 options::OPT_Xpreprocessor);
1188 // -I- is a deprecated GCC feature, reject it.
1189 if (Arg *A = Args.getLastArg(options::OPT_I_))
1190 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1192 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1193 // -isysroot to the CC1 invocation.
1194 StringRef sysroot = C.getSysRoot();
1195 if (sysroot != "") {
1196 if (!Args.hasArg(options::OPT_isysroot)) {
1197 CmdArgs.push_back("-isysroot");
1198 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1202 // Parse additional include paths from environment variables.
1203 // FIXME: We should probably sink the logic for handling these from the
1204 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1205 // CPATH - included following the user specified includes (but prior to
1206 // builtin and standard includes).
1207 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1208 // C_INCLUDE_PATH - system includes enabled when compiling C.
1209 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1210 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1211 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1212 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1213 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1214 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1215 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1217 // While adding the include arguments, we also attempt to retrieve the
1218 // arguments of related offloading toolchains or arguments that are specific
1219 // of an offloading programming model.
1221 // Add C++ include arguments, if needed.
1222 if (types::isCXX(Inputs[0].getType()))
1223 forAllAssociatedToolChains(C, JA, getToolChain(),
1224 [&Args, &CmdArgs](const ToolChain &TC) {
1225 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1228 // Add system include arguments for all targets but IAMCU.
1230 forAllAssociatedToolChains(C, JA, getToolChain(),
1231 [&Args, &CmdArgs](const ToolChain &TC) {
1232 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1235 // For IAMCU add special include arguments.
1236 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1240 // FIXME: Move to target hook.
1241 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1242 switch (Triple.getArch()) {
1246 case llvm::Triple::aarch64:
1247 case llvm::Triple::aarch64_be:
1248 case llvm::Triple::arm:
1249 case llvm::Triple::armeb:
1250 case llvm::Triple::thumb:
1251 case llvm::Triple::thumbeb:
1252 if (Triple.isOSDarwin() || Triple.isOSWindows())
1256 case llvm::Triple::ppc:
1257 case llvm::Triple::ppc64:
1258 if (Triple.isOSDarwin())
1262 case llvm::Triple::hexagon:
1263 case llvm::Triple::ppc64le:
1264 case llvm::Triple::riscv32:
1265 case llvm::Triple::riscv64:
1266 case llvm::Triple::systemz:
1267 case llvm::Triple::xcore:
1272 static bool isNoCommonDefault(const llvm::Triple &Triple) {
1273 switch (Triple.getArch()) {
1275 if (Triple.isOSFuchsia())
1279 case llvm::Triple::xcore:
1280 case llvm::Triple::wasm32:
1281 case llvm::Triple::wasm64:
1286 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1287 ArgStringList &CmdArgs, bool KernelOrKext) const {
1288 // Select the ABI to use.
1289 // FIXME: Support -meabi.
1290 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1291 const char *ABIName = nullptr;
1292 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1293 ABIName = A->getValue();
1295 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1296 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
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("-mllvm");
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::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1337 const ArgList &Args, bool KernelOrKext,
1338 ArgStringList &CmdArgs) const {
1339 const ToolChain &TC = getToolChain();
1341 // Add the target features
1342 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1344 // Add target specific flags.
1345 switch (TC.getArch()) {
1349 case llvm::Triple::arm:
1350 case llvm::Triple::armeb:
1351 case llvm::Triple::thumb:
1352 case llvm::Triple::thumbeb:
1353 // Use the effective triple, which takes into account the deployment target.
1354 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1355 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1358 case llvm::Triple::aarch64:
1359 case llvm::Triple::aarch64_be:
1360 AddAArch64TargetArgs(Args, CmdArgs);
1361 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1364 case llvm::Triple::mips:
1365 case llvm::Triple::mipsel:
1366 case llvm::Triple::mips64:
1367 case llvm::Triple::mips64el:
1368 AddMIPSTargetArgs(Args, CmdArgs);
1371 case llvm::Triple::ppc:
1372 case llvm::Triple::ppc64:
1373 case llvm::Triple::ppc64le:
1374 AddPPCTargetArgs(Args, CmdArgs);
1377 case llvm::Triple::riscv32:
1378 case llvm::Triple::riscv64:
1379 AddRISCVTargetArgs(Args, CmdArgs);
1382 case llvm::Triple::sparc:
1383 case llvm::Triple::sparcel:
1384 case llvm::Triple::sparcv9:
1385 AddSparcTargetArgs(Args, CmdArgs);
1388 case llvm::Triple::systemz:
1389 AddSystemZTargetArgs(Args, CmdArgs);
1392 case llvm::Triple::x86:
1393 case llvm::Triple::x86_64:
1394 AddX86TargetArgs(Args, CmdArgs);
1397 case llvm::Triple::lanai:
1398 AddLanaiTargetArgs(Args, CmdArgs);
1401 case llvm::Triple::hexagon:
1402 AddHexagonTargetArgs(Args, CmdArgs);
1405 case llvm::Triple::wasm32:
1406 case llvm::Triple::wasm64:
1407 AddWebAssemblyTargetArgs(Args, CmdArgs);
1412 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1413 ArgStringList &CmdArgs) const {
1414 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1416 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1417 Args.hasArg(options::OPT_mkernel) ||
1418 Args.hasArg(options::OPT_fapple_kext))
1419 CmdArgs.push_back("-disable-red-zone");
1421 if (!Args.hasFlag(options::OPT_mimplicit_float,
1422 options::OPT_mno_implicit_float, true))
1423 CmdArgs.push_back("-no-implicit-float");
1425 const char *ABIName = nullptr;
1426 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1427 ABIName = A->getValue();
1428 else if (Triple.isOSDarwin())
1429 ABIName = "darwinpcs";
1433 CmdArgs.push_back("-target-abi");
1434 CmdArgs.push_back(ABIName);
1436 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1437 options::OPT_mno_fix_cortex_a53_835769)) {
1438 CmdArgs.push_back("-mllvm");
1439 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1440 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1442 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1443 } else if (Triple.isAndroid()) {
1444 // Enabled A53 errata (835769) workaround by default on android
1445 CmdArgs.push_back("-mllvm");
1446 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1449 // Forward the -mglobal-merge option for explicit control over the pass.
1450 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1451 options::OPT_mno_global_merge)) {
1452 CmdArgs.push_back("-mllvm");
1453 if (A->getOption().matches(options::OPT_mno_global_merge))
1454 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1456 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1460 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1461 ArgStringList &CmdArgs) const {
1462 const Driver &D = getToolChain().getDriver();
1465 const llvm::Triple &Triple = getToolChain().getTriple();
1466 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1468 CmdArgs.push_back("-target-abi");
1469 CmdArgs.push_back(ABIName.data());
1471 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1472 if (ABI == mips::FloatABI::Soft) {
1473 // Floating point operations and argument passing are soft.
1474 CmdArgs.push_back("-msoft-float");
1475 CmdArgs.push_back("-mfloat-abi");
1476 CmdArgs.push_back("soft");
1478 // Floating point operations and argument passing are hard.
1479 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1480 CmdArgs.push_back("-mfloat-abi");
1481 CmdArgs.push_back("hard");
1484 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1485 if (A->getOption().matches(options::OPT_mxgot)) {
1486 CmdArgs.push_back("-mllvm");
1487 CmdArgs.push_back("-mxgot");
1491 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1492 options::OPT_mno_ldc1_sdc1)) {
1493 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1494 CmdArgs.push_back("-mllvm");
1495 CmdArgs.push_back("-mno-ldc1-sdc1");
1499 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1500 options::OPT_mno_check_zero_division)) {
1501 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1502 CmdArgs.push_back("-mllvm");
1503 CmdArgs.push_back("-mno-check-zero-division");
1507 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1508 StringRef v = A->getValue();
1509 CmdArgs.push_back("-mllvm");
1510 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1514 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1516 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1518 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1519 // -mgpopt is the default for static, -fno-pic environments but these two
1520 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1521 // the only case where -mllvm -mgpopt is passed.
1522 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1523 // passed explicitly when compiling something with -mabicalls
1524 // (implictly) in affect. Currently the warning is in the backend.
1526 // When the ABI in use is N64, we also need to determine the PIC mode that
1527 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1529 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1531 llvm::Reloc::Model RelocationModel;
1534 std::tie(RelocationModel, PICLevel, IsPIE) =
1535 ParsePICArgs(getToolChain(), Args);
1537 NoABICalls = NoABICalls ||
1538 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1540 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1541 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1542 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1543 CmdArgs.push_back("-mllvm");
1544 CmdArgs.push_back("-mgpopt");
1546 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1547 options::OPT_mno_local_sdata);
1548 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1549 options::OPT_mno_extern_sdata);
1550 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1551 options::OPT_mno_embedded_data);
1553 CmdArgs.push_back("-mllvm");
1554 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1555 CmdArgs.push_back("-mlocal-sdata=1");
1557 CmdArgs.push_back("-mlocal-sdata=0");
1559 LocalSData->claim();
1563 CmdArgs.push_back("-mllvm");
1564 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1565 CmdArgs.push_back("-mextern-sdata=1");
1567 CmdArgs.push_back("-mextern-sdata=0");
1569 ExternSData->claim();
1573 CmdArgs.push_back("-mllvm");
1574 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1575 CmdArgs.push_back("-membedded-data=1");
1577 CmdArgs.push_back("-membedded-data=0");
1579 EmbeddedData->claim();
1582 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1583 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1588 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1589 StringRef Val = StringRef(A->getValue());
1590 if (mips::hasCompactBranches(CPUName)) {
1591 if (Val == "never" || Val == "always" || Val == "optimal") {
1592 CmdArgs.push_back("-mllvm");
1593 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1595 D.Diag(diag::err_drv_unsupported_option_argument)
1596 << A->getOption().getName() << Val;
1598 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1602 void Clang::AddPPCTargetArgs(const ArgList &Args,
1603 ArgStringList &CmdArgs) const {
1604 // Select the ABI to use.
1605 const char *ABIName = nullptr;
1606 if (getToolChain().getTriple().isOSLinux())
1607 switch (getToolChain().getArch()) {
1608 case llvm::Triple::ppc64: {
1609 // When targeting a processor that supports QPX, or if QPX is
1610 // specifically enabled, default to using the ABI that supports QPX (so
1611 // long as it is not specifically disabled).
1612 bool HasQPX = false;
1613 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1614 HasQPX = A->getValue() == StringRef("a2q");
1615 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1617 ABIName = "elfv1-qpx";
1624 case llvm::Triple::ppc64le:
1631 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1632 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1633 // the option if given as we don't have backend support for any targets
1634 // that don't use the altivec abi.
1635 if (StringRef(A->getValue()) != "altivec")
1636 ABIName = A->getValue();
1638 ppc::FloatABI FloatABI =
1639 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1641 if (FloatABI == ppc::FloatABI::Soft) {
1642 // Floating point operations and argument passing are soft.
1643 CmdArgs.push_back("-msoft-float");
1644 CmdArgs.push_back("-mfloat-abi");
1645 CmdArgs.push_back("soft");
1647 // Floating point operations and argument passing are hard.
1648 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1649 CmdArgs.push_back("-mfloat-abi");
1650 CmdArgs.push_back("hard");
1654 CmdArgs.push_back("-target-abi");
1655 CmdArgs.push_back(ABIName);
1659 void Clang::AddRISCVTargetArgs(const ArgList &Args,
1660 ArgStringList &CmdArgs) const {
1661 // FIXME: currently defaults to the soft-float ABIs. Will need to be
1662 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
1663 const char *ABIName = nullptr;
1664 const llvm::Triple &Triple = getToolChain().getTriple();
1665 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1666 ABIName = A->getValue();
1667 else if (Triple.getArch() == llvm::Triple::riscv32)
1669 else if (Triple.getArch() == llvm::Triple::riscv64)
1672 llvm_unreachable("Unexpected triple!");
1674 CmdArgs.push_back("-target-abi");
1675 CmdArgs.push_back(ABIName);
1678 void Clang::AddSparcTargetArgs(const ArgList &Args,
1679 ArgStringList &CmdArgs) const {
1680 sparc::FloatABI FloatABI =
1681 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1683 if (FloatABI == sparc::FloatABI::Soft) {
1684 // Floating point operations and argument passing are soft.
1685 CmdArgs.push_back("-msoft-float");
1686 CmdArgs.push_back("-mfloat-abi");
1687 CmdArgs.push_back("soft");
1689 // Floating point operations and argument passing are hard.
1690 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1691 CmdArgs.push_back("-mfloat-abi");
1692 CmdArgs.push_back("hard");
1696 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1697 ArgStringList &CmdArgs) const {
1698 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1699 CmdArgs.push_back("-mbackchain");
1702 void Clang::AddX86TargetArgs(const ArgList &Args,
1703 ArgStringList &CmdArgs) const {
1704 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1705 Args.hasArg(options::OPT_mkernel) ||
1706 Args.hasArg(options::OPT_fapple_kext))
1707 CmdArgs.push_back("-disable-red-zone");
1709 // Default to avoid implicit floating-point for kernel/kext code, but allow
1710 // that to be overridden with -mno-soft-float.
1711 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1712 Args.hasArg(options::OPT_fapple_kext));
1713 if (Arg *A = Args.getLastArg(
1714 options::OPT_msoft_float, options::OPT_mno_soft_float,
1715 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1716 const Option &O = A->getOption();
1717 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1718 O.matches(options::OPT_msoft_float));
1720 if (NoImplicitFloat)
1721 CmdArgs.push_back("-no-implicit-float");
1723 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1724 StringRef Value = A->getValue();
1725 if (Value == "intel" || Value == "att") {
1726 CmdArgs.push_back("-mllvm");
1727 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1729 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1730 << A->getOption().getName() << Value;
1732 } else if (getToolChain().getDriver().IsCLMode()) {
1733 CmdArgs.push_back("-mllvm");
1734 CmdArgs.push_back("-x86-asm-syntax=intel");
1737 // Set flags to support MCU ABI.
1738 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1739 CmdArgs.push_back("-mfloat-abi");
1740 CmdArgs.push_back("soft");
1741 CmdArgs.push_back("-mstack-alignment=4");
1745 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1746 ArgStringList &CmdArgs) const {
1747 CmdArgs.push_back("-mqdsp6-compat");
1748 CmdArgs.push_back("-Wreturn-type");
1750 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1751 CmdArgs.push_back("-mllvm");
1752 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1753 Twine(G.getValue())));
1756 if (!Args.hasArg(options::OPT_fno_short_enums))
1757 CmdArgs.push_back("-fshort-enums");
1758 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1759 CmdArgs.push_back("-mllvm");
1760 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1762 CmdArgs.push_back("-mllvm");
1763 CmdArgs.push_back("-machine-sink-split=0");
1766 void Clang::AddLanaiTargetArgs(const ArgList &Args,
1767 ArgStringList &CmdArgs) const {
1768 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1769 StringRef CPUName = A->getValue();
1771 CmdArgs.push_back("-target-cpu");
1772 CmdArgs.push_back(Args.MakeArgString(CPUName));
1774 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1775 StringRef Value = A->getValue();
1776 // Only support mregparm=4 to support old usage. Report error for all other
1779 if (Value.getAsInteger(10, Mregparm)) {
1780 if (Mregparm != 4) {
1781 getToolChain().getDriver().Diag(
1782 diag::err_drv_unsupported_option_argument)
1783 << A->getOption().getName() << Value;
1789 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1790 ArgStringList &CmdArgs) const {
1791 // Default to "hidden" visibility.
1792 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1793 options::OPT_fvisibility_ms_compat)) {
1794 CmdArgs.push_back("-fvisibility");
1795 CmdArgs.push_back("hidden");
1799 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1800 StringRef Target, const InputInfo &Output,
1801 const InputInfo &Input, const ArgList &Args) const {
1802 // If this is a dry run, do not create the compilation database file.
1803 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1806 using llvm::yaml::escape;
1807 const Driver &D = getToolChain().getDriver();
1809 if (!CompilationDatabase) {
1811 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1813 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1817 CompilationDatabase = std::move(File);
1819 auto &CDB = *CompilationDatabase;
1820 SmallString<128> Buf;
1821 if (llvm::sys::fs::current_path(Buf))
1823 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1824 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1825 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1826 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1828 Buf += types::getTypeName(Input.getType());
1829 CDB << ", \"" << escape(Buf) << "\"";
1830 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1833 CDB << ", \"" << escape(Buf) << "\"";
1835 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1836 for (auto &A: Args) {
1837 auto &O = A->getOption();
1838 // Skip language selection, which is positional.
1839 if (O.getID() == options::OPT_x)
1841 // Skip writing dependency output and the compilation database itself.
1842 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1845 if (O.getKind() == Option::InputClass)
1847 // All other arguments are quoted and appended.
1849 A->render(Args, ASL);
1851 CDB << ", \"" << escape(it) << "\"";
1855 CDB << ", \"" << escape(Buf) << "\"]},\n";
1858 static void CollectArgsForIntegratedAssembler(Compilation &C,
1859 const ArgList &Args,
1860 ArgStringList &CmdArgs,
1862 if (UseRelaxAll(C, Args))
1863 CmdArgs.push_back("-mrelax-all");
1865 // Only default to -mincremental-linker-compatible if we think we are
1866 // targeting the MSVC linker.
1867 bool DefaultIncrementalLinkerCompatible =
1868 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1869 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1870 options::OPT_mno_incremental_linker_compatible,
1871 DefaultIncrementalLinkerCompatible))
1872 CmdArgs.push_back("-mincremental-linker-compatible");
1874 switch (C.getDefaultToolChain().getArch()) {
1875 case llvm::Triple::arm:
1876 case llvm::Triple::armeb:
1877 case llvm::Triple::thumb:
1878 case llvm::Triple::thumbeb:
1879 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1880 StringRef Value = A->getValue();
1881 if (Value == "always" || Value == "never" || Value == "arm" ||
1883 CmdArgs.push_back("-mllvm");
1884 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1886 D.Diag(diag::err_drv_unsupported_option_argument)
1887 << A->getOption().getName() << Value;
1895 // When passing -I arguments to the assembler we sometimes need to
1896 // unconditionally take the next argument. For example, when parsing
1897 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1898 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1899 // arg after parsing the '-I' arg.
1900 bool TakeNextArg = false;
1902 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
1903 const char *MipsTargetFeature = nullptr;
1905 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1908 for (StringRef Value : A->getValues()) {
1910 CmdArgs.push_back(Value.data());
1911 TakeNextArg = false;
1915 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1916 Value == "-mbig-obj")
1917 continue; // LLVM handles bigobj automatically
1919 switch (C.getDefaultToolChain().getArch()) {
1922 case llvm::Triple::thumb:
1923 case llvm::Triple::thumbeb:
1924 case llvm::Triple::arm:
1925 case llvm::Triple::armeb:
1926 if (Value == "-mthumb")
1927 // -mthumb has already been processed in ComputeLLVMTriple()
1928 // recognize but skip over here.
1931 case llvm::Triple::mips:
1932 case llvm::Triple::mipsel:
1933 case llvm::Triple::mips64:
1934 case llvm::Triple::mips64el:
1935 if (Value == "--trap") {
1936 CmdArgs.push_back("-target-feature");
1937 CmdArgs.push_back("+use-tcc-in-div");
1940 if (Value == "--break") {
1941 CmdArgs.push_back("-target-feature");
1942 CmdArgs.push_back("-use-tcc-in-div");
1945 if (Value.startswith("-msoft-float")) {
1946 CmdArgs.push_back("-target-feature");
1947 CmdArgs.push_back("+soft-float");
1950 if (Value.startswith("-mhard-float")) {
1951 CmdArgs.push_back("-target-feature");
1952 CmdArgs.push_back("-soft-float");
1956 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1957 .Case("-mips1", "+mips1")
1958 .Case("-mips2", "+mips2")
1959 .Case("-mips3", "+mips3")
1960 .Case("-mips4", "+mips4")
1961 .Case("-mips5", "+mips5")
1962 .Case("-mips32", "+mips32")
1963 .Case("-mips32r2", "+mips32r2")
1964 .Case("-mips32r3", "+mips32r3")
1965 .Case("-mips32r5", "+mips32r5")
1966 .Case("-mips32r6", "+mips32r6")
1967 .Case("-mips64", "+mips64")
1968 .Case("-mips64r2", "+mips64r2")
1969 .Case("-mips64r3", "+mips64r3")
1970 .Case("-mips64r5", "+mips64r5")
1971 .Case("-mips64r6", "+mips64r6")
1973 if (MipsTargetFeature)
1977 if (Value == "-force_cpusubtype_ALL") {
1978 // Do nothing, this is the default and we don't support anything else.
1979 } else if (Value == "-L") {
1980 CmdArgs.push_back("-msave-temp-labels");
1981 } else if (Value == "--fatal-warnings") {
1982 CmdArgs.push_back("-massembler-fatal-warnings");
1983 } else if (Value == "--noexecstack") {
1984 CmdArgs.push_back("-mnoexecstack");
1985 } else if (Value.startswith("-compress-debug-sections") ||
1986 Value.startswith("--compress-debug-sections") ||
1987 Value == "-nocompress-debug-sections" ||
1988 Value == "--nocompress-debug-sections") {
1989 CmdArgs.push_back(Value.data());
1990 } else if (Value == "-mrelax-relocations=yes" ||
1991 Value == "--mrelax-relocations=yes") {
1992 UseRelaxRelocations = true;
1993 } else if (Value == "-mrelax-relocations=no" ||
1994 Value == "--mrelax-relocations=no") {
1995 UseRelaxRelocations = false;
1996 } else if (Value.startswith("-I")) {
1997 CmdArgs.push_back(Value.data());
1998 // We need to consume the next argument if the current arg is a plain
1999 // -I. The next arg will be the include directory.
2002 } else if (Value.startswith("-gdwarf-")) {
2003 // "-gdwarf-N" options are not cc1as options.
2004 unsigned DwarfVersion = DwarfVersionNum(Value);
2005 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2006 CmdArgs.push_back(Value.data());
2008 RenderDebugEnablingArgs(Args, CmdArgs,
2009 codegenoptions::LimitedDebugInfo,
2010 DwarfVersion, llvm::DebuggerKind::Default);
2012 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2013 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2014 // Do nothing, we'll validate it later.
2015 } else if (Value == "-defsym") {
2016 if (A->getNumValues() != 2) {
2017 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2020 const char *S = A->getValue(1);
2021 auto Pair = StringRef(S).split('=');
2022 auto Sym = Pair.first;
2023 auto SVal = Pair.second;
2025 if (Sym.empty() || SVal.empty()) {
2026 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2030 if (SVal.getAsInteger(0, IVal)) {
2031 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2034 CmdArgs.push_back(Value.data());
2037 D.Diag(diag::err_drv_unsupported_option_argument)
2038 << A->getOption().getName() << Value;
2042 if (UseRelaxRelocations)
2043 CmdArgs.push_back("--mrelax-relocations");
2044 if (MipsTargetFeature != nullptr) {
2045 CmdArgs.push_back("-target-feature");
2046 CmdArgs.push_back(MipsTargetFeature);
2050 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2051 bool OFastEnabled, const ArgList &Args,
2052 ArgStringList &CmdArgs) {
2053 // Handle various floating point optimization flags, mapping them to the
2054 // appropriate LLVM code generation flags. This is complicated by several
2055 // "umbrella" flags, so we do this by stepping through the flags incrementally
2056 // adjusting what we think is enabled/disabled, then at the end setting the
2057 // LLVM flags based on the final state.
2058 bool HonorINFs = true;
2059 bool HonorNaNs = true;
2060 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2061 bool MathErrno = TC.IsMathErrnoDefault();
2062 bool AssociativeMath = false;
2063 bool ReciprocalMath = false;
2064 bool SignedZeros = true;
2065 bool TrappingMath = true;
2066 StringRef DenormalFPMath = "";
2067 StringRef FPContract = "";
2069 for (const Arg *A : Args) {
2070 switch (A->getOption().getID()) {
2071 // If this isn't an FP option skip the claim below
2074 // Options controlling individual features
2075 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2076 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2077 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2078 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2079 case options::OPT_fmath_errno: MathErrno = true; break;
2080 case options::OPT_fno_math_errno: MathErrno = false; break;
2081 case options::OPT_fassociative_math: AssociativeMath = true; break;
2082 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2083 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2084 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2085 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2086 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2087 case options::OPT_ftrapping_math: TrappingMath = true; break;
2088 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2090 case options::OPT_fdenormal_fp_math_EQ:
2091 DenormalFPMath = A->getValue();
2094 // Validate and pass through -fp-contract option.
2095 case options::OPT_ffp_contract: {
2096 StringRef Val = A->getValue();
2097 if (Val == "fast" || Val == "on" || Val == "off")
2100 D.Diag(diag::err_drv_unsupported_option_argument)
2101 << A->getOption().getName() << Val;
2105 case options::OPT_ffinite_math_only:
2109 case options::OPT_fno_finite_math_only:
2114 case options::OPT_funsafe_math_optimizations:
2115 AssociativeMath = true;
2116 ReciprocalMath = true;
2117 SignedZeros = false;
2118 TrappingMath = false;
2120 case options::OPT_fno_unsafe_math_optimizations:
2121 AssociativeMath = false;
2122 ReciprocalMath = false;
2124 TrappingMath = true;
2125 // -fno_unsafe_math_optimizations restores default denormal handling
2126 DenormalFPMath = "";
2129 case options::OPT_Ofast:
2130 // If -Ofast is the optimization level, then -ffast-math should be enabled
2134 case options::OPT_ffast_math:
2138 AssociativeMath = true;
2139 ReciprocalMath = true;
2140 SignedZeros = false;
2141 TrappingMath = false;
2142 // If fast-math is set then set the fp-contract mode to fast.
2143 FPContract = "fast";
2145 case options::OPT_fno_fast_math:
2148 // Turning on -ffast-math (with either flag) removes the need for
2149 // MathErrno. However, turning *off* -ffast-math merely restores the
2150 // toolchain default (which may be false).
2151 MathErrno = TC.IsMathErrnoDefault();
2152 AssociativeMath = false;
2153 ReciprocalMath = false;
2155 TrappingMath = true;
2156 // -fno_fast_math restores default denormal and fpcontract handling
2157 DenormalFPMath = "";
2162 // If we handled this option claim it
2167 CmdArgs.push_back("-menable-no-infs");
2170 CmdArgs.push_back("-menable-no-nans");
2173 CmdArgs.push_back("-fmath-errno");
2175 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2177 CmdArgs.push_back("-menable-unsafe-fp-math");
2180 CmdArgs.push_back("-fno-signed-zeros");
2182 if (AssociativeMath && !SignedZeros && !TrappingMath)
2183 CmdArgs.push_back("-mreassociate");
2186 CmdArgs.push_back("-freciprocal-math");
2189 CmdArgs.push_back("-fno-trapping-math");
2191 if (!DenormalFPMath.empty())
2193 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2195 if (!FPContract.empty())
2196 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2198 ParseMRecip(D, Args, CmdArgs);
2200 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2201 // individual features enabled by -ffast-math instead of the option itself as
2202 // that's consistent with gcc's behaviour.
2203 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2204 ReciprocalMath && !SignedZeros && !TrappingMath)
2205 CmdArgs.push_back("-ffast-math");
2207 // Handle __FINITE_MATH_ONLY__ similarly.
2208 if (!HonorINFs && !HonorNaNs)
2209 CmdArgs.push_back("-ffinite-math-only");
2211 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2212 CmdArgs.push_back("-mfpmath");
2213 CmdArgs.push_back(A->getValue());
2216 // Disable a codegen optimization for floating-point casts.
2217 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2218 options::OPT_fstrict_float_cast_overflow, false))
2219 CmdArgs.push_back("-fno-strict-float-cast-overflow");
2222 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2223 const llvm::Triple &Triple,
2224 const InputInfo &Input) {
2225 // Enable region store model by default.
2226 CmdArgs.push_back("-analyzer-store=region");
2228 // Treat blocks as analysis entry points.
2229 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2231 CmdArgs.push_back("-analyzer-eagerly-assume");
2233 // Add default argument set.
2234 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2235 CmdArgs.push_back("-analyzer-checker=core");
2236 CmdArgs.push_back("-analyzer-checker=apiModeling");
2238 if (!Triple.isWindowsMSVCEnvironment()) {
2239 CmdArgs.push_back("-analyzer-checker=unix");
2241 // Enable "unix" checkers that also work on Windows.
2242 CmdArgs.push_back("-analyzer-checker=unix.API");
2243 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2244 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2245 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2246 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2247 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2250 // Disable some unix checkers for PS4.
2251 if (Triple.isPS4CPU()) {
2252 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2253 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2256 if (Triple.isOSDarwin())
2257 CmdArgs.push_back("-analyzer-checker=osx");
2259 CmdArgs.push_back("-analyzer-checker=deadcode");
2261 if (types::isCXX(Input.getType()))
2262 CmdArgs.push_back("-analyzer-checker=cplusplus");
2264 if (!Triple.isPS4CPU()) {
2265 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2266 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2267 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2268 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2269 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2270 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2273 // Default nullability checks.
2274 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2275 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2278 // Set the output format. The default is plist, for (lame) historical reasons.
2279 CmdArgs.push_back("-analyzer-output");
2280 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2281 CmdArgs.push_back(A->getValue());
2283 CmdArgs.push_back("plist");
2285 // Disable the presentation of standard compiler warnings when using
2286 // --analyze. We only want to show static analyzer diagnostics or frontend
2288 CmdArgs.push_back("-w");
2290 // Add -Xanalyzer arguments when running as analyzer.
2291 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2294 static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
2295 ArgStringList &CmdArgs, bool KernelOrKext) {
2296 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2298 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2299 // doesn't even have a stack!
2300 if (EffectiveTriple.isNVPTX())
2303 // -stack-protector=0 is default.
2304 unsigned StackProtectorLevel = 0;
2305 unsigned DefaultStackProtectorLevel =
2306 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2308 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2309 options::OPT_fstack_protector_all,
2310 options::OPT_fstack_protector_strong,
2311 options::OPT_fstack_protector)) {
2312 if (A->getOption().matches(options::OPT_fstack_protector))
2313 StackProtectorLevel =
2314 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2315 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2316 StackProtectorLevel = LangOptions::SSPStrong;
2317 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2318 StackProtectorLevel = LangOptions::SSPReq;
2320 StackProtectorLevel = DefaultStackProtectorLevel;
2323 if (StackProtectorLevel) {
2324 CmdArgs.push_back("-stack-protector");
2325 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2328 // --param ssp-buffer-size=
2329 for (const Arg *A : Args.filtered(options::OPT__param)) {
2330 StringRef Str(A->getValue());
2331 if (Str.startswith("ssp-buffer-size=")) {
2332 if (StackProtectorLevel) {
2333 CmdArgs.push_back("-stack-protector-buffer-size");
2334 // FIXME: Verify the argument is a valid integer.
2335 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2342 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2343 const unsigned ForwardedArguments[] = {
2344 options::OPT_cl_opt_disable,
2345 options::OPT_cl_strict_aliasing,
2346 options::OPT_cl_single_precision_constant,
2347 options::OPT_cl_finite_math_only,
2348 options::OPT_cl_kernel_arg_info,
2349 options::OPT_cl_unsafe_math_optimizations,
2350 options::OPT_cl_fast_relaxed_math,
2351 options::OPT_cl_mad_enable,
2352 options::OPT_cl_no_signed_zeros,
2353 options::OPT_cl_denorms_are_zero,
2354 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2355 options::OPT_cl_uniform_work_group_size
2358 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2359 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2360 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2363 for (const auto &Arg : ForwardedArguments)
2364 if (const auto *A = Args.getLastArg(Arg))
2365 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2368 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2369 ArgStringList &CmdArgs) {
2370 bool ARCMTEnabled = false;
2371 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2372 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2373 options::OPT_ccc_arcmt_modify,
2374 options::OPT_ccc_arcmt_migrate)) {
2375 ARCMTEnabled = true;
2376 switch (A->getOption().getID()) {
2377 default: llvm_unreachable("missed a case");
2378 case options::OPT_ccc_arcmt_check:
2379 CmdArgs.push_back("-arcmt-check");
2381 case options::OPT_ccc_arcmt_modify:
2382 CmdArgs.push_back("-arcmt-modify");
2384 case options::OPT_ccc_arcmt_migrate:
2385 CmdArgs.push_back("-arcmt-migrate");
2386 CmdArgs.push_back("-mt-migrate-directory");
2387 CmdArgs.push_back(A->getValue());
2389 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2390 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2395 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2396 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2397 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2400 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2402 D.Diag(diag::err_drv_argument_not_allowed_with)
2403 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2405 CmdArgs.push_back("-mt-migrate-directory");
2406 CmdArgs.push_back(A->getValue());
2408 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2409 options::OPT_objcmt_migrate_subscripting,
2410 options::OPT_objcmt_migrate_property)) {
2411 // None specified, means enable them all.
2412 CmdArgs.push_back("-objcmt-migrate-literals");
2413 CmdArgs.push_back("-objcmt-migrate-subscripting");
2414 CmdArgs.push_back("-objcmt-migrate-property");
2416 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2417 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2418 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2421 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2422 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2423 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2424 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2425 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2426 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2427 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2428 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2429 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2430 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2431 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2432 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2433 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2434 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2435 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2436 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2440 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2441 const ArgList &Args, ArgStringList &CmdArgs) {
2442 // -fbuiltin is default unless -mkernel is used.
2444 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2445 !Args.hasArg(options::OPT_mkernel));
2447 CmdArgs.push_back("-fno-builtin");
2449 // -ffreestanding implies -fno-builtin.
2450 if (Args.hasArg(options::OPT_ffreestanding))
2451 UseBuiltins = false;
2453 // Process the -fno-builtin-* options.
2454 for (const auto &Arg : Args) {
2455 const Option &O = Arg->getOption();
2456 if (!O.matches(options::OPT_fno_builtin_))
2461 // If -fno-builtin is specified, then there's no need to pass the option to
2466 StringRef FuncName = Arg->getValue();
2467 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2470 // le32-specific flags:
2471 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2473 if (TC.getArch() == llvm::Triple::le32)
2474 CmdArgs.push_back("-fno-math-builtin");
2477 void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2478 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2479 llvm::sys::path::append(Result, "org.llvm.clang.");
2480 appendUserToPath(Result);
2481 llvm::sys::path::append(Result, "ModuleCache");
2484 static void RenderModulesOptions(Compilation &C, const Driver &D,
2485 const ArgList &Args, const InputInfo &Input,
2486 const InputInfo &Output,
2487 ArgStringList &CmdArgs, bool &HaveModules) {
2488 // -fmodules enables the use of precompiled modules (off by default).
2489 // Users can pass -fno-cxx-modules to turn off modules support for
2490 // C++/Objective-C++ programs.
2491 bool HaveClangModules = false;
2492 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2493 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2494 options::OPT_fno_cxx_modules, true);
2495 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2496 CmdArgs.push_back("-fmodules");
2497 HaveClangModules = true;
2501 HaveModules = HaveClangModules;
2502 if (Args.hasArg(options::OPT_fmodules_ts)) {
2503 CmdArgs.push_back("-fmodules-ts");
2507 // -fmodule-maps enables implicit reading of module map files. By default,
2508 // this is enabled if we are using Clang's flavor of precompiled modules.
2509 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2510 options::OPT_fno_implicit_module_maps, HaveClangModules))
2511 CmdArgs.push_back("-fimplicit-module-maps");
2513 // -fmodules-decluse checks that modules used are declared so (off by default)
2514 if (Args.hasFlag(options::OPT_fmodules_decluse,
2515 options::OPT_fno_modules_decluse, false))
2516 CmdArgs.push_back("-fmodules-decluse");
2518 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2519 // all #included headers are part of modules.
2520 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2521 options::OPT_fno_modules_strict_decluse, false))
2522 CmdArgs.push_back("-fmodules-strict-decluse");
2524 // -fno-implicit-modules turns off implicitly compiling modules on demand.
2525 bool ImplicitModules = false;
2526 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2527 options::OPT_fno_implicit_modules, HaveClangModules)) {
2529 CmdArgs.push_back("-fno-implicit-modules");
2530 } else if (HaveModules) {
2531 ImplicitModules = true;
2532 // -fmodule-cache-path specifies where our implicitly-built module files
2533 // should be written.
2534 SmallString<128> Path;
2535 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2536 Path = A->getValue();
2538 if (C.isForDiagnostics()) {
2539 // When generating crash reports, we want to emit the modules along with
2540 // the reproduction sources, so we ignore any provided module path.
2541 Path = Output.getFilename();
2542 llvm::sys::path::replace_extension(Path, ".cache");
2543 llvm::sys::path::append(Path, "modules");
2544 } else if (Path.empty()) {
2545 // No module path was provided: use the default.
2546 Driver::getDefaultModuleCachePath(Path);
2549 const char Arg[] = "-fmodules-cache-path=";
2550 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2551 CmdArgs.push_back(Args.MakeArgString(Path));
2555 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2556 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2557 CmdArgs.push_back(Args.MakeArgString(
2558 std::string("-fprebuilt-module-path=") + A->getValue()));
2563 // -fmodule-name specifies the module that is currently being built (or
2564 // used for header checking by -fmodule-maps).
2565 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2567 // -fmodule-map-file can be used to specify files containing module
2569 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2571 // -fbuiltin-module-map can be used to load the clang
2572 // builtin headers modulemap file.
2573 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2574 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2575 llvm::sys::path::append(BuiltinModuleMap, "include");
2576 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2577 if (llvm::sys::fs::exists(BuiltinModuleMap))
2579 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2582 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2583 // names to precompiled module files (the module is loaded only if used).
2584 // The -fmodule-file=<file> form can be used to unconditionally load
2585 // precompiled module files (whether used or not).
2587 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2589 Args.ClaimAllArgs(options::OPT_fmodule_file);
2591 // When building modules and generating crashdumps, we need to dump a module
2592 // dependency VFS alongside the output.
2593 if (HaveClangModules && C.isForDiagnostics()) {
2594 SmallString<128> VFSDir(Output.getFilename());
2595 llvm::sys::path::replace_extension(VFSDir, ".cache");
2596 // Add the cache directory as a temp so the crash diagnostics pick it up.
2597 C.addTempFile(Args.MakeArgString(VFSDir));
2599 llvm::sys::path::append(VFSDir, "vfs");
2600 CmdArgs.push_back("-module-dependency-dir");
2601 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2604 if (HaveClangModules)
2605 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2607 // Pass through all -fmodules-ignore-macro arguments.
2608 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2609 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2610 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2612 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2614 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2615 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2616 D.Diag(diag::err_drv_argument_not_allowed_with)
2617 << A->getAsString(Args) << "-fbuild-session-timestamp";
2619 llvm::sys::fs::file_status Status;
2620 if (llvm::sys::fs::status(A->getValue(), Status))
2621 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2623 Args.MakeArgString("-fbuild-session-timestamp=" +
2624 Twine((uint64_t)Status.getLastModificationTime()
2629 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2630 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2631 options::OPT_fbuild_session_file))
2632 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2634 Args.AddLastArg(CmdArgs,
2635 options::OPT_fmodules_validate_once_per_build_session);
2638 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2639 options::OPT_fno_modules_validate_system_headers,
2641 CmdArgs.push_back("-fmodules-validate-system-headers");
2643 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2646 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2647 ArgStringList &CmdArgs) {
2648 // -fsigned-char is default.
2649 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2650 options::OPT_fno_signed_char,
2651 options::OPT_funsigned_char,
2652 options::OPT_fno_unsigned_char)) {
2653 if (A->getOption().matches(options::OPT_funsigned_char) ||
2654 A->getOption().matches(options::OPT_fno_signed_char)) {
2655 CmdArgs.push_back("-fno-signed-char");
2657 } else if (!isSignedCharDefault(T)) {
2658 CmdArgs.push_back("-fno-signed-char");
2661 if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2662 CmdArgs.push_back("-fchar8_t");
2664 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2665 options::OPT_fno_short_wchar)) {
2666 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2667 CmdArgs.push_back("-fwchar-type=short");
2668 CmdArgs.push_back("-fno-signed-wchar");
2670 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
2671 CmdArgs.push_back("-fwchar-type=int");
2672 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2673 T.getOS() == llvm::Triple::OpenBSD))
2674 CmdArgs.push_back("-fno-signed-wchar");
2676 CmdArgs.push_back("-fsigned-wchar");
2681 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2682 const llvm::Triple &T, const ArgList &Args,
2683 ObjCRuntime &Runtime, bool InferCovariantReturns,
2684 const InputInfo &Input, ArgStringList &CmdArgs) {
2685 const llvm::Triple::ArchType Arch = TC.getArch();
2687 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2688 // is the default. Except for deployment target of 10.5, next runtime is
2689 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2690 if (Runtime.isNonFragile()) {
2691 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2692 options::OPT_fno_objc_legacy_dispatch,
2693 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2694 if (TC.UseObjCMixedDispatch())
2695 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2697 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2701 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2702 // to do Array/Dictionary subscripting by default.
2703 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2704 !T.isMacOSXVersionLT(10, 7) &&
2705 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2706 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2708 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2709 // NOTE: This logic is duplicated in ToolChains.cpp.
2710 if (isObjCAutoRefCount(Args)) {
2713 CmdArgs.push_back("-fobjc-arc");
2715 // FIXME: It seems like this entire block, and several around it should be
2716 // wrapped in isObjC, but for now we just use it here as this is where it
2717 // was being used previously.
2718 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2719 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2720 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2722 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2725 // Allow the user to enable full exceptions code emission.
2726 // We default off for Objective-C, on for Objective-C++.
2727 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2728 options::OPT_fno_objc_arc_exceptions,
2729 /*default=*/types::isCXX(Input.getType())))
2730 CmdArgs.push_back("-fobjc-arc-exceptions");
2733 // Silence warning for full exception code emission options when explicitly
2734 // set to use no ARC.
2735 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2736 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2737 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2740 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2742 if (InferCovariantReturns)
2743 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2745 // Pass down -fobjc-weak or -fno-objc-weak if present.
2746 if (types::isObjC(Input.getType())) {
2748 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2751 } else if (!Runtime.allowsWeak()) {
2752 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2753 D.Diag(diag::err_objc_weak_unsupported);
2755 WeakArg->render(Args, CmdArgs);
2760 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2761 ArgStringList &CmdArgs) {
2762 bool CaretDefault = true;
2763 bool ColumnDefault = true;
2765 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2766 options::OPT__SLASH_diagnostics_column,
2767 options::OPT__SLASH_diagnostics_caret)) {
2768 switch (A->getOption().getID()) {
2769 case options::OPT__SLASH_diagnostics_caret:
2770 CaretDefault = true;
2771 ColumnDefault = true;
2773 case options::OPT__SLASH_diagnostics_column:
2774 CaretDefault = false;
2775 ColumnDefault = true;
2777 case options::OPT__SLASH_diagnostics_classic:
2778 CaretDefault = false;
2779 ColumnDefault = false;
2784 // -fcaret-diagnostics is default.
2785 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2786 options::OPT_fno_caret_diagnostics, CaretDefault))
2787 CmdArgs.push_back("-fno-caret-diagnostics");
2789 // -fdiagnostics-fixit-info is default, only pass non-default.
2790 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2791 options::OPT_fno_diagnostics_fixit_info))
2792 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2794 // Enable -fdiagnostics-show-option by default.
2795 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2796 options::OPT_fno_diagnostics_show_option))
2797 CmdArgs.push_back("-fdiagnostics-show-option");
2800 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2801 CmdArgs.push_back("-fdiagnostics-show-category");
2802 CmdArgs.push_back(A->getValue());
2805 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2806 options::OPT_fno_diagnostics_show_hotness, false))
2807 CmdArgs.push_back("-fdiagnostics-show-hotness");
2810 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2812 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2813 CmdArgs.push_back(Args.MakeArgString(Opt));
2816 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2817 CmdArgs.push_back("-fdiagnostics-format");
2818 CmdArgs.push_back(A->getValue());
2821 if (const Arg *A = Args.getLastArg(
2822 options::OPT_fdiagnostics_show_note_include_stack,
2823 options::OPT_fno_diagnostics_show_note_include_stack)) {
2824 const Option &O = A->getOption();
2825 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2826 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2828 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2831 // Color diagnostics are parsed by the driver directly from argv and later
2832 // re-parsed to construct this job; claim any possible color diagnostic here
2833 // to avoid warn_drv_unused_argument and diagnose bad
2834 // OPT_fdiagnostics_color_EQ values.
2835 for (const Arg *A : Args) {
2836 const Option &O = A->getOption();
2837 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2838 !O.matches(options::OPT_fdiagnostics_color) &&
2839 !O.matches(options::OPT_fno_color_diagnostics) &&
2840 !O.matches(options::OPT_fno_diagnostics_color) &&
2841 !O.matches(options::OPT_fdiagnostics_color_EQ))
2844 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2845 StringRef Value(A->getValue());
2846 if (Value != "always" && Value != "never" && Value != "auto")
2847 D.Diag(diag::err_drv_clang_unsupported)
2848 << ("-fdiagnostics-color=" + Value).str();
2853 if (D.getDiags().getDiagnosticOptions().ShowColors)
2854 CmdArgs.push_back("-fcolor-diagnostics");
2856 if (Args.hasArg(options::OPT_fansi_escape_codes))
2857 CmdArgs.push_back("-fansi-escape-codes");
2859 if (!Args.hasFlag(options::OPT_fshow_source_location,
2860 options::OPT_fno_show_source_location))
2861 CmdArgs.push_back("-fno-show-source-location");
2863 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2864 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2866 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2868 CmdArgs.push_back("-fno-show-column");
2870 if (!Args.hasFlag(options::OPT_fspell_checking,
2871 options::OPT_fno_spell_checking))
2872 CmdArgs.push_back("-fno-spell-checking");
2875 static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2876 const llvm::Triple &T, const ArgList &Args,
2877 bool EmitCodeView, bool IsWindowsMSVC,
2878 ArgStringList &CmdArgs,
2879 codegenoptions::DebugInfoKind &DebugInfoKind,
2880 const Arg *&SplitDWARFArg) {
2881 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2882 options::OPT_fno_debug_info_for_profiling, false) &&
2883 checkDebugInfoOption(
2884 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
2885 CmdArgs.push_back("-fdebug-info-for-profiling");
2887 // The 'g' groups options involve a somewhat intricate sequence of decisions
2888 // about what to pass from the driver to the frontend, but by the time they
2889 // reach cc1 they've been factored into three well-defined orthogonal choices:
2890 // * what level of debug info to generate
2891 // * what dwarf version to write
2892 // * what debugger tuning to use
2893 // This avoids having to monkey around further in cc1 other than to disable
2894 // codeview if not running in a Windows environment. Perhaps even that
2895 // decision should be made in the driver as well though.
2896 unsigned DWARFVersion = 0;
2897 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2899 bool SplitDWARFInlining =
2900 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2901 options::OPT_fno_split_dwarf_inlining, true);
2903 Args.ClaimAllArgs(options::OPT_g_Group);
2905 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2907 if (SplitDWARFArg && !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
2908 SplitDWARFArg = nullptr;
2909 SplitDWARFInlining = false;
2912 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2913 if (checkDebugInfoOption(A, Args, D, TC)) {
2914 // If the last option explicitly specified a debug-info level, use it.
2915 if (A->getOption().matches(options::OPT_gN_Group)) {
2916 DebugInfoKind = DebugLevelToInfoKind(*A);
2917 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2918 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2919 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2920 // This gets a bit more complicated if you've disabled inline info in
2921 // the skeleton CUs (SplitDWARFInlining) - then there's value in
2922 // composing split-dwarf and line-tables-only, so let those compose
2923 // naturally in that case. And if you just turned off debug info,
2924 // (-gsplit-dwarf -g0) - do that.
2925 if (SplitDWARFArg) {
2926 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2927 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2928 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2929 SplitDWARFInlining))
2930 SplitDWARFArg = nullptr;
2931 } else if (SplitDWARFInlining)
2932 DebugInfoKind = codegenoptions::NoDebugInfo;
2935 // For any other 'g' option, use Limited.
2936 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2939 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2943 // If a debugger tuning argument appeared, remember it.
2945 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2946 if (checkDebugInfoOption(A, Args, D, TC)) {
2947 if (A->getOption().matches(options::OPT_glldb))
2948 DebuggerTuning = llvm::DebuggerKind::LLDB;
2949 else if (A->getOption().matches(options::OPT_gsce))
2950 DebuggerTuning = llvm::DebuggerKind::SCE;
2952 DebuggerTuning = llvm::DebuggerKind::GDB;
2956 // If a -gdwarf argument appeared, remember it.
2958 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2959 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2960 if (checkDebugInfoOption(A, Args, D, TC))
2961 DWARFVersion = DwarfVersionNum(A->getSpelling());
2963 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2964 // argument parsing.
2966 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
2967 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
2969 // DWARFVersion remains at 0 if no explicit choice was made.
2970 CmdArgs.push_back("-gcodeview");
2975 if (!EmitCodeView && DWARFVersion == 0 &&
2976 DebugInfoKind != codegenoptions::NoDebugInfo)
2977 DWARFVersion = TC.GetDefaultDwarfVersion();
2979 // We ignore flag -gstrict-dwarf for now.
2980 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2981 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2983 // Column info is included by default for everything except SCE and
2984 // CodeView. Clang doesn't track end columns, just starting columns, which,
2985 // in theory, is fine for CodeView (and PDB). In practice, however, the
2986 // Microsoft debuggers don't handle missing end columns well, so it's better
2987 // not to include any column info.
2988 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
2989 (void)checkDebugInfoOption(A, Args, D, TC);
2990 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
2991 /*Default=*/!EmitCodeView &&
2992 DebuggerTuning != llvm::DebuggerKind::SCE))
2993 CmdArgs.push_back("-dwarf-column-info");
2995 // FIXME: Move backend command line options to the module.
2996 // If -gline-tables-only is the last option it wins.
2997 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
2998 if (checkDebugInfoOption(A, Args, D, TC)) {
2999 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly) {
3000 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3001 CmdArgs.push_back("-dwarf-ext-refs");
3002 CmdArgs.push_back("-fmodule-format=obj");
3006 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3007 // splitting and extraction.
3008 // FIXME: Currently only works on Linux.
3009 if (T.isOSLinux()) {
3010 if (!SplitDWARFInlining)
3011 CmdArgs.push_back("-fno-split-dwarf-inlining");
3013 if (SplitDWARFArg) {
3014 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3015 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3016 CmdArgs.push_back("-enable-split-dwarf");
3020 // After we've dealt with all combinations of things that could
3021 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3022 // figure out if we need to "upgrade" it to standalone debug info.
3023 // We parse these two '-f' options whether or not they will be used,
3024 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3025 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3026 options::OPT_fno_standalone_debug,
3027 TC.GetDefaultStandaloneDebug());
3028 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3029 (void)checkDebugInfoOption(A, Args, D, TC);
3030 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3031 DebugInfoKind = codegenoptions::FullDebugInfo;
3033 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3035 // Source embedding is a vendor extension to DWARF v5. By now we have
3036 // checked if a DWARF version was stated explicitly, and have otherwise
3037 // fallen back to the target default, so if this is still not at least 5
3038 // we emit an error.
3039 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
3040 if (DWARFVersion < 5)
3041 D.Diag(diag::err_drv_argument_only_allowed_with)
3042 << A->getAsString(Args) << "-gdwarf-5";
3043 else if (checkDebugInfoOption(A, Args, D, TC))
3044 CmdArgs.push_back("-gembed-source");
3047 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3050 // -fdebug-macro turns on macro debug info generation.
3051 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3053 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3055 CmdArgs.push_back("-debug-info-macro");
3057 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3058 if (Args.hasFlag(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3060 if (checkDebugInfoOption(Args.getLastArg(options::OPT_ggnu_pubnames), Args,
3062 CmdArgs.push_back("-ggnu-pubnames");
3064 // -gdwarf-aranges turns on the emission of the aranges section in the
3066 // Always enabled for SCE tuning.
3067 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3068 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3069 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3071 CmdArgs.push_back("-mllvm");
3072 CmdArgs.push_back("-generate-arange-section");
3075 if (Args.hasFlag(options::OPT_fdebug_types_section,
3076 options::OPT_fno_debug_types_section, false)) {
3077 if (!T.isOSBinFormatELF()) {
3078 D.Diag(diag::err_drv_unsupported_opt_for_target)
3079 << Args.getLastArg(options::OPT_fdebug_types_section)
3082 } else if (checkDebugInfoOption(
3083 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3085 CmdArgs.push_back("-mllvm");
3086 CmdArgs.push_back("-generate-type-units");
3090 // Decide how to render forward declarations of template instantiations.
3091 // SCE wants full descriptions, others just get them in the name.
3092 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3093 CmdArgs.push_back("-debug-forward-template-params");
3095 // Do we need to explicitly import anonymous namespaces into the parent
3097 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3098 CmdArgs.push_back("-dwarf-explicit-import");
3100 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
3103 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3104 const InputInfo &Output, const InputInfoList &Inputs,
3105 const ArgList &Args, const char *LinkingOutput) const {
3106 const llvm::Triple &RawTriple = getToolChain().getTriple();
3107 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3108 const std::string &TripleStr = Triple.getTriple();
3111 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3112 const Driver &D = getToolChain().getDriver();
3113 ArgStringList CmdArgs;
3115 // Check number of inputs for sanity. We need at least one input.
3116 assert(Inputs.size() >= 1 && "Must have at least one input.");
3117 const InputInfo &Input = Inputs[0];
3118 // CUDA/HIP compilation may have multiple inputs (source file + results of
3119 // device-side compilations). OpenMP device jobs also take the host IR as a
3120 // second input. All other jobs are expected to have exactly one
3122 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3123 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
3124 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3125 assert((IsCuda || IsHIP || (IsOpenMPDevice && Inputs.size() == 2) ||
3126 Inputs.size() == 1) &&
3127 "Unable to handle multiple inputs.");
3129 const llvm::Triple *AuxTriple =
3130 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3132 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3133 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3134 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3135 bool IsIAMCU = RawTriple.isOSIAMCU();
3137 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3138 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3139 // Windows), we need to pass Windows-specific flags to cc1.
3140 if (IsCuda || IsHIP) {
3141 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3142 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3143 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3146 // C++ is not supported for IAMCU.
3147 if (IsIAMCU && types::isCXX(Input.getType()))
3148 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3150 // Invoke ourselves in -cc1 mode.
3152 // FIXME: Implement custom jobs for internal actions.
3153 CmdArgs.push_back("-cc1");
3155 // Add the "effective" target triple.
3156 CmdArgs.push_back("-triple");
3157 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3159 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3160 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3161 Args.ClaimAllArgs(options::OPT_MJ);
3164 if (IsCuda || IsHIP) {
3165 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3167 std::string NormalizedTriple;
3168 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3169 JA.isDeviceOffloading(Action::OFK_HIP))
3170 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3175 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3176 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3180 CmdArgs.push_back("-aux-triple");
3181 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3184 if (IsOpenMPDevice) {
3185 // We have to pass the triple of the host if compiling for an OpenMP device.
3186 std::string NormalizedTriple =
3187 C.getSingleOffloadToolChain<Action::OFK_Host>()
3190 CmdArgs.push_back("-aux-triple");
3191 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3194 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3195 Triple.getArch() == llvm::Triple::thumb)) {
3196 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3198 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3200 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3204 // Push all default warning arguments that are specific to
3205 // the given target. These come before user provided warning options
3207 getToolChain().addClangWarningOptions(CmdArgs);
3209 // Select the appropriate action.
3210 RewriteKind rewriteKind = RK_None;
3212 if (isa<AnalyzeJobAction>(JA)) {
3213 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3214 CmdArgs.push_back("-analyze");
3215 } else if (isa<MigrateJobAction>(JA)) {
3216 CmdArgs.push_back("-migrate");
3217 } else if (isa<PreprocessJobAction>(JA)) {
3218 if (Output.getType() == types::TY_Dependencies)
3219 CmdArgs.push_back("-Eonly");
3221 CmdArgs.push_back("-E");
3222 if (Args.hasArg(options::OPT_rewrite_objc) &&
3223 !Args.hasArg(options::OPT_g_Group))
3224 CmdArgs.push_back("-P");
3226 } else if (isa<AssembleJobAction>(JA)) {
3227 CmdArgs.push_back("-emit-obj");
3229 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3231 // Also ignore explicit -force_cpusubtype_ALL option.
3232 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3233 } else if (isa<PrecompileJobAction>(JA)) {
3234 // Use PCH if the user requested it.
3235 bool UsePCH = D.CCCUsePCH;
3237 if (JA.getType() == types::TY_Nothing)
3238 CmdArgs.push_back("-fsyntax-only");
3239 else if (JA.getType() == types::TY_ModuleFile)
3240 CmdArgs.push_back("-emit-module-interface");
3242 CmdArgs.push_back("-emit-pch");
3244 CmdArgs.push_back("-emit-pth");
3245 } else if (isa<VerifyPCHJobAction>(JA)) {
3246 CmdArgs.push_back("-verify-pch");
3248 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3249 "Invalid action for clang tool.");
3250 if (JA.getType() == types::TY_Nothing) {
3251 CmdArgs.push_back("-fsyntax-only");
3252 } else if (JA.getType() == types::TY_LLVM_IR ||
3253 JA.getType() == types::TY_LTO_IR) {
3254 CmdArgs.push_back("-emit-llvm");
3255 } else if (JA.getType() == types::TY_LLVM_BC ||
3256 JA.getType() == types::TY_LTO_BC) {
3257 CmdArgs.push_back("-emit-llvm-bc");
3258 } else if (JA.getType() == types::TY_PP_Asm) {
3259 CmdArgs.push_back("-S");
3260 } else if (JA.getType() == types::TY_AST) {
3261 CmdArgs.push_back("-emit-pch");
3262 } else if (JA.getType() == types::TY_ModuleFile) {
3263 CmdArgs.push_back("-module-file-info");
3264 } else if (JA.getType() == types::TY_RewrittenObjC) {
3265 CmdArgs.push_back("-rewrite-objc");
3266 rewriteKind = RK_NonFragile;
3267 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3268 CmdArgs.push_back("-rewrite-objc");
3269 rewriteKind = RK_Fragile;
3271 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3274 // Preserve use-list order by default when emitting bitcode, so that
3275 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3276 // same result as running passes here. For LTO, we don't need to preserve
3277 // the use-list order, since serialization to bitcode is part of the flow.
3278 if (JA.getType() == types::TY_LLVM_BC)
3279 CmdArgs.push_back("-emit-llvm-uselists");
3281 // Device-side jobs do not support LTO.
3282 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3283 JA.isDeviceOffloading(Action::OFK_Host));
3285 if (D.isUsingLTO() && !isDeviceOffloadAction) {
3286 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3288 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3289 // does not support LTO unit features (CFI, whole program vtable opt)
3291 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
3292 D.getLTOMode() == LTOK_Full)
3293 CmdArgs.push_back("-flto-unit");
3297 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3298 if (!types::isLLVMIR(Input.getType()))
3299 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3301 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3304 if (Args.getLastArg(options::OPT_save_temps_EQ))
3305 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3307 // Embed-bitcode option.
3308 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3309 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3310 // Add flags implied by -fembed-bitcode.
3311 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3312 // Disable all llvm IR level optimizations.
3313 CmdArgs.push_back("-disable-llvm-passes");
3315 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3316 CmdArgs.push_back("-fembed-bitcode=marker");
3318 // We normally speed up the clang process a bit by skipping destructors at
3319 // exit, but when we're generating diagnostics we can rely on some of the
3321 if (!C.isForDiagnostics())
3322 CmdArgs.push_back("-disable-free");
3325 const bool IsAssertBuild = false;
3327 const bool IsAssertBuild = true;
3330 // Disable the verification pass in -asserts builds.
3332 CmdArgs.push_back("-disable-llvm-verifier");
3334 // Discard value names in assert builds unless otherwise specified.
3335 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3336 options::OPT_fno_discard_value_names, !IsAssertBuild))
3337 CmdArgs.push_back("-discard-value-names");
3339 // Set the main file name, so that debug info works even with
3341 CmdArgs.push_back("-main-file-name");
3342 CmdArgs.push_back(getBaseInputName(Args, Input));
3344 // Some flags which affect the language (via preprocessor
3346 if (Args.hasArg(options::OPT_static))
3347 CmdArgs.push_back("-static-define");
3349 if (isa<AnalyzeJobAction>(JA))
3350 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
3352 CheckCodeGenerationOptions(D, Args);
3354 unsigned FunctionAlignment = ParseFunctionAlignment(getToolChain(), Args);
3355 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3356 if (FunctionAlignment) {
3357 CmdArgs.push_back("-function-alignment");
3358 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3361 llvm::Reloc::Model RelocationModel;
3364 std::tie(RelocationModel, PICLevel, IsPIE) =
3365 ParsePICArgs(getToolChain(), Args);
3367 const char *RMName = RelocationModelName(RelocationModel);
3369 if ((RelocationModel == llvm::Reloc::ROPI ||
3370 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3371 types::isCXX(Input.getType()) &&
3372 !Args.hasArg(options::OPT_fallow_unsupported))
3373 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3376 CmdArgs.push_back("-mrelocation-model");
3377 CmdArgs.push_back(RMName);
3380 CmdArgs.push_back("-pic-level");
3381 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3383 CmdArgs.push_back("-pic-is-pie");
3386 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3387 CmdArgs.push_back("-meabi");
3388 CmdArgs.push_back(A->getValue());
3391 CmdArgs.push_back("-mthread-model");
3392 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3393 if (!getToolChain().isThreadModelSupported(A->getValue()))
3394 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3395 << A->getValue() << A->getAsString(Args);
3396 CmdArgs.push_back(A->getValue());
3399 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3401 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3403 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3404 options::OPT_fno_merge_all_constants, false))
3405 CmdArgs.push_back("-fmerge-all-constants");
3407 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3408 options::OPT_fdelete_null_pointer_checks, false))
3409 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3411 // LLVM Code Generator Options.
3413 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3414 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3415 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3416 options::OPT_frewrite_map_file_EQ)) {
3417 StringRef Map = A->getValue();
3418 if (!llvm::sys::fs::exists(Map)) {
3419 D.Diag(diag::err_drv_no_such_file) << Map;
3421 CmdArgs.push_back("-frewrite-map-file");
3422 CmdArgs.push_back(A->getValue());
3428 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3429 StringRef v = A->getValue();
3430 CmdArgs.push_back("-mllvm");
3431 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3435 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3437 CmdArgs.push_back("-fno-jump-tables");
3439 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3440 options::OPT_fno_profile_sample_accurate, false))
3441 CmdArgs.push_back("-fprofile-sample-accurate");
3443 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3444 options::OPT_fno_preserve_as_comments, true))
3445 CmdArgs.push_back("-fno-preserve-as-comments");
3447 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3448 CmdArgs.push_back("-mregparm");
3449 CmdArgs.push_back(A->getValue());
3452 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3453 options::OPT_freg_struct_return)) {
3454 if (getToolChain().getArch() != llvm::Triple::x86) {
3455 D.Diag(diag::err_drv_unsupported_opt_for_target)
3456 << A->getSpelling() << RawTriple.str();
3457 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3458 CmdArgs.push_back("-fpcc-struct-return");
3460 assert(A->getOption().matches(options::OPT_freg_struct_return));
3461 CmdArgs.push_back("-freg-struct-return");
3465 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3466 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3468 if (shouldUseFramePointer(Args, RawTriple))
3469 CmdArgs.push_back("-mdisable-fp-elim");
3470 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3471 options::OPT_fno_zero_initialized_in_bss))
3472 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3474 bool OFastEnabled = isOptimizationLevelFast(Args);
3475 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3476 // enabled. This alias option is being used to simplify the hasFlag logic.
3477 OptSpecifier StrictAliasingAliasOption =
3478 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3479 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3480 // doesn't do any TBAA.
3481 bool TBAAOnByDefault = !D.IsCLMode();
3482 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3483 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3484 CmdArgs.push_back("-relaxed-aliasing");
3485 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3486 options::OPT_fno_struct_path_tbaa))
3487 CmdArgs.push_back("-no-struct-path-tbaa");
3488 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3490 CmdArgs.push_back("-fstrict-enums");
3491 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3493 CmdArgs.push_back("-fno-strict-return");
3494 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3495 options::OPT_fno_allow_editor_placeholders, false))
3496 CmdArgs.push_back("-fallow-editor-placeholders");
3497 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3498 options::OPT_fno_strict_vtable_pointers,
3500 CmdArgs.push_back("-fstrict-vtable-pointers");
3501 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3502 options::OPT_fno_force_emit_vtables,
3504 CmdArgs.push_back("-fforce-emit-vtables");
3505 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3506 options::OPT_fno_optimize_sibling_calls))
3507 CmdArgs.push_back("-mdisable-tail-calls");
3508 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
3509 options::OPT_fescaping_block_tail_calls, false))
3510 CmdArgs.push_back("-fno-escaping-block-tail-calls");
3512 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3513 options::OPT_fno_fine_grained_bitfield_accesses);
3515 // Handle segmented stacks.
3516 if (Args.hasArg(options::OPT_fsplit_stack))
3517 CmdArgs.push_back("-split-stacks");
3519 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
3521 // Decide whether to use verbose asm. Verbose assembly is the default on
3522 // toolchains which have the integrated assembler on by default.
3523 bool IsIntegratedAssemblerDefault =
3524 getToolChain().IsIntegratedAssemblerDefault();
3525 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3526 IsIntegratedAssemblerDefault) ||
3527 Args.hasArg(options::OPT_dA))
3528 CmdArgs.push_back("-masm-verbose");
3530 if (!getToolChain().useIntegratedAs())
3531 CmdArgs.push_back("-no-integrated-as");
3533 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3534 CmdArgs.push_back("-mdebug-pass");
3535 CmdArgs.push_back("Structure");
3537 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3538 CmdArgs.push_back("-mdebug-pass");
3539 CmdArgs.push_back("Arguments");
3542 // Enable -mconstructor-aliases except on darwin, where we have to work around
3543 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3544 // aliases aren't supported.
3545 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
3546 CmdArgs.push_back("-mconstructor-aliases");
3548 // Darwin's kernel doesn't support guard variables; just die if we
3550 if (KernelOrKext && RawTriple.isOSDarwin())
3551 CmdArgs.push_back("-fforbid-guard-variables");
3553 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3555 CmdArgs.push_back("-mms-bitfields");
3558 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3559 options::OPT_mno_pie_copy_relocations,
3561 CmdArgs.push_back("-mpie-copy-relocations");
3564 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3565 CmdArgs.push_back("-fno-plt");
3568 // -fhosted is default.
3569 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3570 // use Freestanding.
3572 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3575 CmdArgs.push_back("-ffreestanding");
3577 // This is a coarse approximation of what llvm-gcc actually does, both
3578 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3579 // complicated ways.
3580 bool AsynchronousUnwindTables =
3581 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3582 options::OPT_fno_asynchronous_unwind_tables,
3583 (getToolChain().IsUnwindTablesDefault(Args) ||
3584 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3586 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3587 AsynchronousUnwindTables))
3588 CmdArgs.push_back("-munwind-tables");
3590 getToolChain().addClangTargetOptions(Args, CmdArgs,
3591 JA.getOffloadingDeviceKind());
3593 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3594 CmdArgs.push_back("-mlimit-float-precision");
3595 CmdArgs.push_back(A->getValue());
3598 // FIXME: Handle -mtune=.
3599 (void)Args.hasArg(options::OPT_mtune_EQ);
3601 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3602 CmdArgs.push_back("-mcode-model");
3603 CmdArgs.push_back(A->getValue());
3606 // Add the target cpu
3607 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3609 CmdArgs.push_back("-target-cpu");
3610 CmdArgs.push_back(Args.MakeArgString(CPU));
3613 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
3615 // These two are potentially updated by AddClangCLArgs.
3616 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3617 bool EmitCodeView = false;
3619 // Add clang-cl arguments.
3620 types::ID InputType = Input.getType();
3622 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
3624 EmitCodeView = Args.hasArg(options::OPT_gcodeview);
3626 const Arg *SplitDWARFArg = nullptr;
3627 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3628 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3630 // Add the split debug info name to the command lines here so we
3631 // can propagate it to the backend.
3632 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3633 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3634 isa<BackendJobAction>(JA));
3635 const char *SplitDWARFOut;
3637 CmdArgs.push_back("-split-dwarf-file");
3638 SplitDWARFOut = SplitDebugName(Args, Input);
3639 CmdArgs.push_back(SplitDWARFOut);
3642 // Pass the linker version in use.
3643 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3644 CmdArgs.push_back("-target-linker-version");
3645 CmdArgs.push_back(A->getValue());
3648 if (!shouldUseLeafFramePointer(Args, RawTriple))
3649 CmdArgs.push_back("-momit-leaf-frame-pointer");
3651 // Explicitly error on some things we know we don't support and can't just
3653 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3655 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
3656 getToolChain().getArch() == llvm::Triple::x86) {
3657 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3658 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3659 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3660 << Unsupported->getOption().getName();
3662 // The faltivec option has been superseded by the maltivec option.
3663 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3664 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3665 << Unsupported->getOption().getName()
3666 << "please use -maltivec and include altivec.h explicitly";
3667 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3668 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3669 << Unsupported->getOption().getName() << "please use -mno-altivec";
3672 Args.AddAllArgs(CmdArgs, options::OPT_v);
3673 Args.AddLastArg(CmdArgs, options::OPT_H);
3674 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3675 CmdArgs.push_back("-header-include-file");
3676 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3679 Args.AddLastArg(CmdArgs, options::OPT_P);
3680 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3682 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3683 CmdArgs.push_back("-diagnostic-log-file");
3684 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3688 bool UseSeparateSections = isUseSeparateSections(Triple);
3690 if (Args.hasFlag(options::OPT_ffunction_sections,
3691 options::OPT_fno_function_sections, UseSeparateSections)) {
3692 CmdArgs.push_back("-ffunction-sections");
3695 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3696 UseSeparateSections)) {
3697 CmdArgs.push_back("-fdata-sections");
3700 if (!Args.hasFlag(options::OPT_funique_section_names,
3701 options::OPT_fno_unique_section_names, true))
3702 CmdArgs.push_back("-fno-unique-section-names");
3704 if (auto *A = Args.getLastArg(
3705 options::OPT_finstrument_functions,
3706 options::OPT_finstrument_functions_after_inlining,
3707 options::OPT_finstrument_function_entry_bare))
3708 A->render(Args, CmdArgs);
3710 // NVPTX doesn't support PGO or coverage. There's no runtime support for
3711 // sampling, overhead of call arc collection is way too high and there's no
3712 // way to collect the output.
3713 if (!Triple.isNVPTX())
3714 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
3716 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3717 ABICompatArg->render(Args, CmdArgs);
3719 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
3720 if (RawTriple.isPS4CPU()) {
3721 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
3722 PS4cpu::addSanitizerArgs(getToolChain(), CmdArgs);
3725 // Pass options for controlling the default header search paths.
3726 if (Args.hasArg(options::OPT_nostdinc)) {
3727 CmdArgs.push_back("-nostdsysteminc");
3728 CmdArgs.push_back("-nobuiltininc");
3730 if (Args.hasArg(options::OPT_nostdlibinc))
3731 CmdArgs.push_back("-nostdsysteminc");
3732 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3733 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3736 // Pass the path to compiler resource files.
3737 CmdArgs.push_back("-resource-dir");
3738 CmdArgs.push_back(D.ResourceDir.c_str());
3740 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3742 RenderARCMigrateToolOptions(D, Args, CmdArgs);
3744 // Add preprocessing options like -I, -D, etc. if we are using the
3747 // FIXME: Support -fpreprocessed
3748 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3749 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3751 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3752 // that "The compiler can only warn and ignore the option if not recognized".
3753 // When building with ccache, it will pass -D options to clang even on
3754 // preprocessed inputs and configure concludes that -fPIC is not supported.
3755 Args.ClaimAllArgs(options::OPT_D);
3757 // Manually translate -O4 to -O3; let clang reject others.
3758 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3759 if (A->getOption().matches(options::OPT_O4)) {
3760 CmdArgs.push_back("-O3");
3761 D.Diag(diag::warn_O4_is_O3);
3763 A->render(Args, CmdArgs);
3767 // Warn about ignored options to clang.
3769 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3770 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3775 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3776 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3780 claimNoWarnArgs(Args);
3782 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3784 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3785 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3786 CmdArgs.push_back("-pedantic");
3787 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3788 Args.AddLastArg(CmdArgs, options::OPT_w);
3790 // Fixed point flags
3791 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
3793 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
3795 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3796 // (-ansi is equivalent to -std=c89 or -std=c++98).
3798 // If a std is supplied, only add -trigraphs if it follows the
3800 bool ImplyVCPPCXXVer = false;
3801 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3802 if (Std->getOption().matches(options::OPT_ansi))
3803 if (types::isCXX(InputType))
3804 CmdArgs.push_back("-std=c++98");
3806 CmdArgs.push_back("-std=c89");
3808 Std->render(Args, CmdArgs);
3810 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3811 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3812 options::OPT_ftrigraphs,
3813 options::OPT_fno_trigraphs))
3815 A->render(Args, CmdArgs);
3817 // Honor -std-default.
3819 // FIXME: Clang doesn't correctly handle -std= when the input language
3820 // doesn't match. For the time being just ignore this for C++ inputs;
3821 // eventually we want to do all the standard defaulting here instead of
3822 // splitting it between the driver and clang -cc1.
3823 if (!types::isCXX(InputType))
3824 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3826 else if (IsWindowsMSVC)
3827 ImplyVCPPCXXVer = true;
3829 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3830 options::OPT_fno_trigraphs);
3833 // GCC's behavior for -Wwrite-strings is a bit strange:
3834 // * In C, this "warning flag" changes the types of string literals from
3835 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3836 // for the discarded qualifier.
3837 // * In C++, this is just a normal warning flag.
3839 // Implementing this warning correctly in C is hard, so we follow GCC's
3840 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3841 // a non-const char* in C, rather than using this crude hack.
3842 if (!types::isCXX(InputType)) {
3843 // FIXME: This should behave just like a warning flag, and thus should also
3844 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3846 Args.getLastArg(options::OPT_Wwrite_strings,
3847 options::OPT_Wno_write_strings, options::OPT_w);
3849 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3850 CmdArgs.push_back("-fconst-strings");
3853 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3854 // during C++ compilation, which it is by default. GCC keeps this define even
3855 // in the presence of '-w', match this behavior bug-for-bug.
3856 if (types::isCXX(InputType) &&
3857 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3859 CmdArgs.push_back("-fdeprecated-macro");
3862 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3863 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3864 if (Asm->getOption().matches(options::OPT_fasm))
3865 CmdArgs.push_back("-fgnu-keywords");
3867 CmdArgs.push_back("-fno-gnu-keywords");
3870 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3871 CmdArgs.push_back("-fno-dwarf-directory-asm");
3873 if (ShouldDisableAutolink(Args, getToolChain()))
3874 CmdArgs.push_back("-fno-autolink");
3876 // Add in -fdebug-compilation-dir if necessary.
3877 addDebugCompDirArg(Args, CmdArgs);
3879 addDebugPrefixMapArg(D, Args, CmdArgs);
3881 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3882 options::OPT_ftemplate_depth_EQ)) {
3883 CmdArgs.push_back("-ftemplate-depth");
3884 CmdArgs.push_back(A->getValue());
3887 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3888 CmdArgs.push_back("-foperator-arrow-depth");
3889 CmdArgs.push_back(A->getValue());
3892 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3893 CmdArgs.push_back("-fconstexpr-depth");
3894 CmdArgs.push_back(A->getValue());
3897 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3898 CmdArgs.push_back("-fconstexpr-steps");
3899 CmdArgs.push_back(A->getValue());
3902 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3903 CmdArgs.push_back("-fbracket-depth");
3904 CmdArgs.push_back(A->getValue());
3907 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3908 options::OPT_Wlarge_by_value_copy_def)) {
3909 if (A->getNumValues()) {
3910 StringRef bytes = A->getValue();
3911 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3913 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3916 if (Args.hasArg(options::OPT_relocatable_pch))
3917 CmdArgs.push_back("-relocatable-pch");
3919 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3920 CmdArgs.push_back("-fconstant-string-class");
3921 CmdArgs.push_back(A->getValue());
3924 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3925 CmdArgs.push_back("-ftabstop");
3926 CmdArgs.push_back(A->getValue());
3929 if (Args.hasFlag(options::OPT_fstack_size_section,
3930 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3931 CmdArgs.push_back("-fstack-size-section");
3933 CmdArgs.push_back("-ferror-limit");
3934 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3935 CmdArgs.push_back(A->getValue());
3937 CmdArgs.push_back("19");
3939 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3940 CmdArgs.push_back("-fmacro-backtrace-limit");
3941 CmdArgs.push_back(A->getValue());
3944 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3945 CmdArgs.push_back("-ftemplate-backtrace-limit");
3946 CmdArgs.push_back(A->getValue());
3949 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3950 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3951 CmdArgs.push_back(A->getValue());
3954 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3955 CmdArgs.push_back("-fspell-checking-limit");
3956 CmdArgs.push_back(A->getValue());
3959 // Pass -fmessage-length=.
3960 CmdArgs.push_back("-fmessage-length");
3961 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3962 CmdArgs.push_back(A->getValue());
3964 // If -fmessage-length=N was not specified, determine whether this is a
3965 // terminal and, if so, implicitly define -fmessage-length appropriately.
3966 unsigned N = llvm::sys::Process::StandardErrColumns();
3967 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3970 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3971 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3972 options::OPT_fvisibility_ms_compat)) {
3973 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3974 CmdArgs.push_back("-fvisibility");
3975 CmdArgs.push_back(A->getValue());
3977 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3978 CmdArgs.push_back("-fvisibility");
3979 CmdArgs.push_back("hidden");
3980 CmdArgs.push_back("-ftype-visibility");
3981 CmdArgs.push_back("default");
3985 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3987 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3989 // Forward -f (flag) options which we can pass directly.
3990 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3991 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3992 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
3993 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3994 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
3995 options::OPT_fno_emulated_tls);
3997 // AltiVec-like language extensions aren't relevant for assembling.
3998 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
3999 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4001 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4002 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4004 // Forward flags for OpenMP. We don't do this if the current action is an
4005 // device offloading action other than OpenMP.
4006 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4007 options::OPT_fno_openmp, false) &&
4008 (JA.isDeviceOffloading(Action::OFK_None) ||
4009 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
4010 switch (D.getOpenMPRuntime(Args)) {
4011 case Driver::OMPRT_OMP:
4012 case Driver::OMPRT_IOMP5:
4013 // Clang can generate useful OpenMP code for these two runtime libraries.
4014 CmdArgs.push_back("-fopenmp");
4016 // If no option regarding the use of TLS in OpenMP codegeneration is
4017 // given, decide a default based on the target. Otherwise rely on the
4018 // options and pass the right information to the frontend.
4019 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4020 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4021 CmdArgs.push_back("-fnoopenmp-use-tls");
4022 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4023 options::OPT_fno_openmp_simd);
4024 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4026 // When in OpenMP offloading mode with NVPTX target, forward
4028 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_cuda_mode,
4029 options::OPT_fno_openmp_cuda_mode);
4032 // By default, if Clang doesn't know how to generate useful OpenMP code
4033 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4034 // down to the actual compilation.
4035 // FIXME: It would be better to have a mode which *only* omits IR
4036 // generation based on the OpenMP support so that we get consistent
4037 // semantic analysis, etc.
4041 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4042 options::OPT_fno_openmp_simd);
4043 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4046 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4047 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4049 const XRayArgs &XRay = getToolChain().getXRayArgs();
4050 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
4052 if (getToolChain().SupportsProfiling())
4053 Args.AddLastArg(CmdArgs, options::OPT_pg);
4055 if (getToolChain().SupportsProfiling())
4056 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4058 // -flax-vector-conversions is default.
4059 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4060 options::OPT_fno_lax_vector_conversions))
4061 CmdArgs.push_back("-fno-lax-vector-conversions");
4063 if (Args.getLastArg(options::OPT_fapple_kext) ||
4064 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4065 CmdArgs.push_back("-fapple-kext");
4067 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4068 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4069 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4070 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4071 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4073 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4074 CmdArgs.push_back("-ftrapv-handler");
4075 CmdArgs.push_back(A->getValue());
4078 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4080 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4081 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4082 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4083 if (A->getOption().matches(options::OPT_fwrapv))
4084 CmdArgs.push_back("-fwrapv");
4085 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4086 options::OPT_fno_strict_overflow)) {
4087 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4088 CmdArgs.push_back("-fwrapv");
4091 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4092 options::OPT_fno_reroll_loops))
4093 if (A->getOption().matches(options::OPT_freroll_loops))
4094 CmdArgs.push_back("-freroll-loops");
4096 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4097 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4098 options::OPT_fno_unroll_loops);
4100 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4102 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
4104 // Translate -mstackrealign
4105 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4107 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4109 if (Args.hasArg(options::OPT_mstack_alignment)) {
4110 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4111 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4114 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4115 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4118 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4120 CmdArgs.push_back("-mstack-probe-size=0");
4123 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4124 options::OPT_mno_stack_arg_probe, true))
4125 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4127 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4128 options::OPT_mno_restrict_it)) {
4129 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4130 CmdArgs.push_back("-mllvm");
4131 CmdArgs.push_back("-arm-restrict-it");
4133 CmdArgs.push_back("-mllvm");
4134 CmdArgs.push_back("-arm-no-restrict-it");
4136 } else if (Triple.isOSWindows() &&
4137 (Triple.getArch() == llvm::Triple::arm ||
4138 Triple.getArch() == llvm::Triple::thumb)) {
4139 // Windows on ARM expects restricted IT blocks
4140 CmdArgs.push_back("-mllvm");
4141 CmdArgs.push_back("-arm-restrict-it");
4144 // Forward -cl options to -cc1
4145 RenderOpenCLOptions(Args, CmdArgs);
4147 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4149 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4152 // Forward -f options with positive and negative forms; we translate
4154 if (Arg *A = getLastProfileSampleUseArg(Args)) {
4155 StringRef fname = A->getValue();
4156 if (!llvm::sys::fs::exists(fname))
4157 D.Diag(diag::err_drv_no_such_file) << fname;
4159 A->render(Args, CmdArgs);
4162 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
4164 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4165 options::OPT_fno_assume_sane_operator_new))
4166 CmdArgs.push_back("-fno-assume-sane-operator-new");
4168 // -fblocks=0 is default.
4169 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4170 getToolChain().IsBlocksDefault()) ||
4171 (Args.hasArg(options::OPT_fgnu_runtime) &&
4172 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4173 !Args.hasArg(options::OPT_fno_blocks))) {
4174 CmdArgs.push_back("-fblocks");
4176 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4177 !getToolChain().hasBlocksRuntime())
4178 CmdArgs.push_back("-fblocks-runtime-optional");
4181 // -fencode-extended-block-signature=1 is default.
4182 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4183 CmdArgs.push_back("-fencode-extended-block-signature");
4185 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4187 types::isCXX(InputType)) {
4188 CmdArgs.push_back("-fcoroutines-ts");
4191 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4192 options::OPT_fno_double_square_bracket_attributes);
4194 bool HaveModules = false;
4195 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4197 // -faccess-control is default.
4198 if (Args.hasFlag(options::OPT_fno_access_control,
4199 options::OPT_faccess_control, false))
4200 CmdArgs.push_back("-fno-access-control");
4202 // -felide-constructors is the default.
4203 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4204 options::OPT_felide_constructors, false))
4205 CmdArgs.push_back("-fno-elide-constructors");
4207 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4209 if (KernelOrKext || (types::isCXX(InputType) &&
4210 (RTTIMode == ToolChain::RM_Disabled)))
4211 CmdArgs.push_back("-fno-rtti");
4213 // -fshort-enums=0 is default for all architectures except Hexagon.
4214 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4215 getToolChain().getArch() == llvm::Triple::hexagon))
4216 CmdArgs.push_back("-fshort-enums");
4218 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
4220 // -fuse-cxa-atexit is default.
4222 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4223 !RawTriple.isOSWindows() &&
4224 RawTriple.getOS() != llvm::Triple::Solaris &&
4225 getToolChain().getArch() != llvm::Triple::hexagon &&
4226 getToolChain().getArch() != llvm::Triple::xcore &&
4227 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4228 RawTriple.hasEnvironment())) ||
4230 CmdArgs.push_back("-fno-use-cxa-atexit");
4232 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4233 options::OPT_fno_register_global_dtors_with_atexit,
4234 RawTriple.isOSDarwin() && !KernelOrKext))
4235 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4237 // -fms-extensions=0 is default.
4238 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4240 CmdArgs.push_back("-fms-extensions");
4242 // -fno-use-line-directives is default.
4243 if (Args.hasFlag(options::OPT_fuse_line_directives,
4244 options::OPT_fno_use_line_directives, false))
4245 CmdArgs.push_back("-fuse-line-directives");
4247 // -fms-compatibility=0 is default.
4248 if (Args.hasFlag(options::OPT_fms_compatibility,
4249 options::OPT_fno_ms_compatibility,
4251 Args.hasFlag(options::OPT_fms_extensions,
4252 options::OPT_fno_ms_extensions, true))))
4253 CmdArgs.push_back("-fms-compatibility");
4255 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
4258 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4260 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4261 if (ImplyVCPPCXXVer) {
4262 StringRef LanguageStandard;
4263 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4264 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4265 .Case("c++14", "-std=c++14")
4266 .Case("c++17", "-std=c++17")
4267 .Case("c++latest", "-std=c++2a")
4269 if (LanguageStandard.empty())
4270 D.Diag(clang::diag::warn_drv_unused_argument)
4271 << StdArg->getAsString(Args);
4274 if (LanguageStandard.empty()) {
4275 if (IsMSVC2015Compatible)
4276 LanguageStandard = "-std=c++14";
4278 LanguageStandard = "-std=c++11";
4281 CmdArgs.push_back(LanguageStandard.data());
4284 // -fno-borland-extensions is default.
4285 if (Args.hasFlag(options::OPT_fborland_extensions,
4286 options::OPT_fno_borland_extensions, false))
4287 CmdArgs.push_back("-fborland-extensions");
4289 // -fno-declspec is default, except for PS4.
4290 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4292 CmdArgs.push_back("-fdeclspec");
4293 else if (Args.hasArg(options::OPT_fno_declspec))
4294 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4296 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4298 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4299 options::OPT_fno_threadsafe_statics,
4300 !IsWindowsMSVC || IsMSVC2015Compatible))
4301 CmdArgs.push_back("-fno-threadsafe-statics");
4303 // -fno-delayed-template-parsing is default, except when targeting MSVC.
4304 // Many old Windows SDK versions require this to parse.
4305 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4306 // compiler. We should be able to disable this by default at some point.
4307 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4308 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4309 CmdArgs.push_back("-fdelayed-template-parsing");
4311 // -fgnu-keywords default varies depending on language; only pass if
4313 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4314 options::OPT_fno_gnu_keywords))
4315 A->render(Args, CmdArgs);
4317 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4319 CmdArgs.push_back("-fgnu89-inline");
4321 if (Args.hasArg(options::OPT_fno_inline))
4322 CmdArgs.push_back("-fno-inline");
4324 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4325 options::OPT_finline_hint_functions,
4326 options::OPT_fno_inline_functions))
4327 InlineArg->render(Args, CmdArgs);
4329 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4330 options::OPT_fno_experimental_new_pass_manager);
4332 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4333 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4334 rewriteKind != RK_None, Input, CmdArgs);
4336 if (Args.hasFlag(options::OPT_fapplication_extension,
4337 options::OPT_fno_application_extension, false))
4338 CmdArgs.push_back("-fapplication-extension");
4340 // Handle GCC-style exception args.
4341 if (!C.getDriver().IsCLMode())
4342 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
4345 // Handle exception personalities
4346 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4347 options::OPT_fseh_exceptions,
4348 options::OPT_fdwarf_exceptions);
4350 const Option &Opt = A->getOption();
4351 if (Opt.matches(options::OPT_fsjlj_exceptions))
4352 CmdArgs.push_back("-fsjlj-exceptions");
4353 if (Opt.matches(options::OPT_fseh_exceptions))
4354 CmdArgs.push_back("-fseh-exceptions");
4355 if (Opt.matches(options::OPT_fdwarf_exceptions))
4356 CmdArgs.push_back("-fdwarf-exceptions");
4358 switch (getToolChain().GetExceptionModel(Args)) {
4361 case llvm::ExceptionHandling::DwarfCFI:
4362 CmdArgs.push_back("-fdwarf-exceptions");
4364 case llvm::ExceptionHandling::SjLj:
4365 CmdArgs.push_back("-fsjlj-exceptions");
4367 case llvm::ExceptionHandling::WinEH:
4368 CmdArgs.push_back("-fseh-exceptions");
4373 // C++ "sane" operator new.
4374 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4375 options::OPT_fno_assume_sane_operator_new))
4376 CmdArgs.push_back("-fno-assume-sane-operator-new");
4378 // -frelaxed-template-template-args is off by default, as it is a severe
4379 // breaking change until a corresponding change to template partial ordering
4381 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4382 options::OPT_fno_relaxed_template_template_args, false))
4383 CmdArgs.push_back("-frelaxed-template-template-args");
4385 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4387 if (Args.hasFlag(options::OPT_fsized_deallocation,
4388 options::OPT_fno_sized_deallocation, false))
4389 CmdArgs.push_back("-fsized-deallocation");
4391 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4393 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4394 options::OPT_fno_aligned_allocation,
4395 options::OPT_faligned_new_EQ)) {
4396 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4397 CmdArgs.push_back("-fno-aligned-allocation");
4399 CmdArgs.push_back("-faligned-allocation");
4402 // The default new alignment can be specified using a dedicated option or via
4403 // a GCC-compatible option that also turns on aligned allocation.
4404 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4405 options::OPT_faligned_new_EQ))
4407 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4409 // -fconstant-cfstrings is default, and may be subject to argument translation
4411 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4412 options::OPT_fno_constant_cfstrings) ||
4413 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4414 options::OPT_mno_constant_cfstrings))
4415 CmdArgs.push_back("-fno-constant-cfstrings");
4417 // -fno-pascal-strings is default, only pass non-default.
4418 if (Args.hasFlag(options::OPT_fpascal_strings,
4419 options::OPT_fno_pascal_strings, false))
4420 CmdArgs.push_back("-fpascal-strings");
4422 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4423 // -fno-pack-struct doesn't apply to -fpack-struct=.
4424 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4425 std::string PackStructStr = "-fpack-struct=";
4426 PackStructStr += A->getValue();
4427 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4428 } else if (Args.hasFlag(options::OPT_fpack_struct,
4429 options::OPT_fno_pack_struct, false)) {
4430 CmdArgs.push_back("-fpack-struct=1");
4433 // Handle -fmax-type-align=N and -fno-type-align
4434 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4435 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4436 if (!SkipMaxTypeAlign) {
4437 std::string MaxTypeAlignStr = "-fmax-type-align=";
4438 MaxTypeAlignStr += A->getValue();
4439 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4441 } else if (RawTriple.isOSDarwin()) {
4442 if (!SkipMaxTypeAlign) {
4443 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4444 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4448 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4449 CmdArgs.push_back("-Qn");
4451 // -fcommon is the default unless compiling kernel code or the target says so
4452 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
4453 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4455 CmdArgs.push_back("-fno-common");
4457 // -fsigned-bitfields is default, and clang doesn't yet support
4458 // -funsigned-bitfields.
4459 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4460 options::OPT_funsigned_bitfields))
4461 D.Diag(diag::warn_drv_clang_unsupported)
4462 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4464 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4465 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4466 D.Diag(diag::err_drv_clang_unsupported)
4467 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4469 // -finput_charset=UTF-8 is default. Reject others
4470 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4471 StringRef value = inputCharset->getValue();
4472 if (!value.equals_lower("utf-8"))
4473 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4477 // -fexec_charset=UTF-8 is default. Reject others
4478 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4479 StringRef value = execCharset->getValue();
4480 if (!value.equals_lower("utf-8"))
4481 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4485 RenderDiagnosticsOptions(D, Args, CmdArgs);
4487 // -fno-asm-blocks is default.
4488 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4490 CmdArgs.push_back("-fasm-blocks");
4492 // -fgnu-inline-asm is default.
4493 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4494 options::OPT_fno_gnu_inline_asm, true))
4495 CmdArgs.push_back("-fno-gnu-inline-asm");
4497 // Enable vectorization per default according to the optimization level
4498 // selected. For optimization levels that want vectorization we use the alias
4499 // option to simplify the hasFlag logic.
4500 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4501 OptSpecifier VectorizeAliasOption =
4502 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4503 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4504 options::OPT_fno_vectorize, EnableVec))
4505 CmdArgs.push_back("-vectorize-loops");
4507 // -fslp-vectorize is enabled based on the optimization level selected.
4508 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4509 OptSpecifier SLPVectAliasOption =
4510 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4511 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4512 options::OPT_fno_slp_vectorize, EnableSLPVec))
4513 CmdArgs.push_back("-vectorize-slp");
4515 ParseMPreferVectorWidth(D, Args, CmdArgs);
4517 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4518 A->render(Args, CmdArgs);
4520 if (Arg *A = Args.getLastArg(
4521 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4522 A->render(Args, CmdArgs);
4524 // -fdollars-in-identifiers default varies depending on platform and
4525 // language; only pass if specified.
4526 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4527 options::OPT_fno_dollars_in_identifiers)) {
4528 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4529 CmdArgs.push_back("-fdollars-in-identifiers");
4531 CmdArgs.push_back("-fno-dollars-in-identifiers");
4534 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4535 // practical purposes.
4536 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4537 options::OPT_fno_unit_at_a_time)) {
4538 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4539 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4542 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4543 options::OPT_fno_apple_pragma_pack, false))
4544 CmdArgs.push_back("-fapple-pragma-pack");
4546 if (Args.hasFlag(options::OPT_fsave_optimization_record,
4547 options::OPT_foptimization_record_file_EQ,
4548 options::OPT_fno_save_optimization_record, false)) {
4549 CmdArgs.push_back("-opt-record-file");
4551 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4553 CmdArgs.push_back(A->getValue());
4557 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4558 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4559 F = FinalOutput->getValue();
4563 // Use the input filename.
4564 F = llvm::sys::path::stem(Input.getBaseInput());
4566 // If we're compiling for an offload architecture (i.e. a CUDA device),
4567 // we need to make the file name for the device compilation different
4568 // from the host compilation.
4569 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4570 !JA.isDeviceOffloading(Action::OFK_Host)) {
4571 llvm::sys::path::replace_extension(F, "");
4572 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4573 Triple.normalize());
4575 F += JA.getOffloadingArch();
4579 llvm::sys::path::replace_extension(F, "opt.yaml");
4580 CmdArgs.push_back(Args.MakeArgString(F));
4584 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4585 options::OPT_fno_rewrite_imports, false);
4587 CmdArgs.push_back("-frewrite-imports");
4589 // Enable rewrite includes if the user's asked for it or if we're generating
4591 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4592 // nice to enable this when doing a crashdump for modules as well.
4593 if (Args.hasFlag(options::OPT_frewrite_includes,
4594 options::OPT_fno_rewrite_includes, false) ||
4595 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
4596 CmdArgs.push_back("-frewrite-includes");
4598 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4599 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4600 options::OPT_traditional_cpp)) {
4601 if (isa<PreprocessJobAction>(JA))
4602 CmdArgs.push_back("-traditional-cpp");
4604 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4607 Args.AddLastArg(CmdArgs, options::OPT_dM);
4608 Args.AddLastArg(CmdArgs, options::OPT_dD);
4610 // Handle serialized diagnostics.
4611 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4612 CmdArgs.push_back("-serialize-diagnostic-file");
4613 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4616 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4617 CmdArgs.push_back("-fretain-comments-from-system-headers");
4619 // Forward -fcomment-block-commands to -cc1.
4620 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4621 // Forward -fparse-all-comments to -cc1.
4622 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4624 // Turn -fplugin=name.so into -load name.so
4625 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4626 CmdArgs.push_back("-load");
4627 CmdArgs.push_back(A->getValue());
4631 // Setup statistics file output.
4632 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4633 if (!StatsFile.empty())
4634 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
4636 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4638 // -finclude-default-header flag is for preprocessor,
4639 // do not pass it to other cc1 commands when save-temps is enabled
4640 if (C.getDriver().isSaveTempsEnabled() &&
4641 !isa<PreprocessJobAction>(JA)) {
4642 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4644 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4645 CmdArgs.push_back(Arg->getValue());
4649 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4651 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4654 // We translate this by hand to the -cc1 argument, since nightly test uses
4655 // it and developers have been trained to spell it with -mllvm. Both
4656 // spellings are now deprecated and should be removed.
4657 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4658 CmdArgs.push_back("-disable-llvm-optzns");
4660 A->render(Args, CmdArgs);
4664 // With -save-temps, we want to save the unoptimized bitcode output from the
4665 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4667 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4668 // has slightly different breakdown between stages.
4669 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4670 // pristine IR generated by the frontend. Ideally, a new compile action should
4671 // be added so both IR can be captured.
4672 if (C.getDriver().isSaveTempsEnabled() &&
4673 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4674 isa<CompileJobAction>(JA))
4675 CmdArgs.push_back("-disable-llvm-passes");
4677 if (Output.getType() == types::TY_Dependencies) {
4678 // Handled with other dependency code.
4679 } else if (Output.isFilename()) {
4680 CmdArgs.push_back("-o");
4681 CmdArgs.push_back(Output.getFilename());
4683 assert(Output.isNothing() && "Invalid output.");
4686 addDashXForInput(Args, Input, CmdArgs);
4688 if (Input.isFilename())
4689 CmdArgs.push_back(Input.getFilename());
4691 Input.getInputArg().renderAsInput(Args, CmdArgs);
4693 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4695 const char *Exec = D.getClangProgramPath();
4697 // Optionally embed the -cc1 level arguments into the debug info, for build
4699 // Also record command line arguments into the debug info if
4700 // -grecord-gcc-switches options is set on.
4701 // By default, -gno-record-gcc-switches is set on and no recording.
4702 if (getToolChain().UseDwarfDebugFlags() ||
4703 Args.hasFlag(options::OPT_grecord_gcc_switches,
4704 options::OPT_gno_record_gcc_switches, false)) {
4705 ArgStringList OriginalArgs;
4706 for (const auto &Arg : Args)
4707 Arg->render(Args, OriginalArgs);
4709 SmallString<256> Flags;
4711 for (const char *OriginalArg : OriginalArgs) {
4712 SmallString<128> EscapedArg;
4713 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4715 Flags += EscapedArg;
4717 CmdArgs.push_back("-dwarf-debug-flags");
4718 CmdArgs.push_back(Args.MakeArgString(Flags));
4722 // Host-side cuda compilation receives all device-side outputs in a single
4723 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
4724 if (Inputs.size() > 1) {
4725 assert(Inputs.size() == 2 && "More than one GPU binary!");
4726 CmdArgs.push_back("-fcuda-include-gpubinary");
4727 CmdArgs.push_back(Inputs[1].getFilename());
4730 if (Args.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc, false))
4731 CmdArgs.push_back("-fcuda-rdc");
4732 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
4733 options::OPT_fno_cuda_short_ptr, false))
4734 CmdArgs.push_back("-fcuda-short-ptr");
4737 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4738 // to specify the result of the compile phase on the host, so the meaningful
4739 // device declarations can be identified. Also, -fopenmp-is-device is passed
4740 // along to tell the frontend that it is generating code for a device, so that
4741 // only the relevant declarations are emitted.
4742 if (IsOpenMPDevice) {
4743 CmdArgs.push_back("-fopenmp-is-device");
4744 if (Inputs.size() == 2) {
4745 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4746 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4750 // For all the host OpenMP offloading compile jobs we need to pass the targets
4751 // information using -fopenmp-targets= option.
4752 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
4753 SmallString<128> TargetInfo("-fopenmp-targets=");
4755 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4756 assert(Tgts && Tgts->getNumValues() &&
4757 "OpenMP offloading has to have targets specified.");
4758 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4761 // We need to get the string from the triple because it may be not exactly
4762 // the same as the one we get directly from the arguments.
4763 llvm::Triple T(Tgts->getValue(i));
4764 TargetInfo += T.getTriple();
4766 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4769 bool WholeProgramVTables =
4770 Args.hasFlag(options::OPT_fwhole_program_vtables,
4771 options::OPT_fno_whole_program_vtables, false);
4772 if (WholeProgramVTables) {
4773 if (!D.isUsingLTO())
4774 D.Diag(diag::err_drv_argument_only_allowed_with)
4775 << "-fwhole-program-vtables"
4777 CmdArgs.push_back("-fwhole-program-vtables");
4780 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4781 options::OPT_fno_experimental_isel)) {
4782 CmdArgs.push_back("-mllvm");
4783 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4784 CmdArgs.push_back("-global-isel=1");
4786 // GISel is on by default on AArch64 -O0, so don't bother adding
4787 // the fallback remarks for it. Other combinations will add a warning of
4789 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4790 bool IsOptLevelSupported = false;
4792 Arg *A = Args.getLastArg(options::OPT_O_Group);
4793 if (Triple.getArch() == llvm::Triple::aarch64) {
4794 if (!A || A->getOption().matches(options::OPT_O0))
4795 IsOptLevelSupported = true;
4797 if (!IsArchSupported || !IsOptLevelSupported) {
4798 CmdArgs.push_back("-mllvm");
4799 CmdArgs.push_back("-global-isel-abort=2");
4801 if (!IsArchSupported)
4802 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4804 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4807 CmdArgs.push_back("-global-isel=0");
4811 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
4812 options::OPT_fno_force_enable_int128)) {
4813 if (A->getOption().matches(options::OPT_fforce_enable_int128))
4814 CmdArgs.push_back("-fforce-enable-int128");
4817 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
4818 options::OPT_fno_complete_member_pointers, false))
4819 CmdArgs.push_back("-fcomplete-member-pointers");
4821 if (Arg *A = Args.getLastArg(options::OPT_moutline,
4822 options::OPT_mno_outline)) {
4823 if (A->getOption().matches(options::OPT_moutline)) {
4824 // We only support -moutline in AArch64 right now. If we're not compiling
4825 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
4826 // proper mllvm flags.
4827 if (Triple.getArch() != llvm::Triple::aarch64) {
4828 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
4830 CmdArgs.push_back("-mllvm");
4831 CmdArgs.push_back("-enable-machine-outliner");
4834 // Disable all outlining behaviour.
4835 CmdArgs.push_back("-mllvm");
4836 CmdArgs.push_back("-enable-machine-outliner=never");
4840 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
4841 getToolChain().getTriple().isOSBinFormatELF() &&
4842 getToolChain().useIntegratedAs()))
4843 CmdArgs.push_back("-faddrsig");
4845 // Finally add the compile command to the compilation.
4846 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4847 Output.getType() == types::TY_Object &&
4848 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4850 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4851 C.addCommand(llvm::make_unique<FallbackCommand>(
4852 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4853 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4854 isa<PrecompileJobAction>(JA)) {
4855 // In /fallback builds, run the main compilation even if the pch generation
4856 // fails, so that the main compilation's fallback to cl.exe runs.
4857 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4860 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4863 if (Arg *A = Args.getLastArg(options::OPT_pg))
4864 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4865 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4866 << A->getAsString(Args);
4868 // Claim some arguments which clang supports automatically.
4870 // -fpch-preprocess is used with gcc to add a special marker in the output to
4871 // include the PCH file. Clang's PTH solution is completely transparent, so we
4872 // do not need to deal with it at all.
4873 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4875 // Claim some arguments which clang doesn't support, but we don't
4876 // care to warn the user about.
4877 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4878 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4880 // Disable warnings for clang -E -emit-llvm foo.c
4881 Args.ClaimAllArgs(options::OPT_emit_llvm);
4884 Clang::Clang(const ToolChain &TC)
4885 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4886 // as it is for other tools. Some operations on a Tool actually test
4887 // whether that tool is Clang based on the Tool's Name as a string.
4888 : Tool("clang", "clang frontend", TC, RF_Full) {}
4892 /// Add options related to the Objective-C runtime/ABI.
4894 /// Returns true if the runtime is non-fragile.
4895 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4896 ArgStringList &cmdArgs,
4897 RewriteKind rewriteKind) const {
4898 // Look for the controlling runtime option.
4900 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4901 options::OPT_fobjc_runtime_EQ);
4903 // Just forward -fobjc-runtime= to the frontend. This supercedes
4904 // options about fragility.
4906 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4907 ObjCRuntime runtime;
4908 StringRef value = runtimeArg->getValue();
4909 if (runtime.tryParse(value)) {
4910 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4913 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
4914 (runtime.getVersion() >= VersionTuple(2, 0)))
4915 if (!getToolChain().getTriple().isOSBinFormatELF() &&
4916 !getToolChain().getTriple().isOSBinFormatCOFF()) {
4917 getToolChain().getDriver().Diag(
4918 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
4919 << runtime.getVersion().getMajor();
4922 runtimeArg->render(args, cmdArgs);
4926 // Otherwise, we'll need the ABI "version". Version numbers are
4927 // slightly confusing for historical reasons:
4928 // 1 - Traditional "fragile" ABI
4929 // 2 - Non-fragile ABI, version 1
4930 // 3 - Non-fragile ABI, version 2
4931 unsigned objcABIVersion = 1;
4932 // If -fobjc-abi-version= is present, use that to set the version.
4933 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4934 StringRef value = abiArg->getValue();
4937 else if (value == "2")
4939 else if (value == "3")
4942 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4944 // Otherwise, determine if we are using the non-fragile ABI.
4945 bool nonFragileABIIsDefault =
4946 (rewriteKind == RK_NonFragile ||
4947 (rewriteKind == RK_None &&
4948 getToolChain().IsObjCNonFragileABIDefault()));
4949 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4950 options::OPT_fno_objc_nonfragile_abi,
4951 nonFragileABIIsDefault)) {
4952 // Determine the non-fragile ABI version to use.
4953 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4954 unsigned nonFragileABIVersion = 1;
4956 unsigned nonFragileABIVersion = 2;
4960 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4961 StringRef value = abiArg->getValue();
4963 nonFragileABIVersion = 1;
4964 else if (value == "2")
4965 nonFragileABIVersion = 2;
4967 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4971 objcABIVersion = 1 + nonFragileABIVersion;
4977 // We don't actually care about the ABI version other than whether
4978 // it's non-fragile.
4979 bool isNonFragile = objcABIVersion != 1;
4981 // If we have no runtime argument, ask the toolchain for its default runtime.
4982 // However, the rewriter only really supports the Mac runtime, so assume that.
4983 ObjCRuntime runtime;
4985 switch (rewriteKind) {
4987 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4990 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4993 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4998 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4999 // On Darwin, make this use the default behavior for the toolchain.
5000 if (getToolChain().getTriple().isOSDarwin()) {
5001 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5003 // Otherwise, build for a generic macosx port.
5005 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5010 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5011 // Legacy behaviour is to target the gnustep runtime if we are in
5012 // non-fragile mode or the GCC runtime in fragile mode.
5014 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
5016 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5020 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5024 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5025 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5033 bool Asynch = false;
5034 bool NoUnwindC = false;
5036 } // end anonymous namespace
5038 /// /EH controls whether to run destructor cleanups when exceptions are
5039 /// thrown. There are three modifiers:
5040 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5041 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5042 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5043 /// - c: Assume that extern "C" functions are implicitly nounwind.
5044 /// The default is /EHs-c-, meaning cleanups are disabled.
5045 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5048 std::vector<std::string> EHArgs =
5049 Args.getAllArgValues(options::OPT__SLASH_EH);
5050 for (auto EHVal : EHArgs) {
5051 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5054 EH.Asynch = maybeConsumeDash(EHVal, I);
5059 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5062 EH.Synch = maybeConsumeDash(EHVal, I);
5069 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5073 // The /GX, /GX- flags are only processed if there are not /EH flags.
5074 // The default is that /GX is not specified.
5075 if (EHArgs.empty() &&
5076 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5077 /*default=*/false)) {
5079 EH.NoUnwindC = true;
5085 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5086 ArgStringList &CmdArgs,
5087 codegenoptions::DebugInfoKind *DebugInfoKind,
5088 bool *EmitCodeView) const {
5089 unsigned RTOptionID = options::OPT__SLASH_MT;
5091 if (Args.hasArg(options::OPT__SLASH_LDd))
5092 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5093 // but defining _DEBUG is sticky.
5094 RTOptionID = options::OPT__SLASH_MTd;
5096 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5097 RTOptionID = A->getOption().getID();
5099 StringRef FlagForCRT;
5100 switch (RTOptionID) {
5101 case options::OPT__SLASH_MD:
5102 if (Args.hasArg(options::OPT__SLASH_LDd))
5103 CmdArgs.push_back("-D_DEBUG");
5104 CmdArgs.push_back("-D_MT");
5105 CmdArgs.push_back("-D_DLL");
5106 FlagForCRT = "--dependent-lib=msvcrt";
5108 case options::OPT__SLASH_MDd:
5109 CmdArgs.push_back("-D_DEBUG");
5110 CmdArgs.push_back("-D_MT");
5111 CmdArgs.push_back("-D_DLL");
5112 FlagForCRT = "--dependent-lib=msvcrtd";
5114 case options::OPT__SLASH_MT:
5115 if (Args.hasArg(options::OPT__SLASH_LDd))
5116 CmdArgs.push_back("-D_DEBUG");
5117 CmdArgs.push_back("-D_MT");
5118 CmdArgs.push_back("-flto-visibility-public-std");
5119 FlagForCRT = "--dependent-lib=libcmt";
5121 case options::OPT__SLASH_MTd:
5122 CmdArgs.push_back("-D_DEBUG");
5123 CmdArgs.push_back("-D_MT");
5124 CmdArgs.push_back("-flto-visibility-public-std");
5125 FlagForCRT = "--dependent-lib=libcmtd";
5128 llvm_unreachable("Unexpected option ID.");
5131 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5132 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5134 CmdArgs.push_back(FlagForCRT.data());
5136 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5137 // users want. The /Za flag to cl.exe turns this off, but it's not
5138 // implemented in clang.
5139 CmdArgs.push_back("--dependent-lib=oldnames");
5142 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5143 A->render(Args, CmdArgs);
5145 // This controls whether or not we emit RTTI data for polymorphic types.
5146 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5148 CmdArgs.push_back("-fno-rtti-data");
5150 // This controls whether or not we emit stack-protector instrumentation.
5151 // In MSVC, Buffer Security Check (/GS) is on by default.
5152 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5153 /*default=*/true)) {
5154 CmdArgs.push_back("-stack-protector");
5155 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5158 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5159 if (Arg *DebugInfoArg =
5160 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5161 options::OPT_gline_tables_only)) {
5162 *EmitCodeView = true;
5163 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5164 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5166 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5167 CmdArgs.push_back("-gcodeview");
5169 *EmitCodeView = false;
5172 const Driver &D = getToolChain().getDriver();
5173 EHFlags EH = parseClangCLEHFlags(D, Args);
5174 if (EH.Synch || EH.Asynch) {
5175 if (types::isCXX(InputType))
5176 CmdArgs.push_back("-fcxx-exceptions");
5177 CmdArgs.push_back("-fexceptions");
5179 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5180 CmdArgs.push_back("-fexternc-nounwind");
5182 // /EP should expand to -E -P.
5183 if (Args.hasArg(options::OPT__SLASH_EP)) {
5184 CmdArgs.push_back("-E");
5185 CmdArgs.push_back("-P");
5188 unsigned VolatileOptionID;
5189 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5190 getToolChain().getArch() == llvm::Triple::x86)
5191 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5193 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5195 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5196 VolatileOptionID = A->getOption().getID();
5198 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5199 CmdArgs.push_back("-fms-volatile");
5201 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5202 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5203 if (MostGeneralArg && BestCaseArg)
5204 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5205 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5207 if (MostGeneralArg) {
5208 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5209 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5210 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5212 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5213 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5214 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5215 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5216 << FirstConflict->getAsString(Args)
5217 << SecondConflict->getAsString(Args);
5220 CmdArgs.push_back("-fms-memptr-rep=single");
5221 else if (MultipleArg)
5222 CmdArgs.push_back("-fms-memptr-rep=multiple");
5224 CmdArgs.push_back("-fms-memptr-rep=virtual");
5227 // Parse the default calling convention options.
5229 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
5230 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5231 options::OPT__SLASH_Gregcall)) {
5232 unsigned DCCOptId = CCArg->getOption().getID();
5233 const char *DCCFlag = nullptr;
5234 bool ArchSupported = true;
5235 llvm::Triple::ArchType Arch = getToolChain().getArch();
5237 case options::OPT__SLASH_Gd:
5238 DCCFlag = "-fdefault-calling-conv=cdecl";
5240 case options::OPT__SLASH_Gr:
5241 ArchSupported = Arch == llvm::Triple::x86;
5242 DCCFlag = "-fdefault-calling-conv=fastcall";
5244 case options::OPT__SLASH_Gz:
5245 ArchSupported = Arch == llvm::Triple::x86;
5246 DCCFlag = "-fdefault-calling-conv=stdcall";
5248 case options::OPT__SLASH_Gv:
5249 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5250 DCCFlag = "-fdefault-calling-conv=vectorcall";
5252 case options::OPT__SLASH_Gregcall:
5253 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5254 DCCFlag = "-fdefault-calling-conv=regcall";
5258 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5259 if (ArchSupported && DCCFlag)
5260 CmdArgs.push_back(DCCFlag);
5263 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5264 A->render(Args, CmdArgs);
5266 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5267 CmdArgs.push_back("-fdiagnostics-format");
5268 if (Args.hasArg(options::OPT__SLASH_fallback))
5269 CmdArgs.push_back("msvc-fallback");
5271 CmdArgs.push_back("msvc");
5274 if (Args.hasArg(options::OPT__SLASH_Guard) &&
5275 Args.getLastArgValue(options::OPT__SLASH_Guard).equals_lower("cf"))
5276 CmdArgs.push_back("-cfguard");
5279 visualstudio::Compiler *Clang::getCLFallback() const {
5281 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5282 return CLFallback.get();
5286 const char *Clang::getBaseInputName(const ArgList &Args,
5287 const InputInfo &Input) {
5288 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5291 const char *Clang::getBaseInputStem(const ArgList &Args,
5292 const InputInfoList &Inputs) {
5293 const char *Str = getBaseInputName(Args, Inputs[0]);
5295 if (const char *End = strrchr(Str, '.'))
5296 return Args.MakeArgString(std::string(Str, End));
5301 const char *Clang::getDependencyFileName(const ArgList &Args,
5302 const InputInfoList &Inputs) {
5303 // FIXME: Think about this more.
5306 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5307 std::string Str(OutputOpt->getValue());
5308 Res = Str.substr(0, Str.rfind('.'));
5310 Res = getBaseInputStem(Args, Inputs);
5312 return Args.MakeArgString(Res + ".d");
5317 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5318 ArgStringList &CmdArgs) const {
5321 const llvm::Triple &Triple = getToolChain().getTriple();
5322 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5324 CmdArgs.push_back("-target-abi");
5325 CmdArgs.push_back(ABIName.data());
5328 void ClangAs::AddX86TargetArgs(const ArgList &Args,
5329 ArgStringList &CmdArgs) const {
5330 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5331 StringRef Value = A->getValue();
5332 if (Value == "intel" || Value == "att") {
5333 CmdArgs.push_back("-mllvm");
5334 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5336 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5337 << A->getOption().getName() << Value;
5342 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5343 const InputInfo &Output, const InputInfoList &Inputs,
5344 const ArgList &Args,
5345 const char *LinkingOutput) const {
5346 ArgStringList CmdArgs;
5348 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5349 const InputInfo &Input = Inputs[0];
5351 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5352 const std::string &TripleStr = Triple.getTriple();
5353 const auto &D = getToolChain().getDriver();
5355 // Don't warn about "clang -w -c foo.s"
5356 Args.ClaimAllArgs(options::OPT_w);
5357 // and "clang -emit-llvm -c foo.s"
5358 Args.ClaimAllArgs(options::OPT_emit_llvm);
5360 claimNoWarnArgs(Args);
5362 // Invoke ourselves in -cc1as mode.
5364 // FIXME: Implement custom jobs for internal actions.
5365 CmdArgs.push_back("-cc1as");
5367 // Add the "effective" target triple.
5368 CmdArgs.push_back("-triple");
5369 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5371 // Set the output mode, we currently only expect to be used as a real
5373 CmdArgs.push_back("-filetype");
5374 CmdArgs.push_back("obj");
5376 // Set the main file name, so that debug info works even with
5377 // -save-temps or preprocessed assembly.
5378 CmdArgs.push_back("-main-file-name");
5379 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5381 // Add the target cpu
5382 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5384 CmdArgs.push_back("-target-cpu");
5385 CmdArgs.push_back(Args.MakeArgString(CPU));
5388 // Add the target features
5389 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5391 // Ignore explicit -force_cpusubtype_ALL option.
5392 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5394 // Pass along any -I options so we get proper .include search paths.
5395 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5397 // Determine the original source input.
5398 const Action *SourceAction = &JA;
5399 while (SourceAction->getKind() != Action::InputClass) {
5400 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5401 SourceAction = SourceAction->getInputs()[0];
5404 // Forward -g and handle debug info related flags, assuming we are dealing
5405 // with an actual assembly file.
5406 bool WantDebug = false;
5407 unsigned DwarfVersion = 0;
5408 Args.ClaimAllArgs(options::OPT_g_Group);
5409 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5410 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5411 !A->getOption().matches(options::OPT_ggdb0);
5413 DwarfVersion = DwarfVersionNum(A->getSpelling());
5415 if (DwarfVersion == 0)
5416 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5418 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5420 if (SourceAction->getType() == types::TY_Asm ||
5421 SourceAction->getType() == types::TY_PP_Asm) {
5422 // You might think that it would be ok to set DebugInfoKind outside of
5423 // the guard for source type, however there is a test which asserts
5424 // that some assembler invocation receives no -debug-info-kind,
5425 // and it's not clear whether that test is just overly restrictive.
5426 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5427 : codegenoptions::NoDebugInfo);
5428 // Add the -fdebug-compilation-dir flag if needed.
5429 addDebugCompDirArg(Args, CmdArgs);
5431 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5433 // Set the AT_producer to the clang version when using the integrated
5434 // assembler on assembly source files.
5435 CmdArgs.push_back("-dwarf-debug-producer");
5436 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5438 // And pass along -I options
5439 Args.AddAllArgs(CmdArgs, options::OPT_I);
5441 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5442 llvm::DebuggerKind::Default);
5443 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
5446 // Handle -fPIC et al -- the relocation-model affects the assembler
5447 // for some targets.
5448 llvm::Reloc::Model RelocationModel;
5451 std::tie(RelocationModel, PICLevel, IsPIE) =
5452 ParsePICArgs(getToolChain(), Args);
5454 const char *RMName = RelocationModelName(RelocationModel);
5456 CmdArgs.push_back("-mrelocation-model");
5457 CmdArgs.push_back(RMName);
5460 // Optionally embed the -cc1as level arguments into the debug info, for build
5462 if (getToolChain().UseDwarfDebugFlags()) {
5463 ArgStringList OriginalArgs;
5464 for (const auto &Arg : Args)
5465 Arg->render(Args, OriginalArgs);
5467 SmallString<256> Flags;
5468 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5470 for (const char *OriginalArg : OriginalArgs) {
5471 SmallString<128> EscapedArg;
5472 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5474 Flags += EscapedArg;
5476 CmdArgs.push_back("-dwarf-debug-flags");
5477 CmdArgs.push_back(Args.MakeArgString(Flags));
5480 // FIXME: Add -static support, once we have it.
5482 // Add target specific flags.
5483 switch (getToolChain().getArch()) {
5487 case llvm::Triple::mips:
5488 case llvm::Triple::mipsel:
5489 case llvm::Triple::mips64:
5490 case llvm::Triple::mips64el:
5491 AddMIPSTargetArgs(Args, CmdArgs);
5494 case llvm::Triple::x86:
5495 case llvm::Triple::x86_64:
5496 AddX86TargetArgs(Args, CmdArgs);
5499 case llvm::Triple::arm:
5500 case llvm::Triple::armeb:
5501 case llvm::Triple::thumb:
5502 case llvm::Triple::thumbeb:
5503 // This isn't in AddARMTargetArgs because we want to do this for assembly
5505 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5506 options::OPT_mno_default_build_attributes, true)) {
5507 CmdArgs.push_back("-mllvm");
5508 CmdArgs.push_back("-arm-add-build-attributes");
5513 // Consume all the warning flags. Usually this would be handled more
5514 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5515 // doesn't handle that so rather than warning about unused flags that are
5516 // actually used, we'll lie by omission instead.
5517 // FIXME: Stop lying and consume only the appropriate driver flags
5518 Args.ClaimAllArgs(options::OPT_W_Group);
5520 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5521 getToolChain().getDriver());
5523 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5525 assert(Output.isFilename() && "Unexpected lipo output.");
5526 CmdArgs.push_back("-o");
5527 CmdArgs.push_back(Output.getFilename());
5529 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5530 getToolChain().getTriple().isOSLinux()) {
5531 CmdArgs.push_back("-split-dwarf-file");
5532 CmdArgs.push_back(SplitDebugName(Args, Input));
5535 assert(Input.isFilename() && "Invalid input.");
5536 CmdArgs.push_back(Input.getFilename());
5538 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5539 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5542 // Begin OffloadBundler
5544 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5545 const InputInfo &Output,
5546 const InputInfoList &Inputs,
5547 const llvm::opt::ArgList &TCArgs,
5548 const char *LinkingOutput) const {
5549 // The version with only one output is expected to refer to a bundling job.
5550 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5552 // The bundling command looks like this:
5553 // clang-offload-bundler -type=bc
5554 // -targets=host-triple,openmp-triple1,openmp-triple2
5555 // -outputs=input_file
5556 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5558 ArgStringList CmdArgs;
5561 CmdArgs.push_back(TCArgs.MakeArgString(
5562 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5564 assert(JA.getInputs().size() == Inputs.size() &&
5565 "Not have inputs for all dependence actions??");
5568 SmallString<128> Triples;
5569 Triples += "-targets=";
5570 for (unsigned I = 0; I < Inputs.size(); ++I) {
5574 // Find ToolChain for this input.
5575 Action::OffloadKind CurKind = Action::OFK_Host;
5576 const ToolChain *CurTC = &getToolChain();
5577 const Action *CurDep = JA.getInputs()[I];
5579 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
5581 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
5582 assert(CurTC == nullptr && "Expected one dependence!");
5583 CurKind = A->getOffloadingDeviceKind();
5587 Triples += Action::GetOffloadKindName(CurKind);
5589 Triples += CurTC->getTriple().normalize();
5590 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
5592 Triples += CurDep->getOffloadingArch();
5595 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5597 // Get bundled file command.
5599 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5601 // Get unbundled files command.
5602 SmallString<128> UB;
5604 for (unsigned I = 0; I < Inputs.size(); ++I) {
5608 // Find ToolChain for this input.
5609 const ToolChain *CurTC = &getToolChain();
5610 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5612 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5613 assert(CurTC == nullptr && "Expected one dependence!");
5617 UB += CurTC->getInputFilename(Inputs[I]);
5619 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5621 // All the inputs are encoded as commands.
5622 C.addCommand(llvm::make_unique<Command>(
5624 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5628 void OffloadBundler::ConstructJobMultipleOutputs(
5629 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5630 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5631 const char *LinkingOutput) const {
5632 // The version with multiple outputs is expected to refer to a unbundling job.
5633 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5635 // The unbundling command looks like this:
5636 // clang-offload-bundler -type=bc
5637 // -targets=host-triple,openmp-triple1,openmp-triple2
5638 // -inputs=input_file
5639 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5642 ArgStringList CmdArgs;
5644 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5645 InputInfo Input = Inputs.front();
5648 CmdArgs.push_back(TCArgs.MakeArgString(
5649 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5652 SmallString<128> Triples;
5653 Triples += "-targets=";
5654 auto DepInfo = UA.getDependentActionsInfo();
5655 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5659 auto &Dep = DepInfo[I];
5660 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5662 Triples += Dep.DependentToolChain->getTriple().normalize();
5663 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
5664 !Dep.DependentBoundArch.empty()) {
5666 Triples += Dep.DependentBoundArch;
5670 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5672 // Get bundled file command.
5674 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5676 // Get unbundled files command.
5677 SmallString<128> UB;
5679 for (unsigned I = 0; I < Outputs.size(); ++I) {
5682 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
5684 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5685 CmdArgs.push_back("-unbundle");
5687 // All the inputs are encoded as commands.
5688 C.addCommand(llvm::make_unique<Command>(
5690 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),