1 //===--- LLVM.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "Arch/AArch64.h"
13 #include "Arch/Mips.h"
15 #include "Arch/RISCV.h"
16 #include "Arch/Sparc.h"
17 #include "Arch/SystemZ.h"
20 #include "CommonArgs.h"
23 #include "InputInfo.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/ObjCRuntime.h"
28 #include "clang/Basic/Version.h"
29 #include "clang/Driver/Distro.h"
30 #include "clang/Driver/DriverDiagnostic.h"
31 #include "clang/Driver/Options.h"
32 #include "clang/Driver/SanitizerArgs.h"
33 #include "clang/Driver/XRayArgs.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Config/llvm-config.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Support/CodeGen.h"
38 #include "llvm/Support/Compression.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/TargetParser.h"
43 #include "llvm/Support/YAMLParser.h"
46 #include <unistd.h> // For getuid().
49 using namespace clang::driver;
50 using namespace clang::driver::tools;
51 using namespace clang;
52 using namespace llvm::opt;
54 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
56 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
57 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
58 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
59 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
60 << A->getBaseArg().getAsString(Args)
61 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
66 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
67 // In gcc, only ARM checks this, but it seems reasonable to check universally.
68 if (Args.hasArg(options::OPT_static))
70 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
71 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
75 // Add backslashes to escape spaces and other backslashes.
76 // This is used for the space-separated argument list specified with
77 // the -dwarf-debug-flags option.
78 static void EscapeSpacesAndBackslashes(const char *Arg,
79 SmallVectorImpl<char> &Res) {
93 // Quote target names for inclusion in GNU Make dependency files.
94 // Only the characters '$', '#', ' ', '\t' are quoted.
95 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
96 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
100 // Escape the preceding backslashes
101 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
104 // Escape the space/tab
117 Res.push_back(Target[i]);
121 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
122 /// offloading tool chain that is associated with the current action \a JA.
124 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
125 const ToolChain &RegularToolChain,
126 llvm::function_ref<void(const ToolChain &)> Work) {
127 // Apply Work on the current/regular tool chain.
128 Work(RegularToolChain);
130 // Apply Work on all the offloading tool chains associated with the current
132 if (JA.isHostOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
134 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
136 else if (JA.isHostOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
138 else if (JA.isDeviceOffloading(Action::OFK_HIP))
139 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
141 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
142 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
143 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
145 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
146 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
149 // TODO: Add support for other offloading programming models here.
153 /// This is a helper function for validating the optional refinement step
154 /// parameter in reciprocal argument strings. Return false if there is an error
155 /// parsing the refinement step. Otherwise, return true and set the Position
156 /// of the refinement step in the input string.
157 static bool getRefinementStep(StringRef In, const Driver &D,
158 const Arg &A, size_t &Position) {
159 const char RefinementStepToken = ':';
160 Position = In.find(RefinementStepToken);
161 if (Position != StringRef::npos) {
162 StringRef Option = A.getOption().getName();
163 StringRef RefStep = In.substr(Position + 1);
164 // Allow exactly one numeric character for the additional refinement
165 // step parameter. This is reasonable for all currently-supported
166 // operations and architectures because we would expect that a larger value
167 // of refinement steps would cause the estimate "optimization" to
168 // under-perform the native operation. Also, if the estimate does not
169 // converge quickly, it probably will not ever converge, so further
170 // refinement steps will not produce a better answer.
171 if (RefStep.size() != 1) {
172 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
175 char RefStepChar = RefStep[0];
176 if (RefStepChar < '0' || RefStepChar > '9') {
177 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
184 /// The -mrecip flag requires processing of many optional parameters.
185 static void ParseMRecip(const Driver &D, const ArgList &Args,
186 ArgStringList &OutStrings) {
187 StringRef DisabledPrefixIn = "!";
188 StringRef DisabledPrefixOut = "!";
189 StringRef EnabledPrefixOut = "";
190 StringRef Out = "-mrecip=";
192 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
196 unsigned NumOptions = A->getNumValues();
197 if (NumOptions == 0) {
198 // No option is the same as "all".
199 OutStrings.push_back(Args.MakeArgString(Out + "all"));
203 // Pass through "all", "none", or "default" with an optional refinement step.
204 if (NumOptions == 1) {
205 StringRef Val = A->getValue(0);
207 if (!getRefinementStep(Val, D, *A, RefStepLoc))
209 StringRef ValBase = Val.slice(0, RefStepLoc);
210 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
211 OutStrings.push_back(Args.MakeArgString(Out + Val));
216 // Each reciprocal type may be enabled or disabled individually.
217 // Check each input value for validity, concatenate them all back together,
220 llvm::StringMap<bool> OptionStrings;
221 OptionStrings.insert(std::make_pair("divd", false));
222 OptionStrings.insert(std::make_pair("divf", false));
223 OptionStrings.insert(std::make_pair("vec-divd", false));
224 OptionStrings.insert(std::make_pair("vec-divf", false));
225 OptionStrings.insert(std::make_pair("sqrtd", false));
226 OptionStrings.insert(std::make_pair("sqrtf", false));
227 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
228 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
230 for (unsigned i = 0; i != NumOptions; ++i) {
231 StringRef Val = A->getValue(i);
233 bool IsDisabled = Val.startswith(DisabledPrefixIn);
234 // Ignore the disablement token for string matching.
239 if (!getRefinementStep(Val, D, *A, RefStep))
242 StringRef ValBase = Val.slice(0, RefStep);
243 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
244 if (OptionIter == OptionStrings.end()) {
245 // Try again specifying float suffix.
246 OptionIter = OptionStrings.find(ValBase.str() + 'f');
247 if (OptionIter == OptionStrings.end()) {
248 // The input name did not match any known option string.
249 D.Diag(diag::err_drv_unknown_argument) << Val;
252 // The option was specified without a float or double suffix.
253 // Make sure that the double entry was not already specified.
254 // The float entry will be checked below.
255 if (OptionStrings[ValBase.str() + 'd']) {
256 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
261 if (OptionIter->second == true) {
262 // Duplicate option specified.
263 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
267 // Mark the matched option as found. Do not allow duplicate specifiers.
268 OptionIter->second = true;
270 // If the precision was not specified, also mark the double entry as found.
271 if (ValBase.back() != 'f' && ValBase.back() != 'd')
272 OptionStrings[ValBase.str() + 'd'] = true;
274 // Build the output string.
275 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
276 Out = Args.MakeArgString(Out + Prefix + Val);
277 if (i != NumOptions - 1)
278 Out = Args.MakeArgString(Out + ",");
281 OutStrings.push_back(Args.MakeArgString(Out));
284 /// The -mprefer-vector-width option accepts either a positive integer
285 /// or the string "none".
286 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
287 ArgStringList &CmdArgs) {
288 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
292 StringRef Value = A->getValue();
293 if (Value == "none") {
294 CmdArgs.push_back("-mprefer-vector-width=none");
297 if (Value.getAsInteger(10, Width)) {
298 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
301 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
305 static void getWebAssemblyTargetFeatures(const ArgList &Args,
306 std::vector<StringRef> &Features) {
307 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
310 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
311 const ArgList &Args, ArgStringList &CmdArgs,
313 const Driver &D = TC.getDriver();
314 std::vector<StringRef> Features;
315 switch (Triple.getArch()) {
318 case llvm::Triple::mips:
319 case llvm::Triple::mipsel:
320 case llvm::Triple::mips64:
321 case llvm::Triple::mips64el:
322 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
325 case llvm::Triple::arm:
326 case llvm::Triple::armeb:
327 case llvm::Triple::thumb:
328 case llvm::Triple::thumbeb:
329 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
332 case llvm::Triple::ppc:
333 case llvm::Triple::ppc64:
334 case llvm::Triple::ppc64le:
335 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
337 case llvm::Triple::riscv32:
338 case llvm::Triple::riscv64:
339 riscv::getRISCVTargetFeatures(D, Args, Features);
341 case llvm::Triple::systemz:
342 systemz::getSystemZTargetFeatures(Args, Features);
344 case llvm::Triple::aarch64:
345 case llvm::Triple::aarch64_be:
346 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
348 case llvm::Triple::x86:
349 case llvm::Triple::x86_64:
350 x86::getX86TargetFeatures(D, Triple, Args, Features);
352 case llvm::Triple::hexagon:
353 hexagon::getHexagonTargetFeatures(D, Args, Features);
355 case llvm::Triple::wasm32:
356 case llvm::Triple::wasm64:
357 getWebAssemblyTargetFeatures(Args, Features);
359 case llvm::Triple::sparc:
360 case llvm::Triple::sparcel:
361 case llvm::Triple::sparcv9:
362 sparc::getSparcTargetFeatures(D, Args, Features);
364 case llvm::Triple::r600:
365 case llvm::Triple::amdgcn:
366 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
368 case llvm::Triple::msp430:
369 msp430::getMSP430TargetFeatures(D, Args, Features);
372 // Find the last of each feature.
373 llvm::StringMap<unsigned> LastOpt;
374 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
375 StringRef Name = Features[I];
376 assert(Name[0] == '-' || Name[0] == '+');
377 LastOpt[Name.drop_front(1)] = I;
380 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
381 // If this feature was overridden, ignore it.
382 StringRef Name = Features[I];
383 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
384 assert(LastI != LastOpt.end());
385 unsigned Last = LastI->second;
389 CmdArgs.push_back("-target-feature");
390 CmdArgs.push_back(Name.data());
395 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
396 const llvm::Triple &Triple) {
397 // We use the zero-cost exception tables for Objective-C if the non-fragile
398 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
400 if (runtime.isNonFragile())
403 if (!Triple.isMacOSX())
406 return (!Triple.isMacOSXVersionLT(10, 5) &&
407 (Triple.getArch() == llvm::Triple::x86_64 ||
408 Triple.getArch() == llvm::Triple::arm));
411 /// Adds exception related arguments to the driver command arguments. There's a
412 /// master flag, -fexceptions and also language specific flags to enable/disable
413 /// C++ and Objective-C exceptions. This makes it possible to for example
414 /// disable C++ exceptions but enable Objective-C exceptions.
415 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
416 const ToolChain &TC, bool KernelOrKext,
417 const ObjCRuntime &objcRuntime,
418 ArgStringList &CmdArgs) {
419 const llvm::Triple &Triple = TC.getTriple();
422 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
423 // arguments now to avoid warnings about unused arguments.
424 Args.ClaimAllArgs(options::OPT_fexceptions);
425 Args.ClaimAllArgs(options::OPT_fno_exceptions);
426 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
427 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
428 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
429 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
433 // See if the user explicitly enabled exceptions.
434 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
437 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
438 // is not necessarily sensible, but follows GCC.
439 if (types::isObjC(InputType) &&
440 Args.hasFlag(options::OPT_fobjc_exceptions,
441 options::OPT_fno_objc_exceptions, true)) {
442 CmdArgs.push_back("-fobjc-exceptions");
444 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
447 if (types::isCXX(InputType)) {
448 // Disable C++ EH by default on XCore and PS4.
449 bool CXXExceptionsEnabled =
450 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
451 Arg *ExceptionArg = Args.getLastArg(
452 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
453 options::OPT_fexceptions, options::OPT_fno_exceptions);
455 CXXExceptionsEnabled =
456 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
457 ExceptionArg->getOption().matches(options::OPT_fexceptions);
459 if (CXXExceptionsEnabled) {
460 CmdArgs.push_back("-fcxx-exceptions");
467 CmdArgs.push_back("-fexceptions");
470 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
472 if (TC.getTriple().isOSDarwin()) {
473 // The native darwin assembler doesn't support the linker_option directives,
474 // so we disable them if we think the .s file will be passed to it.
475 Default = TC.useIntegratedAs();
477 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
481 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
482 const ToolChain &TC) {
483 bool UseDwarfDirectory =
484 Args.hasFlag(options::OPT_fdwarf_directory_asm,
485 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
486 return !UseDwarfDirectory;
489 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
490 // to the corresponding DebugInfoKind.
491 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
492 assert(A.getOption().matches(options::OPT_gN_Group) &&
493 "Not a -g option that specifies a debug-info level");
494 if (A.getOption().matches(options::OPT_g0) ||
495 A.getOption().matches(options::OPT_ggdb0))
496 return codegenoptions::NoDebugInfo;
497 if (A.getOption().matches(options::OPT_gline_tables_only) ||
498 A.getOption().matches(options::OPT_ggdb1))
499 return codegenoptions::DebugLineTablesOnly;
500 if (A.getOption().matches(options::OPT_gline_directives_only))
501 return codegenoptions::DebugDirectivesOnly;
502 return codegenoptions::LimitedDebugInfo;
505 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
506 switch (Triple.getArch()){
509 case llvm::Triple::arm:
510 case llvm::Triple::thumb:
511 // ARM Darwin targets require a frame pointer to be always present to aid
512 // offline debugging via backtraces.
513 return Triple.isOSDarwin();
517 static bool useFramePointerForTargetByDefault(const ArgList &Args,
518 const llvm::Triple &Triple) {
519 switch (Triple.getArch()) {
520 case llvm::Triple::xcore:
521 case llvm::Triple::wasm32:
522 case llvm::Triple::wasm64:
523 // XCore never wants frame pointers, regardless of OS.
524 // WebAssembly never wants frame pointers.
526 case llvm::Triple::riscv32:
527 case llvm::Triple::riscv64:
528 return !areOptimizationsEnabled(Args);
533 if (Triple.isOSNetBSD()) {
534 return !areOptimizationsEnabled(Args);
537 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
539 switch (Triple.getArch()) {
540 // Don't use a frame pointer on linux if optimizing for certain targets.
541 case llvm::Triple::mips64:
542 case llvm::Triple::mips64el:
543 case llvm::Triple::mips:
544 case llvm::Triple::mipsel:
545 case llvm::Triple::ppc:
546 case llvm::Triple::ppc64:
547 case llvm::Triple::ppc64le:
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 SmallString<128> cwd;
608 if (!llvm::sys::fs::current_path(cwd)) {
609 CmdArgs.push_back("-fdebug-compilation-dir");
610 CmdArgs.push_back(Args.MakeArgString(cwd));
614 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
615 static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
616 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
617 StringRef Map = A->getValue();
618 if (Map.find('=') == StringRef::npos)
619 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
621 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
626 /// Vectorize at all optimization levels greater than 1 except for -Oz.
627 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
628 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
629 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
630 if (A->getOption().matches(options::OPT_O4) ||
631 A->getOption().matches(options::OPT_Ofast))
634 if (A->getOption().matches(options::OPT_O0))
637 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
640 StringRef S(A->getValue());
644 // Don't vectorize -Oz, unless it's the slp vectorizer.
648 unsigned OptLevel = 0;
649 if (S.getAsInteger(10, OptLevel))
658 /// Add -x lang to \p CmdArgs for \p Input.
659 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
660 ArgStringList &CmdArgs) {
661 // When using -verify-pch, we don't want to provide the type
662 // 'precompiled-header' if it was inferred from the file extension
663 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
666 CmdArgs.push_back("-x");
667 if (Args.hasArg(options::OPT_rewrite_objc))
668 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
670 // Map the driver type to the frontend type. This is mostly an identity
671 // mapping, except that the distinction between module interface units
672 // and other source files does not exist at the frontend layer.
673 const char *ClangType;
674 switch (Input.getType()) {
675 case types::TY_CXXModule:
678 case types::TY_PP_CXXModule:
679 ClangType = "c++-cpp-output";
682 ClangType = types::getTypeName(Input.getType());
685 CmdArgs.push_back(ClangType);
689 static void appendUserToPath(SmallVectorImpl<char> &Result) {
691 const char *Username = getenv("LOGNAME");
693 const char *Username = getenv("USERNAME");
696 // Validate that LoginName can be used in a path, and get its length.
698 for (const char *P = Username; *P; ++P, ++Len) {
699 if (!clang::isAlphanumeric(*P) && *P != '_') {
705 if (Username && Len > 0) {
706 Result.append(Username, Username + Len);
711 // Fallback to user id.
713 std::string UID = llvm::utostr(getuid());
715 // FIXME: Windows seems to have an 'SID' that might work.
716 std::string UID = "9999";
718 Result.append(UID.begin(), UID.end());
721 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
722 const InputInfo &Output, const ArgList &Args,
723 ArgStringList &CmdArgs) {
725 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
726 options::OPT_fprofile_generate_EQ,
727 options::OPT_fno_profile_generate);
728 if (PGOGenerateArg &&
729 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
730 PGOGenerateArg = nullptr;
732 auto *ProfileGenerateArg = Args.getLastArg(
733 options::OPT_fprofile_instr_generate,
734 options::OPT_fprofile_instr_generate_EQ,
735 options::OPT_fno_profile_instr_generate);
736 if (ProfileGenerateArg &&
737 ProfileGenerateArg->getOption().matches(
738 options::OPT_fno_profile_instr_generate))
739 ProfileGenerateArg = nullptr;
741 if (PGOGenerateArg && ProfileGenerateArg)
742 D.Diag(diag::err_drv_argument_not_allowed_with)
743 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
745 auto *ProfileUseArg = getLastProfileUseArg(Args);
747 if (PGOGenerateArg && ProfileUseArg)
748 D.Diag(diag::err_drv_argument_not_allowed_with)
749 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
751 if (ProfileGenerateArg && ProfileUseArg)
752 D.Diag(diag::err_drv_argument_not_allowed_with)
753 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
755 if (ProfileGenerateArg) {
756 if (ProfileGenerateArg->getOption().matches(
757 options::OPT_fprofile_instr_generate_EQ))
758 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
759 ProfileGenerateArg->getValue()));
760 // The default is to use Clang Instrumentation.
761 CmdArgs.push_back("-fprofile-instrument=clang");
764 if (PGOGenerateArg) {
765 CmdArgs.push_back("-fprofile-instrument=llvm");
766 if (PGOGenerateArg->getOption().matches(
767 options::OPT_fprofile_generate_EQ)) {
768 SmallString<128> Path(PGOGenerateArg->getValue());
769 llvm::sys::path::append(Path, "default_%m.profraw");
771 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
776 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
777 CmdArgs.push_back(Args.MakeArgString(
778 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
779 else if ((ProfileUseArg->getOption().matches(
780 options::OPT_fprofile_use_EQ) ||
781 ProfileUseArg->getOption().matches(
782 options::OPT_fprofile_instr_use))) {
783 SmallString<128> Path(
784 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
785 if (Path.empty() || llvm::sys::fs::is_directory(Path))
786 llvm::sys::path::append(Path, "default.profdata");
788 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
792 if (Args.hasArg(options::OPT_ftest_coverage) ||
793 Args.hasArg(options::OPT_coverage))
794 CmdArgs.push_back("-femit-coverage-notes");
795 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
797 Args.hasArg(options::OPT_coverage))
798 CmdArgs.push_back("-femit-coverage-data");
800 if (Args.hasFlag(options::OPT_fcoverage_mapping,
801 options::OPT_fno_coverage_mapping, false)) {
802 if (!ProfileGenerateArg)
803 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
804 << "-fcoverage-mapping"
805 << "-fprofile-instr-generate";
807 CmdArgs.push_back("-fcoverage-mapping");
810 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
811 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
812 if (!Args.hasArg(options::OPT_coverage))
813 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
814 << "-fprofile-exclude-files="
817 StringRef v = Arg->getValue();
819 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
822 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
823 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
824 if (!Args.hasArg(options::OPT_coverage))
825 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
826 << "-fprofile-filter-files="
829 StringRef v = Arg->getValue();
830 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
833 if (C.getArgs().hasArg(options::OPT_c) ||
834 C.getArgs().hasArg(options::OPT_S)) {
835 if (Output.isFilename()) {
836 CmdArgs.push_back("-coverage-notes-file");
837 SmallString<128> OutputFilename;
838 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
839 OutputFilename = FinalOutput->getValue();
841 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
842 SmallString<128> CoverageFilename = OutputFilename;
843 if (llvm::sys::path::is_relative(CoverageFilename)) {
844 SmallString<128> Pwd;
845 if (!llvm::sys::fs::current_path(Pwd)) {
846 llvm::sys::path::append(Pwd, CoverageFilename);
847 CoverageFilename.swap(Pwd);
850 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
851 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
853 // Leave -fprofile-dir= an unused argument unless .gcda emission is
854 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
855 // the flag used. There is no -fno-profile-dir, so the user has no
856 // targeted way to suppress the warning.
857 if (Args.hasArg(options::OPT_fprofile_arcs) ||
858 Args.hasArg(options::OPT_coverage)) {
859 CmdArgs.push_back("-coverage-data-file");
860 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
861 CoverageFilename = FProfileDir->getValue();
862 llvm::sys::path::append(CoverageFilename, OutputFilename);
864 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
865 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
871 /// Check whether the given input tree contains any compilation actions.
872 static bool ContainsCompileAction(const Action *A) {
873 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
876 for (const auto &AI : A->inputs())
877 if (ContainsCompileAction(AI))
883 /// Check if -relax-all should be passed to the internal assembler.
884 /// This is done by default when compiling non-assembler source with -O0.
885 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
886 bool RelaxDefault = true;
888 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
889 RelaxDefault = A->getOption().matches(options::OPT_O0);
892 RelaxDefault = false;
893 for (const auto &Act : C.getActions()) {
894 if (ContainsCompileAction(Act)) {
901 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
905 // Extract the integer N from a string spelled "-dwarf-N", returning 0
906 // on mismatch. The StringRef input (rather than an Arg) allows
907 // for use by the "-Xassembler" option parser.
908 static unsigned DwarfVersionNum(StringRef ArgValue) {
909 return llvm::StringSwitch<unsigned>(ArgValue)
910 .Case("-gdwarf-2", 2)
911 .Case("-gdwarf-3", 3)
912 .Case("-gdwarf-4", 4)
913 .Case("-gdwarf-5", 5)
917 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
918 codegenoptions::DebugInfoKind DebugInfoKind,
919 unsigned DwarfVersion,
920 llvm::DebuggerKind DebuggerTuning) {
921 switch (DebugInfoKind) {
922 case codegenoptions::DebugDirectivesOnly:
923 CmdArgs.push_back("-debug-info-kind=line-directives-only");
925 case codegenoptions::DebugLineTablesOnly:
926 CmdArgs.push_back("-debug-info-kind=line-tables-only");
928 case codegenoptions::LimitedDebugInfo:
929 CmdArgs.push_back("-debug-info-kind=limited");
931 case codegenoptions::FullDebugInfo:
932 CmdArgs.push_back("-debug-info-kind=standalone");
937 if (DwarfVersion > 0)
939 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
940 switch (DebuggerTuning) {
941 case llvm::DebuggerKind::GDB:
942 CmdArgs.push_back("-debugger-tuning=gdb");
944 case llvm::DebuggerKind::LLDB:
945 CmdArgs.push_back("-debugger-tuning=lldb");
947 case llvm::DebuggerKind::SCE:
948 CmdArgs.push_back("-debugger-tuning=sce");
955 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
956 const Driver &D, const ToolChain &TC) {
957 assert(A && "Expected non-nullptr argument.");
958 if (TC.supportsDebugInfoOption(A))
960 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
961 << A->getAsString(Args) << TC.getTripleString();
965 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
966 ArgStringList &CmdArgs,
968 const ToolChain &TC) {
969 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
972 if (checkDebugInfoOption(A, Args, D, TC)) {
973 if (A->getOption().getID() == options::OPT_gz) {
974 if (llvm::zlib::isAvailable())
975 CmdArgs.push_back("-compress-debug-sections");
977 D.Diag(diag::warn_debug_compression_unavailable);
981 StringRef Value = A->getValue();
982 if (Value == "none") {
983 CmdArgs.push_back("-compress-debug-sections=none");
984 } else if (Value == "zlib" || Value == "zlib-gnu") {
985 if (llvm::zlib::isAvailable()) {
987 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
989 D.Diag(diag::warn_debug_compression_unavailable);
992 D.Diag(diag::err_drv_unsupported_option_argument)
993 << A->getOption().getName() << Value;
998 static const char *RelocationModelName(llvm::Reloc::Model Model) {
1000 case llvm::Reloc::Static:
1002 case llvm::Reloc::PIC_:
1004 case llvm::Reloc::DynamicNoPIC:
1005 return "dynamic-no-pic";
1006 case llvm::Reloc::ROPI:
1008 case llvm::Reloc::RWPI:
1010 case llvm::Reloc::ROPI_RWPI:
1013 llvm_unreachable("Unknown Reloc::Model kind");
1016 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1017 const Driver &D, const ArgList &Args,
1018 ArgStringList &CmdArgs,
1019 const InputInfo &Output,
1020 const InputInfoList &Inputs) const {
1022 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1024 CheckPreprocessingOptions(D, Args);
1026 Args.AddLastArg(CmdArgs, options::OPT_C);
1027 Args.AddLastArg(CmdArgs, options::OPT_CC);
1029 // Handle dependency file generation.
1030 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1031 (A = Args.getLastArg(options::OPT_MD)) ||
1032 (A = Args.getLastArg(options::OPT_MMD))) {
1033 // Determine the output location.
1034 const char *DepFile;
1035 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1036 DepFile = MF->getValue();
1037 C.addFailureResultFile(DepFile, &JA);
1038 } else if (Output.getType() == types::TY_Dependencies) {
1039 DepFile = Output.getFilename();
1040 } else if (A->getOption().matches(options::OPT_M) ||
1041 A->getOption().matches(options::OPT_MM)) {
1044 DepFile = getDependencyFileName(Args, Inputs);
1045 C.addFailureResultFile(DepFile, &JA);
1047 CmdArgs.push_back("-dependency-file");
1048 CmdArgs.push_back(DepFile);
1050 // Add a default target if one wasn't specified.
1051 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1052 const char *DepTarget;
1054 // If user provided -o, that is the dependency target, except
1055 // when we are only generating a dependency file.
1056 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1057 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1058 DepTarget = OutputOpt->getValue();
1060 // Otherwise derive from the base input.
1062 // FIXME: This should use the computed output file location.
1063 SmallString<128> P(Inputs[0].getBaseInput());
1064 llvm::sys::path::replace_extension(P, "o");
1065 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1068 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1069 CmdArgs.push_back("-w");
1071 CmdArgs.push_back("-MT");
1072 SmallString<128> Quoted;
1073 QuoteTarget(DepTarget, Quoted);
1074 CmdArgs.push_back(Args.MakeArgString(Quoted));
1077 if (A->getOption().matches(options::OPT_M) ||
1078 A->getOption().matches(options::OPT_MD))
1079 CmdArgs.push_back("-sys-header-deps");
1080 if ((isa<PrecompileJobAction>(JA) &&
1081 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1082 Args.hasArg(options::OPT_fmodule_file_deps))
1083 CmdArgs.push_back("-module-file-deps");
1086 if (Args.hasArg(options::OPT_MG)) {
1087 if (!A || A->getOption().matches(options::OPT_MD) ||
1088 A->getOption().matches(options::OPT_MMD))
1089 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1090 CmdArgs.push_back("-MG");
1093 Args.AddLastArg(CmdArgs, options::OPT_MP);
1094 Args.AddLastArg(CmdArgs, options::OPT_MV);
1096 // Convert all -MQ <target> args to -MT <quoted target>
1097 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1100 if (A->getOption().matches(options::OPT_MQ)) {
1101 CmdArgs.push_back("-MT");
1102 SmallString<128> Quoted;
1103 QuoteTarget(A->getValue(), Quoted);
1104 CmdArgs.push_back(Args.MakeArgString(Quoted));
1106 // -MT flag - no change
1108 A->render(Args, CmdArgs);
1112 // Add offload include arguments specific for CUDA. This must happen before
1113 // we -I or -include anything else, because we must pick up the CUDA headers
1114 // from the particular CUDA installation, rather than from e.g.
1115 // /usr/local/include.
1116 if (JA.isOffloading(Action::OFK_Cuda))
1117 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1119 // Add -i* options, and automatically translate to
1120 // -include-pch/-include-pth for transparent PCH support. It's
1121 // wonky, but we include looking for .gch so we can support seamless
1122 // replacement into a build system already set up to be generating
1125 if (getToolChain().getDriver().IsCLMode()) {
1126 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1127 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1128 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1129 JA.getKind() <= Action::AssembleJobClass) {
1130 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1132 if (YcArg || YuArg) {
1133 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1134 if (!isa<PrecompileJobAction>(JA)) {
1135 CmdArgs.push_back("-include-pch");
1136 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1137 C, !ThroughHeader.empty()
1139 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1142 if (ThroughHeader.empty()) {
1143 CmdArgs.push_back(Args.MakeArgString(
1144 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1147 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1152 bool RenderedImplicitInclude = false;
1153 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1154 if (A->getOption().matches(options::OPT_include)) {
1155 // Handling of gcc-style gch precompiled headers.
1156 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1157 RenderedImplicitInclude = true;
1159 bool FoundPCH = false;
1160 SmallString<128> P(A->getValue());
1161 // We want the files to have a name like foo.h.pch. Add a dummy extension
1162 // so that replace_extension does the right thing.
1164 llvm::sys::path::replace_extension(P, "pch");
1165 if (llvm::sys::fs::exists(P))
1169 llvm::sys::path::replace_extension(P, "gch");
1170 if (llvm::sys::fs::exists(P)) {
1176 if (IsFirstImplicitInclude) {
1178 CmdArgs.push_back("-include-pch");
1179 CmdArgs.push_back(Args.MakeArgString(P));
1182 // Ignore the PCH if not first on command line and emit warning.
1183 D.Diag(diag::warn_drv_pch_not_first_include) << P
1184 << A->getAsString(Args);
1187 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1188 // Handling of paths which must come late. These entries are handled by
1189 // the toolchain itself after the resource dir is inserted in the right
1191 // Do not claim the argument so that the use of the argument does not
1192 // silently go unnoticed on toolchains which do not honour the option.
1196 // Not translated, render as usual.
1198 A->render(Args, CmdArgs);
1201 Args.AddAllArgs(CmdArgs,
1202 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1203 options::OPT_F, options::OPT_index_header_map});
1205 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1207 // FIXME: There is a very unfortunate problem here, some troubled
1208 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1209 // really support that we would have to parse and then translate
1210 // those options. :(
1211 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1212 options::OPT_Xpreprocessor);
1214 // -I- is a deprecated GCC feature, reject it.
1215 if (Arg *A = Args.getLastArg(options::OPT_I_))
1216 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1218 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1219 // -isysroot to the CC1 invocation.
1220 StringRef sysroot = C.getSysRoot();
1221 if (sysroot != "") {
1222 if (!Args.hasArg(options::OPT_isysroot)) {
1223 CmdArgs.push_back("-isysroot");
1224 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1228 // Parse additional include paths from environment variables.
1229 // FIXME: We should probably sink the logic for handling these from the
1230 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1231 // CPATH - included following the user specified includes (but prior to
1232 // builtin and standard includes).
1233 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1234 // C_INCLUDE_PATH - system includes enabled when compiling C.
1235 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1236 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1237 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1238 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1239 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1240 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1241 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1243 // While adding the include arguments, we also attempt to retrieve the
1244 // arguments of related offloading toolchains or arguments that are specific
1245 // of an offloading programming model.
1247 // Add C++ include arguments, if needed.
1248 if (types::isCXX(Inputs[0].getType()))
1249 forAllAssociatedToolChains(C, JA, getToolChain(),
1250 [&Args, &CmdArgs](const ToolChain &TC) {
1251 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1254 // Add system include arguments for all targets but IAMCU.
1256 forAllAssociatedToolChains(C, JA, getToolChain(),
1257 [&Args, &CmdArgs](const ToolChain &TC) {
1258 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1261 // For IAMCU add special include arguments.
1262 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1266 // FIXME: Move to target hook.
1267 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1268 switch (Triple.getArch()) {
1272 case llvm::Triple::aarch64:
1273 case llvm::Triple::aarch64_be:
1274 case llvm::Triple::arm:
1275 case llvm::Triple::armeb:
1276 case llvm::Triple::thumb:
1277 case llvm::Triple::thumbeb:
1278 if (Triple.isOSDarwin() || Triple.isOSWindows())
1282 case llvm::Triple::ppc:
1283 case llvm::Triple::ppc64:
1284 if (Triple.isOSDarwin())
1288 case llvm::Triple::hexagon:
1289 case llvm::Triple::ppc64le:
1290 case llvm::Triple::riscv32:
1291 case llvm::Triple::riscv64:
1292 case llvm::Triple::systemz:
1293 case llvm::Triple::xcore:
1298 static bool isNoCommonDefault(const llvm::Triple &Triple) {
1299 switch (Triple.getArch()) {
1301 if (Triple.isOSFuchsia())
1305 case llvm::Triple::xcore:
1306 case llvm::Triple::wasm32:
1307 case llvm::Triple::wasm64:
1313 void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1314 ArgStringList &CmdArgs) {
1315 // Select the ABI to use.
1316 // FIXME: Support -meabi.
1317 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1318 const char *ABIName = nullptr;
1319 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1320 ABIName = A->getValue();
1322 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1323 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1326 CmdArgs.push_back("-target-abi");
1327 CmdArgs.push_back(ABIName);
1331 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1332 ArgStringList &CmdArgs, bool KernelOrKext) const {
1333 RenderARMABI(Triple, Args, CmdArgs);
1335 // Determine floating point ABI from the options & target defaults.
1336 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1337 if (ABI == arm::FloatABI::Soft) {
1338 // Floating point operations and argument passing are soft.
1339 // FIXME: This changes CPP defines, we need -target-soft-float.
1340 CmdArgs.push_back("-msoft-float");
1341 CmdArgs.push_back("-mfloat-abi");
1342 CmdArgs.push_back("soft");
1343 } else if (ABI == arm::FloatABI::SoftFP) {
1344 // Floating point operations are hard, but argument passing is soft.
1345 CmdArgs.push_back("-mfloat-abi");
1346 CmdArgs.push_back("soft");
1348 // Floating point operations and argument passing are hard.
1349 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1350 CmdArgs.push_back("-mfloat-abi");
1351 CmdArgs.push_back("hard");
1354 // Forward the -mglobal-merge option for explicit control over the pass.
1355 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1356 options::OPT_mno_global_merge)) {
1357 CmdArgs.push_back("-mllvm");
1358 if (A->getOption().matches(options::OPT_mno_global_merge))
1359 CmdArgs.push_back("-arm-global-merge=false");
1361 CmdArgs.push_back("-arm-global-merge=true");
1364 if (!Args.hasFlag(options::OPT_mimplicit_float,
1365 options::OPT_mno_implicit_float, true))
1366 CmdArgs.push_back("-no-implicit-float");
1369 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1370 const ArgList &Args, bool KernelOrKext,
1371 ArgStringList &CmdArgs) const {
1372 const ToolChain &TC = getToolChain();
1374 // Add the target features
1375 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1377 // Add target specific flags.
1378 switch (TC.getArch()) {
1382 case llvm::Triple::arm:
1383 case llvm::Triple::armeb:
1384 case llvm::Triple::thumb:
1385 case llvm::Triple::thumbeb:
1386 // Use the effective triple, which takes into account the deployment target.
1387 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1388 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1391 case llvm::Triple::aarch64:
1392 case llvm::Triple::aarch64_be:
1393 AddAArch64TargetArgs(Args, CmdArgs);
1394 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1397 case llvm::Triple::mips:
1398 case llvm::Triple::mipsel:
1399 case llvm::Triple::mips64:
1400 case llvm::Triple::mips64el:
1401 AddMIPSTargetArgs(Args, CmdArgs);
1404 case llvm::Triple::ppc:
1405 case llvm::Triple::ppc64:
1406 case llvm::Triple::ppc64le:
1407 AddPPCTargetArgs(Args, CmdArgs);
1410 case llvm::Triple::riscv32:
1411 case llvm::Triple::riscv64:
1412 AddRISCVTargetArgs(Args, CmdArgs);
1415 case llvm::Triple::sparc:
1416 case llvm::Triple::sparcel:
1417 case llvm::Triple::sparcv9:
1418 AddSparcTargetArgs(Args, CmdArgs);
1421 case llvm::Triple::systemz:
1422 AddSystemZTargetArgs(Args, CmdArgs);
1425 case llvm::Triple::x86:
1426 case llvm::Triple::x86_64:
1427 AddX86TargetArgs(Args, CmdArgs);
1430 case llvm::Triple::lanai:
1431 AddLanaiTargetArgs(Args, CmdArgs);
1434 case llvm::Triple::hexagon:
1435 AddHexagonTargetArgs(Args, CmdArgs);
1438 case llvm::Triple::wasm32:
1439 case llvm::Triple::wasm64:
1440 AddWebAssemblyTargetArgs(Args, CmdArgs);
1445 // Parse -mbranch-protection=<protection>[+<protection>]* where
1446 // <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1447 // Returns a triple of (return address signing Scope, signing key, require
1449 static std::tuple<StringRef, StringRef, bool>
1450 ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1452 StringRef Scope = "none";
1453 StringRef Key = "a_key";
1454 bool IndirectBranches = false;
1456 StringRef Value = A->getValue();
1457 // This maps onto -mbranch-protection=<scope>+<key>
1459 if (Value.equals("standard")) {
1462 IndirectBranches = true;
1464 } else if (!Value.equals("none")) {
1465 SmallVector<StringRef, 4> BranchProtection;
1466 StringRef(A->getValue()).split(BranchProtection, '+');
1468 auto Protection = BranchProtection.begin();
1469 while (Protection != BranchProtection.end()) {
1470 if (Protection->equals("bti"))
1471 IndirectBranches = true;
1472 else if (Protection->equals("pac-ret")) {
1474 while (++Protection != BranchProtection.end()) {
1475 // Inner loop as "leaf" and "b-key" options must only appear attached
1477 if (Protection->equals("leaf"))
1479 else if (Protection->equals("b-key"))
1486 D.Diag(diag::err_invalid_branch_protection)
1487 << *Protection << A->getAsString(Args);
1492 return std::make_tuple(Scope, Key, IndirectBranches);
1496 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1497 ArgStringList &CmdArgs) {
1498 const char *ABIName = nullptr;
1499 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1500 ABIName = A->getValue();
1501 else if (Triple.isOSDarwin())
1502 ABIName = "darwinpcs";
1506 CmdArgs.push_back("-target-abi");
1507 CmdArgs.push_back(ABIName);
1511 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1512 ArgStringList &CmdArgs) const {
1513 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1515 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1516 Args.hasArg(options::OPT_mkernel) ||
1517 Args.hasArg(options::OPT_fapple_kext))
1518 CmdArgs.push_back("-disable-red-zone");
1520 if (!Args.hasFlag(options::OPT_mimplicit_float,
1521 options::OPT_mno_implicit_float, true))
1522 CmdArgs.push_back("-no-implicit-float");
1524 RenderAArch64ABI(Triple, Args, CmdArgs);
1526 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1527 options::OPT_mno_fix_cortex_a53_835769)) {
1528 CmdArgs.push_back("-mllvm");
1529 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1530 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1532 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1533 } else if (Triple.isAndroid()) {
1534 // Enabled A53 errata (835769) workaround by default on android
1535 CmdArgs.push_back("-mllvm");
1536 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1539 // Forward the -mglobal-merge option for explicit control over the pass.
1540 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1541 options::OPT_mno_global_merge)) {
1542 CmdArgs.push_back("-mllvm");
1543 if (A->getOption().matches(options::OPT_mno_global_merge))
1544 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1546 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1549 // Enable/disable return address signing and indirect branch targets.
1550 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1551 options::OPT_mbranch_protection_EQ)) {
1553 const Driver &D = getToolChain().getDriver();
1555 StringRef Scope, Key;
1556 bool IndirectBranches;
1558 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1559 Scope = A->getValue();
1560 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1561 !Scope.equals("all"))
1562 D.Diag(diag::err_invalid_branch_protection)
1563 << Scope << A->getAsString(Args);
1565 IndirectBranches = false;
1567 std::tie(Scope, Key, IndirectBranches) =
1568 ParseAArch64BranchProtection(D, Args, A);
1571 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1573 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1574 if (IndirectBranches)
1575 CmdArgs.push_back("-mbranch-target-enforce");
1579 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1580 ArgStringList &CmdArgs) const {
1581 const Driver &D = getToolChain().getDriver();
1584 const llvm::Triple &Triple = getToolChain().getTriple();
1585 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1587 CmdArgs.push_back("-target-abi");
1588 CmdArgs.push_back(ABIName.data());
1590 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1591 if (ABI == mips::FloatABI::Soft) {
1592 // Floating point operations and argument passing are soft.
1593 CmdArgs.push_back("-msoft-float");
1594 CmdArgs.push_back("-mfloat-abi");
1595 CmdArgs.push_back("soft");
1597 // Floating point operations and argument passing are hard.
1598 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1599 CmdArgs.push_back("-mfloat-abi");
1600 CmdArgs.push_back("hard");
1603 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1604 if (A->getOption().matches(options::OPT_mxgot)) {
1605 CmdArgs.push_back("-mllvm");
1606 CmdArgs.push_back("-mxgot");
1610 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1611 options::OPT_mno_ldc1_sdc1)) {
1612 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1613 CmdArgs.push_back("-mllvm");
1614 CmdArgs.push_back("-mno-ldc1-sdc1");
1618 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1619 options::OPT_mno_check_zero_division)) {
1620 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1621 CmdArgs.push_back("-mllvm");
1622 CmdArgs.push_back("-mno-check-zero-division");
1626 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1627 StringRef v = A->getValue();
1628 CmdArgs.push_back("-mllvm");
1629 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1633 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1635 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1637 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1638 // -mgpopt is the default for static, -fno-pic environments but these two
1639 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1640 // the only case where -mllvm -mgpopt is passed.
1641 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1642 // passed explicitly when compiling something with -mabicalls
1643 // (implictly) in affect. Currently the warning is in the backend.
1645 // When the ABI in use is N64, we also need to determine the PIC mode that
1646 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1648 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1650 llvm::Reloc::Model RelocationModel;
1653 std::tie(RelocationModel, PICLevel, IsPIE) =
1654 ParsePICArgs(getToolChain(), Args);
1656 NoABICalls = NoABICalls ||
1657 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1659 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1660 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1661 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1662 CmdArgs.push_back("-mllvm");
1663 CmdArgs.push_back("-mgpopt");
1665 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1666 options::OPT_mno_local_sdata);
1667 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1668 options::OPT_mno_extern_sdata);
1669 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1670 options::OPT_mno_embedded_data);
1672 CmdArgs.push_back("-mllvm");
1673 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1674 CmdArgs.push_back("-mlocal-sdata=1");
1676 CmdArgs.push_back("-mlocal-sdata=0");
1678 LocalSData->claim();
1682 CmdArgs.push_back("-mllvm");
1683 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1684 CmdArgs.push_back("-mextern-sdata=1");
1686 CmdArgs.push_back("-mextern-sdata=0");
1688 ExternSData->claim();
1692 CmdArgs.push_back("-mllvm");
1693 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1694 CmdArgs.push_back("-membedded-data=1");
1696 CmdArgs.push_back("-membedded-data=0");
1698 EmbeddedData->claim();
1701 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1702 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1707 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1708 StringRef Val = StringRef(A->getValue());
1709 if (mips::hasCompactBranches(CPUName)) {
1710 if (Val == "never" || Val == "always" || Val == "optimal") {
1711 CmdArgs.push_back("-mllvm");
1712 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1714 D.Diag(diag::err_drv_unsupported_option_argument)
1715 << A->getOption().getName() << Val;
1717 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1720 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1721 options::OPT_mno_relax_pic_calls)) {
1722 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1723 CmdArgs.push_back("-mllvm");
1724 CmdArgs.push_back("-mips-jalr-reloc=0");
1729 void Clang::AddPPCTargetArgs(const ArgList &Args,
1730 ArgStringList &CmdArgs) const {
1731 // Select the ABI to use.
1732 const char *ABIName = nullptr;
1733 if (getToolChain().getTriple().isOSLinux())
1734 switch (getToolChain().getArch()) {
1735 case llvm::Triple::ppc64: {
1736 // When targeting a processor that supports QPX, or if QPX is
1737 // specifically enabled, default to using the ABI that supports QPX (so
1738 // long as it is not specifically disabled).
1739 bool HasQPX = false;
1740 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1741 HasQPX = A->getValue() == StringRef("a2q");
1742 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1744 ABIName = "elfv1-qpx";
1751 case llvm::Triple::ppc64le:
1758 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1759 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1760 // the option if given as we don't have backend support for any targets
1761 // that don't use the altivec abi.
1762 if (StringRef(A->getValue()) != "altivec")
1763 ABIName = A->getValue();
1765 ppc::FloatABI FloatABI =
1766 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1768 if (FloatABI == ppc::FloatABI::Soft) {
1769 // Floating point operations and argument passing are soft.
1770 CmdArgs.push_back("-msoft-float");
1771 CmdArgs.push_back("-mfloat-abi");
1772 CmdArgs.push_back("soft");
1774 // Floating point operations and argument passing are hard.
1775 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1776 CmdArgs.push_back("-mfloat-abi");
1777 CmdArgs.push_back("hard");
1781 CmdArgs.push_back("-target-abi");
1782 CmdArgs.push_back(ABIName);
1786 void Clang::AddRISCVTargetArgs(const ArgList &Args,
1787 ArgStringList &CmdArgs) const {
1788 // FIXME: currently defaults to the soft-float ABIs. Will need to be
1789 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
1790 const char *ABIName = nullptr;
1791 const llvm::Triple &Triple = getToolChain().getTriple();
1792 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1793 ABIName = A->getValue();
1794 else if (Triple.getArch() == llvm::Triple::riscv32)
1796 else if (Triple.getArch() == llvm::Triple::riscv64)
1799 llvm_unreachable("Unexpected triple!");
1801 CmdArgs.push_back("-target-abi");
1802 CmdArgs.push_back(ABIName);
1805 void Clang::AddSparcTargetArgs(const ArgList &Args,
1806 ArgStringList &CmdArgs) const {
1807 sparc::FloatABI FloatABI =
1808 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1810 if (FloatABI == sparc::FloatABI::Soft) {
1811 // Floating point operations and argument passing are soft.
1812 CmdArgs.push_back("-msoft-float");
1813 CmdArgs.push_back("-mfloat-abi");
1814 CmdArgs.push_back("soft");
1816 // Floating point operations and argument passing are hard.
1817 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1818 CmdArgs.push_back("-mfloat-abi");
1819 CmdArgs.push_back("hard");
1823 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1824 ArgStringList &CmdArgs) const {
1825 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1826 CmdArgs.push_back("-mbackchain");
1829 void Clang::AddX86TargetArgs(const ArgList &Args,
1830 ArgStringList &CmdArgs) const {
1831 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1832 Args.hasArg(options::OPT_mkernel) ||
1833 Args.hasArg(options::OPT_fapple_kext))
1834 CmdArgs.push_back("-disable-red-zone");
1836 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1837 options::OPT_mno_tls_direct_seg_refs, true))
1838 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1840 // Default to avoid implicit floating-point for kernel/kext code, but allow
1841 // that to be overridden with -mno-soft-float.
1842 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1843 Args.hasArg(options::OPT_fapple_kext));
1844 if (Arg *A = Args.getLastArg(
1845 options::OPT_msoft_float, options::OPT_mno_soft_float,
1846 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1847 const Option &O = A->getOption();
1848 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1849 O.matches(options::OPT_msoft_float));
1851 if (NoImplicitFloat)
1852 CmdArgs.push_back("-no-implicit-float");
1854 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1855 StringRef Value = A->getValue();
1856 if (Value == "intel" || Value == "att") {
1857 CmdArgs.push_back("-mllvm");
1858 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1860 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1861 << A->getOption().getName() << Value;
1863 } else if (getToolChain().getDriver().IsCLMode()) {
1864 CmdArgs.push_back("-mllvm");
1865 CmdArgs.push_back("-x86-asm-syntax=intel");
1868 // Set flags to support MCU ABI.
1869 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1870 CmdArgs.push_back("-mfloat-abi");
1871 CmdArgs.push_back("soft");
1872 CmdArgs.push_back("-mstack-alignment=4");
1876 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1877 ArgStringList &CmdArgs) const {
1878 CmdArgs.push_back("-mqdsp6-compat");
1879 CmdArgs.push_back("-Wreturn-type");
1881 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1882 CmdArgs.push_back("-mllvm");
1883 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1884 Twine(G.getValue())));
1887 if (!Args.hasArg(options::OPT_fno_short_enums))
1888 CmdArgs.push_back("-fshort-enums");
1889 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1890 CmdArgs.push_back("-mllvm");
1891 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1893 CmdArgs.push_back("-mllvm");
1894 CmdArgs.push_back("-machine-sink-split=0");
1897 void Clang::AddLanaiTargetArgs(const ArgList &Args,
1898 ArgStringList &CmdArgs) const {
1899 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1900 StringRef CPUName = A->getValue();
1902 CmdArgs.push_back("-target-cpu");
1903 CmdArgs.push_back(Args.MakeArgString(CPUName));
1905 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1906 StringRef Value = A->getValue();
1907 // Only support mregparm=4 to support old usage. Report error for all other
1910 if (Value.getAsInteger(10, Mregparm)) {
1911 if (Mregparm != 4) {
1912 getToolChain().getDriver().Diag(
1913 diag::err_drv_unsupported_option_argument)
1914 << A->getOption().getName() << Value;
1920 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1921 ArgStringList &CmdArgs) const {
1922 // Default to "hidden" visibility.
1923 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1924 options::OPT_fvisibility_ms_compat)) {
1925 CmdArgs.push_back("-fvisibility");
1926 CmdArgs.push_back("hidden");
1930 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1931 StringRef Target, const InputInfo &Output,
1932 const InputInfo &Input, const ArgList &Args) const {
1933 // If this is a dry run, do not create the compilation database file.
1934 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1937 using llvm::yaml::escape;
1938 const Driver &D = getToolChain().getDriver();
1940 if (!CompilationDatabase) {
1942 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1944 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1948 CompilationDatabase = std::move(File);
1950 auto &CDB = *CompilationDatabase;
1951 SmallString<128> Buf;
1952 if (llvm::sys::fs::current_path(Buf))
1954 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1955 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1956 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1957 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1959 Buf += types::getTypeName(Input.getType());
1960 CDB << ", \"" << escape(Buf) << "\"";
1961 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1964 CDB << ", \"" << escape(Buf) << "\"";
1966 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1967 for (auto &A: Args) {
1968 auto &O = A->getOption();
1969 // Skip language selection, which is positional.
1970 if (O.getID() == options::OPT_x)
1972 // Skip writing dependency output and the compilation database itself.
1973 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1976 if (O.getKind() == Option::InputClass)
1978 // All other arguments are quoted and appended.
1980 A->render(Args, ASL);
1982 CDB << ", \"" << escape(it) << "\"";
1986 CDB << ", \"" << escape(Buf) << "\"]},\n";
1989 static void CollectArgsForIntegratedAssembler(Compilation &C,
1990 const ArgList &Args,
1991 ArgStringList &CmdArgs,
1993 if (UseRelaxAll(C, Args))
1994 CmdArgs.push_back("-mrelax-all");
1996 // Only default to -mincremental-linker-compatible if we think we are
1997 // targeting the MSVC linker.
1998 bool DefaultIncrementalLinkerCompatible =
1999 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2000 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2001 options::OPT_mno_incremental_linker_compatible,
2002 DefaultIncrementalLinkerCompatible))
2003 CmdArgs.push_back("-mincremental-linker-compatible");
2005 switch (C.getDefaultToolChain().getArch()) {
2006 case llvm::Triple::arm:
2007 case llvm::Triple::armeb:
2008 case llvm::Triple::thumb:
2009 case llvm::Triple::thumbeb:
2010 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2011 StringRef Value = A->getValue();
2012 if (Value == "always" || Value == "never" || Value == "arm" ||
2014 CmdArgs.push_back("-mllvm");
2015 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2017 D.Diag(diag::err_drv_unsupported_option_argument)
2018 << A->getOption().getName() << Value;
2026 // When passing -I arguments to the assembler we sometimes need to
2027 // unconditionally take the next argument. For example, when parsing
2028 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2029 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2030 // arg after parsing the '-I' arg.
2031 bool TakeNextArg = false;
2033 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2034 const char *MipsTargetFeature = nullptr;
2036 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2039 for (StringRef Value : A->getValues()) {
2041 CmdArgs.push_back(Value.data());
2042 TakeNextArg = false;
2046 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2047 Value == "-mbig-obj")
2048 continue; // LLVM handles bigobj automatically
2050 switch (C.getDefaultToolChain().getArch()) {
2053 case llvm::Triple::thumb:
2054 case llvm::Triple::thumbeb:
2055 case llvm::Triple::arm:
2056 case llvm::Triple::armeb:
2057 if (Value == "-mthumb")
2058 // -mthumb has already been processed in ComputeLLVMTriple()
2059 // recognize but skip over here.
2062 case llvm::Triple::mips:
2063 case llvm::Triple::mipsel:
2064 case llvm::Triple::mips64:
2065 case llvm::Triple::mips64el:
2066 if (Value == "--trap") {
2067 CmdArgs.push_back("-target-feature");
2068 CmdArgs.push_back("+use-tcc-in-div");
2071 if (Value == "--break") {
2072 CmdArgs.push_back("-target-feature");
2073 CmdArgs.push_back("-use-tcc-in-div");
2076 if (Value.startswith("-msoft-float")) {
2077 CmdArgs.push_back("-target-feature");
2078 CmdArgs.push_back("+soft-float");
2081 if (Value.startswith("-mhard-float")) {
2082 CmdArgs.push_back("-target-feature");
2083 CmdArgs.push_back("-soft-float");
2087 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2088 .Case("-mips1", "+mips1")
2089 .Case("-mips2", "+mips2")
2090 .Case("-mips3", "+mips3")
2091 .Case("-mips4", "+mips4")
2092 .Case("-mips5", "+mips5")
2093 .Case("-mips32", "+mips32")
2094 .Case("-mips32r2", "+mips32r2")
2095 .Case("-mips32r3", "+mips32r3")
2096 .Case("-mips32r5", "+mips32r5")
2097 .Case("-mips32r6", "+mips32r6")
2098 .Case("-mips64", "+mips64")
2099 .Case("-mips64r2", "+mips64r2")
2100 .Case("-mips64r3", "+mips64r3")
2101 .Case("-mips64r5", "+mips64r5")
2102 .Case("-mips64r6", "+mips64r6")
2104 if (MipsTargetFeature)
2108 if (Value == "-force_cpusubtype_ALL") {
2109 // Do nothing, this is the default and we don't support anything else.
2110 } else if (Value == "-L") {
2111 CmdArgs.push_back("-msave-temp-labels");
2112 } else if (Value == "--fatal-warnings") {
2113 CmdArgs.push_back("-massembler-fatal-warnings");
2114 } else if (Value == "--noexecstack") {
2115 CmdArgs.push_back("-mnoexecstack");
2116 } else if (Value.startswith("-compress-debug-sections") ||
2117 Value.startswith("--compress-debug-sections") ||
2118 Value == "-nocompress-debug-sections" ||
2119 Value == "--nocompress-debug-sections") {
2120 CmdArgs.push_back(Value.data());
2121 } else if (Value == "-mrelax-relocations=yes" ||
2122 Value == "--mrelax-relocations=yes") {
2123 UseRelaxRelocations = true;
2124 } else if (Value == "-mrelax-relocations=no" ||
2125 Value == "--mrelax-relocations=no") {
2126 UseRelaxRelocations = false;
2127 } else if (Value.startswith("-I")) {
2128 CmdArgs.push_back(Value.data());
2129 // We need to consume the next argument if the current arg is a plain
2130 // -I. The next arg will be the include directory.
2133 } else if (Value.startswith("-gdwarf-")) {
2134 // "-gdwarf-N" options are not cc1as options.
2135 unsigned DwarfVersion = DwarfVersionNum(Value);
2136 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2137 CmdArgs.push_back(Value.data());
2139 RenderDebugEnablingArgs(Args, CmdArgs,
2140 codegenoptions::LimitedDebugInfo,
2141 DwarfVersion, llvm::DebuggerKind::Default);
2143 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2144 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2145 // Do nothing, we'll validate it later.
2146 } else if (Value == "-defsym") {
2147 if (A->getNumValues() != 2) {
2148 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2151 const char *S = A->getValue(1);
2152 auto Pair = StringRef(S).split('=');
2153 auto Sym = Pair.first;
2154 auto SVal = Pair.second;
2156 if (Sym.empty() || SVal.empty()) {
2157 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2161 if (SVal.getAsInteger(0, IVal)) {
2162 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2165 CmdArgs.push_back(Value.data());
2167 } else if (Value == "-fdebug-compilation-dir") {
2168 CmdArgs.push_back("-fdebug-compilation-dir");
2171 D.Diag(diag::err_drv_unsupported_option_argument)
2172 << A->getOption().getName() << Value;
2176 if (UseRelaxRelocations)
2177 CmdArgs.push_back("--mrelax-relocations");
2178 if (MipsTargetFeature != nullptr) {
2179 CmdArgs.push_back("-target-feature");
2180 CmdArgs.push_back(MipsTargetFeature);
2183 // forward -fembed-bitcode to assmebler
2184 if (C.getDriver().embedBitcodeEnabled() ||
2185 C.getDriver().embedBitcodeMarkerOnly())
2186 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2189 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2190 bool OFastEnabled, const ArgList &Args,
2191 ArgStringList &CmdArgs) {
2192 // Handle various floating point optimization flags, mapping them to the
2193 // appropriate LLVM code generation flags. This is complicated by several
2194 // "umbrella" flags, so we do this by stepping through the flags incrementally
2195 // adjusting what we think is enabled/disabled, then at the end setting the
2196 // LLVM flags based on the final state.
2197 bool HonorINFs = true;
2198 bool HonorNaNs = true;
2199 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2200 bool MathErrno = TC.IsMathErrnoDefault();
2201 bool AssociativeMath = false;
2202 bool ReciprocalMath = false;
2203 bool SignedZeros = true;
2204 bool TrappingMath = true;
2205 StringRef DenormalFPMath = "";
2206 StringRef FPContract = "";
2208 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2209 CmdArgs.push_back("-mlimit-float-precision");
2210 CmdArgs.push_back(A->getValue());
2213 for (const Arg *A : Args) {
2214 switch (A->getOption().getID()) {
2215 // If this isn't an FP option skip the claim below
2218 // Options controlling individual features
2219 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2220 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2221 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2222 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2223 case options::OPT_fmath_errno: MathErrno = true; break;
2224 case options::OPT_fno_math_errno: MathErrno = false; break;
2225 case options::OPT_fassociative_math: AssociativeMath = true; break;
2226 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2227 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2228 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2229 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2230 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2231 case options::OPT_ftrapping_math: TrappingMath = true; break;
2232 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2234 case options::OPT_fdenormal_fp_math_EQ:
2235 DenormalFPMath = A->getValue();
2238 // Validate and pass through -fp-contract option.
2239 case options::OPT_ffp_contract: {
2240 StringRef Val = A->getValue();
2241 if (Val == "fast" || Val == "on" || Val == "off")
2244 D.Diag(diag::err_drv_unsupported_option_argument)
2245 << A->getOption().getName() << Val;
2249 case options::OPT_ffinite_math_only:
2253 case options::OPT_fno_finite_math_only:
2258 case options::OPT_funsafe_math_optimizations:
2259 AssociativeMath = true;
2260 ReciprocalMath = true;
2261 SignedZeros = false;
2262 TrappingMath = false;
2264 case options::OPT_fno_unsafe_math_optimizations:
2265 AssociativeMath = false;
2266 ReciprocalMath = false;
2268 TrappingMath = true;
2269 // -fno_unsafe_math_optimizations restores default denormal handling
2270 DenormalFPMath = "";
2273 case options::OPT_Ofast:
2274 // If -Ofast is the optimization level, then -ffast-math should be enabled
2278 case options::OPT_ffast_math:
2282 AssociativeMath = true;
2283 ReciprocalMath = true;
2284 SignedZeros = false;
2285 TrappingMath = false;
2286 // If fast-math is set then set the fp-contract mode to fast.
2287 FPContract = "fast";
2289 case options::OPT_fno_fast_math:
2292 // Turning on -ffast-math (with either flag) removes the need for
2293 // MathErrno. However, turning *off* -ffast-math merely restores the
2294 // toolchain default (which may be false).
2295 MathErrno = TC.IsMathErrnoDefault();
2296 AssociativeMath = false;
2297 ReciprocalMath = false;
2299 TrappingMath = true;
2300 // -fno_fast_math restores default denormal and fpcontract handling
2301 DenormalFPMath = "";
2306 // If we handled this option claim it
2311 CmdArgs.push_back("-menable-no-infs");
2314 CmdArgs.push_back("-menable-no-nans");
2317 CmdArgs.push_back("-fmath-errno");
2319 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2321 CmdArgs.push_back("-menable-unsafe-fp-math");
2324 CmdArgs.push_back("-fno-signed-zeros");
2326 if (AssociativeMath && !SignedZeros && !TrappingMath)
2327 CmdArgs.push_back("-mreassociate");
2330 CmdArgs.push_back("-freciprocal-math");
2333 CmdArgs.push_back("-fno-trapping-math");
2335 if (!DenormalFPMath.empty())
2337 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2339 if (!FPContract.empty())
2340 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2342 ParseMRecip(D, Args, CmdArgs);
2344 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2345 // individual features enabled by -ffast-math instead of the option itself as
2346 // that's consistent with gcc's behaviour.
2347 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2348 ReciprocalMath && !SignedZeros && !TrappingMath)
2349 CmdArgs.push_back("-ffast-math");
2351 // Handle __FINITE_MATH_ONLY__ similarly.
2352 if (!HonorINFs && !HonorNaNs)
2353 CmdArgs.push_back("-ffinite-math-only");
2355 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2356 CmdArgs.push_back("-mfpmath");
2357 CmdArgs.push_back(A->getValue());
2360 // Disable a codegen optimization for floating-point casts.
2361 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2362 options::OPT_fstrict_float_cast_overflow, false))
2363 CmdArgs.push_back("-fno-strict-float-cast-overflow");
2366 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2367 const llvm::Triple &Triple,
2368 const InputInfo &Input) {
2369 // Enable region store model by default.
2370 CmdArgs.push_back("-analyzer-store=region");
2372 // Treat blocks as analysis entry points.
2373 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2375 // Add default argument set.
2376 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2377 CmdArgs.push_back("-analyzer-checker=core");
2378 CmdArgs.push_back("-analyzer-checker=apiModeling");
2380 if (!Triple.isWindowsMSVCEnvironment()) {
2381 CmdArgs.push_back("-analyzer-checker=unix");
2383 // Enable "unix" checkers that also work on Windows.
2384 CmdArgs.push_back("-analyzer-checker=unix.API");
2385 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2386 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2387 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2388 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2389 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2392 // Disable some unix checkers for PS4.
2393 if (Triple.isPS4CPU()) {
2394 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2395 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2398 if (Triple.isOSDarwin())
2399 CmdArgs.push_back("-analyzer-checker=osx");
2401 CmdArgs.push_back("-analyzer-checker=deadcode");
2403 if (types::isCXX(Input.getType()))
2404 CmdArgs.push_back("-analyzer-checker=cplusplus");
2406 if (!Triple.isPS4CPU()) {
2407 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2408 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2409 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2410 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2411 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2412 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2415 // Default nullability checks.
2416 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2417 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2420 // Set the output format. The default is plist, for (lame) historical reasons.
2421 CmdArgs.push_back("-analyzer-output");
2422 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2423 CmdArgs.push_back(A->getValue());
2425 CmdArgs.push_back("plist");
2427 // Disable the presentation of standard compiler warnings when using
2428 // --analyze. We only want to show static analyzer diagnostics or frontend
2430 CmdArgs.push_back("-w");
2432 // Add -Xanalyzer arguments when running as analyzer.
2433 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2436 static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
2437 ArgStringList &CmdArgs, bool KernelOrKext) {
2438 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2440 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2441 // doesn't even have a stack!
2442 if (EffectiveTriple.isNVPTX())
2445 // -stack-protector=0 is default.
2446 unsigned StackProtectorLevel = 0;
2447 unsigned DefaultStackProtectorLevel =
2448 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2450 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2451 options::OPT_fstack_protector_all,
2452 options::OPT_fstack_protector_strong,
2453 options::OPT_fstack_protector)) {
2454 if (A->getOption().matches(options::OPT_fstack_protector))
2455 StackProtectorLevel =
2456 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2457 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2458 StackProtectorLevel = LangOptions::SSPStrong;
2459 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2460 StackProtectorLevel = LangOptions::SSPReq;
2462 StackProtectorLevel = DefaultStackProtectorLevel;
2465 if (StackProtectorLevel) {
2466 CmdArgs.push_back("-stack-protector");
2467 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2470 // --param ssp-buffer-size=
2471 for (const Arg *A : Args.filtered(options::OPT__param)) {
2472 StringRef Str(A->getValue());
2473 if (Str.startswith("ssp-buffer-size=")) {
2474 if (StackProtectorLevel) {
2475 CmdArgs.push_back("-stack-protector-buffer-size");
2476 // FIXME: Verify the argument is a valid integer.
2477 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2484 static void RenderTrivialAutoVarInitOptions(const Driver &D,
2485 const ToolChain &TC,
2486 const ArgList &Args,
2487 ArgStringList &CmdArgs) {
2488 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2489 StringRef TrivialAutoVarInit = "";
2491 for (const Arg *A : Args) {
2492 switch (A->getOption().getID()) {
2495 case options::OPT_ftrivial_auto_var_init: {
2497 StringRef Val = A->getValue();
2498 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2499 TrivialAutoVarInit = Val;
2501 D.Diag(diag::err_drv_unsupported_option_argument)
2502 << A->getOption().getName() << Val;
2508 if (TrivialAutoVarInit.empty())
2509 switch (DefaultTrivialAutoVarInit) {
2510 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2512 case LangOptions::TrivialAutoVarInitKind::Pattern:
2513 TrivialAutoVarInit = "pattern";
2515 case LangOptions::TrivialAutoVarInitKind::Zero:
2516 TrivialAutoVarInit = "zero";
2520 if (!TrivialAutoVarInit.empty()) {
2521 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2522 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2524 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2528 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2529 const unsigned ForwardedArguments[] = {
2530 options::OPT_cl_opt_disable,
2531 options::OPT_cl_strict_aliasing,
2532 options::OPT_cl_single_precision_constant,
2533 options::OPT_cl_finite_math_only,
2534 options::OPT_cl_kernel_arg_info,
2535 options::OPT_cl_unsafe_math_optimizations,
2536 options::OPT_cl_fast_relaxed_math,
2537 options::OPT_cl_mad_enable,
2538 options::OPT_cl_no_signed_zeros,
2539 options::OPT_cl_denorms_are_zero,
2540 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2541 options::OPT_cl_uniform_work_group_size
2544 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2545 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2546 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2549 for (const auto &Arg : ForwardedArguments)
2550 if (const auto *A = Args.getLastArg(Arg))
2551 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2554 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2555 ArgStringList &CmdArgs) {
2556 bool ARCMTEnabled = false;
2557 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2558 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2559 options::OPT_ccc_arcmt_modify,
2560 options::OPT_ccc_arcmt_migrate)) {
2561 ARCMTEnabled = true;
2562 switch (A->getOption().getID()) {
2563 default: llvm_unreachable("missed a case");
2564 case options::OPT_ccc_arcmt_check:
2565 CmdArgs.push_back("-arcmt-check");
2567 case options::OPT_ccc_arcmt_modify:
2568 CmdArgs.push_back("-arcmt-modify");
2570 case options::OPT_ccc_arcmt_migrate:
2571 CmdArgs.push_back("-arcmt-migrate");
2572 CmdArgs.push_back("-mt-migrate-directory");
2573 CmdArgs.push_back(A->getValue());
2575 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2576 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2581 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2582 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2583 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2586 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2588 D.Diag(diag::err_drv_argument_not_allowed_with)
2589 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2591 CmdArgs.push_back("-mt-migrate-directory");
2592 CmdArgs.push_back(A->getValue());
2594 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2595 options::OPT_objcmt_migrate_subscripting,
2596 options::OPT_objcmt_migrate_property)) {
2597 // None specified, means enable them all.
2598 CmdArgs.push_back("-objcmt-migrate-literals");
2599 CmdArgs.push_back("-objcmt-migrate-subscripting");
2600 CmdArgs.push_back("-objcmt-migrate-property");
2602 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2603 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2604 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2607 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2608 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2609 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2610 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2611 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2612 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2613 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2614 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2615 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2616 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2617 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2618 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2619 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2620 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2621 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2622 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2626 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2627 const ArgList &Args, ArgStringList &CmdArgs) {
2628 // -fbuiltin is default unless -mkernel is used.
2630 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2631 !Args.hasArg(options::OPT_mkernel));
2633 CmdArgs.push_back("-fno-builtin");
2635 // -ffreestanding implies -fno-builtin.
2636 if (Args.hasArg(options::OPT_ffreestanding))
2637 UseBuiltins = false;
2639 // Process the -fno-builtin-* options.
2640 for (const auto &Arg : Args) {
2641 const Option &O = Arg->getOption();
2642 if (!O.matches(options::OPT_fno_builtin_))
2647 // If -fno-builtin is specified, then there's no need to pass the option to
2652 StringRef FuncName = Arg->getValue();
2653 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2656 // le32-specific flags:
2657 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2659 if (TC.getArch() == llvm::Triple::le32)
2660 CmdArgs.push_back("-fno-math-builtin");
2663 void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2664 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2665 llvm::sys::path::append(Result, "org.llvm.clang.");
2666 appendUserToPath(Result);
2667 llvm::sys::path::append(Result, "ModuleCache");
2670 static void RenderModulesOptions(Compilation &C, const Driver &D,
2671 const ArgList &Args, const InputInfo &Input,
2672 const InputInfo &Output,
2673 ArgStringList &CmdArgs, bool &HaveModules) {
2674 // -fmodules enables the use of precompiled modules (off by default).
2675 // Users can pass -fno-cxx-modules to turn off modules support for
2676 // C++/Objective-C++ programs.
2677 bool HaveClangModules = false;
2678 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2679 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2680 options::OPT_fno_cxx_modules, true);
2681 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2682 CmdArgs.push_back("-fmodules");
2683 HaveClangModules = true;
2687 HaveModules = HaveClangModules;
2688 if (Args.hasArg(options::OPT_fmodules_ts)) {
2689 CmdArgs.push_back("-fmodules-ts");
2693 // -fmodule-maps enables implicit reading of module map files. By default,
2694 // this is enabled if we are using Clang's flavor of precompiled modules.
2695 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2696 options::OPT_fno_implicit_module_maps, HaveClangModules))
2697 CmdArgs.push_back("-fimplicit-module-maps");
2699 // -fmodules-decluse checks that modules used are declared so (off by default)
2700 if (Args.hasFlag(options::OPT_fmodules_decluse,
2701 options::OPT_fno_modules_decluse, false))
2702 CmdArgs.push_back("-fmodules-decluse");
2704 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2705 // all #included headers are part of modules.
2706 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2707 options::OPT_fno_modules_strict_decluse, false))
2708 CmdArgs.push_back("-fmodules-strict-decluse");
2710 // -fno-implicit-modules turns off implicitly compiling modules on demand.
2711 bool ImplicitModules = false;
2712 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2713 options::OPT_fno_implicit_modules, HaveClangModules)) {
2715 CmdArgs.push_back("-fno-implicit-modules");
2716 } else if (HaveModules) {
2717 ImplicitModules = true;
2718 // -fmodule-cache-path specifies where our implicitly-built module files
2719 // should be written.
2720 SmallString<128> Path;
2721 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2722 Path = A->getValue();
2724 if (C.isForDiagnostics()) {
2725 // When generating crash reports, we want to emit the modules along with
2726 // the reproduction sources, so we ignore any provided module path.
2727 Path = Output.getFilename();
2728 llvm::sys::path::replace_extension(Path, ".cache");
2729 llvm::sys::path::append(Path, "modules");
2730 } else if (Path.empty()) {
2731 // No module path was provided: use the default.
2732 Driver::getDefaultModuleCachePath(Path);
2735 const char Arg[] = "-fmodules-cache-path=";
2736 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2737 CmdArgs.push_back(Args.MakeArgString(Path));
2741 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2742 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2743 CmdArgs.push_back(Args.MakeArgString(
2744 std::string("-fprebuilt-module-path=") + A->getValue()));
2749 // -fmodule-name specifies the module that is currently being built (or
2750 // used for header checking by -fmodule-maps).
2751 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2753 // -fmodule-map-file can be used to specify files containing module
2755 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2757 // -fbuiltin-module-map can be used to load the clang
2758 // builtin headers modulemap file.
2759 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2760 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2761 llvm::sys::path::append(BuiltinModuleMap, "include");
2762 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2763 if (llvm::sys::fs::exists(BuiltinModuleMap))
2765 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2768 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2769 // names to precompiled module files (the module is loaded only if used).
2770 // The -fmodule-file=<file> form can be used to unconditionally load
2771 // precompiled module files (whether used or not).
2773 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2775 Args.ClaimAllArgs(options::OPT_fmodule_file);
2777 // When building modules and generating crashdumps, we need to dump a module
2778 // dependency VFS alongside the output.
2779 if (HaveClangModules && C.isForDiagnostics()) {
2780 SmallString<128> VFSDir(Output.getFilename());
2781 llvm::sys::path::replace_extension(VFSDir, ".cache");
2782 // Add the cache directory as a temp so the crash diagnostics pick it up.
2783 C.addTempFile(Args.MakeArgString(VFSDir));
2785 llvm::sys::path::append(VFSDir, "vfs");
2786 CmdArgs.push_back("-module-dependency-dir");
2787 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2790 if (HaveClangModules)
2791 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2793 // Pass through all -fmodules-ignore-macro arguments.
2794 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2795 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2796 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2798 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2800 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2801 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2802 D.Diag(diag::err_drv_argument_not_allowed_with)
2803 << A->getAsString(Args) << "-fbuild-session-timestamp";
2805 llvm::sys::fs::file_status Status;
2806 if (llvm::sys::fs::status(A->getValue(), Status))
2807 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2809 Args.MakeArgString("-fbuild-session-timestamp=" +
2810 Twine((uint64_t)Status.getLastModificationTime()
2815 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2816 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2817 options::OPT_fbuild_session_file))
2818 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2820 Args.AddLastArg(CmdArgs,
2821 options::OPT_fmodules_validate_once_per_build_session);
2824 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2825 options::OPT_fno_modules_validate_system_headers,
2827 CmdArgs.push_back("-fmodules-validate-system-headers");
2829 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2832 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2833 ArgStringList &CmdArgs) {
2834 // -fsigned-char is default.
2835 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2836 options::OPT_fno_signed_char,
2837 options::OPT_funsigned_char,
2838 options::OPT_fno_unsigned_char)) {
2839 if (A->getOption().matches(options::OPT_funsigned_char) ||
2840 A->getOption().matches(options::OPT_fno_signed_char)) {
2841 CmdArgs.push_back("-fno-signed-char");
2843 } else if (!isSignedCharDefault(T)) {
2844 CmdArgs.push_back("-fno-signed-char");
2847 // The default depends on the language standard.
2849 Args.getLastArg(options::OPT_fchar8__t, options::OPT_fno_char8__t))
2850 A->render(Args, CmdArgs);
2852 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2853 options::OPT_fno_short_wchar)) {
2854 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2855 CmdArgs.push_back("-fwchar-type=short");
2856 CmdArgs.push_back("-fno-signed-wchar");
2858 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
2859 CmdArgs.push_back("-fwchar-type=int");
2860 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2862 CmdArgs.push_back("-fno-signed-wchar");
2864 CmdArgs.push_back("-fsigned-wchar");
2869 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2870 const llvm::Triple &T, const ArgList &Args,
2871 ObjCRuntime &Runtime, bool InferCovariantReturns,
2872 const InputInfo &Input, ArgStringList &CmdArgs) {
2873 const llvm::Triple::ArchType Arch = TC.getArch();
2875 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2876 // is the default. Except for deployment target of 10.5, next runtime is
2877 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2878 if (Runtime.isNonFragile()) {
2879 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2880 options::OPT_fno_objc_legacy_dispatch,
2881 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2882 if (TC.UseObjCMixedDispatch())
2883 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2885 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2889 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2890 // to do Array/Dictionary subscripting by default.
2891 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2892 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2893 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2895 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2896 // NOTE: This logic is duplicated in ToolChains.cpp.
2897 if (isObjCAutoRefCount(Args)) {
2900 CmdArgs.push_back("-fobjc-arc");
2902 // FIXME: It seems like this entire block, and several around it should be
2903 // wrapped in isObjC, but for now we just use it here as this is where it
2904 // was being used previously.
2905 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2906 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2907 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2909 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2912 // Allow the user to enable full exceptions code emission.
2913 // We default off for Objective-C, on for Objective-C++.
2914 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2915 options::OPT_fno_objc_arc_exceptions,
2916 /*default=*/types::isCXX(Input.getType())))
2917 CmdArgs.push_back("-fobjc-arc-exceptions");
2920 // Silence warning for full exception code emission options when explicitly
2921 // set to use no ARC.
2922 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2923 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2924 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2927 // Allow the user to control whether messages can be converted to runtime
2929 if (types::isObjC(Input.getType())) {
2930 auto *Arg = Args.getLastArg(
2931 options::OPT_fobjc_convert_messages_to_runtime_calls,
2932 options::OPT_fno_objc_convert_messages_to_runtime_calls);
2934 Arg->getOption().matches(
2935 options::OPT_fno_objc_convert_messages_to_runtime_calls))
2936 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
2939 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2941 if (InferCovariantReturns)
2942 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2944 // Pass down -fobjc-weak or -fno-objc-weak if present.
2945 if (types::isObjC(Input.getType())) {
2947 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2950 } else if (!Runtime.allowsWeak()) {
2951 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2952 D.Diag(diag::err_objc_weak_unsupported);
2954 WeakArg->render(Args, CmdArgs);
2959 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2960 ArgStringList &CmdArgs) {
2961 bool CaretDefault = true;
2962 bool ColumnDefault = true;
2964 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2965 options::OPT__SLASH_diagnostics_column,
2966 options::OPT__SLASH_diagnostics_caret)) {
2967 switch (A->getOption().getID()) {
2968 case options::OPT__SLASH_diagnostics_caret:
2969 CaretDefault = true;
2970 ColumnDefault = true;
2972 case options::OPT__SLASH_diagnostics_column:
2973 CaretDefault = false;
2974 ColumnDefault = true;
2976 case options::OPT__SLASH_diagnostics_classic:
2977 CaretDefault = false;
2978 ColumnDefault = false;
2983 // -fcaret-diagnostics is default.
2984 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2985 options::OPT_fno_caret_diagnostics, CaretDefault))
2986 CmdArgs.push_back("-fno-caret-diagnostics");
2988 // -fdiagnostics-fixit-info is default, only pass non-default.
2989 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2990 options::OPT_fno_diagnostics_fixit_info))
2991 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2993 // Enable -fdiagnostics-show-option by default.
2994 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2995 options::OPT_fno_diagnostics_show_option))
2996 CmdArgs.push_back("-fdiagnostics-show-option");
2999 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3000 CmdArgs.push_back("-fdiagnostics-show-category");
3001 CmdArgs.push_back(A->getValue());
3004 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3005 options::OPT_fno_diagnostics_show_hotness, false))
3006 CmdArgs.push_back("-fdiagnostics-show-hotness");
3009 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3011 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3012 CmdArgs.push_back(Args.MakeArgString(Opt));
3015 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3016 CmdArgs.push_back("-fdiagnostics-format");
3017 CmdArgs.push_back(A->getValue());
3020 if (const Arg *A = Args.getLastArg(
3021 options::OPT_fdiagnostics_show_note_include_stack,
3022 options::OPT_fno_diagnostics_show_note_include_stack)) {
3023 const Option &O = A->getOption();
3024 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3025 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3027 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3030 // Color diagnostics are parsed by the driver directly from argv and later
3031 // re-parsed to construct this job; claim any possible color diagnostic here
3032 // to avoid warn_drv_unused_argument and diagnose bad
3033 // OPT_fdiagnostics_color_EQ values.
3034 for (const Arg *A : Args) {
3035 const Option &O = A->getOption();
3036 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3037 !O.matches(options::OPT_fdiagnostics_color) &&
3038 !O.matches(options::OPT_fno_color_diagnostics) &&
3039 !O.matches(options::OPT_fno_diagnostics_color) &&
3040 !O.matches(options::OPT_fdiagnostics_color_EQ))
3043 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3044 StringRef Value(A->getValue());
3045 if (Value != "always" && Value != "never" && Value != "auto")
3046 D.Diag(diag::err_drv_clang_unsupported)
3047 << ("-fdiagnostics-color=" + Value).str();
3052 if (D.getDiags().getDiagnosticOptions().ShowColors)
3053 CmdArgs.push_back("-fcolor-diagnostics");
3055 if (Args.hasArg(options::OPT_fansi_escape_codes))
3056 CmdArgs.push_back("-fansi-escape-codes");
3058 if (!Args.hasFlag(options::OPT_fshow_source_location,
3059 options::OPT_fno_show_source_location))
3060 CmdArgs.push_back("-fno-show-source-location");
3062 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3063 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3065 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3067 CmdArgs.push_back("-fno-show-column");
3069 if (!Args.hasFlag(options::OPT_fspell_checking,
3070 options::OPT_fno_spell_checking))
3071 CmdArgs.push_back("-fno-spell-checking");
3074 enum class DwarfFissionKind { None, Split, Single };
3076 static DwarfFissionKind getDebugFissionKind(const Driver &D,
3077 const ArgList &Args, Arg *&Arg) {
3079 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3081 return DwarfFissionKind::None;
3083 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3084 return DwarfFissionKind::Split;
3086 StringRef Value = Arg->getValue();
3087 if (Value == "split")
3088 return DwarfFissionKind::Split;
3089 if (Value == "single")
3090 return DwarfFissionKind::Single;
3092 D.Diag(diag::err_drv_unsupported_option_argument)
3093 << Arg->getOption().getName() << Arg->getValue();
3094 return DwarfFissionKind::None;
3097 static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3098 const llvm::Triple &T, const ArgList &Args,
3099 bool EmitCodeView, bool IsWindowsMSVC,
3100 ArgStringList &CmdArgs,
3101 codegenoptions::DebugInfoKind &DebugInfoKind,
3102 DwarfFissionKind &DwarfFission) {
3103 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3104 options::OPT_fno_debug_info_for_profiling, false) &&
3105 checkDebugInfoOption(
3106 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3107 CmdArgs.push_back("-fdebug-info-for-profiling");
3109 // The 'g' groups options involve a somewhat intricate sequence of decisions
3110 // about what to pass from the driver to the frontend, but by the time they
3111 // reach cc1 they've been factored into three well-defined orthogonal choices:
3112 // * what level of debug info to generate
3113 // * what dwarf version to write
3114 // * what debugger tuning to use
3115 // This avoids having to monkey around further in cc1 other than to disable
3116 // codeview if not running in a Windows environment. Perhaps even that
3117 // decision should be made in the driver as well though.
3118 unsigned DWARFVersion = 0;
3119 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3121 bool SplitDWARFInlining =
3122 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3123 options::OPT_fno_split_dwarf_inlining, true);
3125 Args.ClaimAllArgs(options::OPT_g_Group);
3128 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
3130 if (DwarfFission != DwarfFissionKind::None &&
3131 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3132 DwarfFission = DwarfFissionKind::None;
3133 SplitDWARFInlining = false;
3136 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3137 if (checkDebugInfoOption(A, Args, D, TC)) {
3138 // If the last option explicitly specified a debug-info level, use it.
3139 if (A->getOption().matches(options::OPT_gN_Group)) {
3140 DebugInfoKind = DebugLevelToInfoKind(*A);
3141 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
3142 // But -gsplit-dwarf is not a g_group option, hence we have to check the
3143 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
3144 // This gets a bit more complicated if you've disabled inline info in
3145 // the skeleton CUs (SplitDWARFInlining) - then there's value in
3146 // composing split-dwarf and line-tables-only, so let those compose
3147 // naturally in that case. And if you just turned off debug info,
3148 // (-gsplit-dwarf -g0) - do that.
3149 if (DwarfFission != DwarfFissionKind::None) {
3150 if (A->getIndex() > SplitDWARFArg->getIndex()) {
3151 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3152 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3153 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3154 SplitDWARFInlining))
3155 DwarfFission = DwarfFissionKind::None;
3156 } else if (SplitDWARFInlining)
3157 DebugInfoKind = codegenoptions::NoDebugInfo;
3160 // For any other 'g' option, use Limited.
3161 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3164 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3168 // If a debugger tuning argument appeared, remember it.
3170 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3171 if (checkDebugInfoOption(A, Args, D, TC)) {
3172 if (A->getOption().matches(options::OPT_glldb))
3173 DebuggerTuning = llvm::DebuggerKind::LLDB;
3174 else if (A->getOption().matches(options::OPT_gsce))
3175 DebuggerTuning = llvm::DebuggerKind::SCE;
3177 DebuggerTuning = llvm::DebuggerKind::GDB;
3181 // If a -gdwarf argument appeared, remember it.
3183 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3184 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
3185 if (checkDebugInfoOption(A, Args, D, TC))
3186 DWARFVersion = DwarfVersionNum(A->getSpelling());
3188 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3189 if (checkDebugInfoOption(A, Args, D, TC))
3190 EmitCodeView = true;
3193 // If the user asked for debug info but did not explicitly specify -gcodeview
3194 // or -gdwarf, ask the toolchain for the default format.
3195 if (!EmitCodeView && DWARFVersion == 0 &&
3196 DebugInfoKind != codegenoptions::NoDebugInfo) {
3197 switch (TC.getDefaultDebugFormat()) {
3198 case codegenoptions::DIF_CodeView:
3199 EmitCodeView = true;
3201 case codegenoptions::DIF_DWARF:
3202 DWARFVersion = TC.GetDefaultDwarfVersion();
3207 // -gline-directives-only supported only for the DWARF debug info.
3208 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3209 DebugInfoKind = codegenoptions::NoDebugInfo;
3211 // We ignore flag -gstrict-dwarf for now.
3212 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3213 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3215 // Column info is included by default for everything except SCE and
3216 // CodeView. Clang doesn't track end columns, just starting columns, which,
3217 // in theory, is fine for CodeView (and PDB). In practice, however, the
3218 // Microsoft debuggers don't handle missing end columns well, so it's better
3219 // not to include any column info.
3220 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3221 (void)checkDebugInfoOption(A, Args, D, TC);
3222 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3223 /*Default=*/!EmitCodeView &&
3224 DebuggerTuning != llvm::DebuggerKind::SCE))
3225 CmdArgs.push_back("-dwarf-column-info");
3227 // FIXME: Move backend command line options to the module.
3228 // If -gline-tables-only or -gline-directives-only is the last option it wins.
3229 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3230 if (checkDebugInfoOption(A, Args, D, TC)) {
3231 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3232 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
3233 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3234 CmdArgs.push_back("-dwarf-ext-refs");
3235 CmdArgs.push_back("-fmodule-format=obj");
3239 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3240 // splitting and extraction.
3241 // FIXME: Currently only works on Linux and Fuchsia.
3242 if (T.isOSLinux() || T.isOSFuchsia()) {
3243 if (!SplitDWARFInlining)
3244 CmdArgs.push_back("-fno-split-dwarf-inlining");
3246 if (DwarfFission != DwarfFissionKind::None) {
3247 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3248 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3250 if (DwarfFission == DwarfFissionKind::Single)
3251 CmdArgs.push_back("-enable-split-dwarf=single");
3253 CmdArgs.push_back("-enable-split-dwarf");
3257 // After we've dealt with all combinations of things that could
3258 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3259 // figure out if we need to "upgrade" it to standalone debug info.
3260 // We parse these two '-f' options whether or not they will be used,
3261 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3262 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3263 options::OPT_fno_standalone_debug,
3264 TC.GetDefaultStandaloneDebug());
3265 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3266 (void)checkDebugInfoOption(A, Args, D, TC);
3267 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3268 DebugInfoKind = codegenoptions::FullDebugInfo;
3270 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3272 // Source embedding is a vendor extension to DWARF v5. By now we have
3273 // checked if a DWARF version was stated explicitly, and have otherwise
3274 // fallen back to the target default, so if this is still not at least 5
3275 // we emit an error.
3276 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
3277 if (DWARFVersion < 5)
3278 D.Diag(diag::err_drv_argument_only_allowed_with)
3279 << A->getAsString(Args) << "-gdwarf-5";
3280 else if (checkDebugInfoOption(A, Args, D, TC))
3281 CmdArgs.push_back("-gembed-source");
3285 CmdArgs.push_back("-gcodeview");
3287 // Emit codeview type hashes if requested.
3288 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3289 options::OPT_gno_codeview_ghash, false)) {
3290 CmdArgs.push_back("-gcodeview-ghash");
3294 // Adjust the debug info kind for the given toolchain.
3295 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3297 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3300 // -fdebug-macro turns on macro debug info generation.
3301 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3303 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3305 CmdArgs.push_back("-debug-info-macro");
3307 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3308 const auto *PubnamesArg =
3309 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3310 options::OPT_gpubnames, options::OPT_gno_pubnames);
3311 if (DwarfFission != DwarfFissionKind::None ||
3312 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3313 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3315 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3316 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3317 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3318 options::OPT_gpubnames)
3320 : "-ggnu-pubnames");
3322 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3323 options::OPT_fno_debug_ranges_base_address, false)) {
3324 CmdArgs.push_back("-fdebug-ranges-base-address");
3327 // -gdwarf-aranges turns on the emission of the aranges section in the
3329 // Always enabled for SCE tuning.
3330 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3331 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3332 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3334 CmdArgs.push_back("-mllvm");
3335 CmdArgs.push_back("-generate-arange-section");
3338 if (Args.hasFlag(options::OPT_fdebug_types_section,
3339 options::OPT_fno_debug_types_section, false)) {
3340 if (!T.isOSBinFormatELF()) {
3341 D.Diag(diag::err_drv_unsupported_opt_for_target)
3342 << Args.getLastArg(options::OPT_fdebug_types_section)
3345 } else if (checkDebugInfoOption(
3346 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3348 CmdArgs.push_back("-mllvm");
3349 CmdArgs.push_back("-generate-type-units");
3353 // Decide how to render forward declarations of template instantiations.
3354 // SCE wants full descriptions, others just get them in the name.
3355 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3356 CmdArgs.push_back("-debug-forward-template-params");
3358 // Do we need to explicitly import anonymous namespaces into the parent
3360 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3361 CmdArgs.push_back("-dwarf-explicit-import");
3363 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
3366 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3367 const InputInfo &Output, const InputInfoList &Inputs,
3368 const ArgList &Args, const char *LinkingOutput) const {
3369 const auto &TC = getToolChain();
3370 const llvm::Triple &RawTriple = TC.getTriple();
3371 const llvm::Triple &Triple = TC.getEffectiveTriple();
3372 const std::string &TripleStr = Triple.getTriple();
3375 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3376 const Driver &D = TC.getDriver();
3377 ArgStringList CmdArgs;
3379 // Check number of inputs for sanity. We need at least one input.
3380 assert(Inputs.size() >= 1 && "Must have at least one input.");
3381 // CUDA/HIP compilation may have multiple inputs (source file + results of
3382 // device-side compilations). OpenMP device jobs also take the host IR as a
3383 // second input. Module precompilation accepts a list of header files to
3384 // include as part of the module. All other jobs are expected to have exactly
3386 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3387 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
3388 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3389 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3391 // A header module compilation doesn't have a main input file, so invent a
3392 // fake one as a placeholder.
3393 const char *ModuleName = [&]{
3394 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3395 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3397 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
3399 const InputInfo &Input =
3400 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3402 InputInfoList ModuleHeaderInputs;
3403 const InputInfo *CudaDeviceInput = nullptr;
3404 const InputInfo *OpenMPDeviceInput = nullptr;
3405 for (const InputInfo &I : Inputs) {
3407 // This is the primary input.
3408 } else if (IsHeaderModulePrecompile &&
3409 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
3410 types::ID Expected = HeaderModuleInput.getType();
3411 if (I.getType() != Expected) {
3412 D.Diag(diag::err_drv_module_header_wrong_kind)
3413 << I.getFilename() << types::getTypeName(I.getType())
3414 << types::getTypeName(Expected);
3416 ModuleHeaderInputs.push_back(I);
3417 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3418 CudaDeviceInput = &I;
3419 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3420 OpenMPDeviceInput = &I;
3422 llvm_unreachable("unexpectedly given multiple inputs");
3426 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
3427 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3428 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3429 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3430 bool IsIAMCU = RawTriple.isOSIAMCU();
3432 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3433 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3434 // Windows), we need to pass Windows-specific flags to cc1.
3435 if (IsCuda || IsHIP) {
3436 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3437 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3438 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3441 // C++ is not supported for IAMCU.
3442 if (IsIAMCU && types::isCXX(Input.getType()))
3443 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3445 // Invoke ourselves in -cc1 mode.
3447 // FIXME: Implement custom jobs for internal actions.
3448 CmdArgs.push_back("-cc1");
3450 // Add the "effective" target triple.
3451 CmdArgs.push_back("-triple");
3452 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3454 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3455 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3456 Args.ClaimAllArgs(options::OPT_MJ);
3459 if (IsCuda || IsHIP) {
3460 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3462 std::string NormalizedTriple;
3463 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3464 JA.isDeviceOffloading(Action::OFK_HIP))
3465 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3470 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3471 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3475 CmdArgs.push_back("-aux-triple");
3476 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3479 if (IsOpenMPDevice) {
3480 // We have to pass the triple of the host if compiling for an OpenMP device.
3481 std::string NormalizedTriple =
3482 C.getSingleOffloadToolChain<Action::OFK_Host>()
3485 CmdArgs.push_back("-aux-triple");
3486 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3489 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3490 Triple.getArch() == llvm::Triple::thumb)) {
3491 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3493 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3495 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3499 // Push all default warning arguments that are specific to
3500 // the given target. These come before user provided warning options
3502 TC.addClangWarningOptions(CmdArgs);
3504 // Select the appropriate action.
3505 RewriteKind rewriteKind = RK_None;
3507 if (isa<AnalyzeJobAction>(JA)) {
3508 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3509 CmdArgs.push_back("-analyze");
3510 } else if (isa<MigrateJobAction>(JA)) {
3511 CmdArgs.push_back("-migrate");
3512 } else if (isa<PreprocessJobAction>(JA)) {
3513 if (Output.getType() == types::TY_Dependencies)
3514 CmdArgs.push_back("-Eonly");
3516 CmdArgs.push_back("-E");
3517 if (Args.hasArg(options::OPT_rewrite_objc) &&
3518 !Args.hasArg(options::OPT_g_Group))
3519 CmdArgs.push_back("-P");
3521 } else if (isa<AssembleJobAction>(JA)) {
3522 CmdArgs.push_back("-emit-obj");
3524 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3526 // Also ignore explicit -force_cpusubtype_ALL option.
3527 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3528 } else if (isa<PrecompileJobAction>(JA)) {
3529 if (JA.getType() == types::TY_Nothing)
3530 CmdArgs.push_back("-fsyntax-only");
3531 else if (JA.getType() == types::TY_ModuleFile)
3532 CmdArgs.push_back(IsHeaderModulePrecompile
3533 ? "-emit-header-module"
3534 : "-emit-module-interface");
3536 CmdArgs.push_back("-emit-pch");
3537 } else if (isa<VerifyPCHJobAction>(JA)) {
3538 CmdArgs.push_back("-verify-pch");
3540 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3541 "Invalid action for clang tool.");
3542 if (JA.getType() == types::TY_Nothing) {
3543 CmdArgs.push_back("-fsyntax-only");
3544 } else if (JA.getType() == types::TY_LLVM_IR ||
3545 JA.getType() == types::TY_LTO_IR) {
3546 CmdArgs.push_back("-emit-llvm");
3547 } else if (JA.getType() == types::TY_LLVM_BC ||
3548 JA.getType() == types::TY_LTO_BC) {
3549 CmdArgs.push_back("-emit-llvm-bc");
3550 } else if (JA.getType() == types::TY_PP_Asm) {
3551 CmdArgs.push_back("-S");
3552 } else if (JA.getType() == types::TY_AST) {
3553 CmdArgs.push_back("-emit-pch");
3554 } else if (JA.getType() == types::TY_ModuleFile) {
3555 CmdArgs.push_back("-module-file-info");
3556 } else if (JA.getType() == types::TY_RewrittenObjC) {
3557 CmdArgs.push_back("-rewrite-objc");
3558 rewriteKind = RK_NonFragile;
3559 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3560 CmdArgs.push_back("-rewrite-objc");
3561 rewriteKind = RK_Fragile;
3563 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3566 // Preserve use-list order by default when emitting bitcode, so that
3567 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3568 // same result as running passes here. For LTO, we don't need to preserve
3569 // the use-list order, since serialization to bitcode is part of the flow.
3570 if (JA.getType() == types::TY_LLVM_BC)
3571 CmdArgs.push_back("-emit-llvm-uselists");
3573 // Device-side jobs do not support LTO.
3574 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3575 JA.isDeviceOffloading(Action::OFK_Host));
3577 if (D.isUsingLTO() && !isDeviceOffloadAction) {
3578 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3580 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3581 // does not support LTO unit features (CFI, whole program vtable opt)
3583 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
3584 D.getLTOMode() == LTOK_Full)
3585 CmdArgs.push_back("-flto-unit");
3589 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3590 if (!types::isLLVMIR(Input.getType()))
3591 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3593 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3596 if (Args.getLastArg(options::OPT_save_temps_EQ))
3597 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3599 // Embed-bitcode option.
3600 // Only white-listed flags below are allowed to be embedded.
3601 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3602 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3603 // Add flags implied by -fembed-bitcode.
3604 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3605 // Disable all llvm IR level optimizations.
3606 CmdArgs.push_back("-disable-llvm-passes");
3608 // reject options that shouldn't be supported in bitcode
3609 // also reject kernel/kext
3610 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3611 options::OPT_mkernel,
3612 options::OPT_fapple_kext,
3613 options::OPT_ffunction_sections,
3614 options::OPT_fno_function_sections,
3615 options::OPT_fdata_sections,
3616 options::OPT_fno_data_sections,
3617 options::OPT_funique_section_names,
3618 options::OPT_fno_unique_section_names,
3619 options::OPT_mrestrict_it,
3620 options::OPT_mno_restrict_it,
3621 options::OPT_mstackrealign,
3622 options::OPT_mno_stackrealign,
3623 options::OPT_mstack_alignment,
3624 options::OPT_mcmodel_EQ,
3625 options::OPT_mlong_calls,
3626 options::OPT_mno_long_calls,
3627 options::OPT_ggnu_pubnames,
3628 options::OPT_gdwarf_aranges,
3629 options::OPT_fdebug_types_section,
3630 options::OPT_fno_debug_types_section,
3631 options::OPT_fdwarf_directory_asm,
3632 options::OPT_fno_dwarf_directory_asm,
3633 options::OPT_mrelax_all,
3634 options::OPT_mno_relax_all,
3635 options::OPT_ftrap_function_EQ,
3636 options::OPT_ffixed_r9,
3637 options::OPT_mfix_cortex_a53_835769,
3638 options::OPT_mno_fix_cortex_a53_835769,
3639 options::OPT_ffixed_x18,
3640 options::OPT_mglobal_merge,
3641 options::OPT_mno_global_merge,
3642 options::OPT_mred_zone,
3643 options::OPT_mno_red_zone,
3644 options::OPT_Wa_COMMA,
3645 options::OPT_Xassembler,
3648 for (const auto &A : Args)
3649 if (std::find(std::begin(kBitcodeOptionBlacklist),
3650 std::end(kBitcodeOptionBlacklist),
3651 A->getOption().getID()) !=
3652 std::end(kBitcodeOptionBlacklist))
3653 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3655 // Render the CodeGen options that need to be passed.
3656 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3657 options::OPT_fno_optimize_sibling_calls))
3658 CmdArgs.push_back("-mdisable-tail-calls");
3660 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3663 // Render ABI arguments
3664 switch (TC.getArch()) {
3666 case llvm::Triple::arm:
3667 case llvm::Triple::armeb:
3668 case llvm::Triple::thumbeb:
3669 RenderARMABI(Triple, Args, CmdArgs);
3671 case llvm::Triple::aarch64:
3672 case llvm::Triple::aarch64_be:
3673 RenderAArch64ABI(Triple, Args, CmdArgs);
3677 // Optimization level for CodeGen.
3678 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3679 if (A->getOption().matches(options::OPT_O4)) {
3680 CmdArgs.push_back("-O3");
3681 D.Diag(diag::warn_O4_is_O3);
3683 A->render(Args, CmdArgs);
3687 // Input/Output file.
3688 if (Output.getType() == types::TY_Dependencies) {
3689 // Handled with other dependency code.
3690 } else if (Output.isFilename()) {
3691 CmdArgs.push_back("-o");
3692 CmdArgs.push_back(Output.getFilename());
3694 assert(Output.isNothing() && "Input output.");
3697 for (const auto &II : Inputs) {
3698 addDashXForInput(Args, II, CmdArgs);
3699 if (II.isFilename())
3700 CmdArgs.push_back(II.getFilename());
3702 II.getInputArg().renderAsInput(Args, CmdArgs);
3705 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3710 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3711 CmdArgs.push_back("-fembed-bitcode=marker");
3713 // We normally speed up the clang process a bit by skipping destructors at
3714 // exit, but when we're generating diagnostics we can rely on some of the
3716 if (!C.isForDiagnostics())
3717 CmdArgs.push_back("-disable-free");
3720 const bool IsAssertBuild = false;
3722 const bool IsAssertBuild = true;
3725 // Disable the verification pass in -asserts builds.
3727 CmdArgs.push_back("-disable-llvm-verifier");
3729 // Discard value names in assert builds unless otherwise specified.
3730 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3731 options::OPT_fno_discard_value_names, !IsAssertBuild))
3732 CmdArgs.push_back("-discard-value-names");
3734 // Set the main file name, so that debug info works even with
3736 CmdArgs.push_back("-main-file-name");
3737 CmdArgs.push_back(getBaseInputName(Args, Input));
3739 // Some flags which affect the language (via preprocessor
3741 if (Args.hasArg(options::OPT_static))
3742 CmdArgs.push_back("-static-define");
3744 if (Args.hasArg(options::OPT_municode))
3745 CmdArgs.push_back("-DUNICODE");
3747 if (isa<AnalyzeJobAction>(JA))
3748 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
3750 // Enable compatilibily mode to avoid analyzer-config related errors.
3751 // Since we can't access frontend flags through hasArg, let's manually iterate
3753 bool FoundAnalyzerConfig = false;
3754 for (auto Arg : Args.filtered(options::OPT_Xclang))
3755 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3756 FoundAnalyzerConfig = true;
3759 if (!FoundAnalyzerConfig)
3760 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3761 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3762 FoundAnalyzerConfig = true;
3765 if (FoundAnalyzerConfig)
3766 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
3768 CheckCodeGenerationOptions(D, Args);
3770 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
3771 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3772 if (FunctionAlignment) {
3773 CmdArgs.push_back("-function-alignment");
3774 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3777 llvm::Reloc::Model RelocationModel;
3780 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
3782 const char *RMName = RelocationModelName(RelocationModel);
3784 if ((RelocationModel == llvm::Reloc::ROPI ||
3785 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3786 types::isCXX(Input.getType()) &&
3787 !Args.hasArg(options::OPT_fallow_unsupported))
3788 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3791 CmdArgs.push_back("-mrelocation-model");
3792 CmdArgs.push_back(RMName);
3795 CmdArgs.push_back("-pic-level");
3796 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3798 CmdArgs.push_back("-pic-is-pie");
3801 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3802 CmdArgs.push_back("-meabi");
3803 CmdArgs.push_back(A->getValue());
3806 CmdArgs.push_back("-mthread-model");
3807 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3808 if (!TC.isThreadModelSupported(A->getValue()))
3809 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3810 << A->getValue() << A->getAsString(Args);
3811 CmdArgs.push_back(A->getValue());
3814 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
3816 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3818 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3819 options::OPT_fno_merge_all_constants, false))
3820 CmdArgs.push_back("-fmerge-all-constants");
3822 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3823 options::OPT_fdelete_null_pointer_checks, false))
3824 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3826 // LLVM Code Generator Options.
3828 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3829 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3830 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3831 options::OPT_frewrite_map_file_EQ)) {
3832 StringRef Map = A->getValue();
3833 if (!llvm::sys::fs::exists(Map)) {
3834 D.Diag(diag::err_drv_no_such_file) << Map;
3836 CmdArgs.push_back("-frewrite-map-file");
3837 CmdArgs.push_back(A->getValue());
3843 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3844 StringRef v = A->getValue();
3845 CmdArgs.push_back("-mllvm");
3846 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3850 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3852 CmdArgs.push_back("-fno-jump-tables");
3854 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3855 options::OPT_fno_profile_sample_accurate, false))
3856 CmdArgs.push_back("-fprofile-sample-accurate");
3858 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3859 options::OPT_fno_preserve_as_comments, true))
3860 CmdArgs.push_back("-fno-preserve-as-comments");
3862 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3863 CmdArgs.push_back("-mregparm");
3864 CmdArgs.push_back(A->getValue());
3867 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3868 options::OPT_freg_struct_return)) {
3869 if (TC.getArch() != llvm::Triple::x86) {
3870 D.Diag(diag::err_drv_unsupported_opt_for_target)
3871 << A->getSpelling() << RawTriple.str();
3872 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3873 CmdArgs.push_back("-fpcc-struct-return");
3875 assert(A->getOption().matches(options::OPT_freg_struct_return));
3876 CmdArgs.push_back("-freg-struct-return");
3880 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3881 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3883 if (shouldUseFramePointer(Args, RawTriple))
3884 CmdArgs.push_back("-mdisable-fp-elim");
3885 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3886 options::OPT_fno_zero_initialized_in_bss))
3887 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3889 bool OFastEnabled = isOptimizationLevelFast(Args);
3890 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3891 // enabled. This alias option is being used to simplify the hasFlag logic.
3892 OptSpecifier StrictAliasingAliasOption =
3893 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3894 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3895 // doesn't do any TBAA.
3896 bool TBAAOnByDefault = !D.IsCLMode();
3897 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3898 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3899 CmdArgs.push_back("-relaxed-aliasing");
3900 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3901 options::OPT_fno_struct_path_tbaa))
3902 CmdArgs.push_back("-no-struct-path-tbaa");
3903 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3905 CmdArgs.push_back("-fstrict-enums");
3906 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3908 CmdArgs.push_back("-fno-strict-return");
3909 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3910 options::OPT_fno_allow_editor_placeholders, false))
3911 CmdArgs.push_back("-fallow-editor-placeholders");
3912 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3913 options::OPT_fno_strict_vtable_pointers,
3915 CmdArgs.push_back("-fstrict-vtable-pointers");
3916 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3917 options::OPT_fno_force_emit_vtables,
3919 CmdArgs.push_back("-fforce-emit-vtables");
3920 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3921 options::OPT_fno_optimize_sibling_calls))
3922 CmdArgs.push_back("-mdisable-tail-calls");
3923 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
3924 options::OPT_fescaping_block_tail_calls, false))
3925 CmdArgs.push_back("-fno-escaping-block-tail-calls");
3927 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3928 options::OPT_fno_fine_grained_bitfield_accesses);
3930 // Handle segmented stacks.
3931 if (Args.hasArg(options::OPT_fsplit_stack))
3932 CmdArgs.push_back("-split-stacks");
3934 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
3936 // Decide whether to use verbose asm. Verbose assembly is the default on
3937 // toolchains which have the integrated assembler on by default.
3938 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
3939 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3940 IsIntegratedAssemblerDefault) ||
3941 Args.hasArg(options::OPT_dA))
3942 CmdArgs.push_back("-masm-verbose");
3944 if (!TC.useIntegratedAs())
3945 CmdArgs.push_back("-no-integrated-as");
3947 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3948 CmdArgs.push_back("-mdebug-pass");
3949 CmdArgs.push_back("Structure");
3951 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3952 CmdArgs.push_back("-mdebug-pass");
3953 CmdArgs.push_back("Arguments");
3956 // Enable -mconstructor-aliases except on darwin, where we have to work around
3957 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3958 // aliases aren't supported.
3959 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
3960 CmdArgs.push_back("-mconstructor-aliases");
3962 // Darwin's kernel doesn't support guard variables; just die if we
3964 if (KernelOrKext && RawTriple.isOSDarwin())
3965 CmdArgs.push_back("-fforbid-guard-variables");
3967 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3969 CmdArgs.push_back("-mms-bitfields");
3972 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3973 options::OPT_mno_pie_copy_relocations,
3975 CmdArgs.push_back("-mpie-copy-relocations");
3978 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3979 CmdArgs.push_back("-fno-plt");
3982 // -fhosted is default.
3983 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3984 // use Freestanding.
3986 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3989 CmdArgs.push_back("-ffreestanding");
3991 // This is a coarse approximation of what llvm-gcc actually does, both
3992 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3993 // complicated ways.
3994 bool AsynchronousUnwindTables =
3995 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3996 options::OPT_fno_asynchronous_unwind_tables,
3997 (TC.IsUnwindTablesDefault(Args) ||
3998 TC.getSanitizerArgs().needsUnwindTables()) &&
4000 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4001 AsynchronousUnwindTables))
4002 CmdArgs.push_back("-munwind-tables");
4004 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4006 // FIXME: Handle -mtune=.
4007 (void)Args.hasArg(options::OPT_mtune_EQ);
4009 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4010 CmdArgs.push_back("-mcode-model");
4011 CmdArgs.push_back(A->getValue());
4014 // Add the target cpu
4015 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4017 CmdArgs.push_back("-target-cpu");
4018 CmdArgs.push_back(Args.MakeArgString(CPU));
4021 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
4023 // These two are potentially updated by AddClangCLArgs.
4024 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4025 bool EmitCodeView = false;
4027 // Add clang-cl arguments.
4028 types::ID InputType = Input.getType();
4030 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4032 DwarfFissionKind DwarfFission;
4033 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
4034 CmdArgs, DebugInfoKind, DwarfFission);
4036 // Add the split debug info name to the command lines here so we
4037 // can propagate it to the backend.
4038 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
4039 (RawTriple.isOSLinux() || RawTriple.isOSFuchsia()) &&
4040 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4041 isa<BackendJobAction>(JA));
4042 const char *SplitDWARFOut;
4044 CmdArgs.push_back("-split-dwarf-file");
4045 SplitDWARFOut = SplitDebugName(Args, Output);
4046 CmdArgs.push_back(SplitDWARFOut);
4049 // Pass the linker version in use.
4050 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4051 CmdArgs.push_back("-target-linker-version");
4052 CmdArgs.push_back(A->getValue());
4055 if (!shouldUseLeafFramePointer(Args, RawTriple))
4056 CmdArgs.push_back("-momit-leaf-frame-pointer");
4058 // Explicitly error on some things we know we don't support and can't just
4060 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4062 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
4063 TC.getArch() == llvm::Triple::x86) {
4064 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4065 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4066 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4067 << Unsupported->getOption().getName();
4069 // The faltivec option has been superseded by the maltivec option.
4070 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4071 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4072 << Unsupported->getOption().getName()
4073 << "please use -maltivec and include altivec.h explicitly";
4074 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4075 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4076 << Unsupported->getOption().getName() << "please use -mno-altivec";
4079 Args.AddAllArgs(CmdArgs, options::OPT_v);
4080 Args.AddLastArg(CmdArgs, options::OPT_H);
4081 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4082 CmdArgs.push_back("-header-include-file");
4083 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4086 Args.AddLastArg(CmdArgs, options::OPT_P);
4087 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4089 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4090 CmdArgs.push_back("-diagnostic-log-file");
4091 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4095 bool UseSeparateSections = isUseSeparateSections(Triple);
4097 if (Args.hasFlag(options::OPT_ffunction_sections,
4098 options::OPT_fno_function_sections, UseSeparateSections)) {
4099 CmdArgs.push_back("-ffunction-sections");
4102 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4103 UseSeparateSections)) {
4104 CmdArgs.push_back("-fdata-sections");
4107 if (!Args.hasFlag(options::OPT_funique_section_names,
4108 options::OPT_fno_unique_section_names, true))
4109 CmdArgs.push_back("-fno-unique-section-names");
4111 if (auto *A = Args.getLastArg(
4112 options::OPT_finstrument_functions,
4113 options::OPT_finstrument_functions_after_inlining,
4114 options::OPT_finstrument_function_entry_bare))
4115 A->render(Args, CmdArgs);
4117 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4118 // sampling, overhead of call arc collection is way too high and there's no
4119 // way to collect the output.
4120 if (!Triple.isNVPTX())
4121 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4123 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
4124 ABICompatArg->render(Args, CmdArgs);
4126 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
4127 if (RawTriple.isPS4CPU() &&
4128 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
4129 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4130 PS4cpu::addSanitizerArgs(TC, CmdArgs);
4133 // Pass options for controlling the default header search paths.
4134 if (Args.hasArg(options::OPT_nostdinc)) {
4135 CmdArgs.push_back("-nostdsysteminc");
4136 CmdArgs.push_back("-nobuiltininc");
4138 if (Args.hasArg(options::OPT_nostdlibinc))
4139 CmdArgs.push_back("-nostdsysteminc");
4140 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4141 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4144 // Pass the path to compiler resource files.
4145 CmdArgs.push_back("-resource-dir");
4146 CmdArgs.push_back(D.ResourceDir.c_str());
4148 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4150 RenderARCMigrateToolOptions(D, Args, CmdArgs);
4152 // Add preprocessing options like -I, -D, etc. if we are using the
4155 // FIXME: Support -fpreprocessed
4156 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4157 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4159 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4160 // that "The compiler can only warn and ignore the option if not recognized".
4161 // When building with ccache, it will pass -D options to clang even on
4162 // preprocessed inputs and configure concludes that -fPIC is not supported.
4163 Args.ClaimAllArgs(options::OPT_D);
4165 // Manually translate -O4 to -O3; let clang reject others.
4166 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4167 if (A->getOption().matches(options::OPT_O4)) {
4168 CmdArgs.push_back("-O3");
4169 D.Diag(diag::warn_O4_is_O3);
4171 A->render(Args, CmdArgs);
4175 // Warn about ignored options to clang.
4177 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4178 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4183 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4184 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4188 claimNoWarnArgs(Args);
4190 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4192 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4193 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4194 CmdArgs.push_back("-pedantic");
4195 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4196 Args.AddLastArg(CmdArgs, options::OPT_w);
4198 // Fixed point flags
4199 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4201 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4203 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4204 // (-ansi is equivalent to -std=c89 or -std=c++98).
4206 // If a std is supplied, only add -trigraphs if it follows the
4208 bool ImplyVCPPCXXVer = false;
4209 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4210 if (Std->getOption().matches(options::OPT_ansi))
4211 if (types::isCXX(InputType))
4212 CmdArgs.push_back("-std=c++98");
4214 CmdArgs.push_back("-std=c89");
4216 Std->render(Args, CmdArgs);
4218 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4219 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4220 options::OPT_ftrigraphs,
4221 options::OPT_fno_trigraphs))
4223 A->render(Args, CmdArgs);
4225 // Honor -std-default.
4227 // FIXME: Clang doesn't correctly handle -std= when the input language
4228 // doesn't match. For the time being just ignore this for C++ inputs;
4229 // eventually we want to do all the standard defaulting here instead of
4230 // splitting it between the driver and clang -cc1.
4231 if (!types::isCXX(InputType))
4232 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4234 else if (IsWindowsMSVC)
4235 ImplyVCPPCXXVer = true;
4237 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4238 options::OPT_fno_trigraphs);
4241 // GCC's behavior for -Wwrite-strings is a bit strange:
4242 // * In C, this "warning flag" changes the types of string literals from
4243 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4244 // for the discarded qualifier.
4245 // * In C++, this is just a normal warning flag.
4247 // Implementing this warning correctly in C is hard, so we follow GCC's
4248 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4249 // a non-const char* in C, rather than using this crude hack.
4250 if (!types::isCXX(InputType)) {
4251 // FIXME: This should behave just like a warning flag, and thus should also
4252 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4254 Args.getLastArg(options::OPT_Wwrite_strings,
4255 options::OPT_Wno_write_strings, options::OPT_w);
4257 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4258 CmdArgs.push_back("-fconst-strings");
4261 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4262 // during C++ compilation, which it is by default. GCC keeps this define even
4263 // in the presence of '-w', match this behavior bug-for-bug.
4264 if (types::isCXX(InputType) &&
4265 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4267 CmdArgs.push_back("-fdeprecated-macro");
4270 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4271 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4272 if (Asm->getOption().matches(options::OPT_fasm))
4273 CmdArgs.push_back("-fgnu-keywords");
4275 CmdArgs.push_back("-fno-gnu-keywords");
4278 if (ShouldDisableDwarfDirectory(Args, TC))
4279 CmdArgs.push_back("-fno-dwarf-directory-asm");
4281 if (ShouldDisableAutolink(Args, TC))
4282 CmdArgs.push_back("-fno-autolink");
4284 // Add in -fdebug-compilation-dir if necessary.
4285 addDebugCompDirArg(Args, CmdArgs);
4287 addDebugPrefixMapArg(D, Args, CmdArgs);
4289 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4290 options::OPT_ftemplate_depth_EQ)) {
4291 CmdArgs.push_back("-ftemplate-depth");
4292 CmdArgs.push_back(A->getValue());
4295 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4296 CmdArgs.push_back("-foperator-arrow-depth");
4297 CmdArgs.push_back(A->getValue());
4300 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4301 CmdArgs.push_back("-fconstexpr-depth");
4302 CmdArgs.push_back(A->getValue());
4305 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4306 CmdArgs.push_back("-fconstexpr-steps");
4307 CmdArgs.push_back(A->getValue());
4310 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4311 CmdArgs.push_back("-fbracket-depth");
4312 CmdArgs.push_back(A->getValue());
4315 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4316 options::OPT_Wlarge_by_value_copy_def)) {
4317 if (A->getNumValues()) {
4318 StringRef bytes = A->getValue();
4319 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4321 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4324 if (Args.hasArg(options::OPT_relocatable_pch))
4325 CmdArgs.push_back("-relocatable-pch");
4327 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4328 static const char *kCFABIs[] = {
4329 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4332 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4333 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4335 A->render(Args, CmdArgs);
4338 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4339 CmdArgs.push_back("-fconstant-string-class");
4340 CmdArgs.push_back(A->getValue());
4343 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4344 CmdArgs.push_back("-ftabstop");
4345 CmdArgs.push_back(A->getValue());
4348 if (Args.hasFlag(options::OPT_fstack_size_section,
4349 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4350 CmdArgs.push_back("-fstack-size-section");
4352 CmdArgs.push_back("-ferror-limit");
4353 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4354 CmdArgs.push_back(A->getValue());
4356 CmdArgs.push_back("19");
4358 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4359 CmdArgs.push_back("-fmacro-backtrace-limit");
4360 CmdArgs.push_back(A->getValue());
4363 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4364 CmdArgs.push_back("-ftemplate-backtrace-limit");
4365 CmdArgs.push_back(A->getValue());
4368 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4369 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4370 CmdArgs.push_back(A->getValue());
4373 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4374 CmdArgs.push_back("-fspell-checking-limit");
4375 CmdArgs.push_back(A->getValue());
4378 // Pass -fmessage-length=.
4379 CmdArgs.push_back("-fmessage-length");
4380 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4381 CmdArgs.push_back(A->getValue());
4383 // If -fmessage-length=N was not specified, determine whether this is a
4384 // terminal and, if so, implicitly define -fmessage-length appropriately.
4385 unsigned N = llvm::sys::Process::StandardErrColumns();
4386 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4389 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4390 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4391 options::OPT_fvisibility_ms_compat)) {
4392 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4393 CmdArgs.push_back("-fvisibility");
4394 CmdArgs.push_back(A->getValue());
4396 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4397 CmdArgs.push_back("-fvisibility");
4398 CmdArgs.push_back("hidden");
4399 CmdArgs.push_back("-ftype-visibility");
4400 CmdArgs.push_back("default");
4404 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4405 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
4407 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4409 // Forward -f (flag) options which we can pass directly.
4410 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4411 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4412 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
4413 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4414 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4415 options::OPT_fno_emulated_tls);
4416 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
4418 // AltiVec-like language extensions aren't relevant for assembling.
4419 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
4420 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4422 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4423 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4425 // Forward flags for OpenMP. We don't do this if the current action is an
4426 // device offloading action other than OpenMP.
4427 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4428 options::OPT_fno_openmp, false) &&
4429 (JA.isDeviceOffloading(Action::OFK_None) ||
4430 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
4431 switch (D.getOpenMPRuntime(Args)) {
4432 case Driver::OMPRT_OMP:
4433 case Driver::OMPRT_IOMP5:
4434 // Clang can generate useful OpenMP code for these two runtime libraries.
4435 CmdArgs.push_back("-fopenmp");
4437 // If no option regarding the use of TLS in OpenMP codegeneration is
4438 // given, decide a default based on the target. Otherwise rely on the
4439 // options and pass the right information to the frontend.
4440 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4441 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4442 CmdArgs.push_back("-fnoopenmp-use-tls");
4443 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4444 options::OPT_fno_openmp_simd);
4445 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4446 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4447 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
4448 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4449 options::OPT_fno_openmp_optimistic_collapse,
4451 CmdArgs.push_back("-fopenmp-optimistic-collapse");
4453 // When in OpenMP offloading mode with NVPTX target, forward
4455 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4456 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4457 CmdArgs.push_back("-fopenmp-cuda-mode");
4459 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4461 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4462 options::OPT_fno_openmp_cuda_force_full_runtime,
4464 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
4467 // By default, if Clang doesn't know how to generate useful OpenMP code
4468 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4469 // down to the actual compilation.
4470 // FIXME: It would be better to have a mode which *only* omits IR
4471 // generation based on the OpenMP support so that we get consistent
4472 // semantic analysis, etc.
4476 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4477 options::OPT_fno_openmp_simd);
4478 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4481 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4482 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
4484 const XRayArgs &XRay = TC.getXRayArgs();
4485 XRay.addArgs(TC, Args, CmdArgs, InputType);
4487 if (TC.SupportsProfiling())
4488 Args.AddLastArg(CmdArgs, options::OPT_pg);
4490 if (TC.SupportsProfiling())
4491 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4493 // -flax-vector-conversions is default.
4494 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4495 options::OPT_fno_lax_vector_conversions))
4496 CmdArgs.push_back("-fno-lax-vector-conversions");
4498 if (Args.getLastArg(options::OPT_fapple_kext) ||
4499 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4500 CmdArgs.push_back("-fapple-kext");
4502 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4503 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4504 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4505 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4506 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4508 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4509 CmdArgs.push_back("-ftrapv-handler");
4510 CmdArgs.push_back(A->getValue());
4513 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4515 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4516 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4517 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4518 if (A->getOption().matches(options::OPT_fwrapv))
4519 CmdArgs.push_back("-fwrapv");
4520 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4521 options::OPT_fno_strict_overflow)) {
4522 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4523 CmdArgs.push_back("-fwrapv");
4526 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4527 options::OPT_fno_reroll_loops))
4528 if (A->getOption().matches(options::OPT_freroll_loops))
4529 CmdArgs.push_back("-freroll-loops");
4531 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4532 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4533 options::OPT_fno_unroll_loops);
4535 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4537 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4539 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
4541 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
4542 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
4544 // Translate -mstackrealign
4545 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4547 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4549 if (Args.hasArg(options::OPT_mstack_alignment)) {
4550 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4551 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4554 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4555 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4558 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4560 CmdArgs.push_back("-mstack-probe-size=0");
4563 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4564 options::OPT_mno_stack_arg_probe, true))
4565 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4567 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4568 options::OPT_mno_restrict_it)) {
4569 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4570 CmdArgs.push_back("-mllvm");
4571 CmdArgs.push_back("-arm-restrict-it");
4573 CmdArgs.push_back("-mllvm");
4574 CmdArgs.push_back("-arm-no-restrict-it");
4576 } else if (Triple.isOSWindows() &&
4577 (Triple.getArch() == llvm::Triple::arm ||
4578 Triple.getArch() == llvm::Triple::thumb)) {
4579 // Windows on ARM expects restricted IT blocks
4580 CmdArgs.push_back("-mllvm");
4581 CmdArgs.push_back("-arm-restrict-it");
4584 // Forward -cl options to -cc1
4585 RenderOpenCLOptions(Args, CmdArgs);
4587 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4589 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4592 // Forward -f options with positive and negative forms; we translate
4594 if (Arg *A = getLastProfileSampleUseArg(Args)) {
4595 StringRef fname = A->getValue();
4596 if (!llvm::sys::fs::exists(fname))
4597 D.Diag(diag::err_drv_no_such_file) << fname;
4599 A->render(Args, CmdArgs);
4601 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
4603 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
4605 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4606 options::OPT_fno_assume_sane_operator_new))
4607 CmdArgs.push_back("-fno-assume-sane-operator-new");
4609 // -fblocks=0 is default.
4610 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4611 TC.IsBlocksDefault()) ||
4612 (Args.hasArg(options::OPT_fgnu_runtime) &&
4613 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4614 !Args.hasArg(options::OPT_fno_blocks))) {
4615 CmdArgs.push_back("-fblocks");
4617 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
4618 CmdArgs.push_back("-fblocks-runtime-optional");
4621 // -fencode-extended-block-signature=1 is default.
4622 if (TC.IsEncodeExtendedBlockSignatureDefault())
4623 CmdArgs.push_back("-fencode-extended-block-signature");
4625 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4627 types::isCXX(InputType)) {
4628 CmdArgs.push_back("-fcoroutines-ts");
4631 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4632 options::OPT_fno_double_square_bracket_attributes);
4634 bool HaveModules = false;
4635 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4637 // -faccess-control is default.
4638 if (Args.hasFlag(options::OPT_fno_access_control,
4639 options::OPT_faccess_control, false))
4640 CmdArgs.push_back("-fno-access-control");
4642 // -felide-constructors is the default.
4643 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4644 options::OPT_felide_constructors, false))
4645 CmdArgs.push_back("-fno-elide-constructors");
4647 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
4649 if (KernelOrKext || (types::isCXX(InputType) &&
4650 (RTTIMode == ToolChain::RM_Disabled)))
4651 CmdArgs.push_back("-fno-rtti");
4653 // -fshort-enums=0 is default for all architectures except Hexagon.
4654 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4655 TC.getArch() == llvm::Triple::hexagon))
4656 CmdArgs.push_back("-fshort-enums");
4658 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
4660 // -fuse-cxa-atexit is default.
4662 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4663 !RawTriple.isOSWindows() &&
4664 RawTriple.getOS() != llvm::Triple::Solaris &&
4665 TC.getArch() != llvm::Triple::xcore &&
4666 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4667 RawTriple.hasEnvironment())) ||
4669 CmdArgs.push_back("-fno-use-cxa-atexit");
4671 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4672 options::OPT_fno_register_global_dtors_with_atexit,
4673 RawTriple.isOSDarwin() && !KernelOrKext))
4674 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4676 // -fms-extensions=0 is default.
4677 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4679 CmdArgs.push_back("-fms-extensions");
4681 // -fno-use-line-directives is default.
4682 if (Args.hasFlag(options::OPT_fuse_line_directives,
4683 options::OPT_fno_use_line_directives, false))
4684 CmdArgs.push_back("-fuse-line-directives");
4686 // -fms-compatibility=0 is default.
4687 if (Args.hasFlag(options::OPT_fms_compatibility,
4688 options::OPT_fno_ms_compatibility,
4690 Args.hasFlag(options::OPT_fms_extensions,
4691 options::OPT_fno_ms_extensions, true))))
4692 CmdArgs.push_back("-fms-compatibility");
4694 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
4697 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4699 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4700 if (ImplyVCPPCXXVer) {
4701 StringRef LanguageStandard;
4702 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4703 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4704 .Case("c++14", "-std=c++14")
4705 .Case("c++17", "-std=c++17")
4706 .Case("c++latest", "-std=c++2a")
4708 if (LanguageStandard.empty())
4709 D.Diag(clang::diag::warn_drv_unused_argument)
4710 << StdArg->getAsString(Args);
4713 if (LanguageStandard.empty()) {
4714 if (IsMSVC2015Compatible)
4715 LanguageStandard = "-std=c++14";
4717 LanguageStandard = "-std=c++11";
4720 CmdArgs.push_back(LanguageStandard.data());
4723 // -fno-borland-extensions is default.
4724 if (Args.hasFlag(options::OPT_fborland_extensions,
4725 options::OPT_fno_borland_extensions, false))
4726 CmdArgs.push_back("-fborland-extensions");
4728 // -fno-declspec is default, except for PS4.
4729 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4731 CmdArgs.push_back("-fdeclspec");
4732 else if (Args.hasArg(options::OPT_fno_declspec))
4733 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4735 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4737 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4738 options::OPT_fno_threadsafe_statics,
4739 !IsWindowsMSVC || IsMSVC2015Compatible))
4740 CmdArgs.push_back("-fno-threadsafe-statics");
4742 // -fno-delayed-template-parsing is default, except when targeting MSVC.
4743 // Many old Windows SDK versions require this to parse.
4744 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4745 // compiler. We should be able to disable this by default at some point.
4746 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4747 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4748 CmdArgs.push_back("-fdelayed-template-parsing");
4750 // -fgnu-keywords default varies depending on language; only pass if
4752 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4753 options::OPT_fno_gnu_keywords))
4754 A->render(Args, CmdArgs);
4756 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4758 CmdArgs.push_back("-fgnu89-inline");
4760 if (Args.hasArg(options::OPT_fno_inline))
4761 CmdArgs.push_back("-fno-inline");
4763 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4764 options::OPT_finline_hint_functions,
4765 options::OPT_fno_inline_functions))
4766 InlineArg->render(Args, CmdArgs);
4768 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4769 options::OPT_fno_experimental_new_pass_manager);
4771 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4772 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4775 if (Args.hasFlag(options::OPT_fapplication_extension,
4776 options::OPT_fno_application_extension, false))
4777 CmdArgs.push_back("-fapplication-extension");
4779 // Handle GCC-style exception args.
4780 if (!C.getDriver().IsCLMode())
4781 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
4783 // Handle exception personalities
4784 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4785 options::OPT_fseh_exceptions,
4786 options::OPT_fdwarf_exceptions);
4788 const Option &Opt = A->getOption();
4789 if (Opt.matches(options::OPT_fsjlj_exceptions))
4790 CmdArgs.push_back("-fsjlj-exceptions");
4791 if (Opt.matches(options::OPT_fseh_exceptions))
4792 CmdArgs.push_back("-fseh-exceptions");
4793 if (Opt.matches(options::OPT_fdwarf_exceptions))
4794 CmdArgs.push_back("-fdwarf-exceptions");
4796 switch (TC.GetExceptionModel(Args)) {
4799 case llvm::ExceptionHandling::DwarfCFI:
4800 CmdArgs.push_back("-fdwarf-exceptions");
4802 case llvm::ExceptionHandling::SjLj:
4803 CmdArgs.push_back("-fsjlj-exceptions");
4805 case llvm::ExceptionHandling::WinEH:
4806 CmdArgs.push_back("-fseh-exceptions");
4811 // C++ "sane" operator new.
4812 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4813 options::OPT_fno_assume_sane_operator_new))
4814 CmdArgs.push_back("-fno-assume-sane-operator-new");
4816 // -frelaxed-template-template-args is off by default, as it is a severe
4817 // breaking change until a corresponding change to template partial ordering
4819 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4820 options::OPT_fno_relaxed_template_template_args, false))
4821 CmdArgs.push_back("-frelaxed-template-template-args");
4823 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4825 if (Args.hasFlag(options::OPT_fsized_deallocation,
4826 options::OPT_fno_sized_deallocation, false))
4827 CmdArgs.push_back("-fsized-deallocation");
4829 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4831 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4832 options::OPT_fno_aligned_allocation,
4833 options::OPT_faligned_new_EQ)) {
4834 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4835 CmdArgs.push_back("-fno-aligned-allocation");
4837 CmdArgs.push_back("-faligned-allocation");
4840 // The default new alignment can be specified using a dedicated option or via
4841 // a GCC-compatible option that also turns on aligned allocation.
4842 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4843 options::OPT_faligned_new_EQ))
4845 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4847 // -fconstant-cfstrings is default, and may be subject to argument translation
4849 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4850 options::OPT_fno_constant_cfstrings) ||
4851 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4852 options::OPT_mno_constant_cfstrings))
4853 CmdArgs.push_back("-fno-constant-cfstrings");
4855 // -fno-pascal-strings is default, only pass non-default.
4856 if (Args.hasFlag(options::OPT_fpascal_strings,
4857 options::OPT_fno_pascal_strings, false))
4858 CmdArgs.push_back("-fpascal-strings");
4860 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4861 // -fno-pack-struct doesn't apply to -fpack-struct=.
4862 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4863 std::string PackStructStr = "-fpack-struct=";
4864 PackStructStr += A->getValue();
4865 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4866 } else if (Args.hasFlag(options::OPT_fpack_struct,
4867 options::OPT_fno_pack_struct, false)) {
4868 CmdArgs.push_back("-fpack-struct=1");
4871 // Handle -fmax-type-align=N and -fno-type-align
4872 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4873 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4874 if (!SkipMaxTypeAlign) {
4875 std::string MaxTypeAlignStr = "-fmax-type-align=";
4876 MaxTypeAlignStr += A->getValue();
4877 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4879 } else if (RawTriple.isOSDarwin()) {
4880 if (!SkipMaxTypeAlign) {
4881 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4882 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4886 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4887 CmdArgs.push_back("-Qn");
4889 // -fcommon is the default unless compiling kernel code or the target says so
4890 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
4891 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4893 CmdArgs.push_back("-fno-common");
4895 // -fsigned-bitfields is default, and clang doesn't yet support
4896 // -funsigned-bitfields.
4897 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4898 options::OPT_funsigned_bitfields))
4899 D.Diag(diag::warn_drv_clang_unsupported)
4900 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4902 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4903 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4904 D.Diag(diag::err_drv_clang_unsupported)
4905 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4907 // -finput_charset=UTF-8 is default. Reject others
4908 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4909 StringRef value = inputCharset->getValue();
4910 if (!value.equals_lower("utf-8"))
4911 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4915 // -fexec_charset=UTF-8 is default. Reject others
4916 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4917 StringRef value = execCharset->getValue();
4918 if (!value.equals_lower("utf-8"))
4919 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4923 RenderDiagnosticsOptions(D, Args, CmdArgs);
4925 // -fno-asm-blocks is default.
4926 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4928 CmdArgs.push_back("-fasm-blocks");
4930 // -fgnu-inline-asm is default.
4931 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4932 options::OPT_fno_gnu_inline_asm, true))
4933 CmdArgs.push_back("-fno-gnu-inline-asm");
4935 // Enable vectorization per default according to the optimization level
4936 // selected. For optimization levels that want vectorization we use the alias
4937 // option to simplify the hasFlag logic.
4938 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4939 OptSpecifier VectorizeAliasOption =
4940 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4941 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4942 options::OPT_fno_vectorize, EnableVec))
4943 CmdArgs.push_back("-vectorize-loops");
4945 // -fslp-vectorize is enabled based on the optimization level selected.
4946 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4947 OptSpecifier SLPVectAliasOption =
4948 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4949 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4950 options::OPT_fno_slp_vectorize, EnableSLPVec))
4951 CmdArgs.push_back("-vectorize-slp");
4953 ParseMPreferVectorWidth(D, Args, CmdArgs);
4955 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4956 A->render(Args, CmdArgs);
4958 if (Arg *A = Args.getLastArg(
4959 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4960 A->render(Args, CmdArgs);
4962 // -fdollars-in-identifiers default varies depending on platform and
4963 // language; only pass if specified.
4964 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4965 options::OPT_fno_dollars_in_identifiers)) {
4966 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4967 CmdArgs.push_back("-fdollars-in-identifiers");
4969 CmdArgs.push_back("-fno-dollars-in-identifiers");
4972 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4973 // practical purposes.
4974 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4975 options::OPT_fno_unit_at_a_time)) {
4976 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4977 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4980 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4981 options::OPT_fno_apple_pragma_pack, false))
4982 CmdArgs.push_back("-fapple-pragma-pack");
4984 if (Args.hasFlag(options::OPT_fsave_optimization_record,
4985 options::OPT_foptimization_record_file_EQ,
4986 options::OPT_fno_save_optimization_record, false)) {
4987 CmdArgs.push_back("-opt-record-file");
4989 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4991 CmdArgs.push_back(A->getValue());
4995 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4996 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4997 F = FinalOutput->getValue();
5001 // Use the input filename.
5002 F = llvm::sys::path::stem(Input.getBaseInput());
5004 // If we're compiling for an offload architecture (i.e. a CUDA device),
5005 // we need to make the file name for the device compilation different
5006 // from the host compilation.
5007 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5008 !JA.isDeviceOffloading(Action::OFK_Host)) {
5009 llvm::sys::path::replace_extension(F, "");
5010 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5011 Triple.normalize());
5013 F += JA.getOffloadingArch();
5017 llvm::sys::path::replace_extension(F, "opt.yaml");
5018 CmdArgs.push_back(Args.MakeArgString(F));
5022 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5023 options::OPT_fno_rewrite_imports, false);
5025 CmdArgs.push_back("-frewrite-imports");
5027 // Enable rewrite includes if the user's asked for it or if we're generating
5029 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5030 // nice to enable this when doing a crashdump for modules as well.
5031 if (Args.hasFlag(options::OPT_frewrite_includes,
5032 options::OPT_fno_rewrite_includes, false) ||
5033 (C.isForDiagnostics() && !HaveModules))
5034 CmdArgs.push_back("-frewrite-includes");
5036 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5037 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5038 options::OPT_traditional_cpp)) {
5039 if (isa<PreprocessJobAction>(JA))
5040 CmdArgs.push_back("-traditional-cpp");
5042 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5045 Args.AddLastArg(CmdArgs, options::OPT_dM);
5046 Args.AddLastArg(CmdArgs, options::OPT_dD);
5048 // Handle serialized diagnostics.
5049 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5050 CmdArgs.push_back("-serialize-diagnostic-file");
5051 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5054 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5055 CmdArgs.push_back("-fretain-comments-from-system-headers");
5057 // Forward -fcomment-block-commands to -cc1.
5058 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5059 // Forward -fparse-all-comments to -cc1.
5060 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5062 // Turn -fplugin=name.so into -load name.so
5063 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5064 CmdArgs.push_back("-load");
5065 CmdArgs.push_back(A->getValue());
5069 // Setup statistics file output.
5070 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5071 if (!StatsFile.empty())
5072 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
5074 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5076 // -finclude-default-header flag is for preprocessor,
5077 // do not pass it to other cc1 commands when save-temps is enabled
5078 if (C.getDriver().isSaveTempsEnabled() &&
5079 !isa<PreprocessJobAction>(JA)) {
5080 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5082 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5083 CmdArgs.push_back(Arg->getValue());
5087 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5089 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5092 // We translate this by hand to the -cc1 argument, since nightly test uses
5093 // it and developers have been trained to spell it with -mllvm. Both
5094 // spellings are now deprecated and should be removed.
5095 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5096 CmdArgs.push_back("-disable-llvm-optzns");
5098 A->render(Args, CmdArgs);
5102 // With -save-temps, we want to save the unoptimized bitcode output from the
5103 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5105 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5106 // has slightly different breakdown between stages.
5107 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5108 // pristine IR generated by the frontend. Ideally, a new compile action should
5109 // be added so both IR can be captured.
5110 if (C.getDriver().isSaveTempsEnabled() &&
5111 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5112 isa<CompileJobAction>(JA))
5113 CmdArgs.push_back("-disable-llvm-passes");
5115 if (Output.getType() == types::TY_Dependencies) {
5116 // Handled with other dependency code.
5117 } else if (Output.isFilename()) {
5118 CmdArgs.push_back("-o");
5119 CmdArgs.push_back(Output.getFilename());
5121 assert(Output.isNothing() && "Invalid output.");
5124 addDashXForInput(Args, Input, CmdArgs);
5126 ArrayRef<InputInfo> FrontendInputs = Input;
5127 if (IsHeaderModulePrecompile)
5128 FrontendInputs = ModuleHeaderInputs;
5129 else if (Input.isNothing())
5130 FrontendInputs = {};
5132 for (const InputInfo &Input : FrontendInputs) {
5133 if (Input.isFilename())
5134 CmdArgs.push_back(Input.getFilename());
5136 Input.getInputArg().renderAsInput(Args, CmdArgs);
5139 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5141 const char *Exec = D.getClangProgramPath();
5143 // Optionally embed the -cc1 level arguments into the debug info or a
5144 // section, for build analysis.
5145 // Also record command line arguments into the debug info if
5146 // -grecord-gcc-switches options is set on.
5147 // By default, -gno-record-gcc-switches is set on and no recording.
5148 auto GRecordSwitches =
5149 Args.hasFlag(options::OPT_grecord_command_line,
5150 options::OPT_gno_record_command_line, false);
5151 auto FRecordSwitches =
5152 Args.hasFlag(options::OPT_frecord_command_line,
5153 options::OPT_fno_record_command_line, false);
5154 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5155 D.Diag(diag::err_drv_unsupported_opt_for_target)
5156 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5158 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
5159 ArgStringList OriginalArgs;
5160 for (const auto &Arg : Args)
5161 Arg->render(Args, OriginalArgs);
5163 SmallString<256> Flags;
5165 for (const char *OriginalArg : OriginalArgs) {
5166 SmallString<128> EscapedArg;
5167 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5169 Flags += EscapedArg;
5171 auto FlagsArgString = Args.MakeArgString(Flags);
5172 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5173 CmdArgs.push_back("-dwarf-debug-flags");
5174 CmdArgs.push_back(FlagsArgString);
5176 if (FRecordSwitches) {
5177 CmdArgs.push_back("-record-command-line");
5178 CmdArgs.push_back(FlagsArgString);
5182 // Host-side cuda compilation receives all device-side outputs in a single
5183 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5184 if ((IsCuda || IsHIP) && CudaDeviceInput) {
5185 CmdArgs.push_back("-fcuda-include-gpubinary");
5186 CmdArgs.push_back(CudaDeviceInput->getFilename());
5187 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5188 CmdArgs.push_back("-fgpu-rdc");
5192 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5193 options::OPT_fno_cuda_short_ptr, false))
5194 CmdArgs.push_back("-fcuda-short-ptr");
5197 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5198 // to specify the result of the compile phase on the host, so the meaningful
5199 // device declarations can be identified. Also, -fopenmp-is-device is passed
5200 // along to tell the frontend that it is generating code for a device, so that
5201 // only the relevant declarations are emitted.
5202 if (IsOpenMPDevice) {
5203 CmdArgs.push_back("-fopenmp-is-device");
5204 if (OpenMPDeviceInput) {
5205 CmdArgs.push_back("-fopenmp-host-ir-file-path");
5206 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
5210 // For all the host OpenMP offloading compile jobs we need to pass the targets
5211 // information using -fopenmp-targets= option.
5212 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
5213 SmallString<128> TargetInfo("-fopenmp-targets=");
5215 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5216 assert(Tgts && Tgts->getNumValues() &&
5217 "OpenMP offloading has to have targets specified.");
5218 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5221 // We need to get the string from the triple because it may be not exactly
5222 // the same as the one we get directly from the arguments.
5223 llvm::Triple T(Tgts->getValue(i));
5224 TargetInfo += T.getTriple();
5226 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5229 bool WholeProgramVTables =
5230 Args.hasFlag(options::OPT_fwhole_program_vtables,
5231 options::OPT_fno_whole_program_vtables, false);
5232 if (WholeProgramVTables) {
5233 if (!D.isUsingLTO())
5234 D.Diag(diag::err_drv_argument_only_allowed_with)
5235 << "-fwhole-program-vtables"
5237 CmdArgs.push_back("-fwhole-program-vtables");
5240 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5242 Args.hasFlag(options::OPT_fsplit_lto_unit,
5243 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5244 if (RequiresSplitLTOUnit && !SplitLTOUnit)
5245 D.Diag(diag::err_drv_argument_not_allowed_with)
5246 << "-fno-split-lto-unit"
5247 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5249 CmdArgs.push_back("-fsplit-lto-unit");
5251 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5252 options::OPT_fno_experimental_isel)) {
5253 CmdArgs.push_back("-mllvm");
5254 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5255 CmdArgs.push_back("-global-isel=1");
5257 // GISel is on by default on AArch64 -O0, so don't bother adding
5258 // the fallback remarks for it. Other combinations will add a warning of
5260 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5261 bool IsOptLevelSupported = false;
5263 Arg *A = Args.getLastArg(options::OPT_O_Group);
5264 if (Triple.getArch() == llvm::Triple::aarch64) {
5265 if (!A || A->getOption().matches(options::OPT_O0))
5266 IsOptLevelSupported = true;
5268 if (!IsArchSupported || !IsOptLevelSupported) {
5269 CmdArgs.push_back("-mllvm");
5270 CmdArgs.push_back("-global-isel-abort=2");
5272 if (!IsArchSupported)
5273 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5275 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5278 CmdArgs.push_back("-global-isel=0");
5282 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5283 options::OPT_fno_force_enable_int128)) {
5284 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5285 CmdArgs.push_back("-fforce-enable-int128");
5288 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5289 options::OPT_fno_complete_member_pointers, false))
5290 CmdArgs.push_back("-fcomplete-member-pointers");
5292 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5293 options::OPT_fno_cxx_static_destructors, true))
5294 CmdArgs.push_back("-fno-c++-static-destructors");
5296 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5297 options::OPT_mno_outline)) {
5298 if (A->getOption().matches(options::OPT_moutline)) {
5299 // We only support -moutline in AArch64 right now. If we're not compiling
5300 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5301 // proper mllvm flags.
5302 if (Triple.getArch() != llvm::Triple::aarch64) {
5303 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5305 CmdArgs.push_back("-mllvm");
5306 CmdArgs.push_back("-enable-machine-outliner");
5309 // Disable all outlining behaviour.
5310 CmdArgs.push_back("-mllvm");
5311 CmdArgs.push_back("-enable-machine-outliner=never");
5315 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
5316 (TC.getTriple().isOSBinFormatELF() ||
5317 TC.getTriple().isOSBinFormatCOFF()) &&
5318 !TC.getTriple().isPS4() &&
5319 !TC.getTriple().isOSNetBSD() &&
5320 !Distro(D.getVFS()).IsGentoo() &&
5321 !TC.getTriple().isAndroid() &&
5322 TC.useIntegratedAs()))
5323 CmdArgs.push_back("-faddrsig");
5325 // Finally add the compile command to the compilation.
5326 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5327 Output.getType() == types::TY_Object &&
5328 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5330 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5331 C.addCommand(llvm::make_unique<FallbackCommand>(
5332 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5333 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5334 isa<PrecompileJobAction>(JA)) {
5335 // In /fallback builds, run the main compilation even if the pch generation
5336 // fails, so that the main compilation's fallback to cl.exe runs.
5337 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5340 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5343 // Make the compile command echo its inputs for /showFilenames.
5344 if (Output.getType() == types::TY_Object &&
5345 Args.hasFlag(options::OPT__SLASH_showFilenames,
5346 options::OPT__SLASH_showFilenames_, false)) {
5347 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5350 if (Arg *A = Args.getLastArg(options::OPT_pg))
5351 if (!shouldUseFramePointer(Args, Triple))
5352 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5353 << A->getAsString(Args);
5355 // Claim some arguments which clang supports automatically.
5357 // -fpch-preprocess is used with gcc to add a special marker in the output to
5358 // include the PCH file.
5359 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5361 // Claim some arguments which clang doesn't support, but we don't
5362 // care to warn the user about.
5363 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5364 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5366 // Disable warnings for clang -E -emit-llvm foo.c
5367 Args.ClaimAllArgs(options::OPT_emit_llvm);
5370 Clang::Clang(const ToolChain &TC)
5371 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5372 // as it is for other tools. Some operations on a Tool actually test
5373 // whether that tool is Clang based on the Tool's Name as a string.
5374 : Tool("clang", "clang frontend", TC, RF_Full) {}
5378 /// Add options related to the Objective-C runtime/ABI.
5380 /// Returns true if the runtime is non-fragile.
5381 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5382 ArgStringList &cmdArgs,
5383 RewriteKind rewriteKind) const {
5384 // Look for the controlling runtime option.
5386 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5387 options::OPT_fobjc_runtime_EQ);
5389 // Just forward -fobjc-runtime= to the frontend. This supercedes
5390 // options about fragility.
5392 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5393 ObjCRuntime runtime;
5394 StringRef value = runtimeArg->getValue();
5395 if (runtime.tryParse(value)) {
5396 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5399 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5400 (runtime.getVersion() >= VersionTuple(2, 0)))
5401 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5402 !getToolChain().getTriple().isOSBinFormatCOFF()) {
5403 getToolChain().getDriver().Diag(
5404 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5405 << runtime.getVersion().getMajor();
5408 runtimeArg->render(args, cmdArgs);
5412 // Otherwise, we'll need the ABI "version". Version numbers are
5413 // slightly confusing for historical reasons:
5414 // 1 - Traditional "fragile" ABI
5415 // 2 - Non-fragile ABI, version 1
5416 // 3 - Non-fragile ABI, version 2
5417 unsigned objcABIVersion = 1;
5418 // If -fobjc-abi-version= is present, use that to set the version.
5419 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5420 StringRef value = abiArg->getValue();
5423 else if (value == "2")
5425 else if (value == "3")
5428 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5430 // Otherwise, determine if we are using the non-fragile ABI.
5431 bool nonFragileABIIsDefault =
5432 (rewriteKind == RK_NonFragile ||
5433 (rewriteKind == RK_None &&
5434 getToolChain().IsObjCNonFragileABIDefault()));
5435 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5436 options::OPT_fno_objc_nonfragile_abi,
5437 nonFragileABIIsDefault)) {
5438 // Determine the non-fragile ABI version to use.
5439 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5440 unsigned nonFragileABIVersion = 1;
5442 unsigned nonFragileABIVersion = 2;
5446 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5447 StringRef value = abiArg->getValue();
5449 nonFragileABIVersion = 1;
5450 else if (value == "2")
5451 nonFragileABIVersion = 2;
5453 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5457 objcABIVersion = 1 + nonFragileABIVersion;
5463 // We don't actually care about the ABI version other than whether
5464 // it's non-fragile.
5465 bool isNonFragile = objcABIVersion != 1;
5467 // If we have no runtime argument, ask the toolchain for its default runtime.
5468 // However, the rewriter only really supports the Mac runtime, so assume that.
5469 ObjCRuntime runtime;
5471 switch (rewriteKind) {
5473 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5476 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5479 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5484 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5485 // On Darwin, make this use the default behavior for the toolchain.
5486 if (getToolChain().getTriple().isOSDarwin()) {
5487 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5489 // Otherwise, build for a generic macosx port.
5491 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5496 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5497 // Legacy behaviour is to target the gnustep runtime if we are in
5498 // non-fragile mode or the GCC runtime in fragile mode.
5500 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
5502 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5506 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5510 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5511 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5519 bool Asynch = false;
5520 bool NoUnwindC = false;
5522 } // end anonymous namespace
5524 /// /EH controls whether to run destructor cleanups when exceptions are
5525 /// thrown. There are three modifiers:
5526 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5527 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5528 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5529 /// - c: Assume that extern "C" functions are implicitly nounwind.
5530 /// The default is /EHs-c-, meaning cleanups are disabled.
5531 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5534 std::vector<std::string> EHArgs =
5535 Args.getAllArgValues(options::OPT__SLASH_EH);
5536 for (auto EHVal : EHArgs) {
5537 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5540 EH.Asynch = maybeConsumeDash(EHVal, I);
5545 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5548 EH.Synch = maybeConsumeDash(EHVal, I);
5555 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5559 // The /GX, /GX- flags are only processed if there are not /EH flags.
5560 // The default is that /GX is not specified.
5561 if (EHArgs.empty() &&
5562 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5563 /*default=*/false)) {
5565 EH.NoUnwindC = true;
5571 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5572 ArgStringList &CmdArgs,
5573 codegenoptions::DebugInfoKind *DebugInfoKind,
5574 bool *EmitCodeView) const {
5575 unsigned RTOptionID = options::OPT__SLASH_MT;
5577 if (Args.hasArg(options::OPT__SLASH_LDd))
5578 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5579 // but defining _DEBUG is sticky.
5580 RTOptionID = options::OPT__SLASH_MTd;
5582 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5583 RTOptionID = A->getOption().getID();
5585 StringRef FlagForCRT;
5586 switch (RTOptionID) {
5587 case options::OPT__SLASH_MD:
5588 if (Args.hasArg(options::OPT__SLASH_LDd))
5589 CmdArgs.push_back("-D_DEBUG");
5590 CmdArgs.push_back("-D_MT");
5591 CmdArgs.push_back("-D_DLL");
5592 FlagForCRT = "--dependent-lib=msvcrt";
5594 case options::OPT__SLASH_MDd:
5595 CmdArgs.push_back("-D_DEBUG");
5596 CmdArgs.push_back("-D_MT");
5597 CmdArgs.push_back("-D_DLL");
5598 FlagForCRT = "--dependent-lib=msvcrtd";
5600 case options::OPT__SLASH_MT:
5601 if (Args.hasArg(options::OPT__SLASH_LDd))
5602 CmdArgs.push_back("-D_DEBUG");
5603 CmdArgs.push_back("-D_MT");
5604 CmdArgs.push_back("-flto-visibility-public-std");
5605 FlagForCRT = "--dependent-lib=libcmt";
5607 case options::OPT__SLASH_MTd:
5608 CmdArgs.push_back("-D_DEBUG");
5609 CmdArgs.push_back("-D_MT");
5610 CmdArgs.push_back("-flto-visibility-public-std");
5611 FlagForCRT = "--dependent-lib=libcmtd";
5614 llvm_unreachable("Unexpected option ID.");
5617 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5618 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5620 CmdArgs.push_back(FlagForCRT.data());
5622 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5623 // users want. The /Za flag to cl.exe turns this off, but it's not
5624 // implemented in clang.
5625 CmdArgs.push_back("--dependent-lib=oldnames");
5628 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5629 A->render(Args, CmdArgs);
5631 // This controls whether or not we emit RTTI data for polymorphic types.
5632 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5634 CmdArgs.push_back("-fno-rtti-data");
5636 // This controls whether or not we emit stack-protector instrumentation.
5637 // In MSVC, Buffer Security Check (/GS) is on by default.
5638 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5639 /*default=*/true)) {
5640 CmdArgs.push_back("-stack-protector");
5641 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5644 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5645 if (Arg *DebugInfoArg =
5646 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5647 options::OPT_gline_tables_only)) {
5648 *EmitCodeView = true;
5649 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5650 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5652 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5654 *EmitCodeView = false;
5657 const Driver &D = getToolChain().getDriver();
5658 EHFlags EH = parseClangCLEHFlags(D, Args);
5659 if (EH.Synch || EH.Asynch) {
5660 if (types::isCXX(InputType))
5661 CmdArgs.push_back("-fcxx-exceptions");
5662 CmdArgs.push_back("-fexceptions");
5664 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5665 CmdArgs.push_back("-fexternc-nounwind");
5667 // /EP should expand to -E -P.
5668 if (Args.hasArg(options::OPT__SLASH_EP)) {
5669 CmdArgs.push_back("-E");
5670 CmdArgs.push_back("-P");
5673 unsigned VolatileOptionID;
5674 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5675 getToolChain().getArch() == llvm::Triple::x86)
5676 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5678 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5680 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5681 VolatileOptionID = A->getOption().getID();
5683 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5684 CmdArgs.push_back("-fms-volatile");
5686 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5687 options::OPT__SLASH_Zc_dllexportInlines,
5689 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5690 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5692 CmdArgs.push_back("-fno-dllexport-inlines");
5696 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5697 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5698 if (MostGeneralArg && BestCaseArg)
5699 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5700 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5702 if (MostGeneralArg) {
5703 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5704 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5705 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5707 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5708 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5709 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5710 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5711 << FirstConflict->getAsString(Args)
5712 << SecondConflict->getAsString(Args);
5715 CmdArgs.push_back("-fms-memptr-rep=single");
5716 else if (MultipleArg)
5717 CmdArgs.push_back("-fms-memptr-rep=multiple");
5719 CmdArgs.push_back("-fms-memptr-rep=virtual");
5722 // Parse the default calling convention options.
5724 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
5725 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5726 options::OPT__SLASH_Gregcall)) {
5727 unsigned DCCOptId = CCArg->getOption().getID();
5728 const char *DCCFlag = nullptr;
5729 bool ArchSupported = true;
5730 llvm::Triple::ArchType Arch = getToolChain().getArch();
5732 case options::OPT__SLASH_Gd:
5733 DCCFlag = "-fdefault-calling-conv=cdecl";
5735 case options::OPT__SLASH_Gr:
5736 ArchSupported = Arch == llvm::Triple::x86;
5737 DCCFlag = "-fdefault-calling-conv=fastcall";
5739 case options::OPT__SLASH_Gz:
5740 ArchSupported = Arch == llvm::Triple::x86;
5741 DCCFlag = "-fdefault-calling-conv=stdcall";
5743 case options::OPT__SLASH_Gv:
5744 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5745 DCCFlag = "-fdefault-calling-conv=vectorcall";
5747 case options::OPT__SLASH_Gregcall:
5748 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5749 DCCFlag = "-fdefault-calling-conv=regcall";
5753 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5754 if (ArchSupported && DCCFlag)
5755 CmdArgs.push_back(DCCFlag);
5758 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5759 A->render(Args, CmdArgs);
5761 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5762 CmdArgs.push_back("-fdiagnostics-format");
5763 if (Args.hasArg(options::OPT__SLASH_fallback))
5764 CmdArgs.push_back("msvc-fallback");
5766 CmdArgs.push_back("msvc");
5769 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5770 SmallVector<StringRef, 1> SplitArgs;
5771 StringRef(A->getValue()).split(SplitArgs, ",");
5772 bool Instrument = false;
5773 bool NoChecks = false;
5774 for (StringRef Arg : SplitArgs) {
5775 if (Arg.equals_lower("cf"))
5777 else if (Arg.equals_lower("cf-"))
5779 else if (Arg.equals_lower("nochecks"))
5781 else if (Arg.equals_lower("nochecks-"))
5784 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5786 // Currently there's no support emitting CFG instrumentation; the flag only
5787 // emits the table of address-taken functions.
5788 if (Instrument || NoChecks)
5789 CmdArgs.push_back("-cfguard");
5793 visualstudio::Compiler *Clang::getCLFallback() const {
5795 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5796 return CLFallback.get();
5800 const char *Clang::getBaseInputName(const ArgList &Args,
5801 const InputInfo &Input) {
5802 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5805 const char *Clang::getBaseInputStem(const ArgList &Args,
5806 const InputInfoList &Inputs) {
5807 const char *Str = getBaseInputName(Args, Inputs[0]);
5809 if (const char *End = strrchr(Str, '.'))
5810 return Args.MakeArgString(std::string(Str, End));
5815 const char *Clang::getDependencyFileName(const ArgList &Args,
5816 const InputInfoList &Inputs) {
5817 // FIXME: Think about this more.
5820 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5821 std::string Str(OutputOpt->getValue());
5822 Res = Str.substr(0, Str.rfind('.'));
5824 Res = getBaseInputStem(Args, Inputs);
5826 return Args.MakeArgString(Res + ".d");
5831 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5832 ArgStringList &CmdArgs) const {
5835 const llvm::Triple &Triple = getToolChain().getTriple();
5836 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5838 CmdArgs.push_back("-target-abi");
5839 CmdArgs.push_back(ABIName.data());
5842 void ClangAs::AddX86TargetArgs(const ArgList &Args,
5843 ArgStringList &CmdArgs) const {
5844 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5845 StringRef Value = A->getValue();
5846 if (Value == "intel" || Value == "att") {
5847 CmdArgs.push_back("-mllvm");
5848 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5850 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5851 << A->getOption().getName() << Value;
5856 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5857 const InputInfo &Output, const InputInfoList &Inputs,
5858 const ArgList &Args,
5859 const char *LinkingOutput) const {
5860 ArgStringList CmdArgs;
5862 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5863 const InputInfo &Input = Inputs[0];
5865 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5866 const std::string &TripleStr = Triple.getTriple();
5867 const auto &D = getToolChain().getDriver();
5869 // Don't warn about "clang -w -c foo.s"
5870 Args.ClaimAllArgs(options::OPT_w);
5871 // and "clang -emit-llvm -c foo.s"
5872 Args.ClaimAllArgs(options::OPT_emit_llvm);
5874 claimNoWarnArgs(Args);
5876 // Invoke ourselves in -cc1as mode.
5878 // FIXME: Implement custom jobs for internal actions.
5879 CmdArgs.push_back("-cc1as");
5881 // Add the "effective" target triple.
5882 CmdArgs.push_back("-triple");
5883 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5885 // Set the output mode, we currently only expect to be used as a real
5887 CmdArgs.push_back("-filetype");
5888 CmdArgs.push_back("obj");
5890 // Set the main file name, so that debug info works even with
5891 // -save-temps or preprocessed assembly.
5892 CmdArgs.push_back("-main-file-name");
5893 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5895 // Add the target cpu
5896 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5898 CmdArgs.push_back("-target-cpu");
5899 CmdArgs.push_back(Args.MakeArgString(CPU));
5902 // Add the target features
5903 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5905 // Ignore explicit -force_cpusubtype_ALL option.
5906 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5908 // Pass along any -I options so we get proper .include search paths.
5909 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5911 // Determine the original source input.
5912 const Action *SourceAction = &JA;
5913 while (SourceAction->getKind() != Action::InputClass) {
5914 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5915 SourceAction = SourceAction->getInputs()[0];
5918 // Forward -g and handle debug info related flags, assuming we are dealing
5919 // with an actual assembly file.
5920 bool WantDebug = false;
5921 unsigned DwarfVersion = 0;
5922 Args.ClaimAllArgs(options::OPT_g_Group);
5923 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5924 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5925 !A->getOption().matches(options::OPT_ggdb0);
5927 DwarfVersion = DwarfVersionNum(A->getSpelling());
5929 if (DwarfVersion == 0)
5930 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5932 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5934 if (SourceAction->getType() == types::TY_Asm ||
5935 SourceAction->getType() == types::TY_PP_Asm) {
5936 // You might think that it would be ok to set DebugInfoKind outside of
5937 // the guard for source type, however there is a test which asserts
5938 // that some assembler invocation receives no -debug-info-kind,
5939 // and it's not clear whether that test is just overly restrictive.
5940 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5941 : codegenoptions::NoDebugInfo);
5942 // Add the -fdebug-compilation-dir flag if needed.
5943 addDebugCompDirArg(Args, CmdArgs);
5945 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5947 // Set the AT_producer to the clang version when using the integrated
5948 // assembler on assembly source files.
5949 CmdArgs.push_back("-dwarf-debug-producer");
5950 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5952 // And pass along -I options
5953 Args.AddAllArgs(CmdArgs, options::OPT_I);
5955 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5956 llvm::DebuggerKind::Default);
5957 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
5960 // Handle -fPIC et al -- the relocation-model affects the assembler
5961 // for some targets.
5962 llvm::Reloc::Model RelocationModel;
5965 std::tie(RelocationModel, PICLevel, IsPIE) =
5966 ParsePICArgs(getToolChain(), Args);
5968 const char *RMName = RelocationModelName(RelocationModel);
5970 CmdArgs.push_back("-mrelocation-model");
5971 CmdArgs.push_back(RMName);
5974 // Optionally embed the -cc1as level arguments into the debug info, for build
5976 if (getToolChain().UseDwarfDebugFlags()) {
5977 ArgStringList OriginalArgs;
5978 for (const auto &Arg : Args)
5979 Arg->render(Args, OriginalArgs);
5981 SmallString<256> Flags;
5982 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5984 for (const char *OriginalArg : OriginalArgs) {
5985 SmallString<128> EscapedArg;
5986 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5988 Flags += EscapedArg;
5990 CmdArgs.push_back("-dwarf-debug-flags");
5991 CmdArgs.push_back(Args.MakeArgString(Flags));
5994 // FIXME: Add -static support, once we have it.
5996 // Add target specific flags.
5997 switch (getToolChain().getArch()) {
6001 case llvm::Triple::mips:
6002 case llvm::Triple::mipsel:
6003 case llvm::Triple::mips64:
6004 case llvm::Triple::mips64el:
6005 AddMIPSTargetArgs(Args, CmdArgs);
6008 case llvm::Triple::x86:
6009 case llvm::Triple::x86_64:
6010 AddX86TargetArgs(Args, CmdArgs);
6013 case llvm::Triple::arm:
6014 case llvm::Triple::armeb:
6015 case llvm::Triple::thumb:
6016 case llvm::Triple::thumbeb:
6017 // This isn't in AddARMTargetArgs because we want to do this for assembly
6019 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6020 options::OPT_mno_default_build_attributes, true)) {
6021 CmdArgs.push_back("-mllvm");
6022 CmdArgs.push_back("-arm-add-build-attributes");
6027 // Consume all the warning flags. Usually this would be handled more
6028 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6029 // doesn't handle that so rather than warning about unused flags that are
6030 // actually used, we'll lie by omission instead.
6031 // FIXME: Stop lying and consume only the appropriate driver flags
6032 Args.ClaimAllArgs(options::OPT_W_Group);
6034 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6035 getToolChain().getDriver());
6037 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6039 assert(Output.isFilename() && "Unexpected lipo output.");
6040 CmdArgs.push_back("-o");
6041 CmdArgs.push_back(Output.getFilename());
6043 const llvm::Triple &T = getToolChain().getTriple();
6045 if ((getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split) &&
6046 (T.isOSLinux() || T.isOSFuchsia())) {
6047 CmdArgs.push_back("-split-dwarf-file");
6048 CmdArgs.push_back(SplitDebugName(Args, Output));
6051 assert(Input.isFilename() && "Invalid input.");
6052 CmdArgs.push_back(Input.getFilename());
6054 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6055 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6058 // Begin OffloadBundler
6060 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6061 const InputInfo &Output,
6062 const InputInfoList &Inputs,
6063 const llvm::opt::ArgList &TCArgs,
6064 const char *LinkingOutput) const {
6065 // The version with only one output is expected to refer to a bundling job.
6066 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6068 // The bundling command looks like this:
6069 // clang-offload-bundler -type=bc
6070 // -targets=host-triple,openmp-triple1,openmp-triple2
6071 // -outputs=input_file
6072 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6074 ArgStringList CmdArgs;
6077 CmdArgs.push_back(TCArgs.MakeArgString(
6078 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6080 assert(JA.getInputs().size() == Inputs.size() &&
6081 "Not have inputs for all dependence actions??");
6084 SmallString<128> Triples;
6085 Triples += "-targets=";
6086 for (unsigned I = 0; I < Inputs.size(); ++I) {
6090 // Find ToolChain for this input.
6091 Action::OffloadKind CurKind = Action::OFK_Host;
6092 const ToolChain *CurTC = &getToolChain();
6093 const Action *CurDep = JA.getInputs()[I];
6095 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
6097 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
6098 assert(CurTC == nullptr && "Expected one dependence!");
6099 CurKind = A->getOffloadingDeviceKind();
6103 Triples += Action::GetOffloadKindName(CurKind);
6105 Triples += CurTC->getTriple().normalize();
6106 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6108 Triples += CurDep->getOffloadingArch();
6111 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6113 // Get bundled file command.
6115 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6117 // Get unbundled files command.
6118 SmallString<128> UB;
6120 for (unsigned I = 0; I < Inputs.size(); ++I) {
6124 // Find ToolChain for this input.
6125 const ToolChain *CurTC = &getToolChain();
6126 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6128 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6129 assert(CurTC == nullptr && "Expected one dependence!");
6133 UB += CurTC->getInputFilename(Inputs[I]);
6135 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6137 // All the inputs are encoded as commands.
6138 C.addCommand(llvm::make_unique<Command>(
6140 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6144 void OffloadBundler::ConstructJobMultipleOutputs(
6145 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6146 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6147 const char *LinkingOutput) const {
6148 // The version with multiple outputs is expected to refer to a unbundling job.
6149 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6151 // The unbundling command looks like this:
6152 // clang-offload-bundler -type=bc
6153 // -targets=host-triple,openmp-triple1,openmp-triple2
6154 // -inputs=input_file
6155 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6158 ArgStringList CmdArgs;
6160 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6161 InputInfo Input = Inputs.front();
6164 CmdArgs.push_back(TCArgs.MakeArgString(
6165 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6168 SmallString<128> Triples;
6169 Triples += "-targets=";
6170 auto DepInfo = UA.getDependentActionsInfo();
6171 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6175 auto &Dep = DepInfo[I];
6176 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6178 Triples += Dep.DependentToolChain->getTriple().normalize();
6179 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6180 !Dep.DependentBoundArch.empty()) {
6182 Triples += Dep.DependentBoundArch;
6186 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6188 // Get bundled file command.
6190 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6192 // Get unbundled files command.
6193 SmallString<128> UB;
6195 for (unsigned I = 0; I < Outputs.size(); ++I) {
6198 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
6200 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6201 CmdArgs.push_back("-unbundle");
6203 // All the inputs are encoded as commands.
6204 C.addCommand(llvm::make_unique<Command>(
6206 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),