1 //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 #include "Arch/AArch64.h"
12 #include "Arch/Mips.h"
14 #include "Arch/RISCV.h"
15 #include "Arch/Sparc.h"
16 #include "Arch/SystemZ.h"
19 #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/Distro.h"
29 #include "clang/Driver/DriverDiagnostic.h"
30 #include "clang/Driver/Options.h"
31 #include "clang/Driver/SanitizerArgs.h"
32 #include "clang/Driver/XRayArgs.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Config/llvm-config.h"
35 #include "llvm/Option/ArgList.h"
36 #include "llvm/Support/CodeGen.h"
37 #include "llvm/Support/Compression.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/TargetParser.h"
42 #include "llvm/Support/YAMLParser.h"
45 #include <unistd.h> // For getuid().
48 using namespace clang::driver;
49 using namespace clang::driver::tools;
50 using namespace clang;
51 using namespace llvm::opt;
53 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
55 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
56 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
57 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
58 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
59 << A->getBaseArg().getAsString(Args)
60 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
65 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
66 // In gcc, only ARM checks this, but it seems reasonable to check universally.
67 if (Args.hasArg(options::OPT_static))
69 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
70 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
74 // Add backslashes to escape spaces and other backslashes.
75 // This is used for the space-separated argument list specified with
76 // the -dwarf-debug-flags option.
77 static void EscapeSpacesAndBackslashes(const char *Arg,
78 SmallVectorImpl<char> &Res) {
92 // Quote target names for inclusion in GNU Make dependency files.
93 // Only the characters '$', '#', ' ', '\t' are quoted.
94 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
95 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
99 // Escape the preceding backslashes
100 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
103 // Escape the space/tab
116 Res.push_back(Target[i]);
120 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
121 /// offloading tool chain that is associated with the current action \a JA.
123 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
124 const ToolChain &RegularToolChain,
125 llvm::function_ref<void(const ToolChain &)> Work) {
126 // Apply Work on the current/regular tool chain.
127 Work(RegularToolChain);
129 // Apply Work on all the offloading tool chains associated with the current
131 if (JA.isHostOffloading(Action::OFK_Cuda))
132 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
133 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
134 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
135 else if (JA.isHostOffloading(Action::OFK_HIP))
136 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
137 else if (JA.isDeviceOffloading(Action::OFK_HIP))
138 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
140 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
141 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
142 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
144 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
145 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
148 // TODO: Add support for other offloading programming models here.
152 /// This is a helper function for validating the optional refinement step
153 /// parameter in reciprocal argument strings. Return false if there is an error
154 /// parsing the refinement step. Otherwise, return true and set the Position
155 /// of the refinement step in the input string.
156 static bool getRefinementStep(StringRef In, const Driver &D,
157 const Arg &A, size_t &Position) {
158 const char RefinementStepToken = ':';
159 Position = In.find(RefinementStepToken);
160 if (Position != StringRef::npos) {
161 StringRef Option = A.getOption().getName();
162 StringRef RefStep = In.substr(Position + 1);
163 // Allow exactly one numeric character for the additional refinement
164 // step parameter. This is reasonable for all currently-supported
165 // operations and architectures because we would expect that a larger value
166 // of refinement steps would cause the estimate "optimization" to
167 // under-perform the native operation. Also, if the estimate does not
168 // converge quickly, it probably will not ever converge, so further
169 // refinement steps will not produce a better answer.
170 if (RefStep.size() != 1) {
171 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
174 char RefStepChar = RefStep[0];
175 if (RefStepChar < '0' || RefStepChar > '9') {
176 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
183 /// The -mrecip flag requires processing of many optional parameters.
184 static void ParseMRecip(const Driver &D, const ArgList &Args,
185 ArgStringList &OutStrings) {
186 StringRef DisabledPrefixIn = "!";
187 StringRef DisabledPrefixOut = "!";
188 StringRef EnabledPrefixOut = "";
189 StringRef Out = "-mrecip=";
191 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
195 unsigned NumOptions = A->getNumValues();
196 if (NumOptions == 0) {
197 // No option is the same as "all".
198 OutStrings.push_back(Args.MakeArgString(Out + "all"));
202 // Pass through "all", "none", or "default" with an optional refinement step.
203 if (NumOptions == 1) {
204 StringRef Val = A->getValue(0);
206 if (!getRefinementStep(Val, D, *A, RefStepLoc))
208 StringRef ValBase = Val.slice(0, RefStepLoc);
209 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
210 OutStrings.push_back(Args.MakeArgString(Out + Val));
215 // Each reciprocal type may be enabled or disabled individually.
216 // Check each input value for validity, concatenate them all back together,
219 llvm::StringMap<bool> OptionStrings;
220 OptionStrings.insert(std::make_pair("divd", false));
221 OptionStrings.insert(std::make_pair("divf", false));
222 OptionStrings.insert(std::make_pair("vec-divd", false));
223 OptionStrings.insert(std::make_pair("vec-divf", false));
224 OptionStrings.insert(std::make_pair("sqrtd", false));
225 OptionStrings.insert(std::make_pair("sqrtf", false));
226 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
227 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
229 for (unsigned i = 0; i != NumOptions; ++i) {
230 StringRef Val = A->getValue(i);
232 bool IsDisabled = Val.startswith(DisabledPrefixIn);
233 // Ignore the disablement token for string matching.
238 if (!getRefinementStep(Val, D, *A, RefStep))
241 StringRef ValBase = Val.slice(0, RefStep);
242 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
243 if (OptionIter == OptionStrings.end()) {
244 // Try again specifying float suffix.
245 OptionIter = OptionStrings.find(ValBase.str() + 'f');
246 if (OptionIter == OptionStrings.end()) {
247 // The input name did not match any known option string.
248 D.Diag(diag::err_drv_unknown_argument) << Val;
251 // The option was specified without a float or double suffix.
252 // Make sure that the double entry was not already specified.
253 // The float entry will be checked below.
254 if (OptionStrings[ValBase.str() + 'd']) {
255 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
260 if (OptionIter->second == true) {
261 // Duplicate option specified.
262 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
266 // Mark the matched option as found. Do not allow duplicate specifiers.
267 OptionIter->second = true;
269 // If the precision was not specified, also mark the double entry as found.
270 if (ValBase.back() != 'f' && ValBase.back() != 'd')
271 OptionStrings[ValBase.str() + 'd'] = true;
273 // Build the output string.
274 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
275 Out = Args.MakeArgString(Out + Prefix + Val);
276 if (i != NumOptions - 1)
277 Out = Args.MakeArgString(Out + ",");
280 OutStrings.push_back(Args.MakeArgString(Out));
283 /// The -mprefer-vector-width option accepts either a positive integer
284 /// or the string "none".
285 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
286 ArgStringList &CmdArgs) {
287 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
291 StringRef Value = A->getValue();
292 if (Value == "none") {
293 CmdArgs.push_back("-mprefer-vector-width=none");
296 if (Value.getAsInteger(10, Width)) {
297 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
300 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
304 static void getWebAssemblyTargetFeatures(const ArgList &Args,
305 std::vector<StringRef> &Features) {
306 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
309 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
310 const ArgList &Args, ArgStringList &CmdArgs,
312 const Driver &D = TC.getDriver();
313 std::vector<StringRef> Features;
314 switch (Triple.getArch()) {
317 case llvm::Triple::mips:
318 case llvm::Triple::mipsel:
319 case llvm::Triple::mips64:
320 case llvm::Triple::mips64el:
321 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
324 case llvm::Triple::arm:
325 case llvm::Triple::armeb:
326 case llvm::Triple::thumb:
327 case llvm::Triple::thumbeb:
328 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
331 case llvm::Triple::ppc:
332 case llvm::Triple::ppc64:
333 case llvm::Triple::ppc64le:
334 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
336 case llvm::Triple::riscv32:
337 case llvm::Triple::riscv64:
338 riscv::getRISCVTargetFeatures(D, Args, Features);
340 case llvm::Triple::systemz:
341 systemz::getSystemZTargetFeatures(Args, Features);
343 case llvm::Triple::aarch64:
344 case llvm::Triple::aarch64_be:
345 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
347 case llvm::Triple::x86:
348 case llvm::Triple::x86_64:
349 x86::getX86TargetFeatures(D, Triple, Args, Features);
351 case llvm::Triple::hexagon:
352 hexagon::getHexagonTargetFeatures(D, Args, Features);
354 case llvm::Triple::wasm32:
355 case llvm::Triple::wasm64:
356 getWebAssemblyTargetFeatures(Args, Features);
358 case llvm::Triple::sparc:
359 case llvm::Triple::sparcel:
360 case llvm::Triple::sparcv9:
361 sparc::getSparcTargetFeatures(D, Args, Features);
363 case llvm::Triple::r600:
364 case llvm::Triple::amdgcn:
365 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
367 case llvm::Triple::msp430:
368 msp430::getMSP430TargetFeatures(D, Args, Features);
371 // Find the last of each feature.
372 llvm::StringMap<unsigned> LastOpt;
373 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
374 StringRef Name = Features[I];
375 assert(Name[0] == '-' || Name[0] == '+');
376 LastOpt[Name.drop_front(1)] = I;
379 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
380 // If this feature was overridden, ignore it.
381 StringRef Name = Features[I];
382 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
383 assert(LastI != LastOpt.end());
384 unsigned Last = LastI->second;
388 CmdArgs.push_back("-target-feature");
389 CmdArgs.push_back(Name.data());
394 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
395 const llvm::Triple &Triple) {
396 // We use the zero-cost exception tables for Objective-C if the non-fragile
397 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
399 if (runtime.isNonFragile())
402 if (!Triple.isMacOSX())
405 return (!Triple.isMacOSXVersionLT(10, 5) &&
406 (Triple.getArch() == llvm::Triple::x86_64 ||
407 Triple.getArch() == llvm::Triple::arm));
410 /// Adds exception related arguments to the driver command arguments. There's a
411 /// master flag, -fexceptions and also language specific flags to enable/disable
412 /// C++ and Objective-C exceptions. This makes it possible to for example
413 /// disable C++ exceptions but enable Objective-C exceptions.
414 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
415 const ToolChain &TC, bool KernelOrKext,
416 const ObjCRuntime &objcRuntime,
417 ArgStringList &CmdArgs) {
418 const llvm::Triple &Triple = TC.getTriple();
421 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
422 // arguments now to avoid warnings about unused arguments.
423 Args.ClaimAllArgs(options::OPT_fexceptions);
424 Args.ClaimAllArgs(options::OPT_fno_exceptions);
425 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
426 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
427 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
428 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
432 // See if the user explicitly enabled exceptions.
433 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
436 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
437 // is not necessarily sensible, but follows GCC.
438 if (types::isObjC(InputType) &&
439 Args.hasFlag(options::OPT_fobjc_exceptions,
440 options::OPT_fno_objc_exceptions, true)) {
441 CmdArgs.push_back("-fobjc-exceptions");
443 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
446 if (types::isCXX(InputType)) {
447 // Disable C++ EH by default on XCore and PS4.
448 bool CXXExceptionsEnabled =
449 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
450 Arg *ExceptionArg = Args.getLastArg(
451 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
452 options::OPT_fexceptions, options::OPT_fno_exceptions);
454 CXXExceptionsEnabled =
455 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
456 ExceptionArg->getOption().matches(options::OPT_fexceptions);
458 if (CXXExceptionsEnabled) {
459 CmdArgs.push_back("-fcxx-exceptions");
466 CmdArgs.push_back("-fexceptions");
469 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
471 if (TC.getTriple().isOSDarwin()) {
472 // The native darwin assembler doesn't support the linker_option directives,
473 // so we disable them if we think the .s file will be passed to it.
474 Default = TC.useIntegratedAs();
476 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
480 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
481 const ToolChain &TC) {
482 bool UseDwarfDirectory =
483 Args.hasFlag(options::OPT_fdwarf_directory_asm,
484 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
485 return !UseDwarfDirectory;
488 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
489 // to the corresponding DebugInfoKind.
490 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
491 assert(A.getOption().matches(options::OPT_gN_Group) &&
492 "Not a -g option that specifies a debug-info level");
493 if (A.getOption().matches(options::OPT_g0) ||
494 A.getOption().matches(options::OPT_ggdb0))
495 return codegenoptions::NoDebugInfo;
496 if (A.getOption().matches(options::OPT_gline_tables_only) ||
497 A.getOption().matches(options::OPT_ggdb1))
498 return codegenoptions::DebugLineTablesOnly;
499 if (A.getOption().matches(options::OPT_gline_directives_only))
500 return codegenoptions::DebugDirectivesOnly;
501 return codegenoptions::LimitedDebugInfo;
504 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
505 switch (Triple.getArch()){
508 case llvm::Triple::arm:
509 case llvm::Triple::thumb:
510 // ARM Darwin targets require a frame pointer to be always present to aid
511 // offline debugging via backtraces.
512 return Triple.isOSDarwin();
516 static bool useFramePointerForTargetByDefault(const ArgList &Args,
517 const llvm::Triple &Triple) {
518 switch (Triple.getArch()) {
519 case llvm::Triple::xcore:
520 case llvm::Triple::wasm32:
521 case llvm::Triple::wasm64:
522 case llvm::Triple::msp430:
523 // XCore never wants frame pointers, regardless of OS.
524 // WebAssembly never wants frame pointers.
526 case llvm::Triple::ppc:
527 case llvm::Triple::ppc64:
528 case llvm::Triple::ppc64le:
529 case llvm::Triple::riscv32:
530 case llvm::Triple::riscv64:
531 return !areOptimizationsEnabled(Args);
536 if (Triple.isOSNetBSD()) {
537 return !areOptimizationsEnabled(Args);
540 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
542 switch (Triple.getArch()) {
543 // Don't use a frame pointer on linux if optimizing for certain targets.
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 case llvm::Triple::mips:
547 case llvm::Triple::mipsel:
548 case llvm::Triple::systemz:
549 case llvm::Triple::x86:
550 case llvm::Triple::x86_64:
551 return !areOptimizationsEnabled(Args);
557 if (Triple.isOSWindows()) {
558 switch (Triple.getArch()) {
559 case llvm::Triple::x86:
560 return !areOptimizationsEnabled(Args);
561 case llvm::Triple::x86_64:
562 return Triple.isOSBinFormatMachO();
563 case llvm::Triple::arm:
564 case llvm::Triple::thumb:
565 // Windows on ARM builds with FPO disabled to aid fast stack walking
568 // All other supported Windows ISAs use xdata unwind information, so frame
569 // pointers are not generally useful.
577 static bool shouldUseFramePointer(const ArgList &Args,
578 const llvm::Triple &Triple) {
579 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
580 options::OPT_fomit_frame_pointer))
581 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
582 mustUseNonLeafFramePointerForTarget(Triple);
584 if (Args.hasArg(options::OPT_pg))
587 return useFramePointerForTargetByDefault(Args, Triple);
590 static bool shouldUseLeafFramePointer(const ArgList &Args,
591 const llvm::Triple &Triple) {
592 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
593 options::OPT_momit_leaf_frame_pointer))
594 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
596 if (Args.hasArg(options::OPT_pg))
599 if (Triple.isPS4CPU())
602 return useFramePointerForTargetByDefault(Args, Triple);
605 /// Add a CC1 option to specify the debug compilation directory.
606 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
607 if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
608 CmdArgs.push_back("-fdebug-compilation-dir");
609 CmdArgs.push_back(A->getValue());
611 SmallString<128> cwd;
612 if (!llvm::sys::fs::current_path(cwd)) {
613 CmdArgs.push_back("-fdebug-compilation-dir");
614 CmdArgs.push_back(Args.MakeArgString(cwd));
619 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
620 static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
621 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
622 StringRef Map = A->getValue();
623 if (Map.find('=') == StringRef::npos)
624 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
626 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
631 /// Vectorize at all optimization levels greater than 1 except for -Oz.
632 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
634 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
635 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
636 if (A->getOption().matches(options::OPT_O4) ||
637 A->getOption().matches(options::OPT_Ofast))
640 if (A->getOption().matches(options::OPT_O0))
643 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
646 StringRef S(A->getValue());
650 // Don't vectorize -Oz, unless it's the slp vectorizer.
654 unsigned OptLevel = 0;
655 if (S.getAsInteger(10, OptLevel))
664 /// Add -x lang to \p CmdArgs for \p Input.
665 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
666 ArgStringList &CmdArgs) {
667 // When using -verify-pch, we don't want to provide the type
668 // 'precompiled-header' if it was inferred from the file extension
669 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
672 CmdArgs.push_back("-x");
673 if (Args.hasArg(options::OPT_rewrite_objc))
674 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
676 // Map the driver type to the frontend type. This is mostly an identity
677 // mapping, except that the distinction between module interface units
678 // and other source files does not exist at the frontend layer.
679 const char *ClangType;
680 switch (Input.getType()) {
681 case types::TY_CXXModule:
684 case types::TY_PP_CXXModule:
685 ClangType = "c++-cpp-output";
688 ClangType = types::getTypeName(Input.getType());
691 CmdArgs.push_back(ClangType);
695 static void appendUserToPath(SmallVectorImpl<char> &Result) {
697 const char *Username = getenv("LOGNAME");
699 const char *Username = getenv("USERNAME");
702 // Validate that LoginName can be used in a path, and get its length.
704 for (const char *P = Username; *P; ++P, ++Len) {
705 if (!clang::isAlphanumeric(*P) && *P != '_') {
711 if (Username && Len > 0) {
712 Result.append(Username, Username + Len);
717 // Fallback to user id.
719 std::string UID = llvm::utostr(getuid());
721 // FIXME: Windows seems to have an 'SID' that might work.
722 std::string UID = "9999";
724 Result.append(UID.begin(), UID.end());
727 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
728 const Driver &D, const InputInfo &Output,
730 ArgStringList &CmdArgs) {
732 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
733 options::OPT_fprofile_generate_EQ,
734 options::OPT_fno_profile_generate);
735 if (PGOGenerateArg &&
736 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
737 PGOGenerateArg = nullptr;
739 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
740 options::OPT_fcs_profile_generate_EQ,
741 options::OPT_fno_profile_generate);
742 if (CSPGOGenerateArg &&
743 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
744 CSPGOGenerateArg = nullptr;
746 auto *ProfileGenerateArg = Args.getLastArg(
747 options::OPT_fprofile_instr_generate,
748 options::OPT_fprofile_instr_generate_EQ,
749 options::OPT_fno_profile_instr_generate);
750 if (ProfileGenerateArg &&
751 ProfileGenerateArg->getOption().matches(
752 options::OPT_fno_profile_instr_generate))
753 ProfileGenerateArg = nullptr;
755 if (PGOGenerateArg && ProfileGenerateArg)
756 D.Diag(diag::err_drv_argument_not_allowed_with)
757 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
759 auto *ProfileUseArg = getLastProfileUseArg(Args);
761 if (PGOGenerateArg && ProfileUseArg)
762 D.Diag(diag::err_drv_argument_not_allowed_with)
763 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
765 if (ProfileGenerateArg && ProfileUseArg)
766 D.Diag(diag::err_drv_argument_not_allowed_with)
767 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
769 if (CSPGOGenerateArg && PGOGenerateArg)
770 D.Diag(diag::err_drv_argument_not_allowed_with)
771 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
773 if (ProfileGenerateArg) {
774 if (ProfileGenerateArg->getOption().matches(
775 options::OPT_fprofile_instr_generate_EQ))
776 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
777 ProfileGenerateArg->getValue()));
778 // The default is to use Clang Instrumentation.
779 CmdArgs.push_back("-fprofile-instrument=clang");
780 if (TC.getTriple().isWindowsMSVCEnvironment()) {
781 // Add dependent lib for clang_rt.profile
782 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
783 TC.getCompilerRT(Args, "profile")));
787 Arg *PGOGenArg = nullptr;
788 if (PGOGenerateArg) {
789 assert(!CSPGOGenerateArg);
790 PGOGenArg = PGOGenerateArg;
791 CmdArgs.push_back("-fprofile-instrument=llvm");
793 if (CSPGOGenerateArg) {
794 assert(!PGOGenerateArg);
795 PGOGenArg = CSPGOGenerateArg;
796 CmdArgs.push_back("-fprofile-instrument=csllvm");
799 if (TC.getTriple().isWindowsMSVCEnvironment()) {
800 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
801 TC.getCompilerRT(Args, "profile")));
803 if (PGOGenArg->getOption().matches(
804 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
805 : options::OPT_fcs_profile_generate_EQ)) {
806 SmallString<128> Path(PGOGenArg->getValue());
807 llvm::sys::path::append(Path, "default_%m.profraw");
809 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
814 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
815 CmdArgs.push_back(Args.MakeArgString(
816 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
817 else if ((ProfileUseArg->getOption().matches(
818 options::OPT_fprofile_use_EQ) ||
819 ProfileUseArg->getOption().matches(
820 options::OPT_fprofile_instr_use))) {
821 SmallString<128> Path(
822 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
823 if (Path.empty() || llvm::sys::fs::is_directory(Path))
824 llvm::sys::path::append(Path, "default.profdata");
826 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
830 if (Args.hasArg(options::OPT_ftest_coverage) ||
831 Args.hasArg(options::OPT_coverage))
832 CmdArgs.push_back("-femit-coverage-notes");
833 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
835 Args.hasArg(options::OPT_coverage))
836 CmdArgs.push_back("-femit-coverage-data");
838 if (Args.hasFlag(options::OPT_fcoverage_mapping,
839 options::OPT_fno_coverage_mapping, false)) {
840 if (!ProfileGenerateArg)
841 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
842 << "-fcoverage-mapping"
843 << "-fprofile-instr-generate";
845 CmdArgs.push_back("-fcoverage-mapping");
848 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
849 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
850 if (!Args.hasArg(options::OPT_coverage))
851 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
852 << "-fprofile-exclude-files="
855 StringRef v = Arg->getValue();
857 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
860 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
861 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
862 if (!Args.hasArg(options::OPT_coverage))
863 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
864 << "-fprofile-filter-files="
867 StringRef v = Arg->getValue();
868 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
871 if (C.getArgs().hasArg(options::OPT_c) ||
872 C.getArgs().hasArg(options::OPT_S)) {
873 if (Output.isFilename()) {
874 CmdArgs.push_back("-coverage-notes-file");
875 SmallString<128> OutputFilename;
876 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
877 OutputFilename = FinalOutput->getValue();
879 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
880 SmallString<128> CoverageFilename = OutputFilename;
881 if (llvm::sys::path::is_relative(CoverageFilename)) {
882 SmallString<128> Pwd;
883 if (!llvm::sys::fs::current_path(Pwd)) {
884 llvm::sys::path::append(Pwd, CoverageFilename);
885 CoverageFilename.swap(Pwd);
888 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
889 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
891 // Leave -fprofile-dir= an unused argument unless .gcda emission is
892 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
893 // the flag used. There is no -fno-profile-dir, so the user has no
894 // targeted way to suppress the warning.
895 if (Args.hasArg(options::OPT_fprofile_arcs) ||
896 Args.hasArg(options::OPT_coverage)) {
897 CmdArgs.push_back("-coverage-data-file");
898 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
899 CoverageFilename = FProfileDir->getValue();
900 llvm::sys::path::append(CoverageFilename, OutputFilename);
902 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
903 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
909 /// Check whether the given input tree contains any compilation actions.
910 static bool ContainsCompileAction(const Action *A) {
911 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
914 for (const auto &AI : A->inputs())
915 if (ContainsCompileAction(AI))
921 /// Check if -relax-all should be passed to the internal assembler.
922 /// This is done by default when compiling non-assembler source with -O0.
923 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
924 bool RelaxDefault = true;
926 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
927 RelaxDefault = A->getOption().matches(options::OPT_O0);
930 RelaxDefault = false;
931 for (const auto &Act : C.getActions()) {
932 if (ContainsCompileAction(Act)) {
939 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
943 // Extract the integer N from a string spelled "-dwarf-N", returning 0
944 // on mismatch. The StringRef input (rather than an Arg) allows
945 // for use by the "-Xassembler" option parser.
946 static unsigned DwarfVersionNum(StringRef ArgValue) {
947 return llvm::StringSwitch<unsigned>(ArgValue)
948 .Case("-gdwarf-2", 2)
949 .Case("-gdwarf-3", 3)
950 .Case("-gdwarf-4", 4)
951 .Case("-gdwarf-5", 5)
955 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
956 codegenoptions::DebugInfoKind DebugInfoKind,
957 unsigned DwarfVersion,
958 llvm::DebuggerKind DebuggerTuning) {
959 switch (DebugInfoKind) {
960 case codegenoptions::DebugDirectivesOnly:
961 CmdArgs.push_back("-debug-info-kind=line-directives-only");
963 case codegenoptions::DebugLineTablesOnly:
964 CmdArgs.push_back("-debug-info-kind=line-tables-only");
966 case codegenoptions::LimitedDebugInfo:
967 CmdArgs.push_back("-debug-info-kind=limited");
969 case codegenoptions::FullDebugInfo:
970 CmdArgs.push_back("-debug-info-kind=standalone");
975 if (DwarfVersion > 0)
977 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
978 switch (DebuggerTuning) {
979 case llvm::DebuggerKind::GDB:
980 CmdArgs.push_back("-debugger-tuning=gdb");
982 case llvm::DebuggerKind::LLDB:
983 CmdArgs.push_back("-debugger-tuning=lldb");
985 case llvm::DebuggerKind::SCE:
986 CmdArgs.push_back("-debugger-tuning=sce");
993 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
994 const Driver &D, const ToolChain &TC) {
995 assert(A && "Expected non-nullptr argument.");
996 if (TC.supportsDebugInfoOption(A))
998 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
999 << A->getAsString(Args) << TC.getTripleString();
1003 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1004 ArgStringList &CmdArgs,
1006 const ToolChain &TC) {
1007 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
1010 if (checkDebugInfoOption(A, Args, D, TC)) {
1011 if (A->getOption().getID() == options::OPT_gz) {
1012 if (llvm::zlib::isAvailable())
1013 CmdArgs.push_back("--compress-debug-sections");
1015 D.Diag(diag::warn_debug_compression_unavailable);
1019 StringRef Value = A->getValue();
1020 if (Value == "none") {
1021 CmdArgs.push_back("--compress-debug-sections=none");
1022 } else if (Value == "zlib" || Value == "zlib-gnu") {
1023 if (llvm::zlib::isAvailable()) {
1025 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1027 D.Diag(diag::warn_debug_compression_unavailable);
1030 D.Diag(diag::err_drv_unsupported_option_argument)
1031 << A->getOption().getName() << Value;
1036 static const char *RelocationModelName(llvm::Reloc::Model Model) {
1038 case llvm::Reloc::Static:
1040 case llvm::Reloc::PIC_:
1042 case llvm::Reloc::DynamicNoPIC:
1043 return "dynamic-no-pic";
1044 case llvm::Reloc::ROPI:
1046 case llvm::Reloc::RWPI:
1048 case llvm::Reloc::ROPI_RWPI:
1051 llvm_unreachable("Unknown Reloc::Model kind");
1054 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1055 const Driver &D, const ArgList &Args,
1056 ArgStringList &CmdArgs,
1057 const InputInfo &Output,
1058 const InputInfoList &Inputs) const {
1060 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1062 CheckPreprocessingOptions(D, Args);
1064 Args.AddLastArg(CmdArgs, options::OPT_C);
1065 Args.AddLastArg(CmdArgs, options::OPT_CC);
1067 // Handle dependency file generation.
1068 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1069 (A = Args.getLastArg(options::OPT_MD)) ||
1070 (A = Args.getLastArg(options::OPT_MMD))) {
1071 // Determine the output location.
1072 const char *DepFile;
1073 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1074 DepFile = MF->getValue();
1075 C.addFailureResultFile(DepFile, &JA);
1076 } else if (Output.getType() == types::TY_Dependencies) {
1077 DepFile = Output.getFilename();
1078 } else if (A->getOption().matches(options::OPT_M) ||
1079 A->getOption().matches(options::OPT_MM)) {
1082 DepFile = getDependencyFileName(Args, Inputs);
1083 C.addFailureResultFile(DepFile, &JA);
1085 CmdArgs.push_back("-dependency-file");
1086 CmdArgs.push_back(DepFile);
1088 // Add a default target if one wasn't specified.
1089 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1090 const char *DepTarget;
1092 // If user provided -o, that is the dependency target, except
1093 // when we are only generating a dependency file.
1094 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1095 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1096 DepTarget = OutputOpt->getValue();
1098 // Otherwise derive from the base input.
1100 // FIXME: This should use the computed output file location.
1101 SmallString<128> P(Inputs[0].getBaseInput());
1102 llvm::sys::path::replace_extension(P, "o");
1103 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1106 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1107 CmdArgs.push_back("-w");
1109 CmdArgs.push_back("-MT");
1110 SmallString<128> Quoted;
1111 QuoteTarget(DepTarget, Quoted);
1112 CmdArgs.push_back(Args.MakeArgString(Quoted));
1115 if (A->getOption().matches(options::OPT_M) ||
1116 A->getOption().matches(options::OPT_MD))
1117 CmdArgs.push_back("-sys-header-deps");
1118 if ((isa<PrecompileJobAction>(JA) &&
1119 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1120 Args.hasArg(options::OPT_fmodule_file_deps))
1121 CmdArgs.push_back("-module-file-deps");
1124 if (Args.hasArg(options::OPT_MG)) {
1125 if (!A || A->getOption().matches(options::OPT_MD) ||
1126 A->getOption().matches(options::OPT_MMD))
1127 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1128 CmdArgs.push_back("-MG");
1131 Args.AddLastArg(CmdArgs, options::OPT_MP);
1132 Args.AddLastArg(CmdArgs, options::OPT_MV);
1134 // Convert all -MQ <target> args to -MT <quoted target>
1135 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1138 if (A->getOption().matches(options::OPT_MQ)) {
1139 CmdArgs.push_back("-MT");
1140 SmallString<128> Quoted;
1141 QuoteTarget(A->getValue(), Quoted);
1142 CmdArgs.push_back(Args.MakeArgString(Quoted));
1144 // -MT flag - no change
1146 A->render(Args, CmdArgs);
1150 // Add offload include arguments specific for CUDA. This must happen before
1151 // we -I or -include anything else, because we must pick up the CUDA headers
1152 // from the particular CUDA installation, rather than from e.g.
1153 // /usr/local/include.
1154 if (JA.isOffloading(Action::OFK_Cuda))
1155 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1157 // If we are offloading to a target via OpenMP we need to include the
1158 // openmp_wrappers folder which contains alternative system headers.
1159 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1160 getToolChain().getTriple().isNVPTX()){
1161 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1162 // Add openmp_wrappers/* to our system include path. This lets us wrap
1163 // standard library headers.
1164 SmallString<128> P(D.ResourceDir);
1165 llvm::sys::path::append(P, "include");
1166 llvm::sys::path::append(P, "openmp_wrappers");
1167 CmdArgs.push_back("-internal-isystem");
1168 CmdArgs.push_back(Args.MakeArgString(P));
1171 CmdArgs.push_back("-include");
1172 CmdArgs.push_back("__clang_openmp_math_declares.h");
1175 // Add -i* options, and automatically translate to
1176 // -include-pch/-include-pth for transparent PCH support. It's
1177 // wonky, but we include looking for .gch so we can support seamless
1178 // replacement into a build system already set up to be generating
1181 if (getToolChain().getDriver().IsCLMode()) {
1182 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1183 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1184 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1185 JA.getKind() <= Action::AssembleJobClass) {
1186 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1188 if (YcArg || YuArg) {
1189 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1190 if (!isa<PrecompileJobAction>(JA)) {
1191 CmdArgs.push_back("-include-pch");
1192 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1193 C, !ThroughHeader.empty()
1195 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1198 if (ThroughHeader.empty()) {
1199 CmdArgs.push_back(Args.MakeArgString(
1200 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1203 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1208 bool RenderedImplicitInclude = false;
1209 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1210 if (A->getOption().matches(options::OPT_include)) {
1211 // Handling of gcc-style gch precompiled headers.
1212 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1213 RenderedImplicitInclude = true;
1215 bool FoundPCH = false;
1216 SmallString<128> P(A->getValue());
1217 // We want the files to have a name like foo.h.pch. Add a dummy extension
1218 // so that replace_extension does the right thing.
1220 llvm::sys::path::replace_extension(P, "pch");
1221 if (llvm::sys::fs::exists(P))
1225 llvm::sys::path::replace_extension(P, "gch");
1226 if (llvm::sys::fs::exists(P)) {
1232 if (IsFirstImplicitInclude) {
1234 CmdArgs.push_back("-include-pch");
1235 CmdArgs.push_back(Args.MakeArgString(P));
1238 // Ignore the PCH if not first on command line and emit warning.
1239 D.Diag(diag::warn_drv_pch_not_first_include) << P
1240 << A->getAsString(Args);
1243 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1244 // Handling of paths which must come late. These entries are handled by
1245 // the toolchain itself after the resource dir is inserted in the right
1247 // Do not claim the argument so that the use of the argument does not
1248 // silently go unnoticed on toolchains which do not honour the option.
1252 // Not translated, render as usual.
1254 A->render(Args, CmdArgs);
1257 Args.AddAllArgs(CmdArgs,
1258 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1259 options::OPT_F, options::OPT_index_header_map});
1261 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1263 // FIXME: There is a very unfortunate problem here, some troubled
1264 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1265 // really support that we would have to parse and then translate
1266 // those options. :(
1267 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1268 options::OPT_Xpreprocessor);
1270 // -I- is a deprecated GCC feature, reject it.
1271 if (Arg *A = Args.getLastArg(options::OPT_I_))
1272 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1274 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1275 // -isysroot to the CC1 invocation.
1276 StringRef sysroot = C.getSysRoot();
1277 if (sysroot != "") {
1278 if (!Args.hasArg(options::OPT_isysroot)) {
1279 CmdArgs.push_back("-isysroot");
1280 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1284 // Parse additional include paths from environment variables.
1285 // FIXME: We should probably sink the logic for handling these from the
1286 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1287 // CPATH - included following the user specified includes (but prior to
1288 // builtin and standard includes).
1289 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1290 // C_INCLUDE_PATH - system includes enabled when compiling C.
1291 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1292 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1293 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1294 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1295 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1296 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1297 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1299 // While adding the include arguments, we also attempt to retrieve the
1300 // arguments of related offloading toolchains or arguments that are specific
1301 // of an offloading programming model.
1303 // Add C++ include arguments, if needed.
1304 if (types::isCXX(Inputs[0].getType()))
1305 forAllAssociatedToolChains(C, JA, getToolChain(),
1306 [&Args, &CmdArgs](const ToolChain &TC) {
1307 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1310 // Add system include arguments for all targets but IAMCU.
1312 forAllAssociatedToolChains(C, JA, getToolChain(),
1313 [&Args, &CmdArgs](const ToolChain &TC) {
1314 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1317 // For IAMCU add special include arguments.
1318 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1322 // FIXME: Move to target hook.
1323 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1324 switch (Triple.getArch()) {
1328 case llvm::Triple::aarch64:
1329 case llvm::Triple::aarch64_be:
1330 case llvm::Triple::arm:
1331 case llvm::Triple::armeb:
1332 case llvm::Triple::thumb:
1333 case llvm::Triple::thumbeb:
1334 if (Triple.isOSDarwin() || Triple.isOSWindows())
1338 case llvm::Triple::ppc:
1339 case llvm::Triple::ppc64:
1340 if (Triple.isOSDarwin())
1344 case llvm::Triple::hexagon:
1345 case llvm::Triple::ppc64le:
1346 case llvm::Triple::riscv32:
1347 case llvm::Triple::riscv64:
1348 case llvm::Triple::systemz:
1349 case llvm::Triple::xcore:
1354 static bool isNoCommonDefault(const llvm::Triple &Triple) {
1355 switch (Triple.getArch()) {
1357 if (Triple.isOSFuchsia())
1361 case llvm::Triple::xcore:
1362 case llvm::Triple::wasm32:
1363 case llvm::Triple::wasm64:
1369 void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1370 ArgStringList &CmdArgs) {
1371 // Select the ABI to use.
1372 // FIXME: Support -meabi.
1373 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1374 const char *ABIName = nullptr;
1375 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1376 ABIName = A->getValue();
1378 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1379 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1382 CmdArgs.push_back("-target-abi");
1383 CmdArgs.push_back(ABIName);
1387 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1388 ArgStringList &CmdArgs, bool KernelOrKext) const {
1389 RenderARMABI(Triple, Args, CmdArgs);
1391 // Determine floating point ABI from the options & target defaults.
1392 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1393 if (ABI == arm::FloatABI::Soft) {
1394 // Floating point operations and argument passing are soft.
1395 // FIXME: This changes CPP defines, we need -target-soft-float.
1396 CmdArgs.push_back("-msoft-float");
1397 CmdArgs.push_back("-mfloat-abi");
1398 CmdArgs.push_back("soft");
1399 } else if (ABI == arm::FloatABI::SoftFP) {
1400 // Floating point operations are hard, but argument passing is soft.
1401 CmdArgs.push_back("-mfloat-abi");
1402 CmdArgs.push_back("soft");
1404 // Floating point operations and argument passing are hard.
1405 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1406 CmdArgs.push_back("-mfloat-abi");
1407 CmdArgs.push_back("hard");
1410 // Forward the -mglobal-merge option for explicit control over the pass.
1411 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1412 options::OPT_mno_global_merge)) {
1413 CmdArgs.push_back("-mllvm");
1414 if (A->getOption().matches(options::OPT_mno_global_merge))
1415 CmdArgs.push_back("-arm-global-merge=false");
1417 CmdArgs.push_back("-arm-global-merge=true");
1420 if (!Args.hasFlag(options::OPT_mimplicit_float,
1421 options::OPT_mno_implicit_float, true))
1422 CmdArgs.push_back("-no-implicit-float");
1424 if (Args.getLastArg(options::OPT_mcmse))
1425 CmdArgs.push_back("-mcmse");
1428 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1429 const ArgList &Args, bool KernelOrKext,
1430 ArgStringList &CmdArgs) const {
1431 const ToolChain &TC = getToolChain();
1433 // Add the target features
1434 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1436 // Add target specific flags.
1437 switch (TC.getArch()) {
1441 case llvm::Triple::arm:
1442 case llvm::Triple::armeb:
1443 case llvm::Triple::thumb:
1444 case llvm::Triple::thumbeb:
1445 // Use the effective triple, which takes into account the deployment target.
1446 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1447 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1450 case llvm::Triple::aarch64:
1451 case llvm::Triple::aarch64_be:
1452 AddAArch64TargetArgs(Args, CmdArgs);
1453 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1456 case llvm::Triple::mips:
1457 case llvm::Triple::mipsel:
1458 case llvm::Triple::mips64:
1459 case llvm::Triple::mips64el:
1460 AddMIPSTargetArgs(Args, CmdArgs);
1463 case llvm::Triple::ppc:
1464 case llvm::Triple::ppc64:
1465 case llvm::Triple::ppc64le:
1466 AddPPCTargetArgs(Args, CmdArgs);
1469 case llvm::Triple::riscv32:
1470 case llvm::Triple::riscv64:
1471 AddRISCVTargetArgs(Args, CmdArgs);
1474 case llvm::Triple::sparc:
1475 case llvm::Triple::sparcel:
1476 case llvm::Triple::sparcv9:
1477 AddSparcTargetArgs(Args, CmdArgs);
1480 case llvm::Triple::systemz:
1481 AddSystemZTargetArgs(Args, CmdArgs);
1484 case llvm::Triple::x86:
1485 case llvm::Triple::x86_64:
1486 AddX86TargetArgs(Args, CmdArgs);
1489 case llvm::Triple::lanai:
1490 AddLanaiTargetArgs(Args, CmdArgs);
1493 case llvm::Triple::hexagon:
1494 AddHexagonTargetArgs(Args, CmdArgs);
1497 case llvm::Triple::wasm32:
1498 case llvm::Triple::wasm64:
1499 AddWebAssemblyTargetArgs(Args, CmdArgs);
1504 // Parse -mbranch-protection=<protection>[+<protection>]* where
1505 // <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1506 // Returns a triple of (return address signing Scope, signing key, require
1508 static std::tuple<StringRef, StringRef, bool>
1509 ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1511 StringRef Scope = "none";
1512 StringRef Key = "a_key";
1513 bool IndirectBranches = false;
1515 StringRef Value = A->getValue();
1516 // This maps onto -mbranch-protection=<scope>+<key>
1518 if (Value.equals("standard")) {
1521 IndirectBranches = true;
1523 } else if (!Value.equals("none")) {
1524 SmallVector<StringRef, 4> BranchProtection;
1525 StringRef(A->getValue()).split(BranchProtection, '+');
1527 auto Protection = BranchProtection.begin();
1528 while (Protection != BranchProtection.end()) {
1529 if (Protection->equals("bti"))
1530 IndirectBranches = true;
1531 else if (Protection->equals("pac-ret")) {
1533 while (++Protection != BranchProtection.end()) {
1534 // Inner loop as "leaf" and "b-key" options must only appear attached
1536 if (Protection->equals("leaf"))
1538 else if (Protection->equals("b-key"))
1545 D.Diag(diag::err_invalid_branch_protection)
1546 << *Protection << A->getAsString(Args);
1551 return std::make_tuple(Scope, Key, IndirectBranches);
1555 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1556 ArgStringList &CmdArgs) {
1557 const char *ABIName = nullptr;
1558 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1559 ABIName = A->getValue();
1560 else if (Triple.isOSDarwin())
1561 ABIName = "darwinpcs";
1565 CmdArgs.push_back("-target-abi");
1566 CmdArgs.push_back(ABIName);
1570 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1571 ArgStringList &CmdArgs) const {
1572 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1574 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1575 Args.hasArg(options::OPT_mkernel) ||
1576 Args.hasArg(options::OPT_fapple_kext))
1577 CmdArgs.push_back("-disable-red-zone");
1579 if (!Args.hasFlag(options::OPT_mimplicit_float,
1580 options::OPT_mno_implicit_float, true))
1581 CmdArgs.push_back("-no-implicit-float");
1583 RenderAArch64ABI(Triple, Args, CmdArgs);
1585 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1586 options::OPT_mno_fix_cortex_a53_835769)) {
1587 CmdArgs.push_back("-mllvm");
1588 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1589 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1591 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1592 } else if (Triple.isAndroid()) {
1593 // Enabled A53 errata (835769) workaround by default on android
1594 CmdArgs.push_back("-mllvm");
1595 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1598 // Forward the -mglobal-merge option for explicit control over the pass.
1599 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1600 options::OPT_mno_global_merge)) {
1601 CmdArgs.push_back("-mllvm");
1602 if (A->getOption().matches(options::OPT_mno_global_merge))
1603 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1605 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1608 // Enable/disable return address signing and indirect branch targets.
1609 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1610 options::OPT_mbranch_protection_EQ)) {
1612 const Driver &D = getToolChain().getDriver();
1614 StringRef Scope, Key;
1615 bool IndirectBranches;
1617 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1618 Scope = A->getValue();
1619 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1620 !Scope.equals("all"))
1621 D.Diag(diag::err_invalid_branch_protection)
1622 << Scope << A->getAsString(Args);
1624 IndirectBranches = false;
1626 std::tie(Scope, Key, IndirectBranches) =
1627 ParseAArch64BranchProtection(D, Args, A);
1630 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1632 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1633 if (IndirectBranches)
1634 CmdArgs.push_back("-mbranch-target-enforce");
1638 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1639 ArgStringList &CmdArgs) const {
1640 const Driver &D = getToolChain().getDriver();
1643 const llvm::Triple &Triple = getToolChain().getTriple();
1644 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1646 CmdArgs.push_back("-target-abi");
1647 CmdArgs.push_back(ABIName.data());
1649 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1650 if (ABI == mips::FloatABI::Soft) {
1651 // Floating point operations and argument passing are soft.
1652 CmdArgs.push_back("-msoft-float");
1653 CmdArgs.push_back("-mfloat-abi");
1654 CmdArgs.push_back("soft");
1656 // Floating point operations and argument passing are hard.
1657 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1658 CmdArgs.push_back("-mfloat-abi");
1659 CmdArgs.push_back("hard");
1662 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1663 if (A->getOption().matches(options::OPT_mxgot)) {
1664 CmdArgs.push_back("-mllvm");
1665 CmdArgs.push_back("-mxgot");
1669 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1670 options::OPT_mno_ldc1_sdc1)) {
1671 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1672 CmdArgs.push_back("-mllvm");
1673 CmdArgs.push_back("-mno-ldc1-sdc1");
1677 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1678 options::OPT_mno_check_zero_division)) {
1679 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1680 CmdArgs.push_back("-mllvm");
1681 CmdArgs.push_back("-mno-check-zero-division");
1685 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1686 StringRef v = A->getValue();
1687 CmdArgs.push_back("-mllvm");
1688 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1692 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1694 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1696 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1697 // -mgpopt is the default for static, -fno-pic environments but these two
1698 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1699 // the only case where -mllvm -mgpopt is passed.
1700 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1701 // passed explicitly when compiling something with -mabicalls
1702 // (implictly) in affect. Currently the warning is in the backend.
1704 // When the ABI in use is N64, we also need to determine the PIC mode that
1705 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1707 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1709 llvm::Reloc::Model RelocationModel;
1712 std::tie(RelocationModel, PICLevel, IsPIE) =
1713 ParsePICArgs(getToolChain(), Args);
1715 NoABICalls = NoABICalls ||
1716 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1718 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1719 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1720 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1721 CmdArgs.push_back("-mllvm");
1722 CmdArgs.push_back("-mgpopt");
1724 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1725 options::OPT_mno_local_sdata);
1726 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1727 options::OPT_mno_extern_sdata);
1728 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1729 options::OPT_mno_embedded_data);
1731 CmdArgs.push_back("-mllvm");
1732 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1733 CmdArgs.push_back("-mlocal-sdata=1");
1735 CmdArgs.push_back("-mlocal-sdata=0");
1737 LocalSData->claim();
1741 CmdArgs.push_back("-mllvm");
1742 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1743 CmdArgs.push_back("-mextern-sdata=1");
1745 CmdArgs.push_back("-mextern-sdata=0");
1747 ExternSData->claim();
1751 CmdArgs.push_back("-mllvm");
1752 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1753 CmdArgs.push_back("-membedded-data=1");
1755 CmdArgs.push_back("-membedded-data=0");
1757 EmbeddedData->claim();
1760 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1761 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1766 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1767 StringRef Val = StringRef(A->getValue());
1768 if (mips::hasCompactBranches(CPUName)) {
1769 if (Val == "never" || Val == "always" || Val == "optimal") {
1770 CmdArgs.push_back("-mllvm");
1771 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1773 D.Diag(diag::err_drv_unsupported_option_argument)
1774 << A->getOption().getName() << Val;
1776 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1779 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1780 options::OPT_mno_relax_pic_calls)) {
1781 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1782 CmdArgs.push_back("-mllvm");
1783 CmdArgs.push_back("-mips-jalr-reloc=0");
1788 void Clang::AddPPCTargetArgs(const ArgList &Args,
1789 ArgStringList &CmdArgs) const {
1790 // Select the ABI to use.
1791 const char *ABIName = nullptr;
1792 if (getToolChain().getTriple().isOSLinux())
1793 switch (getToolChain().getArch()) {
1794 case llvm::Triple::ppc64: {
1795 // When targeting a processor that supports QPX, or if QPX is
1796 // specifically enabled, default to using the ABI that supports QPX (so
1797 // long as it is not specifically disabled).
1798 bool HasQPX = false;
1799 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1800 HasQPX = A->getValue() == StringRef("a2q");
1801 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1803 ABIName = "elfv1-qpx";
1810 case llvm::Triple::ppc64le:
1817 bool IEEELongDouble = false;
1818 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1819 StringRef V = A->getValue();
1820 if (V == "ieeelongdouble")
1821 IEEELongDouble = true;
1822 else if (V == "ibmlongdouble")
1823 IEEELongDouble = false;
1824 else if (V != "altivec")
1825 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1826 // the option if given as we don't have backend support for any targets
1827 // that don't use the altivec abi.
1828 ABIName = A->getValue();
1831 CmdArgs.push_back("-mabi=ieeelongdouble");
1833 ppc::FloatABI FloatABI =
1834 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1836 if (FloatABI == ppc::FloatABI::Soft) {
1837 // Floating point operations and argument passing are soft.
1838 CmdArgs.push_back("-msoft-float");
1839 CmdArgs.push_back("-mfloat-abi");
1840 CmdArgs.push_back("soft");
1842 // Floating point operations and argument passing are hard.
1843 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1844 CmdArgs.push_back("-mfloat-abi");
1845 CmdArgs.push_back("hard");
1849 CmdArgs.push_back("-target-abi");
1850 CmdArgs.push_back(ABIName);
1854 void Clang::AddRISCVTargetArgs(const ArgList &Args,
1855 ArgStringList &CmdArgs) const {
1856 // FIXME: currently defaults to the soft-float ABIs. Will need to be
1857 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
1858 const char *ABIName = nullptr;
1859 const llvm::Triple &Triple = getToolChain().getTriple();
1860 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1861 ABIName = A->getValue();
1862 else if (Triple.getArch() == llvm::Triple::riscv32)
1864 else if (Triple.getArch() == llvm::Triple::riscv64)
1867 llvm_unreachable("Unexpected triple!");
1869 CmdArgs.push_back("-target-abi");
1870 CmdArgs.push_back(ABIName);
1873 void Clang::AddSparcTargetArgs(const ArgList &Args,
1874 ArgStringList &CmdArgs) const {
1875 sparc::FloatABI FloatABI =
1876 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1878 if (FloatABI == sparc::FloatABI::Soft) {
1879 // Floating point operations and argument passing are soft.
1880 CmdArgs.push_back("-msoft-float");
1881 CmdArgs.push_back("-mfloat-abi");
1882 CmdArgs.push_back("soft");
1884 // Floating point operations and argument passing are hard.
1885 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1886 CmdArgs.push_back("-mfloat-abi");
1887 CmdArgs.push_back("hard");
1891 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1892 ArgStringList &CmdArgs) const {
1893 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1894 CmdArgs.push_back("-mbackchain");
1897 void Clang::AddX86TargetArgs(const ArgList &Args,
1898 ArgStringList &CmdArgs) const {
1899 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1900 Args.hasArg(options::OPT_mkernel) ||
1901 Args.hasArg(options::OPT_fapple_kext))
1902 CmdArgs.push_back("-disable-red-zone");
1904 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1905 options::OPT_mno_tls_direct_seg_refs, true))
1906 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1908 // Default to avoid implicit floating-point for kernel/kext code, but allow
1909 // that to be overridden with -mno-soft-float.
1910 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1911 Args.hasArg(options::OPT_fapple_kext));
1912 if (Arg *A = Args.getLastArg(
1913 options::OPT_msoft_float, options::OPT_mno_soft_float,
1914 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1915 const Option &O = A->getOption();
1916 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1917 O.matches(options::OPT_msoft_float));
1919 if (NoImplicitFloat)
1920 CmdArgs.push_back("-no-implicit-float");
1922 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1923 StringRef Value = A->getValue();
1924 if (Value == "intel" || Value == "att") {
1925 CmdArgs.push_back("-mllvm");
1926 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1928 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1929 << A->getOption().getName() << Value;
1931 } else if (getToolChain().getDriver().IsCLMode()) {
1932 CmdArgs.push_back("-mllvm");
1933 CmdArgs.push_back("-x86-asm-syntax=intel");
1936 // Set flags to support MCU ABI.
1937 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1938 CmdArgs.push_back("-mfloat-abi");
1939 CmdArgs.push_back("soft");
1940 CmdArgs.push_back("-mstack-alignment=4");
1944 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1945 ArgStringList &CmdArgs) const {
1946 CmdArgs.push_back("-mqdsp6-compat");
1947 CmdArgs.push_back("-Wreturn-type");
1949 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1950 CmdArgs.push_back("-mllvm");
1951 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1952 Twine(G.getValue())));
1955 if (!Args.hasArg(options::OPT_fno_short_enums))
1956 CmdArgs.push_back("-fshort-enums");
1957 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1958 CmdArgs.push_back("-mllvm");
1959 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1961 CmdArgs.push_back("-mllvm");
1962 CmdArgs.push_back("-machine-sink-split=0");
1965 void Clang::AddLanaiTargetArgs(const ArgList &Args,
1966 ArgStringList &CmdArgs) const {
1967 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1968 StringRef CPUName = A->getValue();
1970 CmdArgs.push_back("-target-cpu");
1971 CmdArgs.push_back(Args.MakeArgString(CPUName));
1973 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1974 StringRef Value = A->getValue();
1975 // Only support mregparm=4 to support old usage. Report error for all other
1978 if (Value.getAsInteger(10, Mregparm)) {
1979 if (Mregparm != 4) {
1980 getToolChain().getDriver().Diag(
1981 diag::err_drv_unsupported_option_argument)
1982 << A->getOption().getName() << Value;
1988 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1989 ArgStringList &CmdArgs) const {
1990 // Default to "hidden" visibility.
1991 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1992 options::OPT_fvisibility_ms_compat)) {
1993 CmdArgs.push_back("-fvisibility");
1994 CmdArgs.push_back("hidden");
1998 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1999 StringRef Target, const InputInfo &Output,
2000 const InputInfo &Input, const ArgList &Args) const {
2001 // If this is a dry run, do not create the compilation database file.
2002 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2005 using llvm::yaml::escape;
2006 const Driver &D = getToolChain().getDriver();
2008 if (!CompilationDatabase) {
2010 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
2012 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2016 CompilationDatabase = std::move(File);
2018 auto &CDB = *CompilationDatabase;
2019 SmallString<128> Buf;
2020 if (llvm::sys::fs::current_path(Buf))
2022 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
2023 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2024 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2025 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2027 Buf += types::getTypeName(Input.getType());
2028 CDB << ", \"" << escape(Buf) << "\"";
2029 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2032 CDB << ", \"" << escape(Buf) << "\"";
2034 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2035 for (auto &A: Args) {
2036 auto &O = A->getOption();
2037 // Skip language selection, which is positional.
2038 if (O.getID() == options::OPT_x)
2040 // Skip writing dependency output and the compilation database itself.
2041 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2044 if (O.getKind() == Option::InputClass)
2046 // All other arguments are quoted and appended.
2048 A->render(Args, ASL);
2050 CDB << ", \"" << escape(it) << "\"";
2054 CDB << ", \"" << escape(Buf) << "\"]},\n";
2057 static void CollectArgsForIntegratedAssembler(Compilation &C,
2058 const ArgList &Args,
2059 ArgStringList &CmdArgs,
2061 if (UseRelaxAll(C, Args))
2062 CmdArgs.push_back("-mrelax-all");
2064 // Only default to -mincremental-linker-compatible if we think we are
2065 // targeting the MSVC linker.
2066 bool DefaultIncrementalLinkerCompatible =
2067 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2068 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2069 options::OPT_mno_incremental_linker_compatible,
2070 DefaultIncrementalLinkerCompatible))
2071 CmdArgs.push_back("-mincremental-linker-compatible");
2073 switch (C.getDefaultToolChain().getArch()) {
2074 case llvm::Triple::arm:
2075 case llvm::Triple::armeb:
2076 case llvm::Triple::thumb:
2077 case llvm::Triple::thumbeb:
2078 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2079 StringRef Value = A->getValue();
2080 if (Value == "always" || Value == "never" || Value == "arm" ||
2082 CmdArgs.push_back("-mllvm");
2083 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2085 D.Diag(diag::err_drv_unsupported_option_argument)
2086 << A->getOption().getName() << Value;
2094 // When passing -I arguments to the assembler we sometimes need to
2095 // unconditionally take the next argument. For example, when parsing
2096 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2097 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2098 // arg after parsing the '-I' arg.
2099 bool TakeNextArg = false;
2101 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2102 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
2103 const char *MipsTargetFeature = nullptr;
2105 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2108 for (StringRef Value : A->getValues()) {
2110 CmdArgs.push_back(Value.data());
2111 TakeNextArg = false;
2115 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2116 Value == "-mbig-obj")
2117 continue; // LLVM handles bigobj automatically
2119 switch (C.getDefaultToolChain().getArch()) {
2122 case llvm::Triple::thumb:
2123 case llvm::Triple::thumbeb:
2124 case llvm::Triple::arm:
2125 case llvm::Triple::armeb:
2126 if (Value == "-mthumb")
2127 // -mthumb has already been processed in ComputeLLVMTriple()
2128 // recognize but skip over here.
2131 case llvm::Triple::mips:
2132 case llvm::Triple::mipsel:
2133 case llvm::Triple::mips64:
2134 case llvm::Triple::mips64el:
2135 if (Value == "--trap") {
2136 CmdArgs.push_back("-target-feature");
2137 CmdArgs.push_back("+use-tcc-in-div");
2140 if (Value == "--break") {
2141 CmdArgs.push_back("-target-feature");
2142 CmdArgs.push_back("-use-tcc-in-div");
2145 if (Value.startswith("-msoft-float")) {
2146 CmdArgs.push_back("-target-feature");
2147 CmdArgs.push_back("+soft-float");
2150 if (Value.startswith("-mhard-float")) {
2151 CmdArgs.push_back("-target-feature");
2152 CmdArgs.push_back("-soft-float");
2156 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2157 .Case("-mips1", "+mips1")
2158 .Case("-mips2", "+mips2")
2159 .Case("-mips3", "+mips3")
2160 .Case("-mips4", "+mips4")
2161 .Case("-mips5", "+mips5")
2162 .Case("-mips32", "+mips32")
2163 .Case("-mips32r2", "+mips32r2")
2164 .Case("-mips32r3", "+mips32r3")
2165 .Case("-mips32r5", "+mips32r5")
2166 .Case("-mips32r6", "+mips32r6")
2167 .Case("-mips64", "+mips64")
2168 .Case("-mips64r2", "+mips64r2")
2169 .Case("-mips64r3", "+mips64r3")
2170 .Case("-mips64r5", "+mips64r5")
2171 .Case("-mips64r6", "+mips64r6")
2173 if (MipsTargetFeature)
2177 if (Value == "-force_cpusubtype_ALL") {
2178 // Do nothing, this is the default and we don't support anything else.
2179 } else if (Value == "-L") {
2180 CmdArgs.push_back("-msave-temp-labels");
2181 } else if (Value == "--fatal-warnings") {
2182 CmdArgs.push_back("-massembler-fatal-warnings");
2183 } else if (Value == "--noexecstack") {
2184 UseNoExecStack = true;
2185 } else if (Value.startswith("-compress-debug-sections") ||
2186 Value.startswith("--compress-debug-sections") ||
2187 Value == "-nocompress-debug-sections" ||
2188 Value == "--nocompress-debug-sections") {
2189 CmdArgs.push_back(Value.data());
2190 } else if (Value == "-mrelax-relocations=yes" ||
2191 Value == "--mrelax-relocations=yes") {
2192 UseRelaxRelocations = true;
2193 } else if (Value == "-mrelax-relocations=no" ||
2194 Value == "--mrelax-relocations=no") {
2195 UseRelaxRelocations = false;
2196 } else if (Value.startswith("-I")) {
2197 CmdArgs.push_back(Value.data());
2198 // We need to consume the next argument if the current arg is a plain
2199 // -I. The next arg will be the include directory.
2202 } else if (Value.startswith("-gdwarf-")) {
2203 // "-gdwarf-N" options are not cc1as options.
2204 unsigned DwarfVersion = DwarfVersionNum(Value);
2205 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2206 CmdArgs.push_back(Value.data());
2208 RenderDebugEnablingArgs(Args, CmdArgs,
2209 codegenoptions::LimitedDebugInfo,
2210 DwarfVersion, llvm::DebuggerKind::Default);
2212 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2213 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2214 // Do nothing, we'll validate it later.
2215 } else if (Value == "-defsym") {
2216 if (A->getNumValues() != 2) {
2217 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2220 const char *S = A->getValue(1);
2221 auto Pair = StringRef(S).split('=');
2222 auto Sym = Pair.first;
2223 auto SVal = Pair.second;
2225 if (Sym.empty() || SVal.empty()) {
2226 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2230 if (SVal.getAsInteger(0, IVal)) {
2231 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2234 CmdArgs.push_back(Value.data());
2236 } else if (Value == "-fdebug-compilation-dir") {
2237 CmdArgs.push_back("-fdebug-compilation-dir");
2240 D.Diag(diag::err_drv_unsupported_option_argument)
2241 << A->getOption().getName() << Value;
2245 if (UseRelaxRelocations)
2246 CmdArgs.push_back("--mrelax-relocations");
2248 CmdArgs.push_back("-mnoexecstack");
2249 if (MipsTargetFeature != nullptr) {
2250 CmdArgs.push_back("-target-feature");
2251 CmdArgs.push_back(MipsTargetFeature);
2254 // forward -fembed-bitcode to assmebler
2255 if (C.getDriver().embedBitcodeEnabled() ||
2256 C.getDriver().embedBitcodeMarkerOnly())
2257 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2260 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2261 bool OFastEnabled, const ArgList &Args,
2262 ArgStringList &CmdArgs) {
2263 // Handle various floating point optimization flags, mapping them to the
2264 // appropriate LLVM code generation flags. This is complicated by several
2265 // "umbrella" flags, so we do this by stepping through the flags incrementally
2266 // adjusting what we think is enabled/disabled, then at the end setting the
2267 // LLVM flags based on the final state.
2268 bool HonorINFs = true;
2269 bool HonorNaNs = true;
2270 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2271 bool MathErrno = TC.IsMathErrnoDefault();
2272 bool AssociativeMath = false;
2273 bool ReciprocalMath = false;
2274 bool SignedZeros = true;
2275 bool TrappingMath = true;
2276 StringRef DenormalFPMath = "";
2277 StringRef FPContract = "";
2279 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2280 CmdArgs.push_back("-mlimit-float-precision");
2281 CmdArgs.push_back(A->getValue());
2284 for (const Arg *A : Args) {
2285 switch (A->getOption().getID()) {
2286 // If this isn't an FP option skip the claim below
2289 // Options controlling individual features
2290 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2291 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2292 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2293 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2294 case options::OPT_fmath_errno: MathErrno = true; break;
2295 case options::OPT_fno_math_errno: MathErrno = false; break;
2296 case options::OPT_fassociative_math: AssociativeMath = true; break;
2297 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2298 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2299 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2300 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2301 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2302 case options::OPT_ftrapping_math: TrappingMath = true; break;
2303 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2305 case options::OPT_fdenormal_fp_math_EQ:
2306 DenormalFPMath = A->getValue();
2309 // Validate and pass through -fp-contract option.
2310 case options::OPT_ffp_contract: {
2311 StringRef Val = A->getValue();
2312 if (Val == "fast" || Val == "on" || Val == "off")
2315 D.Diag(diag::err_drv_unsupported_option_argument)
2316 << A->getOption().getName() << Val;
2320 case options::OPT_ffinite_math_only:
2324 case options::OPT_fno_finite_math_only:
2329 case options::OPT_funsafe_math_optimizations:
2330 AssociativeMath = true;
2331 ReciprocalMath = true;
2332 SignedZeros = false;
2333 TrappingMath = false;
2335 case options::OPT_fno_unsafe_math_optimizations:
2336 AssociativeMath = false;
2337 ReciprocalMath = false;
2339 TrappingMath = true;
2340 // -fno_unsafe_math_optimizations restores default denormal handling
2341 DenormalFPMath = "";
2344 case options::OPT_Ofast:
2345 // If -Ofast is the optimization level, then -ffast-math should be enabled
2349 case options::OPT_ffast_math:
2353 AssociativeMath = true;
2354 ReciprocalMath = true;
2355 SignedZeros = false;
2356 TrappingMath = false;
2357 // If fast-math is set then set the fp-contract mode to fast.
2358 FPContract = "fast";
2360 case options::OPT_fno_fast_math:
2363 // Turning on -ffast-math (with either flag) removes the need for
2364 // MathErrno. However, turning *off* -ffast-math merely restores the
2365 // toolchain default (which may be false).
2366 MathErrno = TC.IsMathErrnoDefault();
2367 AssociativeMath = false;
2368 ReciprocalMath = false;
2370 TrappingMath = true;
2371 // -fno_fast_math restores default denormal and fpcontract handling
2372 DenormalFPMath = "";
2377 // If we handled this option claim it
2382 CmdArgs.push_back("-menable-no-infs");
2385 CmdArgs.push_back("-menable-no-nans");
2388 CmdArgs.push_back("-fmath-errno");
2390 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2392 CmdArgs.push_back("-menable-unsafe-fp-math");
2395 CmdArgs.push_back("-fno-signed-zeros");
2397 if (AssociativeMath && !SignedZeros && !TrappingMath)
2398 CmdArgs.push_back("-mreassociate");
2401 CmdArgs.push_back("-freciprocal-math");
2404 CmdArgs.push_back("-fno-trapping-math");
2406 if (!DenormalFPMath.empty())
2408 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2410 if (!FPContract.empty())
2411 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2413 ParseMRecip(D, Args, CmdArgs);
2415 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2416 // individual features enabled by -ffast-math instead of the option itself as
2417 // that's consistent with gcc's behaviour.
2418 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2419 ReciprocalMath && !SignedZeros && !TrappingMath)
2420 CmdArgs.push_back("-ffast-math");
2422 // Handle __FINITE_MATH_ONLY__ similarly.
2423 if (!HonorINFs && !HonorNaNs)
2424 CmdArgs.push_back("-ffinite-math-only");
2426 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2427 CmdArgs.push_back("-mfpmath");
2428 CmdArgs.push_back(A->getValue());
2431 // Disable a codegen optimization for floating-point casts.
2432 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2433 options::OPT_fstrict_float_cast_overflow, false))
2434 CmdArgs.push_back("-fno-strict-float-cast-overflow");
2437 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2438 const llvm::Triple &Triple,
2439 const InputInfo &Input) {
2440 // Enable region store model by default.
2441 CmdArgs.push_back("-analyzer-store=region");
2443 // Treat blocks as analysis entry points.
2444 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2446 // Add default argument set.
2447 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2448 CmdArgs.push_back("-analyzer-checker=core");
2449 CmdArgs.push_back("-analyzer-checker=apiModeling");
2451 if (!Triple.isWindowsMSVCEnvironment()) {
2452 CmdArgs.push_back("-analyzer-checker=unix");
2454 // Enable "unix" checkers that also work on Windows.
2455 CmdArgs.push_back("-analyzer-checker=unix.API");
2456 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2457 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2458 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2459 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2460 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2463 // Disable some unix checkers for PS4.
2464 if (Triple.isPS4CPU()) {
2465 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2466 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2469 if (Triple.isOSDarwin())
2470 CmdArgs.push_back("-analyzer-checker=osx");
2472 CmdArgs.push_back("-analyzer-checker=deadcode");
2474 if (types::isCXX(Input.getType()))
2475 CmdArgs.push_back("-analyzer-checker=cplusplus");
2477 if (!Triple.isPS4CPU()) {
2478 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2479 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2480 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2481 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2482 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2483 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2486 // Default nullability checks.
2487 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2488 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2491 // Set the output format. The default is plist, for (lame) historical reasons.
2492 CmdArgs.push_back("-analyzer-output");
2493 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2494 CmdArgs.push_back(A->getValue());
2496 CmdArgs.push_back("plist");
2498 // Disable the presentation of standard compiler warnings when using
2499 // --analyze. We only want to show static analyzer diagnostics or frontend
2501 CmdArgs.push_back("-w");
2503 // Add -Xanalyzer arguments when running as analyzer.
2504 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2507 static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
2508 ArgStringList &CmdArgs, bool KernelOrKext) {
2509 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2511 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2512 // doesn't even have a stack!
2513 if (EffectiveTriple.isNVPTX())
2516 // -stack-protector=0 is default.
2517 unsigned StackProtectorLevel = 0;
2518 unsigned DefaultStackProtectorLevel =
2519 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2521 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2522 options::OPT_fstack_protector_all,
2523 options::OPT_fstack_protector_strong,
2524 options::OPT_fstack_protector)) {
2525 if (A->getOption().matches(options::OPT_fstack_protector))
2526 StackProtectorLevel =
2527 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2528 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2529 StackProtectorLevel = LangOptions::SSPStrong;
2530 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2531 StackProtectorLevel = LangOptions::SSPReq;
2533 StackProtectorLevel = DefaultStackProtectorLevel;
2536 if (StackProtectorLevel) {
2537 CmdArgs.push_back("-stack-protector");
2538 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2541 // --param ssp-buffer-size=
2542 for (const Arg *A : Args.filtered(options::OPT__param)) {
2543 StringRef Str(A->getValue());
2544 if (Str.startswith("ssp-buffer-size=")) {
2545 if (StackProtectorLevel) {
2546 CmdArgs.push_back("-stack-protector-buffer-size");
2547 // FIXME: Verify the argument is a valid integer.
2548 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2555 static void RenderTrivialAutoVarInitOptions(const Driver &D,
2556 const ToolChain &TC,
2557 const ArgList &Args,
2558 ArgStringList &CmdArgs) {
2559 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2560 StringRef TrivialAutoVarInit = "";
2562 for (const Arg *A : Args) {
2563 switch (A->getOption().getID()) {
2566 case options::OPT_ftrivial_auto_var_init: {
2568 StringRef Val = A->getValue();
2569 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2570 TrivialAutoVarInit = Val;
2572 D.Diag(diag::err_drv_unsupported_option_argument)
2573 << A->getOption().getName() << Val;
2579 if (TrivialAutoVarInit.empty())
2580 switch (DefaultTrivialAutoVarInit) {
2581 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2583 case LangOptions::TrivialAutoVarInitKind::Pattern:
2584 TrivialAutoVarInit = "pattern";
2586 case LangOptions::TrivialAutoVarInitKind::Zero:
2587 TrivialAutoVarInit = "zero";
2591 if (!TrivialAutoVarInit.empty()) {
2592 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2593 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2595 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2599 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2600 const unsigned ForwardedArguments[] = {
2601 options::OPT_cl_opt_disable,
2602 options::OPT_cl_strict_aliasing,
2603 options::OPT_cl_single_precision_constant,
2604 options::OPT_cl_finite_math_only,
2605 options::OPT_cl_kernel_arg_info,
2606 options::OPT_cl_unsafe_math_optimizations,
2607 options::OPT_cl_fast_relaxed_math,
2608 options::OPT_cl_mad_enable,
2609 options::OPT_cl_no_signed_zeros,
2610 options::OPT_cl_denorms_are_zero,
2611 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2612 options::OPT_cl_uniform_work_group_size
2615 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2616 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2617 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2620 for (const auto &Arg : ForwardedArguments)
2621 if (const auto *A = Args.getLastArg(Arg))
2622 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2625 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2626 ArgStringList &CmdArgs) {
2627 bool ARCMTEnabled = false;
2628 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2629 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2630 options::OPT_ccc_arcmt_modify,
2631 options::OPT_ccc_arcmt_migrate)) {
2632 ARCMTEnabled = true;
2633 switch (A->getOption().getID()) {
2634 default: llvm_unreachable("missed a case");
2635 case options::OPT_ccc_arcmt_check:
2636 CmdArgs.push_back("-arcmt-check");
2638 case options::OPT_ccc_arcmt_modify:
2639 CmdArgs.push_back("-arcmt-modify");
2641 case options::OPT_ccc_arcmt_migrate:
2642 CmdArgs.push_back("-arcmt-migrate");
2643 CmdArgs.push_back("-mt-migrate-directory");
2644 CmdArgs.push_back(A->getValue());
2646 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2647 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2652 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2653 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2654 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2657 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2659 D.Diag(diag::err_drv_argument_not_allowed_with)
2660 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2662 CmdArgs.push_back("-mt-migrate-directory");
2663 CmdArgs.push_back(A->getValue());
2665 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2666 options::OPT_objcmt_migrate_subscripting,
2667 options::OPT_objcmt_migrate_property)) {
2668 // None specified, means enable them all.
2669 CmdArgs.push_back("-objcmt-migrate-literals");
2670 CmdArgs.push_back("-objcmt-migrate-subscripting");
2671 CmdArgs.push_back("-objcmt-migrate-property");
2673 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2674 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2675 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2678 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2679 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2680 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2681 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2682 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2683 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2684 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2685 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2686 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2687 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2688 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2689 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2690 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2691 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2692 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2693 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2697 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2698 const ArgList &Args, ArgStringList &CmdArgs) {
2699 // -fbuiltin is default unless -mkernel is used.
2701 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2702 !Args.hasArg(options::OPT_mkernel));
2704 CmdArgs.push_back("-fno-builtin");
2706 // -ffreestanding implies -fno-builtin.
2707 if (Args.hasArg(options::OPT_ffreestanding))
2708 UseBuiltins = false;
2710 // Process the -fno-builtin-* options.
2711 for (const auto &Arg : Args) {
2712 const Option &O = Arg->getOption();
2713 if (!O.matches(options::OPT_fno_builtin_))
2718 // If -fno-builtin is specified, then there's no need to pass the option to
2723 StringRef FuncName = Arg->getValue();
2724 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2727 // le32-specific flags:
2728 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2730 if (TC.getArch() == llvm::Triple::le32)
2731 CmdArgs.push_back("-fno-math-builtin");
2734 void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2735 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2736 llvm::sys::path::append(Result, "org.llvm.clang.");
2737 appendUserToPath(Result);
2738 llvm::sys::path::append(Result, "ModuleCache");
2741 static void RenderModulesOptions(Compilation &C, const Driver &D,
2742 const ArgList &Args, const InputInfo &Input,
2743 const InputInfo &Output,
2744 ArgStringList &CmdArgs, bool &HaveModules) {
2745 // -fmodules enables the use of precompiled modules (off by default).
2746 // Users can pass -fno-cxx-modules to turn off modules support for
2747 // C++/Objective-C++ programs.
2748 bool HaveClangModules = false;
2749 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2750 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2751 options::OPT_fno_cxx_modules, true);
2752 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2753 CmdArgs.push_back("-fmodules");
2754 HaveClangModules = true;
2758 HaveModules |= HaveClangModules;
2759 if (Args.hasArg(options::OPT_fmodules_ts)) {
2760 CmdArgs.push_back("-fmodules-ts");
2764 // -fmodule-maps enables implicit reading of module map files. By default,
2765 // this is enabled if we are using Clang's flavor of precompiled modules.
2766 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2767 options::OPT_fno_implicit_module_maps, HaveClangModules))
2768 CmdArgs.push_back("-fimplicit-module-maps");
2770 // -fmodules-decluse checks that modules used are declared so (off by default)
2771 if (Args.hasFlag(options::OPT_fmodules_decluse,
2772 options::OPT_fno_modules_decluse, false))
2773 CmdArgs.push_back("-fmodules-decluse");
2775 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2776 // all #included headers are part of modules.
2777 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2778 options::OPT_fno_modules_strict_decluse, false))
2779 CmdArgs.push_back("-fmodules-strict-decluse");
2781 // -fno-implicit-modules turns off implicitly compiling modules on demand.
2782 bool ImplicitModules = false;
2783 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2784 options::OPT_fno_implicit_modules, HaveClangModules)) {
2786 CmdArgs.push_back("-fno-implicit-modules");
2787 } else if (HaveModules) {
2788 ImplicitModules = true;
2789 // -fmodule-cache-path specifies where our implicitly-built module files
2790 // should be written.
2791 SmallString<128> Path;
2792 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2793 Path = A->getValue();
2795 if (C.isForDiagnostics()) {
2796 // When generating crash reports, we want to emit the modules along with
2797 // the reproduction sources, so we ignore any provided module path.
2798 Path = Output.getFilename();
2799 llvm::sys::path::replace_extension(Path, ".cache");
2800 llvm::sys::path::append(Path, "modules");
2801 } else if (Path.empty()) {
2802 // No module path was provided: use the default.
2803 Driver::getDefaultModuleCachePath(Path);
2806 const char Arg[] = "-fmodules-cache-path=";
2807 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2808 CmdArgs.push_back(Args.MakeArgString(Path));
2812 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2813 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2814 CmdArgs.push_back(Args.MakeArgString(
2815 std::string("-fprebuilt-module-path=") + A->getValue()));
2820 // -fmodule-name specifies the module that is currently being built (or
2821 // used for header checking by -fmodule-maps).
2822 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2824 // -fmodule-map-file can be used to specify files containing module
2826 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2828 // -fbuiltin-module-map can be used to load the clang
2829 // builtin headers modulemap file.
2830 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2831 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2832 llvm::sys::path::append(BuiltinModuleMap, "include");
2833 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2834 if (llvm::sys::fs::exists(BuiltinModuleMap))
2836 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2839 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2840 // names to precompiled module files (the module is loaded only if used).
2841 // The -fmodule-file=<file> form can be used to unconditionally load
2842 // precompiled module files (whether used or not).
2844 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2846 Args.ClaimAllArgs(options::OPT_fmodule_file);
2848 // When building modules and generating crashdumps, we need to dump a module
2849 // dependency VFS alongside the output.
2850 if (HaveClangModules && C.isForDiagnostics()) {
2851 SmallString<128> VFSDir(Output.getFilename());
2852 llvm::sys::path::replace_extension(VFSDir, ".cache");
2853 // Add the cache directory as a temp so the crash diagnostics pick it up.
2854 C.addTempFile(Args.MakeArgString(VFSDir));
2856 llvm::sys::path::append(VFSDir, "vfs");
2857 CmdArgs.push_back("-module-dependency-dir");
2858 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2861 if (HaveClangModules)
2862 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2864 // Pass through all -fmodules-ignore-macro arguments.
2865 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2866 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2867 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2869 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2871 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2872 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2873 D.Diag(diag::err_drv_argument_not_allowed_with)
2874 << A->getAsString(Args) << "-fbuild-session-timestamp";
2876 llvm::sys::fs::file_status Status;
2877 if (llvm::sys::fs::status(A->getValue(), Status))
2878 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2880 Args.MakeArgString("-fbuild-session-timestamp=" +
2881 Twine((uint64_t)Status.getLastModificationTime()
2886 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2887 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2888 options::OPT_fbuild_session_file))
2889 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2891 Args.AddLastArg(CmdArgs,
2892 options::OPT_fmodules_validate_once_per_build_session);
2895 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2896 options::OPT_fno_modules_validate_system_headers,
2898 CmdArgs.push_back("-fmodules-validate-system-headers");
2900 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2903 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2904 ArgStringList &CmdArgs) {
2905 // -fsigned-char is default.
2906 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2907 options::OPT_fno_signed_char,
2908 options::OPT_funsigned_char,
2909 options::OPT_fno_unsigned_char)) {
2910 if (A->getOption().matches(options::OPT_funsigned_char) ||
2911 A->getOption().matches(options::OPT_fno_signed_char)) {
2912 CmdArgs.push_back("-fno-signed-char");
2914 } else if (!isSignedCharDefault(T)) {
2915 CmdArgs.push_back("-fno-signed-char");
2918 // The default depends on the language standard.
2919 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
2921 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2922 options::OPT_fno_short_wchar)) {
2923 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2924 CmdArgs.push_back("-fwchar-type=short");
2925 CmdArgs.push_back("-fno-signed-wchar");
2927 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
2928 CmdArgs.push_back("-fwchar-type=int");
2929 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2931 CmdArgs.push_back("-fno-signed-wchar");
2933 CmdArgs.push_back("-fsigned-wchar");
2938 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2939 const llvm::Triple &T, const ArgList &Args,
2940 ObjCRuntime &Runtime, bool InferCovariantReturns,
2941 const InputInfo &Input, ArgStringList &CmdArgs) {
2942 const llvm::Triple::ArchType Arch = TC.getArch();
2944 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2945 // is the default. Except for deployment target of 10.5, next runtime is
2946 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2947 if (Runtime.isNonFragile()) {
2948 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2949 options::OPT_fno_objc_legacy_dispatch,
2950 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2951 if (TC.UseObjCMixedDispatch())
2952 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2954 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2958 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2959 // to do Array/Dictionary subscripting by default.
2960 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2961 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2962 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2964 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2965 // NOTE: This logic is duplicated in ToolChains.cpp.
2966 if (isObjCAutoRefCount(Args)) {
2969 CmdArgs.push_back("-fobjc-arc");
2971 // FIXME: It seems like this entire block, and several around it should be
2972 // wrapped in isObjC, but for now we just use it here as this is where it
2973 // was being used previously.
2974 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2975 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2976 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2978 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2981 // Allow the user to enable full exceptions code emission.
2982 // We default off for Objective-C, on for Objective-C++.
2983 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2984 options::OPT_fno_objc_arc_exceptions,
2985 /*Default=*/types::isCXX(Input.getType())))
2986 CmdArgs.push_back("-fobjc-arc-exceptions");
2989 // Silence warning for full exception code emission options when explicitly
2990 // set to use no ARC.
2991 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2992 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2993 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2996 // Allow the user to control whether messages can be converted to runtime
2998 if (types::isObjC(Input.getType())) {
2999 auto *Arg = Args.getLastArg(
3000 options::OPT_fobjc_convert_messages_to_runtime_calls,
3001 options::OPT_fno_objc_convert_messages_to_runtime_calls);
3003 Arg->getOption().matches(
3004 options::OPT_fno_objc_convert_messages_to_runtime_calls))
3005 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3008 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3010 if (InferCovariantReturns)
3011 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3013 // Pass down -fobjc-weak or -fno-objc-weak if present.
3014 if (types::isObjC(Input.getType())) {
3016 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3019 } else if (!Runtime.allowsWeak()) {
3020 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3021 D.Diag(diag::err_objc_weak_unsupported);
3023 WeakArg->render(Args, CmdArgs);
3028 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3029 ArgStringList &CmdArgs) {
3030 bool CaretDefault = true;
3031 bool ColumnDefault = true;
3033 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3034 options::OPT__SLASH_diagnostics_column,
3035 options::OPT__SLASH_diagnostics_caret)) {
3036 switch (A->getOption().getID()) {
3037 case options::OPT__SLASH_diagnostics_caret:
3038 CaretDefault = true;
3039 ColumnDefault = true;
3041 case options::OPT__SLASH_diagnostics_column:
3042 CaretDefault = false;
3043 ColumnDefault = true;
3045 case options::OPT__SLASH_diagnostics_classic:
3046 CaretDefault = false;
3047 ColumnDefault = false;
3052 // -fcaret-diagnostics is default.
3053 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3054 options::OPT_fno_caret_diagnostics, CaretDefault))
3055 CmdArgs.push_back("-fno-caret-diagnostics");
3057 // -fdiagnostics-fixit-info is default, only pass non-default.
3058 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3059 options::OPT_fno_diagnostics_fixit_info))
3060 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3062 // Enable -fdiagnostics-show-option by default.
3063 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3064 options::OPT_fno_diagnostics_show_option))
3065 CmdArgs.push_back("-fdiagnostics-show-option");
3068 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3069 CmdArgs.push_back("-fdiagnostics-show-category");
3070 CmdArgs.push_back(A->getValue());
3073 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3074 options::OPT_fno_diagnostics_show_hotness, false))
3075 CmdArgs.push_back("-fdiagnostics-show-hotness");
3078 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3080 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3081 CmdArgs.push_back(Args.MakeArgString(Opt));
3084 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3085 CmdArgs.push_back("-fdiagnostics-format");
3086 CmdArgs.push_back(A->getValue());
3089 if (const Arg *A = Args.getLastArg(
3090 options::OPT_fdiagnostics_show_note_include_stack,
3091 options::OPT_fno_diagnostics_show_note_include_stack)) {
3092 const Option &O = A->getOption();
3093 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3094 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3096 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3099 // Color diagnostics are parsed by the driver directly from argv and later
3100 // re-parsed to construct this job; claim any possible color diagnostic here
3101 // to avoid warn_drv_unused_argument and diagnose bad
3102 // OPT_fdiagnostics_color_EQ values.
3103 for (const Arg *A : Args) {
3104 const Option &O = A->getOption();
3105 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3106 !O.matches(options::OPT_fdiagnostics_color) &&
3107 !O.matches(options::OPT_fno_color_diagnostics) &&
3108 !O.matches(options::OPT_fno_diagnostics_color) &&
3109 !O.matches(options::OPT_fdiagnostics_color_EQ))
3112 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3113 StringRef Value(A->getValue());
3114 if (Value != "always" && Value != "never" && Value != "auto")
3115 D.Diag(diag::err_drv_clang_unsupported)
3116 << ("-fdiagnostics-color=" + Value).str();
3121 if (D.getDiags().getDiagnosticOptions().ShowColors)
3122 CmdArgs.push_back("-fcolor-diagnostics");
3124 if (Args.hasArg(options::OPT_fansi_escape_codes))
3125 CmdArgs.push_back("-fansi-escape-codes");
3127 if (!Args.hasFlag(options::OPT_fshow_source_location,
3128 options::OPT_fno_show_source_location))
3129 CmdArgs.push_back("-fno-show-source-location");
3131 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3132 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3134 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3136 CmdArgs.push_back("-fno-show-column");
3138 if (!Args.hasFlag(options::OPT_fspell_checking,
3139 options::OPT_fno_spell_checking))
3140 CmdArgs.push_back("-fno-spell-checking");
3143 enum class DwarfFissionKind { None, Split, Single };
3145 static DwarfFissionKind getDebugFissionKind(const Driver &D,
3146 const ArgList &Args, Arg *&Arg) {
3148 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3150 return DwarfFissionKind::None;
3152 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3153 return DwarfFissionKind::Split;
3155 StringRef Value = Arg->getValue();
3156 if (Value == "split")
3157 return DwarfFissionKind::Split;
3158 if (Value == "single")
3159 return DwarfFissionKind::Single;
3161 D.Diag(diag::err_drv_unsupported_option_argument)
3162 << Arg->getOption().getName() << Arg->getValue();
3163 return DwarfFissionKind::None;
3166 static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3167 const llvm::Triple &T, const ArgList &Args,
3168 bool EmitCodeView, bool IsWindowsMSVC,
3169 ArgStringList &CmdArgs,
3170 codegenoptions::DebugInfoKind &DebugInfoKind,
3171 DwarfFissionKind &DwarfFission) {
3172 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3173 options::OPT_fno_debug_info_for_profiling, false) &&
3174 checkDebugInfoOption(
3175 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3176 CmdArgs.push_back("-fdebug-info-for-profiling");
3178 // The 'g' groups options involve a somewhat intricate sequence of decisions
3179 // about what to pass from the driver to the frontend, but by the time they
3180 // reach cc1 they've been factored into three well-defined orthogonal choices:
3181 // * what level of debug info to generate
3182 // * what dwarf version to write
3183 // * what debugger tuning to use
3184 // This avoids having to monkey around further in cc1 other than to disable
3185 // codeview if not running in a Windows environment. Perhaps even that
3186 // decision should be made in the driver as well though.
3187 unsigned DWARFVersion = 0;
3188 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3190 bool SplitDWARFInlining =
3191 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3192 options::OPT_fno_split_dwarf_inlining, true);
3194 Args.ClaimAllArgs(options::OPT_g_Group);
3197 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
3199 if (DwarfFission != DwarfFissionKind::None &&
3200 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3201 DwarfFission = DwarfFissionKind::None;
3202 SplitDWARFInlining = false;
3206 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3207 options::OPT_gsplit_dwarf_EQ)) {
3208 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3210 // If the last option explicitly specified a debug-info level, use it.
3211 if (checkDebugInfoOption(A, Args, D, TC) &&
3212 A->getOption().matches(options::OPT_gN_Group)) {
3213 DebugInfoKind = DebugLevelToInfoKind(*A);
3214 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3215 // complicated if you've disabled inline info in the skeleton CUs
3216 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3217 // line-tables-only, so let those compose naturally in that case.
3218 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3219 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3220 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3221 SplitDWARFInlining))
3222 DwarfFission = DwarfFissionKind::None;
3226 // If a debugger tuning argument appeared, remember it.
3228 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3229 if (checkDebugInfoOption(A, Args, D, TC)) {
3230 if (A->getOption().matches(options::OPT_glldb))
3231 DebuggerTuning = llvm::DebuggerKind::LLDB;
3232 else if (A->getOption().matches(options::OPT_gsce))
3233 DebuggerTuning = llvm::DebuggerKind::SCE;
3235 DebuggerTuning = llvm::DebuggerKind::GDB;
3239 // If a -gdwarf argument appeared, remember it.
3241 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3242 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
3243 if (checkDebugInfoOption(A, Args, D, TC))
3244 DWARFVersion = DwarfVersionNum(A->getSpelling());
3246 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3247 if (checkDebugInfoOption(A, Args, D, TC))
3248 EmitCodeView = true;
3251 // If the user asked for debug info but did not explicitly specify -gcodeview
3252 // or -gdwarf, ask the toolchain for the default format.
3253 if (!EmitCodeView && DWARFVersion == 0 &&
3254 DebugInfoKind != codegenoptions::NoDebugInfo) {
3255 switch (TC.getDefaultDebugFormat()) {
3256 case codegenoptions::DIF_CodeView:
3257 EmitCodeView = true;
3259 case codegenoptions::DIF_DWARF:
3260 DWARFVersion = TC.GetDefaultDwarfVersion();
3265 // -gline-directives-only supported only for the DWARF debug info.
3266 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3267 DebugInfoKind = codegenoptions::NoDebugInfo;
3269 // We ignore flag -gstrict-dwarf for now.
3270 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3271 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3273 // Column info is included by default for everything except SCE and
3274 // CodeView. Clang doesn't track end columns, just starting columns, which,
3275 // in theory, is fine for CodeView (and PDB). In practice, however, the
3276 // Microsoft debuggers don't handle missing end columns well, so it's better
3277 // not to include any column info.
3278 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3279 (void)checkDebugInfoOption(A, Args, D, TC);
3280 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3281 /*Default=*/!EmitCodeView &&
3282 DebuggerTuning != llvm::DebuggerKind::SCE))
3283 CmdArgs.push_back("-dwarf-column-info");
3285 // FIXME: Move backend command line options to the module.
3286 // If -gline-tables-only or -gline-directives-only is the last option it wins.
3287 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3288 if (checkDebugInfoOption(A, Args, D, TC)) {
3289 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3290 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
3291 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3292 CmdArgs.push_back("-dwarf-ext-refs");
3293 CmdArgs.push_back("-fmodule-format=obj");
3297 if (T.isOSBinFormatELF() && !SplitDWARFInlining)
3298 CmdArgs.push_back("-fno-split-dwarf-inlining");
3300 // After we've dealt with all combinations of things that could
3301 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3302 // figure out if we need to "upgrade" it to standalone debug info.
3303 // We parse these two '-f' options whether or not they will be used,
3304 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3305 bool NeedFullDebug = Args.hasFlag(
3306 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3307 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3308 TC.GetDefaultStandaloneDebug());
3309 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3310 (void)checkDebugInfoOption(A, Args, D, TC);
3311 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3312 DebugInfoKind = codegenoptions::FullDebugInfo;
3314 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3316 // Source embedding is a vendor extension to DWARF v5. By now we have
3317 // checked if a DWARF version was stated explicitly, and have otherwise
3318 // fallen back to the target default, so if this is still not at least 5
3319 // we emit an error.
3320 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
3321 if (DWARFVersion < 5)
3322 D.Diag(diag::err_drv_argument_only_allowed_with)
3323 << A->getAsString(Args) << "-gdwarf-5";
3324 else if (checkDebugInfoOption(A, Args, D, TC))
3325 CmdArgs.push_back("-gembed-source");
3329 CmdArgs.push_back("-gcodeview");
3331 // Emit codeview type hashes if requested.
3332 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3333 options::OPT_gno_codeview_ghash, false)) {
3334 CmdArgs.push_back("-gcodeview-ghash");
3338 // Adjust the debug info kind for the given toolchain.
3339 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3341 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3344 // -fdebug-macro turns on macro debug info generation.
3345 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3347 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3349 CmdArgs.push_back("-debug-info-macro");
3351 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3352 const auto *PubnamesArg =
3353 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3354 options::OPT_gpubnames, options::OPT_gno_pubnames);
3355 if (DwarfFission != DwarfFissionKind::None ||
3356 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3357 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3359 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3360 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3361 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3362 options::OPT_gpubnames)
3364 : "-ggnu-pubnames");
3366 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3367 options::OPT_fno_debug_ranges_base_address, false)) {
3368 CmdArgs.push_back("-fdebug-ranges-base-address");
3371 // -gdwarf-aranges turns on the emission of the aranges section in the
3373 // Always enabled for SCE tuning.
3374 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3375 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3376 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3378 CmdArgs.push_back("-mllvm");
3379 CmdArgs.push_back("-generate-arange-section");
3382 if (Args.hasFlag(options::OPT_fdebug_types_section,
3383 options::OPT_fno_debug_types_section, false)) {
3384 if (!T.isOSBinFormatELF()) {
3385 D.Diag(diag::err_drv_unsupported_opt_for_target)
3386 << Args.getLastArg(options::OPT_fdebug_types_section)
3389 } else if (checkDebugInfoOption(
3390 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3392 CmdArgs.push_back("-mllvm");
3393 CmdArgs.push_back("-generate-type-units");
3397 // Decide how to render forward declarations of template instantiations.
3398 // SCE wants full descriptions, others just get them in the name.
3399 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3400 CmdArgs.push_back("-debug-forward-template-params");
3402 // Do we need to explicitly import anonymous namespaces into the parent
3404 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3405 CmdArgs.push_back("-dwarf-explicit-import");
3407 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
3410 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3411 const InputInfo &Output, const InputInfoList &Inputs,
3412 const ArgList &Args, const char *LinkingOutput) const {
3413 const auto &TC = getToolChain();
3414 const llvm::Triple &RawTriple = TC.getTriple();
3415 const llvm::Triple &Triple = TC.getEffectiveTriple();
3416 const std::string &TripleStr = Triple.getTriple();
3419 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3420 const Driver &D = TC.getDriver();
3421 ArgStringList CmdArgs;
3423 // Check number of inputs for sanity. We need at least one input.
3424 assert(Inputs.size() >= 1 && "Must have at least one input.");
3425 // CUDA/HIP compilation may have multiple inputs (source file + results of
3426 // device-side compilations). OpenMP device jobs also take the host IR as a
3427 // second input. Module precompilation accepts a list of header files to
3428 // include as part of the module. All other jobs are expected to have exactly
3430 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3431 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
3432 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3433 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3435 // A header module compilation doesn't have a main input file, so invent a
3436 // fake one as a placeholder.
3437 const char *ModuleName = [&]{
3438 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3439 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3441 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
3443 const InputInfo &Input =
3444 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3446 InputInfoList ModuleHeaderInputs;
3447 const InputInfo *CudaDeviceInput = nullptr;
3448 const InputInfo *OpenMPDeviceInput = nullptr;
3449 for (const InputInfo &I : Inputs) {
3451 // This is the primary input.
3452 } else if (IsHeaderModulePrecompile &&
3453 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
3454 types::ID Expected = HeaderModuleInput.getType();
3455 if (I.getType() != Expected) {
3456 D.Diag(diag::err_drv_module_header_wrong_kind)
3457 << I.getFilename() << types::getTypeName(I.getType())
3458 << types::getTypeName(Expected);
3460 ModuleHeaderInputs.push_back(I);
3461 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3462 CudaDeviceInput = &I;
3463 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3464 OpenMPDeviceInput = &I;
3466 llvm_unreachable("unexpectedly given multiple inputs");
3470 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
3471 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3472 bool IsIAMCU = RawTriple.isOSIAMCU();
3474 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3475 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3476 // Windows), we need to pass Windows-specific flags to cc1.
3477 if (IsCuda || IsHIP)
3478 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3480 // C++ is not supported for IAMCU.
3481 if (IsIAMCU && types::isCXX(Input.getType()))
3482 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3484 // Invoke ourselves in -cc1 mode.
3486 // FIXME: Implement custom jobs for internal actions.
3487 CmdArgs.push_back("-cc1");
3489 // Add the "effective" target triple.
3490 CmdArgs.push_back("-triple");
3491 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3493 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3494 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3495 Args.ClaimAllArgs(options::OPT_MJ);
3498 if (IsCuda || IsHIP) {
3499 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3501 std::string NormalizedTriple;
3502 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3503 JA.isDeviceOffloading(Action::OFK_HIP))
3504 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3508 // Host-side compilation.
3510 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3511 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3515 // We need to figure out which CUDA version we're compiling for, as that
3516 // determines how we load and launch GPU kernels.
3517 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3518 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3519 assert(CTC && "Expected valid CUDA Toolchain.");
3520 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3521 CmdArgs.push_back(Args.MakeArgString(
3522 Twine("-target-sdk-version=") +
3523 CudaVersionToString(CTC->CudaInstallation.version())));
3526 CmdArgs.push_back("-aux-triple");
3527 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3530 if (IsOpenMPDevice) {
3531 // We have to pass the triple of the host if compiling for an OpenMP device.
3532 std::string NormalizedTriple =
3533 C.getSingleOffloadToolChain<Action::OFK_Host>()
3536 CmdArgs.push_back("-aux-triple");
3537 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3540 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3541 Triple.getArch() == llvm::Triple::thumb)) {
3542 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3544 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3546 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3550 // Push all default warning arguments that are specific to
3551 // the given target. These come before user provided warning options
3553 TC.addClangWarningOptions(CmdArgs);
3555 // Select the appropriate action.
3556 RewriteKind rewriteKind = RK_None;
3558 if (isa<AnalyzeJobAction>(JA)) {
3559 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3560 CmdArgs.push_back("-analyze");
3561 } else if (isa<MigrateJobAction>(JA)) {
3562 CmdArgs.push_back("-migrate");
3563 } else if (isa<PreprocessJobAction>(JA)) {
3564 if (Output.getType() == types::TY_Dependencies)
3565 CmdArgs.push_back("-Eonly");
3567 CmdArgs.push_back("-E");
3568 if (Args.hasArg(options::OPT_rewrite_objc) &&
3569 !Args.hasArg(options::OPT_g_Group))
3570 CmdArgs.push_back("-P");
3572 } else if (isa<AssembleJobAction>(JA)) {
3573 CmdArgs.push_back("-emit-obj");
3575 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3577 // Also ignore explicit -force_cpusubtype_ALL option.
3578 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3579 } else if (isa<PrecompileJobAction>(JA)) {
3580 if (JA.getType() == types::TY_Nothing)
3581 CmdArgs.push_back("-fsyntax-only");
3582 else if (JA.getType() == types::TY_ModuleFile)
3583 CmdArgs.push_back(IsHeaderModulePrecompile
3584 ? "-emit-header-module"
3585 : "-emit-module-interface");
3587 CmdArgs.push_back("-emit-pch");
3588 } else if (isa<VerifyPCHJobAction>(JA)) {
3589 CmdArgs.push_back("-verify-pch");
3591 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3592 "Invalid action for clang tool.");
3593 if (JA.getType() == types::TY_Nothing) {
3594 CmdArgs.push_back("-fsyntax-only");
3595 } else if (JA.getType() == types::TY_LLVM_IR ||
3596 JA.getType() == types::TY_LTO_IR) {
3597 CmdArgs.push_back("-emit-llvm");
3598 } else if (JA.getType() == types::TY_LLVM_BC ||
3599 JA.getType() == types::TY_LTO_BC) {
3600 CmdArgs.push_back("-emit-llvm-bc");
3601 } else if (JA.getType() == types::TY_IFS) {
3602 StringRef StubFormat =
3603 llvm::StringSwitch<StringRef>(
3604 Args.hasArg(options::OPT_iterface_stub_version_EQ)
3605 ? Args.getLastArgValue(options::OPT_iterface_stub_version_EQ)
3607 .Case("experimental-yaml-elf-v1", "experimental-yaml-elf-v1")
3608 .Case("experimental-tapi-elf-v1", "experimental-tapi-elf-v1")
3611 if (StubFormat.empty())
3612 D.Diag(diag::err_drv_invalid_value)
3613 << "Must specify a valid interface stub format type using "
3614 << "-interface-stub-version=<experimental-tapi-elf-v1 | "
3615 "experimental-yaml-elf-v1>";
3617 CmdArgs.push_back("-emit-interface-stubs");
3619 Args.MakeArgString(Twine("-interface-stub-version=") + StubFormat));
3620 } else if (JA.getType() == types::TY_PP_Asm) {
3621 CmdArgs.push_back("-S");
3622 } else if (JA.getType() == types::TY_AST) {
3623 CmdArgs.push_back("-emit-pch");
3624 } else if (JA.getType() == types::TY_ModuleFile) {
3625 CmdArgs.push_back("-module-file-info");
3626 } else if (JA.getType() == types::TY_RewrittenObjC) {
3627 CmdArgs.push_back("-rewrite-objc");
3628 rewriteKind = RK_NonFragile;
3629 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3630 CmdArgs.push_back("-rewrite-objc");
3631 rewriteKind = RK_Fragile;
3633 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3636 // Preserve use-list order by default when emitting bitcode, so that
3637 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3638 // same result as running passes here. For LTO, we don't need to preserve
3639 // the use-list order, since serialization to bitcode is part of the flow.
3640 if (JA.getType() == types::TY_LLVM_BC)
3641 CmdArgs.push_back("-emit-llvm-uselists");
3643 // Device-side jobs do not support LTO.
3644 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3645 JA.isDeviceOffloading(Action::OFK_Host));
3647 if (D.isUsingLTO() && !isDeviceOffloadAction) {
3648 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3650 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3651 // does not support LTO unit features (CFI, whole program vtable opt)
3653 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
3654 D.getLTOMode() == LTOK_Full)
3655 CmdArgs.push_back("-flto-unit");
3659 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3660 if (!types::isLLVMIR(Input.getType()))
3661 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
3662 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3665 if (Args.getLastArg(options::OPT_save_temps_EQ))
3666 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3668 // Embed-bitcode option.
3669 // Only white-listed flags below are allowed to be embedded.
3670 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3671 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3672 // Add flags implied by -fembed-bitcode.
3673 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3674 // Disable all llvm IR level optimizations.
3675 CmdArgs.push_back("-disable-llvm-passes");
3677 // Render target options such as -fuse-init-array on modern ELF platforms.
3678 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3680 // reject options that shouldn't be supported in bitcode
3681 // also reject kernel/kext
3682 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3683 options::OPT_mkernel,
3684 options::OPT_fapple_kext,
3685 options::OPT_ffunction_sections,
3686 options::OPT_fno_function_sections,
3687 options::OPT_fdata_sections,
3688 options::OPT_fno_data_sections,
3689 options::OPT_funique_section_names,
3690 options::OPT_fno_unique_section_names,
3691 options::OPT_mrestrict_it,
3692 options::OPT_mno_restrict_it,
3693 options::OPT_mstackrealign,
3694 options::OPT_mno_stackrealign,
3695 options::OPT_mstack_alignment,
3696 options::OPT_mcmodel_EQ,
3697 options::OPT_mlong_calls,
3698 options::OPT_mno_long_calls,
3699 options::OPT_ggnu_pubnames,
3700 options::OPT_gdwarf_aranges,
3701 options::OPT_fdebug_types_section,
3702 options::OPT_fno_debug_types_section,
3703 options::OPT_fdwarf_directory_asm,
3704 options::OPT_fno_dwarf_directory_asm,
3705 options::OPT_mrelax_all,
3706 options::OPT_mno_relax_all,
3707 options::OPT_ftrap_function_EQ,
3708 options::OPT_ffixed_r9,
3709 options::OPT_mfix_cortex_a53_835769,
3710 options::OPT_mno_fix_cortex_a53_835769,
3711 options::OPT_ffixed_x18,
3712 options::OPT_mglobal_merge,
3713 options::OPT_mno_global_merge,
3714 options::OPT_mred_zone,
3715 options::OPT_mno_red_zone,
3716 options::OPT_Wa_COMMA,
3717 options::OPT_Xassembler,
3720 for (const auto &A : Args)
3721 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
3722 std::end(kBitcodeOptionBlacklist))
3723 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3725 // Render the CodeGen options that need to be passed.
3726 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3727 options::OPT_fno_optimize_sibling_calls))
3728 CmdArgs.push_back("-mdisable-tail-calls");
3730 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3733 // Render ABI arguments
3734 switch (TC.getArch()) {
3736 case llvm::Triple::arm:
3737 case llvm::Triple::armeb:
3738 case llvm::Triple::thumbeb:
3739 RenderARMABI(Triple, Args, CmdArgs);
3741 case llvm::Triple::aarch64:
3742 case llvm::Triple::aarch64_be:
3743 RenderAArch64ABI(Triple, Args, CmdArgs);
3747 // Optimization level for CodeGen.
3748 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3749 if (A->getOption().matches(options::OPT_O4)) {
3750 CmdArgs.push_back("-O3");
3751 D.Diag(diag::warn_O4_is_O3);
3753 A->render(Args, CmdArgs);
3757 // Input/Output file.
3758 if (Output.getType() == types::TY_Dependencies) {
3759 // Handled with other dependency code.
3760 } else if (Output.isFilename()) {
3761 CmdArgs.push_back("-o");
3762 CmdArgs.push_back(Output.getFilename());
3764 assert(Output.isNothing() && "Input output.");
3767 for (const auto &II : Inputs) {
3768 addDashXForInput(Args, II, CmdArgs);
3769 if (II.isFilename())
3770 CmdArgs.push_back(II.getFilename());
3772 II.getInputArg().renderAsInput(Args, CmdArgs);
3775 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3780 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3781 CmdArgs.push_back("-fembed-bitcode=marker");
3783 // We normally speed up the clang process a bit by skipping destructors at
3784 // exit, but when we're generating diagnostics we can rely on some of the
3786 if (!C.isForDiagnostics())
3787 CmdArgs.push_back("-disable-free");
3790 const bool IsAssertBuild = false;
3792 const bool IsAssertBuild = true;
3795 // Disable the verification pass in -asserts builds.
3797 CmdArgs.push_back("-disable-llvm-verifier");
3799 // Discard value names in assert builds unless otherwise specified.
3800 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3801 options::OPT_fno_discard_value_names, !IsAssertBuild))
3802 CmdArgs.push_back("-discard-value-names");
3804 // Set the main file name, so that debug info works even with
3806 CmdArgs.push_back("-main-file-name");
3807 CmdArgs.push_back(getBaseInputName(Args, Input));
3809 // Some flags which affect the language (via preprocessor
3811 if (Args.hasArg(options::OPT_static))
3812 CmdArgs.push_back("-static-define");
3814 if (Args.hasArg(options::OPT_municode))
3815 CmdArgs.push_back("-DUNICODE");
3817 if (isa<AnalyzeJobAction>(JA))
3818 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
3820 // Enable compatilibily mode to avoid analyzer-config related errors.
3821 // Since we can't access frontend flags through hasArg, let's manually iterate
3823 bool FoundAnalyzerConfig = false;
3824 for (auto Arg : Args.filtered(options::OPT_Xclang))
3825 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3826 FoundAnalyzerConfig = true;
3829 if (!FoundAnalyzerConfig)
3830 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3831 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3832 FoundAnalyzerConfig = true;
3835 if (FoundAnalyzerConfig)
3836 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
3838 CheckCodeGenerationOptions(D, Args);
3840 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
3841 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3842 if (FunctionAlignment) {
3843 CmdArgs.push_back("-function-alignment");
3844 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3847 llvm::Reloc::Model RelocationModel;
3850 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
3852 const char *RMName = RelocationModelName(RelocationModel);
3854 if ((RelocationModel == llvm::Reloc::ROPI ||
3855 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3856 types::isCXX(Input.getType()) &&
3857 !Args.hasArg(options::OPT_fallow_unsupported))
3858 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3861 CmdArgs.push_back("-mrelocation-model");
3862 CmdArgs.push_back(RMName);
3865 CmdArgs.push_back("-pic-level");
3866 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3868 CmdArgs.push_back("-pic-is-pie");
3871 if (RelocationModel == llvm::Reloc::ROPI ||
3872 RelocationModel == llvm::Reloc::ROPI_RWPI)
3873 CmdArgs.push_back("-fropi");
3874 if (RelocationModel == llvm::Reloc::RWPI ||
3875 RelocationModel == llvm::Reloc::ROPI_RWPI)
3876 CmdArgs.push_back("-frwpi");
3878 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3879 CmdArgs.push_back("-meabi");
3880 CmdArgs.push_back(A->getValue());
3883 CmdArgs.push_back("-mthread-model");
3884 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3885 if (!TC.isThreadModelSupported(A->getValue()))
3886 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3887 << A->getValue() << A->getAsString(Args);
3888 CmdArgs.push_back(A->getValue());
3891 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
3893 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3895 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3896 options::OPT_fno_merge_all_constants, false))
3897 CmdArgs.push_back("-fmerge-all-constants");
3899 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3900 options::OPT_fdelete_null_pointer_checks, false))
3901 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3903 // LLVM Code Generator Options.
3905 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3906 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3907 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3908 options::OPT_frewrite_map_file_EQ)) {
3909 StringRef Map = A->getValue();
3910 if (!llvm::sys::fs::exists(Map)) {
3911 D.Diag(diag::err_drv_no_such_file) << Map;
3913 CmdArgs.push_back("-frewrite-map-file");
3914 CmdArgs.push_back(A->getValue());
3920 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3921 StringRef v = A->getValue();
3922 CmdArgs.push_back("-mllvm");
3923 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3927 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3929 CmdArgs.push_back("-fno-jump-tables");
3931 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3932 options::OPT_fno_profile_sample_accurate, false))
3933 CmdArgs.push_back("-fprofile-sample-accurate");
3935 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3936 options::OPT_fno_preserve_as_comments, true))
3937 CmdArgs.push_back("-fno-preserve-as-comments");
3939 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3940 CmdArgs.push_back("-mregparm");
3941 CmdArgs.push_back(A->getValue());
3944 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3945 options::OPT_freg_struct_return)) {
3946 if (TC.getArch() != llvm::Triple::x86) {
3947 D.Diag(diag::err_drv_unsupported_opt_for_target)
3948 << A->getSpelling() << RawTriple.str();
3949 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3950 CmdArgs.push_back("-fpcc-struct-return");
3952 assert(A->getOption().matches(options::OPT_freg_struct_return));
3953 CmdArgs.push_back("-freg-struct-return");
3957 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3958 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3960 if (shouldUseFramePointer(Args, RawTriple))
3961 CmdArgs.push_back("-mdisable-fp-elim");
3962 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3963 options::OPT_fno_zero_initialized_in_bss))
3964 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3966 bool OFastEnabled = isOptimizationLevelFast(Args);
3967 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3968 // enabled. This alias option is being used to simplify the hasFlag logic.
3969 OptSpecifier StrictAliasingAliasOption =
3970 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3971 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3972 // doesn't do any TBAA.
3973 bool TBAAOnByDefault = !D.IsCLMode();
3974 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3975 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3976 CmdArgs.push_back("-relaxed-aliasing");
3977 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3978 options::OPT_fno_struct_path_tbaa))
3979 CmdArgs.push_back("-no-struct-path-tbaa");
3980 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3982 CmdArgs.push_back("-fstrict-enums");
3983 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3985 CmdArgs.push_back("-fno-strict-return");
3986 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3987 options::OPT_fno_allow_editor_placeholders, false))
3988 CmdArgs.push_back("-fallow-editor-placeholders");
3989 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3990 options::OPT_fno_strict_vtable_pointers,
3992 CmdArgs.push_back("-fstrict-vtable-pointers");
3993 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3994 options::OPT_fno_force_emit_vtables,
3996 CmdArgs.push_back("-fforce-emit-vtables");
3997 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3998 options::OPT_fno_optimize_sibling_calls))
3999 CmdArgs.push_back("-mdisable-tail-calls");
4000 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
4001 options::OPT_fescaping_block_tail_calls, false))
4002 CmdArgs.push_back("-fno-escaping-block-tail-calls");
4004 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4005 options::OPT_fno_fine_grained_bitfield_accesses);
4007 // Handle segmented stacks.
4008 if (Args.hasArg(options::OPT_fsplit_stack))
4009 CmdArgs.push_back("-split-stacks");
4011 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
4013 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_64,
4014 options::OPT_mlong_double_128)) {
4015 if (TC.getArch() == llvm::Triple::x86 ||
4016 TC.getArch() == llvm::Triple::x86_64 ||
4017 TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64())
4018 A->render(Args, CmdArgs);
4020 D.Diag(diag::err_drv_unsupported_opt_for_target)
4021 << A->getAsString(Args) << TripleStr;
4024 // Decide whether to use verbose asm. Verbose assembly is the default on
4025 // toolchains which have the integrated assembler on by default.
4026 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
4027 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4028 IsIntegratedAssemblerDefault) ||
4029 Args.hasArg(options::OPT_dA))
4030 CmdArgs.push_back("-masm-verbose");
4032 if (!TC.useIntegratedAs())
4033 CmdArgs.push_back("-no-integrated-as");
4035 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4036 CmdArgs.push_back("-mdebug-pass");
4037 CmdArgs.push_back("Structure");
4039 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4040 CmdArgs.push_back("-mdebug-pass");
4041 CmdArgs.push_back("Arguments");
4044 // Enable -mconstructor-aliases except on darwin, where we have to work around
4045 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4046 // aliases aren't supported.
4047 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
4048 CmdArgs.push_back("-mconstructor-aliases");
4050 // Darwin's kernel doesn't support guard variables; just die if we
4052 if (KernelOrKext && RawTriple.isOSDarwin())
4053 CmdArgs.push_back("-fforbid-guard-variables");
4055 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4057 CmdArgs.push_back("-mms-bitfields");
4060 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4061 options::OPT_mno_pie_copy_relocations,
4063 CmdArgs.push_back("-mpie-copy-relocations");
4066 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4067 CmdArgs.push_back("-fno-plt");
4070 // -fhosted is default.
4071 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4072 // use Freestanding.
4074 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4077 CmdArgs.push_back("-ffreestanding");
4079 // This is a coarse approximation of what llvm-gcc actually does, both
4080 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4081 // complicated ways.
4082 bool AsynchronousUnwindTables =
4083 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4084 options::OPT_fno_asynchronous_unwind_tables,
4085 (TC.IsUnwindTablesDefault(Args) ||
4086 TC.getSanitizerArgs().needsUnwindTables()) &&
4088 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4089 AsynchronousUnwindTables))
4090 CmdArgs.push_back("-munwind-tables");
4092 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4094 // FIXME: Handle -mtune=.
4095 (void)Args.hasArg(options::OPT_mtune_EQ);
4097 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4098 CmdArgs.push_back("-mcode-model");
4099 CmdArgs.push_back(A->getValue());
4102 // Add the target cpu
4103 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4105 CmdArgs.push_back("-target-cpu");
4106 CmdArgs.push_back(Args.MakeArgString(CPU));
4109 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
4111 // These two are potentially updated by AddClangCLArgs.
4112 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4113 bool EmitCodeView = false;
4115 // Add clang-cl arguments.
4116 types::ID InputType = Input.getType();
4118 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4120 DwarfFissionKind DwarfFission;
4121 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
4122 CmdArgs, DebugInfoKind, DwarfFission);
4124 // Add the split debug info name to the command lines here so we
4125 // can propagate it to the backend.
4126 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
4127 TC.getTriple().isOSBinFormatELF() &&
4128 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4129 isa<BackendJobAction>(JA));
4131 const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
4132 CmdArgs.push_back("-split-dwarf-file");
4133 CmdArgs.push_back(SplitDWARFOut);
4134 if (DwarfFission == DwarfFissionKind::Split) {
4135 CmdArgs.push_back("-split-dwarf-output");
4136 CmdArgs.push_back(SplitDWARFOut);
4140 // Pass the linker version in use.
4141 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4142 CmdArgs.push_back("-target-linker-version");
4143 CmdArgs.push_back(A->getValue());
4146 if (!shouldUseLeafFramePointer(Args, RawTriple))
4147 CmdArgs.push_back("-momit-leaf-frame-pointer");
4149 // Explicitly error on some things we know we don't support and can't just
4151 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4153 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
4154 TC.getArch() == llvm::Triple::x86) {
4155 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4156 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4157 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4158 << Unsupported->getOption().getName();
4160 // The faltivec option has been superseded by the maltivec option.
4161 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4162 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4163 << Unsupported->getOption().getName()
4164 << "please use -maltivec and include altivec.h explicitly";
4165 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4166 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4167 << Unsupported->getOption().getName() << "please use -mno-altivec";
4170 Args.AddAllArgs(CmdArgs, options::OPT_v);
4171 Args.AddLastArg(CmdArgs, options::OPT_H);
4172 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4173 CmdArgs.push_back("-header-include-file");
4174 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4177 Args.AddLastArg(CmdArgs, options::OPT_P);
4178 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4180 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4181 CmdArgs.push_back("-diagnostic-log-file");
4182 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4186 bool UseSeparateSections = isUseSeparateSections(Triple);
4188 if (Args.hasFlag(options::OPT_ffunction_sections,
4189 options::OPT_fno_function_sections, UseSeparateSections)) {
4190 CmdArgs.push_back("-ffunction-sections");
4193 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4194 UseSeparateSections)) {
4195 CmdArgs.push_back("-fdata-sections");
4198 if (!Args.hasFlag(options::OPT_funique_section_names,
4199 options::OPT_fno_unique_section_names, true))
4200 CmdArgs.push_back("-fno-unique-section-names");
4202 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
4203 options::OPT_finstrument_functions_after_inlining,
4204 options::OPT_finstrument_function_entry_bare);
4206 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4207 // sampling, overhead of call arc collection is way too high and there's no
4208 // way to collect the output.
4209 if (!Triple.isNVPTX())
4210 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
4212 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
4214 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
4215 if (RawTriple.isPS4CPU() &&
4216 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
4217 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4218 PS4cpu::addSanitizerArgs(TC, CmdArgs);
4221 // Pass options for controlling the default header search paths.
4222 if (Args.hasArg(options::OPT_nostdinc)) {
4223 CmdArgs.push_back("-nostdsysteminc");
4224 CmdArgs.push_back("-nobuiltininc");
4226 if (Args.hasArg(options::OPT_nostdlibinc))
4227 CmdArgs.push_back("-nostdsysteminc");
4228 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4229 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4232 // Pass the path to compiler resource files.
4233 CmdArgs.push_back("-resource-dir");
4234 CmdArgs.push_back(D.ResourceDir.c_str());
4236 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4238 RenderARCMigrateToolOptions(D, Args, CmdArgs);
4240 // Add preprocessing options like -I, -D, etc. if we are using the
4243 // FIXME: Support -fpreprocessed
4244 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4245 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4247 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4248 // that "The compiler can only warn and ignore the option if not recognized".
4249 // When building with ccache, it will pass -D options to clang even on
4250 // preprocessed inputs and configure concludes that -fPIC is not supported.
4251 Args.ClaimAllArgs(options::OPT_D);
4253 // Manually translate -O4 to -O3; let clang reject others.
4254 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4255 if (A->getOption().matches(options::OPT_O4)) {
4256 CmdArgs.push_back("-O3");
4257 D.Diag(diag::warn_O4_is_O3);
4259 A->render(Args, CmdArgs);
4263 // Warn about ignored options to clang.
4265 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4266 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4271 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4272 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4276 claimNoWarnArgs(Args);
4278 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4280 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4281 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4282 CmdArgs.push_back("-pedantic");
4283 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4284 Args.AddLastArg(CmdArgs, options::OPT_w);
4286 // Fixed point flags
4287 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4289 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4291 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4292 // (-ansi is equivalent to -std=c89 or -std=c++98).
4294 // If a std is supplied, only add -trigraphs if it follows the
4296 bool ImplyVCPPCXXVer = false;
4297 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
4299 if (Std->getOption().matches(options::OPT_ansi))
4300 if (types::isCXX(InputType))
4301 CmdArgs.push_back("-std=c++98");
4303 CmdArgs.push_back("-std=c89");
4305 Std->render(Args, CmdArgs);
4307 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4308 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4309 options::OPT_ftrigraphs,
4310 options::OPT_fno_trigraphs))
4312 A->render(Args, CmdArgs);
4314 // Honor -std-default.
4316 // FIXME: Clang doesn't correctly handle -std= when the input language
4317 // doesn't match. For the time being just ignore this for C++ inputs;
4318 // eventually we want to do all the standard defaulting here instead of
4319 // splitting it between the driver and clang -cc1.
4320 if (!types::isCXX(InputType))
4321 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4323 else if (IsWindowsMSVC)
4324 ImplyVCPPCXXVer = true;
4326 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4327 options::OPT_fno_trigraphs);
4330 // GCC's behavior for -Wwrite-strings is a bit strange:
4331 // * In C, this "warning flag" changes the types of string literals from
4332 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4333 // for the discarded qualifier.
4334 // * In C++, this is just a normal warning flag.
4336 // Implementing this warning correctly in C is hard, so we follow GCC's
4337 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4338 // a non-const char* in C, rather than using this crude hack.
4339 if (!types::isCXX(InputType)) {
4340 // FIXME: This should behave just like a warning flag, and thus should also
4341 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4343 Args.getLastArg(options::OPT_Wwrite_strings,
4344 options::OPT_Wno_write_strings, options::OPT_w);
4346 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4347 CmdArgs.push_back("-fconst-strings");
4350 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4351 // during C++ compilation, which it is by default. GCC keeps this define even
4352 // in the presence of '-w', match this behavior bug-for-bug.
4353 if (types::isCXX(InputType) &&
4354 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4356 CmdArgs.push_back("-fdeprecated-macro");
4359 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4360 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4361 if (Asm->getOption().matches(options::OPT_fasm))
4362 CmdArgs.push_back("-fgnu-keywords");
4364 CmdArgs.push_back("-fno-gnu-keywords");
4367 if (ShouldDisableDwarfDirectory(Args, TC))
4368 CmdArgs.push_back("-fno-dwarf-directory-asm");
4370 if (ShouldDisableAutolink(Args, TC))
4371 CmdArgs.push_back("-fno-autolink");
4373 // Add in -fdebug-compilation-dir if necessary.
4374 addDebugCompDirArg(Args, CmdArgs);
4376 addDebugPrefixMapArg(D, Args, CmdArgs);
4378 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4379 options::OPT_ftemplate_depth_EQ)) {
4380 CmdArgs.push_back("-ftemplate-depth");
4381 CmdArgs.push_back(A->getValue());
4384 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4385 CmdArgs.push_back("-foperator-arrow-depth");
4386 CmdArgs.push_back(A->getValue());
4389 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4390 CmdArgs.push_back("-fconstexpr-depth");
4391 CmdArgs.push_back(A->getValue());
4394 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4395 CmdArgs.push_back("-fconstexpr-steps");
4396 CmdArgs.push_back(A->getValue());
4399 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4400 CmdArgs.push_back("-fbracket-depth");
4401 CmdArgs.push_back(A->getValue());
4404 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4405 options::OPT_Wlarge_by_value_copy_def)) {
4406 if (A->getNumValues()) {
4407 StringRef bytes = A->getValue();
4408 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4410 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4413 if (Args.hasArg(options::OPT_relocatable_pch))
4414 CmdArgs.push_back("-relocatable-pch");
4416 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4417 static const char *kCFABIs[] = {
4418 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4421 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4422 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4424 A->render(Args, CmdArgs);
4427 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4428 CmdArgs.push_back("-fconstant-string-class");
4429 CmdArgs.push_back(A->getValue());
4432 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4433 CmdArgs.push_back("-ftabstop");
4434 CmdArgs.push_back(A->getValue());
4437 if (Args.hasFlag(options::OPT_fstack_size_section,
4438 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4439 CmdArgs.push_back("-fstack-size-section");
4441 CmdArgs.push_back("-ferror-limit");
4442 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4443 CmdArgs.push_back(A->getValue());
4445 CmdArgs.push_back("19");
4447 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4448 CmdArgs.push_back("-fmacro-backtrace-limit");
4449 CmdArgs.push_back(A->getValue());
4452 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4453 CmdArgs.push_back("-ftemplate-backtrace-limit");
4454 CmdArgs.push_back(A->getValue());
4457 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4458 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4459 CmdArgs.push_back(A->getValue());
4462 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4463 CmdArgs.push_back("-fspell-checking-limit");
4464 CmdArgs.push_back(A->getValue());
4467 // Pass -fmessage-length=.
4468 CmdArgs.push_back("-fmessage-length");
4469 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4470 CmdArgs.push_back(A->getValue());
4472 // If -fmessage-length=N was not specified, determine whether this is a
4473 // terminal and, if so, implicitly define -fmessage-length appropriately.
4474 unsigned N = llvm::sys::Process::StandardErrColumns();
4475 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4478 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4479 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4480 options::OPT_fvisibility_ms_compat)) {
4481 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4482 CmdArgs.push_back("-fvisibility");
4483 CmdArgs.push_back(A->getValue());
4485 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4486 CmdArgs.push_back("-fvisibility");
4487 CmdArgs.push_back("hidden");
4488 CmdArgs.push_back("-ftype-visibility");
4489 CmdArgs.push_back("default");
4493 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4494 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
4496 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4498 // Forward -f (flag) options which we can pass directly.
4499 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4500 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4501 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
4502 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4503 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4504 options::OPT_fno_emulated_tls);
4505 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
4507 // AltiVec-like language extensions aren't relevant for assembling.
4508 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
4509 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4511 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4512 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4514 // Forward flags for OpenMP. We don't do this if the current action is an
4515 // device offloading action other than OpenMP.
4516 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4517 options::OPT_fno_openmp, false) &&
4518 (JA.isDeviceOffloading(Action::OFK_None) ||
4519 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
4520 switch (D.getOpenMPRuntime(Args)) {
4521 case Driver::OMPRT_OMP:
4522 case Driver::OMPRT_IOMP5:
4523 // Clang can generate useful OpenMP code for these two runtime libraries.
4524 CmdArgs.push_back("-fopenmp");
4526 // If no option regarding the use of TLS in OpenMP codegeneration is
4527 // given, decide a default based on the target. Otherwise rely on the
4528 // options and pass the right information to the frontend.
4529 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4530 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4531 CmdArgs.push_back("-fnoopenmp-use-tls");
4532 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4533 options::OPT_fno_openmp_simd);
4534 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4535 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4536 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
4537 Args.AddAllArgs(CmdArgs,
4538 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
4539 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4540 options::OPT_fno_openmp_optimistic_collapse,
4542 CmdArgs.push_back("-fopenmp-optimistic-collapse");
4544 // When in OpenMP offloading mode with NVPTX target, forward
4546 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4547 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4548 CmdArgs.push_back("-fopenmp-cuda-mode");
4550 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4552 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4553 options::OPT_fno_openmp_cuda_force_full_runtime,
4555 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
4558 // By default, if Clang doesn't know how to generate useful OpenMP code
4559 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4560 // down to the actual compilation.
4561 // FIXME: It would be better to have a mode which *only* omits IR
4562 // generation based on the OpenMP support so that we get consistent
4563 // semantic analysis, etc.
4567 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4568 options::OPT_fno_openmp_simd);
4569 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4572 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4573 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
4575 const XRayArgs &XRay = TC.getXRayArgs();
4576 XRay.addArgs(TC, Args, CmdArgs, InputType);
4578 if (TC.SupportsProfiling())
4579 Args.AddLastArg(CmdArgs, options::OPT_pg);
4581 if (TC.SupportsProfiling())
4582 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4584 // -flax-vector-conversions is default.
4585 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4586 options::OPT_fno_lax_vector_conversions))
4587 CmdArgs.push_back("-fno-lax-vector-conversions");
4589 if (Args.getLastArg(options::OPT_fapple_kext) ||
4590 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4591 CmdArgs.push_back("-fapple-kext");
4593 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4594 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4595 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4596 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4597 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
4598 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4599 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
4601 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4602 CmdArgs.push_back("-ftrapv-handler");
4603 CmdArgs.push_back(A->getValue());
4606 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4608 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4609 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4610 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4611 if (A->getOption().matches(options::OPT_fwrapv))
4612 CmdArgs.push_back("-fwrapv");
4613 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4614 options::OPT_fno_strict_overflow)) {
4615 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4616 CmdArgs.push_back("-fwrapv");
4619 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4620 options::OPT_fno_reroll_loops))
4621 if (A->getOption().matches(options::OPT_freroll_loops))
4622 CmdArgs.push_back("-freroll-loops");
4624 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4625 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4626 options::OPT_fno_unroll_loops);
4628 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4630 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4632 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
4634 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
4635 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
4637 // Translate -mstackrealign
4638 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4640 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4642 if (Args.hasArg(options::OPT_mstack_alignment)) {
4643 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4644 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4647 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4648 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4651 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4653 CmdArgs.push_back("-mstack-probe-size=0");
4656 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4657 options::OPT_mno_stack_arg_probe, true))
4658 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4660 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4661 options::OPT_mno_restrict_it)) {
4662 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4663 CmdArgs.push_back("-mllvm");
4664 CmdArgs.push_back("-arm-restrict-it");
4666 CmdArgs.push_back("-mllvm");
4667 CmdArgs.push_back("-arm-no-restrict-it");
4669 } else if (Triple.isOSWindows() &&
4670 (Triple.getArch() == llvm::Triple::arm ||
4671 Triple.getArch() == llvm::Triple::thumb)) {
4672 // Windows on ARM expects restricted IT blocks
4673 CmdArgs.push_back("-mllvm");
4674 CmdArgs.push_back("-arm-restrict-it");
4677 // Forward -cl options to -cc1
4678 RenderOpenCLOptions(Args, CmdArgs);
4680 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4682 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4685 // Forward -f options with positive and negative forms; we translate
4687 if (Arg *A = getLastProfileSampleUseArg(Args)) {
4688 auto *PGOArg = Args.getLastArg(
4689 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4690 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4691 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4693 D.Diag(diag::err_drv_argument_not_allowed_with)
4694 << "SampleUse with PGO options";
4696 StringRef fname = A->getValue();
4697 if (!llvm::sys::fs::exists(fname))
4698 D.Diag(diag::err_drv_no_such_file) << fname;
4700 A->render(Args, CmdArgs);
4702 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
4704 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
4706 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4707 options::OPT_fno_assume_sane_operator_new))
4708 CmdArgs.push_back("-fno-assume-sane-operator-new");
4710 // -fblocks=0 is default.
4711 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4712 TC.IsBlocksDefault()) ||
4713 (Args.hasArg(options::OPT_fgnu_runtime) &&
4714 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4715 !Args.hasArg(options::OPT_fno_blocks))) {
4716 CmdArgs.push_back("-fblocks");
4718 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
4719 CmdArgs.push_back("-fblocks-runtime-optional");
4722 // -fencode-extended-block-signature=1 is default.
4723 if (TC.IsEncodeExtendedBlockSignatureDefault())
4724 CmdArgs.push_back("-fencode-extended-block-signature");
4726 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4728 types::isCXX(InputType)) {
4729 CmdArgs.push_back("-fcoroutines-ts");
4732 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4733 options::OPT_fno_double_square_bracket_attributes);
4735 // -faccess-control is default.
4736 if (Args.hasFlag(options::OPT_fno_access_control,
4737 options::OPT_faccess_control, false))
4738 CmdArgs.push_back("-fno-access-control");
4740 // -felide-constructors is the default.
4741 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4742 options::OPT_felide_constructors, false))
4743 CmdArgs.push_back("-fno-elide-constructors");
4745 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
4747 if (KernelOrKext || (types::isCXX(InputType) &&
4748 (RTTIMode == ToolChain::RM_Disabled)))
4749 CmdArgs.push_back("-fno-rtti");
4751 // -fshort-enums=0 is default for all architectures except Hexagon.
4752 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4753 TC.getArch() == llvm::Triple::hexagon))
4754 CmdArgs.push_back("-fshort-enums");
4756 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
4758 // -fuse-cxa-atexit is default.
4760 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4761 !RawTriple.isOSWindows() &&
4762 TC.getArch() != llvm::Triple::xcore &&
4763 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4764 RawTriple.hasEnvironment())) ||
4766 CmdArgs.push_back("-fno-use-cxa-atexit");
4768 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4769 options::OPT_fno_register_global_dtors_with_atexit,
4770 RawTriple.isOSDarwin() && !KernelOrKext))
4771 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4773 // -fms-extensions=0 is default.
4774 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4776 CmdArgs.push_back("-fms-extensions");
4778 // -fno-use-line-directives is default.
4779 if (Args.hasFlag(options::OPT_fuse_line_directives,
4780 options::OPT_fno_use_line_directives, false))
4781 CmdArgs.push_back("-fuse-line-directives");
4783 // -fms-compatibility=0 is default.
4784 if (Args.hasFlag(options::OPT_fms_compatibility,
4785 options::OPT_fno_ms_compatibility,
4787 Args.hasFlag(options::OPT_fms_extensions,
4788 options::OPT_fno_ms_extensions, true))))
4789 CmdArgs.push_back("-fms-compatibility");
4791 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
4794 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4796 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4797 if (ImplyVCPPCXXVer) {
4798 StringRef LanguageStandard;
4799 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4801 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4802 .Case("c++14", "-std=c++14")
4803 .Case("c++17", "-std=c++17")
4804 .Case("c++latest", "-std=c++2a")
4806 if (LanguageStandard.empty())
4807 D.Diag(clang::diag::warn_drv_unused_argument)
4808 << StdArg->getAsString(Args);
4811 if (LanguageStandard.empty()) {
4812 if (IsMSVC2015Compatible)
4813 LanguageStandard = "-std=c++14";
4815 LanguageStandard = "-std=c++11";
4818 CmdArgs.push_back(LanguageStandard.data());
4821 // -fno-borland-extensions is default.
4822 if (Args.hasFlag(options::OPT_fborland_extensions,
4823 options::OPT_fno_borland_extensions, false))
4824 CmdArgs.push_back("-fborland-extensions");
4826 // -fno-declspec is default, except for PS4.
4827 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4829 CmdArgs.push_back("-fdeclspec");
4830 else if (Args.hasArg(options::OPT_fno_declspec))
4831 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4833 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4835 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4836 options::OPT_fno_threadsafe_statics,
4837 !IsWindowsMSVC || IsMSVC2015Compatible))
4838 CmdArgs.push_back("-fno-threadsafe-statics");
4840 // -fno-delayed-template-parsing is default, except when targeting MSVC.
4841 // Many old Windows SDK versions require this to parse.
4842 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4843 // compiler. We should be able to disable this by default at some point.
4844 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4845 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4846 CmdArgs.push_back("-fdelayed-template-parsing");
4848 // -fgnu-keywords default varies depending on language; only pass if
4850 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
4851 options::OPT_fno_gnu_keywords);
4853 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4855 CmdArgs.push_back("-fgnu89-inline");
4857 if (Args.hasArg(options::OPT_fno_inline))
4858 CmdArgs.push_back("-fno-inline");
4860 Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
4861 options::OPT_finline_hint_functions,
4862 options::OPT_fno_inline_functions);
4864 // FIXME: Find a better way to determine whether the language has modules
4865 // support by default, or just assume that all languages do.
4867 Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
4868 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4870 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4871 options::OPT_fno_experimental_new_pass_manager);
4873 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4874 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4877 if (Args.hasFlag(options::OPT_fapplication_extension,
4878 options::OPT_fno_application_extension, false))
4879 CmdArgs.push_back("-fapplication-extension");
4881 // Handle GCC-style exception args.
4882 if (!C.getDriver().IsCLMode())
4883 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
4885 // Handle exception personalities
4886 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4887 options::OPT_fseh_exceptions,
4888 options::OPT_fdwarf_exceptions);
4890 const Option &Opt = A->getOption();
4891 if (Opt.matches(options::OPT_fsjlj_exceptions))
4892 CmdArgs.push_back("-fsjlj-exceptions");
4893 if (Opt.matches(options::OPT_fseh_exceptions))
4894 CmdArgs.push_back("-fseh-exceptions");
4895 if (Opt.matches(options::OPT_fdwarf_exceptions))
4896 CmdArgs.push_back("-fdwarf-exceptions");
4898 switch (TC.GetExceptionModel(Args)) {
4901 case llvm::ExceptionHandling::DwarfCFI:
4902 CmdArgs.push_back("-fdwarf-exceptions");
4904 case llvm::ExceptionHandling::SjLj:
4905 CmdArgs.push_back("-fsjlj-exceptions");
4907 case llvm::ExceptionHandling::WinEH:
4908 CmdArgs.push_back("-fseh-exceptions");
4913 // C++ "sane" operator new.
4914 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4915 options::OPT_fno_assume_sane_operator_new))
4916 CmdArgs.push_back("-fno-assume-sane-operator-new");
4918 // -frelaxed-template-template-args is off by default, as it is a severe
4919 // breaking change until a corresponding change to template partial ordering
4921 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4922 options::OPT_fno_relaxed_template_template_args, false))
4923 CmdArgs.push_back("-frelaxed-template-template-args");
4925 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4927 if (Args.hasFlag(options::OPT_fsized_deallocation,
4928 options::OPT_fno_sized_deallocation, false))
4929 CmdArgs.push_back("-fsized-deallocation");
4931 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4933 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4934 options::OPT_fno_aligned_allocation,
4935 options::OPT_faligned_new_EQ)) {
4936 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4937 CmdArgs.push_back("-fno-aligned-allocation");
4939 CmdArgs.push_back("-faligned-allocation");
4942 // The default new alignment can be specified using a dedicated option or via
4943 // a GCC-compatible option that also turns on aligned allocation.
4944 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4945 options::OPT_faligned_new_EQ))
4947 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4949 // -fconstant-cfstrings is default, and may be subject to argument translation
4951 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4952 options::OPT_fno_constant_cfstrings) ||
4953 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4954 options::OPT_mno_constant_cfstrings))
4955 CmdArgs.push_back("-fno-constant-cfstrings");
4957 // -fno-pascal-strings is default, only pass non-default.
4958 if (Args.hasFlag(options::OPT_fpascal_strings,
4959 options::OPT_fno_pascal_strings, false))
4960 CmdArgs.push_back("-fpascal-strings");
4962 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4963 // -fno-pack-struct doesn't apply to -fpack-struct=.
4964 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4965 std::string PackStructStr = "-fpack-struct=";
4966 PackStructStr += A->getValue();
4967 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4968 } else if (Args.hasFlag(options::OPT_fpack_struct,
4969 options::OPT_fno_pack_struct, false)) {
4970 CmdArgs.push_back("-fpack-struct=1");
4973 // Handle -fmax-type-align=N and -fno-type-align
4974 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4975 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4976 if (!SkipMaxTypeAlign) {
4977 std::string MaxTypeAlignStr = "-fmax-type-align=";
4978 MaxTypeAlignStr += A->getValue();
4979 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4981 } else if (RawTriple.isOSDarwin()) {
4982 if (!SkipMaxTypeAlign) {
4983 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4984 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4988 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4989 CmdArgs.push_back("-Qn");
4991 // -fcommon is the default unless compiling kernel code or the target says so
4992 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
4993 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4995 CmdArgs.push_back("-fno-common");
4997 // -fsigned-bitfields is default, and clang doesn't yet support
4998 // -funsigned-bitfields.
4999 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5000 options::OPT_funsigned_bitfields))
5001 D.Diag(diag::warn_drv_clang_unsupported)
5002 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5004 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5005 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5006 D.Diag(diag::err_drv_clang_unsupported)
5007 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5009 // -finput_charset=UTF-8 is default. Reject others
5010 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5011 StringRef value = inputCharset->getValue();
5012 if (!value.equals_lower("utf-8"))
5013 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5017 // -fexec_charset=UTF-8 is default. Reject others
5018 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5019 StringRef value = execCharset->getValue();
5020 if (!value.equals_lower("utf-8"))
5021 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5025 RenderDiagnosticsOptions(D, Args, CmdArgs);
5027 // -fno-asm-blocks is default.
5028 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5030 CmdArgs.push_back("-fasm-blocks");
5032 // -fgnu-inline-asm is default.
5033 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5034 options::OPT_fno_gnu_inline_asm, true))
5035 CmdArgs.push_back("-fno-gnu-inline-asm");
5037 // Enable vectorization per default according to the optimization level
5038 // selected. For optimization levels that want vectorization we use the alias
5039 // option to simplify the hasFlag logic.
5040 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5041 OptSpecifier VectorizeAliasOption =
5042 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5043 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5044 options::OPT_fno_vectorize, EnableVec))
5045 CmdArgs.push_back("-vectorize-loops");
5047 // -fslp-vectorize is enabled based on the optimization level selected.
5048 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5049 OptSpecifier SLPVectAliasOption =
5050 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5051 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5052 options::OPT_fno_slp_vectorize, EnableSLPVec))
5053 CmdArgs.push_back("-vectorize-slp");
5055 ParseMPreferVectorWidth(D, Args, CmdArgs);
5057 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
5058 Args.AddLastArg(CmdArgs,
5059 options::OPT_fsanitize_undefined_strip_path_components_EQ);
5061 // -fdollars-in-identifiers default varies depending on platform and
5062 // language; only pass if specified.
5063 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5064 options::OPT_fno_dollars_in_identifiers)) {
5065 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5066 CmdArgs.push_back("-fdollars-in-identifiers");
5068 CmdArgs.push_back("-fno-dollars-in-identifiers");
5071 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5072 // practical purposes.
5073 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5074 options::OPT_fno_unit_at_a_time)) {
5075 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5076 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5079 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5080 options::OPT_fno_apple_pragma_pack, false))
5081 CmdArgs.push_back("-fapple-pragma-pack");
5083 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
5084 if (Args.hasFlag(options::OPT_fsave_optimization_record,
5085 options::OPT_foptimization_record_file_EQ,
5086 options::OPT_fno_save_optimization_record, false) ||
5087 Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5088 options::OPT_fno_save_optimization_record, false) ||
5089 Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5090 options::OPT_fno_save_optimization_record, false)) {
5091 CmdArgs.push_back("-opt-record-file");
5093 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5095 CmdArgs.push_back(A->getValue());
5099 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5100 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5101 F = FinalOutput->getValue();
5105 // Use the input filename.
5106 F = llvm::sys::path::stem(Input.getBaseInput());
5108 // If we're compiling for an offload architecture (i.e. a CUDA device),
5109 // we need to make the file name for the device compilation different
5110 // from the host compilation.
5111 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5112 !JA.isDeviceOffloading(Action::OFK_Host)) {
5113 llvm::sys::path::replace_extension(F, "");
5114 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5115 Triple.normalize());
5117 F += JA.getOffloadingArch();
5121 std::string Extension = "opt.";
5123 Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
5124 Extension += A->getValue();
5126 Extension += "yaml";
5128 llvm::sys::path::replace_extension(F, Extension);
5129 CmdArgs.push_back(Args.MakeArgString(F));
5133 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5134 CmdArgs.push_back("-opt-record-passes");
5135 CmdArgs.push_back(A->getValue());
5139 Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
5140 CmdArgs.push_back("-opt-record-format");
5141 CmdArgs.push_back(A->getValue());
5145 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5146 options::OPT_fno_rewrite_imports, false);
5148 CmdArgs.push_back("-frewrite-imports");
5150 // Enable rewrite includes if the user's asked for it or if we're generating
5152 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5153 // nice to enable this when doing a crashdump for modules as well.
5154 if (Args.hasFlag(options::OPT_frewrite_includes,
5155 options::OPT_fno_rewrite_includes, false) ||
5156 (C.isForDiagnostics() && !HaveModules))
5157 CmdArgs.push_back("-frewrite-includes");
5159 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5160 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5161 options::OPT_traditional_cpp)) {
5162 if (isa<PreprocessJobAction>(JA))
5163 CmdArgs.push_back("-traditional-cpp");
5165 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5168 Args.AddLastArg(CmdArgs, options::OPT_dM);
5169 Args.AddLastArg(CmdArgs, options::OPT_dD);
5171 // Handle serialized diagnostics.
5172 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5173 CmdArgs.push_back("-serialize-diagnostic-file");
5174 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5177 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5178 CmdArgs.push_back("-fretain-comments-from-system-headers");
5180 // Forward -fcomment-block-commands to -cc1.
5181 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5182 // Forward -fparse-all-comments to -cc1.
5183 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5185 // Turn -fplugin=name.so into -load name.so
5186 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5187 CmdArgs.push_back("-load");
5188 CmdArgs.push_back(A->getValue());
5192 // Forward -fpass-plugin=name.so to -cc1.
5193 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5195 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5199 // Setup statistics file output.
5200 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5201 if (!StatsFile.empty())
5202 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
5204 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5206 // -finclude-default-header flag is for preprocessor,
5207 // do not pass it to other cc1 commands when save-temps is enabled
5208 if (C.getDriver().isSaveTempsEnabled() &&
5209 !isa<PreprocessJobAction>(JA)) {
5210 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5212 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5213 CmdArgs.push_back(Arg->getValue());
5217 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5219 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5222 // We translate this by hand to the -cc1 argument, since nightly test uses
5223 // it and developers have been trained to spell it with -mllvm. Both
5224 // spellings are now deprecated and should be removed.
5225 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5226 CmdArgs.push_back("-disable-llvm-optzns");
5228 A->render(Args, CmdArgs);
5232 // With -save-temps, we want to save the unoptimized bitcode output from the
5233 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5235 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5236 // has slightly different breakdown between stages.
5237 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5238 // pristine IR generated by the frontend. Ideally, a new compile action should
5239 // be added so both IR can be captured.
5240 if (C.getDriver().isSaveTempsEnabled() &&
5241 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5242 isa<CompileJobAction>(JA))
5243 CmdArgs.push_back("-disable-llvm-passes");
5245 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5247 const char *Exec = D.getClangProgramPath();
5249 // Optionally embed the -cc1 level arguments into the debug info or a
5250 // section, for build analysis.
5251 // Also record command line arguments into the debug info if
5252 // -grecord-gcc-switches options is set on.
5253 // By default, -gno-record-gcc-switches is set on and no recording.
5254 auto GRecordSwitches =
5255 Args.hasFlag(options::OPT_grecord_command_line,
5256 options::OPT_gno_record_command_line, false);
5257 auto FRecordSwitches =
5258 Args.hasFlag(options::OPT_frecord_command_line,
5259 options::OPT_fno_record_command_line, false);
5260 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5261 D.Diag(diag::err_drv_unsupported_opt_for_target)
5262 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5264 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
5265 ArgStringList OriginalArgs;
5266 for (const auto &Arg : Args)
5267 Arg->render(Args, OriginalArgs);
5269 SmallString<256> Flags;
5271 for (const char *OriginalArg : OriginalArgs) {
5272 SmallString<128> EscapedArg;
5273 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5275 Flags += EscapedArg;
5277 auto FlagsArgString = Args.MakeArgString(Flags);
5278 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5279 CmdArgs.push_back("-dwarf-debug-flags");
5280 CmdArgs.push_back(FlagsArgString);
5282 if (FRecordSwitches) {
5283 CmdArgs.push_back("-record-command-line");
5284 CmdArgs.push_back(FlagsArgString);
5288 // Host-side cuda compilation receives all device-side outputs in a single
5289 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5290 if ((IsCuda || IsHIP) && CudaDeviceInput) {
5291 CmdArgs.push_back("-fcuda-include-gpubinary");
5292 CmdArgs.push_back(CudaDeviceInput->getFilename());
5293 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5294 CmdArgs.push_back("-fgpu-rdc");
5298 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5299 options::OPT_fno_cuda_short_ptr, false))
5300 CmdArgs.push_back("-fcuda-short-ptr");
5303 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5304 // to specify the result of the compile phase on the host, so the meaningful
5305 // device declarations can be identified. Also, -fopenmp-is-device is passed
5306 // along to tell the frontend that it is generating code for a device, so that
5307 // only the relevant declarations are emitted.
5308 if (IsOpenMPDevice) {
5309 CmdArgs.push_back("-fopenmp-is-device");
5310 if (OpenMPDeviceInput) {
5311 CmdArgs.push_back("-fopenmp-host-ir-file-path");
5312 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
5316 // For all the host OpenMP offloading compile jobs we need to pass the targets
5317 // information using -fopenmp-targets= option.
5318 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
5319 SmallString<128> TargetInfo("-fopenmp-targets=");
5321 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5322 assert(Tgts && Tgts->getNumValues() &&
5323 "OpenMP offloading has to have targets specified.");
5324 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5327 // We need to get the string from the triple because it may be not exactly
5328 // the same as the one we get directly from the arguments.
5329 llvm::Triple T(Tgts->getValue(i));
5330 TargetInfo += T.getTriple();
5332 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5335 bool WholeProgramVTables =
5336 Args.hasFlag(options::OPT_fwhole_program_vtables,
5337 options::OPT_fno_whole_program_vtables, false);
5338 if (WholeProgramVTables) {
5339 if (!D.isUsingLTO())
5340 D.Diag(diag::err_drv_argument_only_allowed_with)
5341 << "-fwhole-program-vtables"
5343 CmdArgs.push_back("-fwhole-program-vtables");
5346 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5348 Args.hasFlag(options::OPT_fsplit_lto_unit,
5349 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5350 if (RequiresSplitLTOUnit && !SplitLTOUnit)
5351 D.Diag(diag::err_drv_argument_not_allowed_with)
5352 << "-fno-split-lto-unit"
5353 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5355 CmdArgs.push_back("-fsplit-lto-unit");
5357 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5358 options::OPT_fno_experimental_isel)) {
5359 CmdArgs.push_back("-mllvm");
5360 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5361 CmdArgs.push_back("-global-isel=1");
5363 // GISel is on by default on AArch64 -O0, so don't bother adding
5364 // the fallback remarks for it. Other combinations will add a warning of
5366 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5367 bool IsOptLevelSupported = false;
5369 Arg *A = Args.getLastArg(options::OPT_O_Group);
5370 if (Triple.getArch() == llvm::Triple::aarch64) {
5371 if (!A || A->getOption().matches(options::OPT_O0))
5372 IsOptLevelSupported = true;
5374 if (!IsArchSupported || !IsOptLevelSupported) {
5375 CmdArgs.push_back("-mllvm");
5376 CmdArgs.push_back("-global-isel-abort=2");
5378 if (!IsArchSupported)
5379 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5381 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5384 CmdArgs.push_back("-global-isel=0");
5388 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5389 CmdArgs.push_back("-forder-file-instrumentation");
5390 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5391 // on, we need to pass these flags as linker flags and that will be handled
5392 // outside of the compiler.
5393 if (!D.isUsingLTO()) {
5394 CmdArgs.push_back("-mllvm");
5395 CmdArgs.push_back("-enable-order-file-instrumentation");
5399 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5400 options::OPT_fno_force_enable_int128)) {
5401 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5402 CmdArgs.push_back("-fforce-enable-int128");
5405 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5406 options::OPT_fno_complete_member_pointers, false))
5407 CmdArgs.push_back("-fcomplete-member-pointers");
5409 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5410 options::OPT_fno_cxx_static_destructors, true))
5411 CmdArgs.push_back("-fno-c++-static-destructors");
5413 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5414 options::OPT_mno_outline)) {
5415 if (A->getOption().matches(options::OPT_moutline)) {
5416 // We only support -moutline in AArch64 right now. If we're not compiling
5417 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5418 // proper mllvm flags.
5419 if (Triple.getArch() != llvm::Triple::aarch64) {
5420 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5422 CmdArgs.push_back("-mllvm");
5423 CmdArgs.push_back("-enable-machine-outliner");
5426 // Disable all outlining behaviour.
5427 CmdArgs.push_back("-mllvm");
5428 CmdArgs.push_back("-enable-machine-outliner=never");
5432 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
5433 (TC.getTriple().isOSBinFormatELF() ||
5434 TC.getTriple().isOSBinFormatCOFF()) &&
5435 !TC.getTriple().isPS4() &&
5436 !TC.getTriple().isOSNetBSD() &&
5437 !Distro(D.getVFS()).IsGentoo() &&
5438 !TC.getTriple().isAndroid() &&
5439 TC.useIntegratedAs()))
5440 CmdArgs.push_back("-faddrsig");
5442 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
5443 std::string Str = A->getAsString(Args);
5444 if (!TC.getTriple().isOSBinFormatELF())
5445 D.Diag(diag::err_drv_unsupported_opt_for_target)
5446 << Str << TC.getTripleString();
5447 CmdArgs.push_back(Args.MakeArgString(Str));
5450 // Add the "-o out -x type src.c" flags last. This is done primarily to make
5451 // the -cc1 command easier to edit when reproducing compiler crashes.
5452 if (Output.getType() == types::TY_Dependencies) {
5453 // Handled with other dependency code.
5454 } else if (Output.isFilename()) {
5455 CmdArgs.push_back("-o");
5456 CmdArgs.push_back(Output.getFilename());
5458 assert(Output.isNothing() && "Invalid output.");
5461 addDashXForInput(Args, Input, CmdArgs);
5463 ArrayRef<InputInfo> FrontendInputs = Input;
5464 if (IsHeaderModulePrecompile)
5465 FrontendInputs = ModuleHeaderInputs;
5466 else if (Input.isNothing())
5467 FrontendInputs = {};
5469 for (const InputInfo &Input : FrontendInputs) {
5470 if (Input.isFilename())
5471 CmdArgs.push_back(Input.getFilename());
5473 Input.getInputArg().renderAsInput(Args, CmdArgs);
5476 // Finally add the compile command to the compilation.
5477 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5478 Output.getType() == types::TY_Object &&
5479 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5481 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5482 C.addCommand(llvm::make_unique<FallbackCommand>(
5483 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5484 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5485 isa<PrecompileJobAction>(JA)) {
5486 // In /fallback builds, run the main compilation even if the pch generation
5487 // fails, so that the main compilation's fallback to cl.exe runs.
5488 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5491 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5494 // Make the compile command echo its inputs for /showFilenames.
5495 if (Output.getType() == types::TY_Object &&
5496 Args.hasFlag(options::OPT__SLASH_showFilenames,
5497 options::OPT__SLASH_showFilenames_, false)) {
5498 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5501 if (Arg *A = Args.getLastArg(options::OPT_pg))
5502 if (!shouldUseFramePointer(Args, Triple))
5503 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5504 << A->getAsString(Args);
5506 // Claim some arguments which clang supports automatically.
5508 // -fpch-preprocess is used with gcc to add a special marker in the output to
5509 // include the PCH file.
5510 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5512 // Claim some arguments which clang doesn't support, but we don't
5513 // care to warn the user about.
5514 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5515 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5517 // Disable warnings for clang -E -emit-llvm foo.c
5518 Args.ClaimAllArgs(options::OPT_emit_llvm);
5521 Clang::Clang(const ToolChain &TC)
5522 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5523 // as it is for other tools. Some operations on a Tool actually test
5524 // whether that tool is Clang based on the Tool's Name as a string.
5525 : Tool("clang", "clang frontend", TC, RF_Full) {}
5529 /// Add options related to the Objective-C runtime/ABI.
5531 /// Returns true if the runtime is non-fragile.
5532 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5533 ArgStringList &cmdArgs,
5534 RewriteKind rewriteKind) const {
5535 // Look for the controlling runtime option.
5537 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5538 options::OPT_fobjc_runtime_EQ);
5540 // Just forward -fobjc-runtime= to the frontend. This supercedes
5541 // options about fragility.
5543 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5544 ObjCRuntime runtime;
5545 StringRef value = runtimeArg->getValue();
5546 if (runtime.tryParse(value)) {
5547 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5550 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5551 (runtime.getVersion() >= VersionTuple(2, 0)))
5552 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5553 !getToolChain().getTriple().isOSBinFormatCOFF()) {
5554 getToolChain().getDriver().Diag(
5555 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5556 << runtime.getVersion().getMajor();
5559 runtimeArg->render(args, cmdArgs);
5563 // Otherwise, we'll need the ABI "version". Version numbers are
5564 // slightly confusing for historical reasons:
5565 // 1 - Traditional "fragile" ABI
5566 // 2 - Non-fragile ABI, version 1
5567 // 3 - Non-fragile ABI, version 2
5568 unsigned objcABIVersion = 1;
5569 // If -fobjc-abi-version= is present, use that to set the version.
5570 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5571 StringRef value = abiArg->getValue();
5574 else if (value == "2")
5576 else if (value == "3")
5579 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5581 // Otherwise, determine if we are using the non-fragile ABI.
5582 bool nonFragileABIIsDefault =
5583 (rewriteKind == RK_NonFragile ||
5584 (rewriteKind == RK_None &&
5585 getToolChain().IsObjCNonFragileABIDefault()));
5586 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5587 options::OPT_fno_objc_nonfragile_abi,
5588 nonFragileABIIsDefault)) {
5589 // Determine the non-fragile ABI version to use.
5590 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5591 unsigned nonFragileABIVersion = 1;
5593 unsigned nonFragileABIVersion = 2;
5597 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5598 StringRef value = abiArg->getValue();
5600 nonFragileABIVersion = 1;
5601 else if (value == "2")
5602 nonFragileABIVersion = 2;
5604 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5608 objcABIVersion = 1 + nonFragileABIVersion;
5614 // We don't actually care about the ABI version other than whether
5615 // it's non-fragile.
5616 bool isNonFragile = objcABIVersion != 1;
5618 // If we have no runtime argument, ask the toolchain for its default runtime.
5619 // However, the rewriter only really supports the Mac runtime, so assume that.
5620 ObjCRuntime runtime;
5622 switch (rewriteKind) {
5624 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5627 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5630 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5635 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5636 // On Darwin, make this use the default behavior for the toolchain.
5637 if (getToolChain().getTriple().isOSDarwin()) {
5638 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5640 // Otherwise, build for a generic macosx port.
5642 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5647 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5648 // Legacy behaviour is to target the gnustep runtime if we are in
5649 // non-fragile mode or the GCC runtime in fragile mode.
5651 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
5653 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5657 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5661 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5662 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5670 bool Asynch = false;
5671 bool NoUnwindC = false;
5673 } // end anonymous namespace
5675 /// /EH controls whether to run destructor cleanups when exceptions are
5676 /// thrown. There are three modifiers:
5677 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5678 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5679 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5680 /// - c: Assume that extern "C" functions are implicitly nounwind.
5681 /// The default is /EHs-c-, meaning cleanups are disabled.
5682 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5685 std::vector<std::string> EHArgs =
5686 Args.getAllArgValues(options::OPT__SLASH_EH);
5687 for (auto EHVal : EHArgs) {
5688 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5691 EH.Asynch = maybeConsumeDash(EHVal, I);
5696 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5699 EH.Synch = maybeConsumeDash(EHVal, I);
5706 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5710 // The /GX, /GX- flags are only processed if there are not /EH flags.
5711 // The default is that /GX is not specified.
5712 if (EHArgs.empty() &&
5713 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5714 /*Default=*/false)) {
5716 EH.NoUnwindC = true;
5722 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5723 ArgStringList &CmdArgs,
5724 codegenoptions::DebugInfoKind *DebugInfoKind,
5725 bool *EmitCodeView) const {
5726 unsigned RTOptionID = options::OPT__SLASH_MT;
5728 if (Args.hasArg(options::OPT__SLASH_LDd))
5729 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5730 // but defining _DEBUG is sticky.
5731 RTOptionID = options::OPT__SLASH_MTd;
5733 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5734 RTOptionID = A->getOption().getID();
5736 StringRef FlagForCRT;
5737 switch (RTOptionID) {
5738 case options::OPT__SLASH_MD:
5739 if (Args.hasArg(options::OPT__SLASH_LDd))
5740 CmdArgs.push_back("-D_DEBUG");
5741 CmdArgs.push_back("-D_MT");
5742 CmdArgs.push_back("-D_DLL");
5743 FlagForCRT = "--dependent-lib=msvcrt";
5745 case options::OPT__SLASH_MDd:
5746 CmdArgs.push_back("-D_DEBUG");
5747 CmdArgs.push_back("-D_MT");
5748 CmdArgs.push_back("-D_DLL");
5749 FlagForCRT = "--dependent-lib=msvcrtd";
5751 case options::OPT__SLASH_MT:
5752 if (Args.hasArg(options::OPT__SLASH_LDd))
5753 CmdArgs.push_back("-D_DEBUG");
5754 CmdArgs.push_back("-D_MT");
5755 CmdArgs.push_back("-flto-visibility-public-std");
5756 FlagForCRT = "--dependent-lib=libcmt";
5758 case options::OPT__SLASH_MTd:
5759 CmdArgs.push_back("-D_DEBUG");
5760 CmdArgs.push_back("-D_MT");
5761 CmdArgs.push_back("-flto-visibility-public-std");
5762 FlagForCRT = "--dependent-lib=libcmtd";
5765 llvm_unreachable("Unexpected option ID.");
5768 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5769 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5771 CmdArgs.push_back(FlagForCRT.data());
5773 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5774 // users want. The /Za flag to cl.exe turns this off, but it's not
5775 // implemented in clang.
5776 CmdArgs.push_back("--dependent-lib=oldnames");
5779 Args.AddLastArg(CmdArgs, options::OPT_show_includes);
5781 // This controls whether or not we emit RTTI data for polymorphic types.
5782 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5784 CmdArgs.push_back("-fno-rtti-data");
5786 // This controls whether or not we emit stack-protector instrumentation.
5787 // In MSVC, Buffer Security Check (/GS) is on by default.
5788 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5789 /*Default=*/true)) {
5790 CmdArgs.push_back("-stack-protector");
5791 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5794 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5795 if (Arg *DebugInfoArg =
5796 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5797 options::OPT_gline_tables_only)) {
5798 *EmitCodeView = true;
5799 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5800 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5802 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5804 *EmitCodeView = false;
5807 const Driver &D = getToolChain().getDriver();
5808 EHFlags EH = parseClangCLEHFlags(D, Args);
5809 if (EH.Synch || EH.Asynch) {
5810 if (types::isCXX(InputType))
5811 CmdArgs.push_back("-fcxx-exceptions");
5812 CmdArgs.push_back("-fexceptions");
5814 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5815 CmdArgs.push_back("-fexternc-nounwind");
5817 // /EP should expand to -E -P.
5818 if (Args.hasArg(options::OPT__SLASH_EP)) {
5819 CmdArgs.push_back("-E");
5820 CmdArgs.push_back("-P");
5823 unsigned VolatileOptionID;
5824 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5825 getToolChain().getArch() == llvm::Triple::x86)
5826 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5828 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5830 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5831 VolatileOptionID = A->getOption().getID();
5833 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5834 CmdArgs.push_back("-fms-volatile");
5836 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5837 options::OPT__SLASH_Zc_dllexportInlines,
5839 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5840 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5842 CmdArgs.push_back("-fno-dllexport-inlines");
5846 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5847 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5848 if (MostGeneralArg && BestCaseArg)
5849 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5850 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5852 if (MostGeneralArg) {
5853 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5854 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5855 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5857 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5858 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5859 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5860 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5861 << FirstConflict->getAsString(Args)
5862 << SecondConflict->getAsString(Args);
5865 CmdArgs.push_back("-fms-memptr-rep=single");
5866 else if (MultipleArg)
5867 CmdArgs.push_back("-fms-memptr-rep=multiple");
5869 CmdArgs.push_back("-fms-memptr-rep=virtual");
5872 // Parse the default calling convention options.
5874 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
5875 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5876 options::OPT__SLASH_Gregcall)) {
5877 unsigned DCCOptId = CCArg->getOption().getID();
5878 const char *DCCFlag = nullptr;
5879 bool ArchSupported = true;
5880 llvm::Triple::ArchType Arch = getToolChain().getArch();
5882 case options::OPT__SLASH_Gd:
5883 DCCFlag = "-fdefault-calling-conv=cdecl";
5885 case options::OPT__SLASH_Gr:
5886 ArchSupported = Arch == llvm::Triple::x86;
5887 DCCFlag = "-fdefault-calling-conv=fastcall";
5889 case options::OPT__SLASH_Gz:
5890 ArchSupported = Arch == llvm::Triple::x86;
5891 DCCFlag = "-fdefault-calling-conv=stdcall";
5893 case options::OPT__SLASH_Gv:
5894 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5895 DCCFlag = "-fdefault-calling-conv=vectorcall";
5897 case options::OPT__SLASH_Gregcall:
5898 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5899 DCCFlag = "-fdefault-calling-conv=regcall";
5903 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5904 if (ArchSupported && DCCFlag)
5905 CmdArgs.push_back(DCCFlag);
5908 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
5910 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5911 CmdArgs.push_back("-fdiagnostics-format");
5912 if (Args.hasArg(options::OPT__SLASH_fallback))
5913 CmdArgs.push_back("msvc-fallback");
5915 CmdArgs.push_back("msvc");
5918 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5919 SmallVector<StringRef, 1> SplitArgs;
5920 StringRef(A->getValue()).split(SplitArgs, ",");
5921 bool Instrument = false;
5922 bool NoChecks = false;
5923 for (StringRef Arg : SplitArgs) {
5924 if (Arg.equals_lower("cf"))
5926 else if (Arg.equals_lower("cf-"))
5928 else if (Arg.equals_lower("nochecks"))
5930 else if (Arg.equals_lower("nochecks-"))
5933 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5935 // Currently there's no support emitting CFG instrumentation; the flag only
5936 // emits the table of address-taken functions.
5937 if (Instrument || NoChecks)
5938 CmdArgs.push_back("-cfguard");
5942 visualstudio::Compiler *Clang::getCLFallback() const {
5944 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5945 return CLFallback.get();
5949 const char *Clang::getBaseInputName(const ArgList &Args,
5950 const InputInfo &Input) {
5951 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5954 const char *Clang::getBaseInputStem(const ArgList &Args,
5955 const InputInfoList &Inputs) {
5956 const char *Str = getBaseInputName(Args, Inputs[0]);
5958 if (const char *End = strrchr(Str, '.'))
5959 return Args.MakeArgString(std::string(Str, End));
5964 const char *Clang::getDependencyFileName(const ArgList &Args,
5965 const InputInfoList &Inputs) {
5966 // FIXME: Think about this more.
5969 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5970 std::string Str(OutputOpt->getValue());
5971 Res = Str.substr(0, Str.rfind('.'));
5973 Res = getBaseInputStem(Args, Inputs);
5975 return Args.MakeArgString(Res + ".d");
5980 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5981 ArgStringList &CmdArgs) const {
5984 const llvm::Triple &Triple = getToolChain().getTriple();
5985 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5987 CmdArgs.push_back("-target-abi");
5988 CmdArgs.push_back(ABIName.data());
5991 void ClangAs::AddX86TargetArgs(const ArgList &Args,
5992 ArgStringList &CmdArgs) const {
5993 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5994 StringRef Value = A->getValue();
5995 if (Value == "intel" || Value == "att") {
5996 CmdArgs.push_back("-mllvm");
5997 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5999 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
6000 << A->getOption().getName() << Value;
6005 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
6006 ArgStringList &CmdArgs) const {
6007 const llvm::Triple &Triple = getToolChain().getTriple();
6008 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
6010 CmdArgs.push_back("-target-abi");
6011 CmdArgs.push_back(ABIName.data());
6014 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6015 const InputInfo &Output, const InputInfoList &Inputs,
6016 const ArgList &Args,
6017 const char *LinkingOutput) const {
6018 ArgStringList CmdArgs;
6020 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6021 const InputInfo &Input = Inputs[0];
6023 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
6024 const std::string &TripleStr = Triple.getTriple();
6025 const auto &D = getToolChain().getDriver();
6027 // Don't warn about "clang -w -c foo.s"
6028 Args.ClaimAllArgs(options::OPT_w);
6029 // and "clang -emit-llvm -c foo.s"
6030 Args.ClaimAllArgs(options::OPT_emit_llvm);
6032 claimNoWarnArgs(Args);
6034 // Invoke ourselves in -cc1as mode.
6036 // FIXME: Implement custom jobs for internal actions.
6037 CmdArgs.push_back("-cc1as");
6039 // Add the "effective" target triple.
6040 CmdArgs.push_back("-triple");
6041 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6043 // Set the output mode, we currently only expect to be used as a real
6045 CmdArgs.push_back("-filetype");
6046 CmdArgs.push_back("obj");
6048 // Set the main file name, so that debug info works even with
6049 // -save-temps or preprocessed assembly.
6050 CmdArgs.push_back("-main-file-name");
6051 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6053 // Add the target cpu
6054 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6056 CmdArgs.push_back("-target-cpu");
6057 CmdArgs.push_back(Args.MakeArgString(CPU));
6060 // Add the target features
6061 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6063 // Ignore explicit -force_cpusubtype_ALL option.
6064 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6066 // Pass along any -I options so we get proper .include search paths.
6067 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6069 // Determine the original source input.
6070 const Action *SourceAction = &JA;
6071 while (SourceAction->getKind() != Action::InputClass) {
6072 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6073 SourceAction = SourceAction->getInputs()[0];
6076 // Forward -g and handle debug info related flags, assuming we are dealing
6077 // with an actual assembly file.
6078 bool WantDebug = false;
6079 unsigned DwarfVersion = 0;
6080 Args.ClaimAllArgs(options::OPT_g_Group);
6081 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6082 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6083 !A->getOption().matches(options::OPT_ggdb0);
6085 DwarfVersion = DwarfVersionNum(A->getSpelling());
6087 if (DwarfVersion == 0)
6088 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6090 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6092 if (SourceAction->getType() == types::TY_Asm ||
6093 SourceAction->getType() == types::TY_PP_Asm) {
6094 // You might think that it would be ok to set DebugInfoKind outside of
6095 // the guard for source type, however there is a test which asserts
6096 // that some assembler invocation receives no -debug-info-kind,
6097 // and it's not clear whether that test is just overly restrictive.
6098 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6099 : codegenoptions::NoDebugInfo);
6100 // Add the -fdebug-compilation-dir flag if needed.
6101 addDebugCompDirArg(Args, CmdArgs);
6103 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6105 // Set the AT_producer to the clang version when using the integrated
6106 // assembler on assembly source files.
6107 CmdArgs.push_back("-dwarf-debug-producer");
6108 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6110 // And pass along -I options
6111 Args.AddAllArgs(CmdArgs, options::OPT_I);
6113 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6114 llvm::DebuggerKind::Default);
6115 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
6118 // Handle -fPIC et al -- the relocation-model affects the assembler
6119 // for some targets.
6120 llvm::Reloc::Model RelocationModel;
6123 std::tie(RelocationModel, PICLevel, IsPIE) =
6124 ParsePICArgs(getToolChain(), Args);
6126 const char *RMName = RelocationModelName(RelocationModel);
6128 CmdArgs.push_back("-mrelocation-model");
6129 CmdArgs.push_back(RMName);
6132 // Optionally embed the -cc1as level arguments into the debug info, for build
6134 if (getToolChain().UseDwarfDebugFlags()) {
6135 ArgStringList OriginalArgs;
6136 for (const auto &Arg : Args)
6137 Arg->render(Args, OriginalArgs);
6139 SmallString<256> Flags;
6140 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6142 for (const char *OriginalArg : OriginalArgs) {
6143 SmallString<128> EscapedArg;
6144 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6146 Flags += EscapedArg;
6148 CmdArgs.push_back("-dwarf-debug-flags");
6149 CmdArgs.push_back(Args.MakeArgString(Flags));
6152 // FIXME: Add -static support, once we have it.
6154 // Add target specific flags.
6155 switch (getToolChain().getArch()) {
6159 case llvm::Triple::mips:
6160 case llvm::Triple::mipsel:
6161 case llvm::Triple::mips64:
6162 case llvm::Triple::mips64el:
6163 AddMIPSTargetArgs(Args, CmdArgs);
6166 case llvm::Triple::x86:
6167 case llvm::Triple::x86_64:
6168 AddX86TargetArgs(Args, CmdArgs);
6171 case llvm::Triple::arm:
6172 case llvm::Triple::armeb:
6173 case llvm::Triple::thumb:
6174 case llvm::Triple::thumbeb:
6175 // This isn't in AddARMTargetArgs because we want to do this for assembly
6177 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6178 options::OPT_mno_default_build_attributes, true)) {
6179 CmdArgs.push_back("-mllvm");
6180 CmdArgs.push_back("-arm-add-build-attributes");
6184 case llvm::Triple::riscv32:
6185 case llvm::Triple::riscv64:
6186 AddRISCVTargetArgs(Args, CmdArgs);
6190 // Consume all the warning flags. Usually this would be handled more
6191 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6192 // doesn't handle that so rather than warning about unused flags that are
6193 // actually used, we'll lie by omission instead.
6194 // FIXME: Stop lying and consume only the appropriate driver flags
6195 Args.ClaimAllArgs(options::OPT_W_Group);
6197 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6198 getToolChain().getDriver());
6200 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6202 assert(Output.isFilename() && "Unexpected lipo output.");
6203 CmdArgs.push_back("-o");
6204 CmdArgs.push_back(Output.getFilename());
6206 const llvm::Triple &T = getToolChain().getTriple();
6208 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6209 T.isOSBinFormatELF()) {
6210 CmdArgs.push_back("-split-dwarf-output");
6211 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
6214 assert(Input.isFilename() && "Invalid input.");
6215 CmdArgs.push_back(Input.getFilename());
6217 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6218 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6221 // Begin OffloadBundler
6223 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6224 const InputInfo &Output,
6225 const InputInfoList &Inputs,
6226 const llvm::opt::ArgList &TCArgs,
6227 const char *LinkingOutput) const {
6228 // The version with only one output is expected to refer to a bundling job.
6229 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6231 // The bundling command looks like this:
6232 // clang-offload-bundler -type=bc
6233 // -targets=host-triple,openmp-triple1,openmp-triple2
6234 // -outputs=input_file
6235 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6237 ArgStringList CmdArgs;
6240 CmdArgs.push_back(TCArgs.MakeArgString(
6241 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6243 assert(JA.getInputs().size() == Inputs.size() &&
6244 "Not have inputs for all dependence actions??");
6247 SmallString<128> Triples;
6248 Triples += "-targets=";
6249 for (unsigned I = 0; I < Inputs.size(); ++I) {
6253 // Find ToolChain for this input.
6254 Action::OffloadKind CurKind = Action::OFK_Host;
6255 const ToolChain *CurTC = &getToolChain();
6256 const Action *CurDep = JA.getInputs()[I];
6258 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
6260 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
6261 assert(CurTC == nullptr && "Expected one dependence!");
6262 CurKind = A->getOffloadingDeviceKind();
6266 Triples += Action::GetOffloadKindName(CurKind);
6268 Triples += CurTC->getTriple().normalize();
6269 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6271 Triples += CurDep->getOffloadingArch();
6274 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6276 // Get bundled file command.
6278 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6280 // Get unbundled files command.
6281 SmallString<128> UB;
6283 for (unsigned I = 0; I < Inputs.size(); ++I) {
6287 // Find ToolChain for this input.
6288 const ToolChain *CurTC = &getToolChain();
6289 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6291 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6292 assert(CurTC == nullptr && "Expected one dependence!");
6296 UB += CurTC->getInputFilename(Inputs[I]);
6298 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6300 // All the inputs are encoded as commands.
6301 C.addCommand(llvm::make_unique<Command>(
6303 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6307 void OffloadBundler::ConstructJobMultipleOutputs(
6308 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6309 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6310 const char *LinkingOutput) const {
6311 // The version with multiple outputs is expected to refer to a unbundling job.
6312 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6314 // The unbundling command looks like this:
6315 // clang-offload-bundler -type=bc
6316 // -targets=host-triple,openmp-triple1,openmp-triple2
6317 // -inputs=input_file
6318 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6321 ArgStringList CmdArgs;
6323 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6324 InputInfo Input = Inputs.front();
6327 CmdArgs.push_back(TCArgs.MakeArgString(
6328 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6331 SmallString<128> Triples;
6332 Triples += "-targets=";
6333 auto DepInfo = UA.getDependentActionsInfo();
6334 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6338 auto &Dep = DepInfo[I];
6339 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6341 Triples += Dep.DependentToolChain->getTriple().normalize();
6342 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6343 !Dep.DependentBoundArch.empty()) {
6345 Triples += Dep.DependentBoundArch;
6349 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6351 // Get bundled file command.
6353 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6355 // Get unbundled files command.
6356 SmallString<128> UB;
6358 for (unsigned I = 0; I < Outputs.size(); ++I) {
6361 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
6363 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6364 CmdArgs.push_back("-unbundle");
6366 // All the inputs are encoded as commands.
6367 C.addCommand(llvm::make_unique<Command>(
6369 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),