1 //===--- Tools.cpp - Tools 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 "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Compilation.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "clang/Driver/Util.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/TargetParser.h"
47 #include <unistd.h> // For getuid().
50 using namespace clang::driver;
51 using namespace clang::driver::tools;
52 using namespace clang;
53 using namespace llvm::opt;
55 static void handleTargetFeaturesGroup(const ArgList &Args,
56 std::vector<const char *> &Features,
58 for (const Arg *A : Args.filtered(Group)) {
59 StringRef Name = A->getOption().getName();
63 assert(Name.startswith("m") && "Invalid feature name.");
64 Name = Name.substr(1);
66 bool IsNegative = Name.startswith("no-");
68 Name = Name.substr(3);
69 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
73 static const char *getSparcAsmModeForCPU(StringRef Name,
74 const llvm::Triple &Triple) {
75 if (Triple.getArch() == llvm::Triple::sparcv9) {
76 return llvm::StringSwitch<const char *>(Name)
77 .Case("niagara", "-Av9b")
78 .Case("niagara2", "-Av9b")
79 .Case("niagara3", "-Av9d")
80 .Case("niagara4", "-Av9d")
83 return llvm::StringSwitch<const char *>(Name)
85 .Case("supersparc", "-Av8")
86 .Case("sparclite", "-Asparclite")
87 .Case("f934", "-Asparclite")
88 .Case("hypersparc", "-Av8")
89 .Case("sparclite86x", "-Asparclite")
90 .Case("sparclet", "-Asparclet")
91 .Case("tsc701", "-Asparclet")
92 .Case("v9", "-Av8plus")
93 .Case("ultrasparc", "-Av8plus")
94 .Case("ultrasparc3", "-Av8plus")
95 .Case("niagara", "-Av8plusb")
96 .Case("niagara2", "-Av8plusb")
97 .Case("niagara3", "-Av8plusd")
98 .Case("niagara4", "-Av8plusd")
99 .Case("leon2", "-Av8")
100 .Case("at697e", "-Av8")
101 .Case("at697f", "-Av8")
102 .Case("leon3", "-Av8")
103 .Case("ut699", "-Av8")
104 .Case("gr712rc", "-Av8")
105 .Case("leon4", "-Av8")
106 .Case("gr740", "-Av8")
111 /// CheckPreprocessingOptions - Perform some validation of preprocessing
112 /// arguments that is shared with gcc.
113 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
114 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
115 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
116 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
117 D.Diag(diag::err_drv_argument_only_allowed_with)
118 << A->getBaseArg().getAsString(Args)
119 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
124 /// CheckCodeGenerationOptions - Perform some validation of code generation
125 /// arguments that is shared with gcc.
126 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
127 // In gcc, only ARM checks this, but it seems reasonable to check universally.
128 if (Args.hasArg(options::OPT_static))
130 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
131 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
135 // Add backslashes to escape spaces and other backslashes.
136 // This is used for the space-separated argument list specified with
137 // the -dwarf-debug-flags option.
138 static void EscapeSpacesAndBackslashes(const char *Arg,
139 SmallVectorImpl<char> &Res) {
140 for (; *Arg; ++Arg) {
153 // Quote target names for inclusion in GNU Make dependency files.
154 // Only the characters '$', '#', ' ', '\t' are quoted.
155 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
156 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
160 // Escape the preceding backslashes
161 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
164 // Escape the space/tab
177 Res.push_back(Target[i]);
181 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
182 const char *ArgName, const char *EnvVar) {
183 const char *DirList = ::getenv(EnvVar);
184 bool CombinedArg = false;
187 return; // Nothing to do.
189 StringRef Name(ArgName);
190 if (Name.equals("-I") || Name.equals("-L"))
193 StringRef Dirs(DirList);
194 if (Dirs.empty()) // Empty string should not add '.'.
197 StringRef::size_type Delim;
198 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
199 if (Delim == 0) { // Leading colon.
201 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
203 CmdArgs.push_back(ArgName);
204 CmdArgs.push_back(".");
209 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
211 CmdArgs.push_back(ArgName);
212 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
215 Dirs = Dirs.substr(Delim + 1);
218 if (Dirs.empty()) { // Trailing colon.
220 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
222 CmdArgs.push_back(ArgName);
223 CmdArgs.push_back(".");
225 } else { // Add the last path.
227 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
229 CmdArgs.push_back(ArgName);
230 CmdArgs.push_back(Args.MakeArgString(Dirs));
235 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
236 const ArgList &Args, ArgStringList &CmdArgs) {
237 const Driver &D = TC.getDriver();
239 // Add extra linker input arguments which are not treated as inputs
240 // (constructed via -Xarch_).
241 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
243 for (const auto &II : Inputs) {
244 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
245 // Don't try to pass LLVM inputs unless we have native support.
246 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
248 // Add filenames immediately.
249 if (II.isFilename()) {
250 CmdArgs.push_back(II.getFilename());
254 // Otherwise, this is a linker input argument.
255 const Arg &A = II.getInputArg();
257 // Handle reserved library options.
258 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
259 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
260 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
261 TC.AddCCKextLibArgs(Args, CmdArgs);
262 else if (A.getOption().matches(options::OPT_z)) {
263 // Pass -z prefix for gcc linker compatibility.
265 A.render(Args, CmdArgs);
267 A.renderAsInput(Args, CmdArgs);
271 // LIBRARY_PATH - included following the user specified library paths.
272 // and only supported on native toolchains.
273 if (!TC.isCrossCompiling())
274 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
277 /// \brief Determine whether Objective-C automated reference counting is
279 static bool isObjCAutoRefCount(const ArgList &Args) {
280 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
283 /// \brief Determine whether we are linking the ObjC runtime.
284 static bool isObjCRuntimeLinked(const ArgList &Args) {
285 if (isObjCAutoRefCount(Args)) {
286 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
289 return Args.hasArg(options::OPT_fobjc_link_runtime);
292 static bool forwardToGCC(const Option &O) {
293 // Don't forward inputs from the original command line. They are added from
295 return O.getKind() != Option::InputClass &&
296 !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
299 /// Add the C++ include args of other offloading toolchains. If this is a host
300 /// job, the device toolchains are added. If this is a device job, the host
301 /// toolchains will be added.
302 static void addExtraOffloadCXXStdlibIncludeArgs(Compilation &C,
305 ArgStringList &CmdArgs) {
307 if (JA.isHostOffloading(Action::OFK_Cuda))
308 C.getSingleOffloadToolChain<Action::OFK_Cuda>()
309 ->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
310 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
311 C.getSingleOffloadToolChain<Action::OFK_Host>()
312 ->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
314 // TODO: Add support for other programming models here.
317 /// Add the include args that are specific of each offloading programming model.
318 static void addExtraOffloadSpecificIncludeArgs(Compilation &C,
321 ArgStringList &CmdArgs) {
323 if (JA.isHostOffloading(Action::OFK_Cuda))
324 C.getSingleOffloadToolChain<Action::OFK_Host>()->AddCudaIncludeArgs(
326 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
327 C.getSingleOffloadToolChain<Action::OFK_Cuda>()->AddCudaIncludeArgs(
330 // TODO: Add support for other programming models here.
333 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
334 const Driver &D, const ArgList &Args,
335 ArgStringList &CmdArgs,
336 const InputInfo &Output,
337 const InputInfoList &Inputs) const {
339 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
341 CheckPreprocessingOptions(D, Args);
343 Args.AddLastArg(CmdArgs, options::OPT_C);
344 Args.AddLastArg(CmdArgs, options::OPT_CC);
346 // Handle dependency file generation.
347 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
348 (A = Args.getLastArg(options::OPT_MD)) ||
349 (A = Args.getLastArg(options::OPT_MMD))) {
350 // Determine the output location.
352 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
353 DepFile = MF->getValue();
354 C.addFailureResultFile(DepFile, &JA);
355 } else if (Output.getType() == types::TY_Dependencies) {
356 DepFile = Output.getFilename();
357 } else if (A->getOption().matches(options::OPT_M) ||
358 A->getOption().matches(options::OPT_MM)) {
361 DepFile = getDependencyFileName(Args, Inputs);
362 C.addFailureResultFile(DepFile, &JA);
364 CmdArgs.push_back("-dependency-file");
365 CmdArgs.push_back(DepFile);
367 // Add a default target if one wasn't specified.
368 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
369 const char *DepTarget;
371 // If user provided -o, that is the dependency target, except
372 // when we are only generating a dependency file.
373 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
374 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
375 DepTarget = OutputOpt->getValue();
377 // Otherwise derive from the base input.
379 // FIXME: This should use the computed output file location.
380 SmallString<128> P(Inputs[0].getBaseInput());
381 llvm::sys::path::replace_extension(P, "o");
382 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
385 CmdArgs.push_back("-MT");
386 SmallString<128> Quoted;
387 QuoteTarget(DepTarget, Quoted);
388 CmdArgs.push_back(Args.MakeArgString(Quoted));
391 if (A->getOption().matches(options::OPT_M) ||
392 A->getOption().matches(options::OPT_MD))
393 CmdArgs.push_back("-sys-header-deps");
394 if ((isa<PrecompileJobAction>(JA) &&
395 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
396 Args.hasArg(options::OPT_fmodule_file_deps))
397 CmdArgs.push_back("-module-file-deps");
400 if (Args.hasArg(options::OPT_MG)) {
401 if (!A || A->getOption().matches(options::OPT_MD) ||
402 A->getOption().matches(options::OPT_MMD))
403 D.Diag(diag::err_drv_mg_requires_m_or_mm);
404 CmdArgs.push_back("-MG");
407 Args.AddLastArg(CmdArgs, options::OPT_MP);
408 Args.AddLastArg(CmdArgs, options::OPT_MV);
410 // Convert all -MQ <target> args to -MT <quoted target>
411 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
414 if (A->getOption().matches(options::OPT_MQ)) {
415 CmdArgs.push_back("-MT");
416 SmallString<128> Quoted;
417 QuoteTarget(A->getValue(), Quoted);
418 CmdArgs.push_back(Args.MakeArgString(Quoted));
420 // -MT flag - no change
422 A->render(Args, CmdArgs);
426 // Add -i* options, and automatically translate to
427 // -include-pch/-include-pth for transparent PCH support. It's
428 // wonky, but we include looking for .gch so we can support seamless
429 // replacement into a build system already set up to be generating
431 int YcIndex = -1, YuIndex = -1;
434 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
435 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
436 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
437 // Walk the whole i_Group and skip non "-include" flags so that the index
438 // here matches the index in the next loop below.
440 if (!A->getOption().matches(options::OPT_include))
442 if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
444 if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
448 if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
449 Driver::InputList Inputs;
450 D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
451 assert(Inputs.size() == 1 && "Need one input when building pch");
452 CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
453 Inputs[0].second->getValue()));
456 bool RenderedImplicitInclude = false;
458 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
461 if (getToolChain().getDriver().IsCLMode() &&
462 A->getOption().matches(options::OPT_include)) {
463 // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
464 // include is compiled into foo.h, and everything after goes into
465 // the .obj file. /Yufoo.h means that all includes prior to and including
466 // foo.h are completely skipped and replaced with a use of the pch file
467 // for foo.h. (Each flag can have at most one value, multiple /Yc flags
468 // just mean that the last one wins.) If /Yc and /Yu are both present
469 // and refer to the same file, /Yc wins.
470 // Note that OPT__SLASH_FI gets mapped to OPT_include.
471 // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
472 // cl.exe seems to support both flags with different values, but that
473 // seems strange (which flag does /Fp now refer to?), so don't implement
474 // that until someone needs it.
475 int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
476 if (PchIndex != -1) {
477 if (isa<PrecompileJobAction>(JA)) {
478 // When building the pch, skip all includes after the pch.
479 assert(YcIndex != -1 && PchIndex == YcIndex);
483 // When using the pch, skip all includes prior to the pch.
488 if (AI == PchIndex) {
490 CmdArgs.push_back("-include-pch");
492 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
497 } else if (A->getOption().matches(options::OPT_include)) {
498 // Handling of gcc-style gch precompiled headers.
499 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
500 RenderedImplicitInclude = true;
502 // Use PCH if the user requested it.
503 bool UsePCH = D.CCCUsePCH;
505 bool FoundPTH = false;
506 bool FoundPCH = false;
507 SmallString<128> P(A->getValue());
508 // We want the files to have a name like foo.h.pch. Add a dummy extension
509 // so that replace_extension does the right thing.
512 llvm::sys::path::replace_extension(P, "pch");
513 if (llvm::sys::fs::exists(P))
518 llvm::sys::path::replace_extension(P, "pth");
519 if (llvm::sys::fs::exists(P))
523 if (!FoundPCH && !FoundPTH) {
524 llvm::sys::path::replace_extension(P, "gch");
525 if (llvm::sys::fs::exists(P)) {
531 if (FoundPCH || FoundPTH) {
532 if (IsFirstImplicitInclude) {
535 CmdArgs.push_back("-include-pch");
537 CmdArgs.push_back("-include-pth");
538 CmdArgs.push_back(Args.MakeArgString(P));
541 // Ignore the PCH if not first on command line and emit warning.
542 D.Diag(diag::warn_drv_pch_not_first_include) << P
543 << A->getAsString(Args);
546 } else if (A->getOption().matches(options::OPT_isystem_after)) {
547 // Handling of paths which must come late. These entries are handled by
548 // the toolchain itself after the resource dir is inserted in the right
550 // Do not claim the argument so that the use of the argument does not
551 // silently go unnoticed on toolchains which do not honour the option.
555 // Not translated, render as usual.
557 A->render(Args, CmdArgs);
560 Args.AddAllArgs(CmdArgs,
561 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
562 options::OPT_F, options::OPT_index_header_map});
564 // Add -Wp, and -Xpreprocessor if using the preprocessor.
566 // FIXME: There is a very unfortunate problem here, some troubled
567 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
568 // really support that we would have to parse and then translate
570 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
571 options::OPT_Xpreprocessor);
573 // -I- is a deprecated GCC feature, reject it.
574 if (Arg *A = Args.getLastArg(options::OPT_I_))
575 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
577 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
578 // -isysroot to the CC1 invocation.
579 StringRef sysroot = C.getSysRoot();
581 if (!Args.hasArg(options::OPT_isysroot)) {
582 CmdArgs.push_back("-isysroot");
583 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
587 // Parse additional include paths from environment variables.
588 // FIXME: We should probably sink the logic for handling these from the
589 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
590 // CPATH - included following the user specified includes (but prior to
591 // builtin and standard includes).
592 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
593 // C_INCLUDE_PATH - system includes enabled when compiling C.
594 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
595 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
596 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
597 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
598 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
599 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
600 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
602 // While adding the include arguments, we also attempt to retrieve the
603 // arguments of related offloading toolchains or arguments that are specific
604 // of an offloading programming model.
606 // Add C++ include arguments, if needed.
607 if (types::isCXX(Inputs[0].getType())) {
608 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
609 addExtraOffloadCXXStdlibIncludeArgs(C, JA, Args, CmdArgs);
612 // Add system include arguments for all targets but IAMCU.
614 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
615 addExtraOffloadCXXStdlibIncludeArgs(C, JA, Args, CmdArgs);
617 // For IAMCU add special include arguments.
618 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
621 // Add offload include arguments, if needed.
622 addExtraOffloadSpecificIncludeArgs(C, JA, Args, CmdArgs);
625 // FIXME: Move to target hook.
626 static bool isSignedCharDefault(const llvm::Triple &Triple) {
627 switch (Triple.getArch()) {
631 case llvm::Triple::aarch64:
632 case llvm::Triple::aarch64_be:
633 case llvm::Triple::arm:
634 case llvm::Triple::armeb:
635 case llvm::Triple::thumb:
636 case llvm::Triple::thumbeb:
637 if (Triple.isOSDarwin() || Triple.isOSWindows())
641 case llvm::Triple::ppc:
642 case llvm::Triple::ppc64:
643 if (Triple.isOSDarwin())
647 case llvm::Triple::hexagon:
648 case llvm::Triple::ppc64le:
649 case llvm::Triple::systemz:
650 case llvm::Triple::xcore:
655 static bool isNoCommonDefault(const llvm::Triple &Triple) {
656 switch (Triple.getArch()) {
660 case llvm::Triple::xcore:
661 case llvm::Triple::wasm32:
662 case llvm::Triple::wasm64:
670 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
671 llvm::StringRef Arch = Triple.getArchName();
672 return llvm::ARM::parseArchVersion(Arch);
675 // True if M-profile.
676 static bool isARMMProfile(const llvm::Triple &Triple) {
677 llvm::StringRef Arch = Triple.getArchName();
678 unsigned Profile = llvm::ARM::parseArchProfile(Arch);
679 return Profile == llvm::ARM::PK_M;
682 // Get Arch/CPU from args.
683 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
684 llvm::StringRef &CPU, bool FromAs = false) {
685 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
687 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
688 Arch = A->getValue();
693 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
694 StringRef Value = A->getValue();
695 if (Value.startswith("-mcpu="))
696 CPU = Value.substr(6);
697 if (Value.startswith("-march="))
698 Arch = Value.substr(7);
703 // FIXME: Use ARMTargetParser.
704 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
705 const ArgList &Args, StringRef HWDiv,
706 std::vector<const char *> &Features) {
707 unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
708 if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
709 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
713 static void getARMFPUFeatures(const Driver &D, const Arg *A,
714 const ArgList &Args, StringRef FPU,
715 std::vector<const char *> &Features) {
716 unsigned FPUID = llvm::ARM::parseFPU(FPU);
717 if (!llvm::ARM::getFPUFeatures(FPUID, Features))
718 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
721 // Decode ARM features from string like +[no]featureA+[no]featureB+...
722 static bool DecodeARMFeatures(const Driver &D, StringRef text,
723 std::vector<const char *> &Features) {
724 SmallVector<StringRef, 8> Split;
725 text.split(Split, StringRef("+"), -1, false);
727 for (StringRef Feature : Split) {
728 const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
730 Features.push_back(FeatureName);
737 // Check if -march is valid by checking if it can be canonicalised and parsed.
738 // getARMArch is used here instead of just checking the -march value in order
739 // to handle -march=native correctly.
740 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
741 llvm::StringRef ArchName,
742 std::vector<const char *> &Features,
743 const llvm::Triple &Triple) {
744 std::pair<StringRef, StringRef> Split = ArchName.split("+");
746 std::string MArch = arm::getARMArch(ArchName, Triple);
747 if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
748 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
749 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
752 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
753 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
754 llvm::StringRef CPUName, llvm::StringRef ArchName,
755 std::vector<const char *> &Features,
756 const llvm::Triple &Triple) {
757 std::pair<StringRef, StringRef> Split = CPUName.split("+");
759 std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
760 if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
761 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
762 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
765 static bool useAAPCSForMachO(const llvm::Triple &T) {
766 // The backend is hardwired to assume AAPCS for M-class processors, ensure
767 // the frontend matches that.
768 return T.getEnvironment() == llvm::Triple::EABI ||
769 T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
772 // Select the float ABI as determined by -msoft-float, -mhard-float, and
774 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
775 const Driver &D = TC.getDriver();
776 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
777 auto SubArch = getARMSubArchVersionNumber(Triple);
778 arm::FloatABI ABI = FloatABI::Invalid;
780 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
781 options::OPT_mfloat_abi_EQ)) {
782 if (A->getOption().matches(options::OPT_msoft_float)) {
783 ABI = FloatABI::Soft;
784 } else if (A->getOption().matches(options::OPT_mhard_float)) {
785 ABI = FloatABI::Hard;
787 ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
788 .Case("soft", FloatABI::Soft)
789 .Case("softfp", FloatABI::SoftFP)
790 .Case("hard", FloatABI::Hard)
791 .Default(FloatABI::Invalid);
792 if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
793 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
794 ABI = FloatABI::Soft;
798 // It is incorrect to select hard float ABI on MachO platforms if the ABI is
800 if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
801 ABI == FloatABI::Hard) {
802 D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
803 << Triple.getArchName();
807 // If unspecified, choose the default based on the platform.
808 if (ABI == FloatABI::Invalid) {
809 switch (Triple.getOS()) {
810 case llvm::Triple::Darwin:
811 case llvm::Triple::MacOSX:
812 case llvm::Triple::IOS:
813 case llvm::Triple::TvOS: {
814 // Darwin defaults to "softfp" for v6 and v7.
815 ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
816 ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
819 case llvm::Triple::WatchOS:
820 ABI = FloatABI::Hard;
823 // FIXME: this is invalid for WindowsCE
824 case llvm::Triple::Win32:
825 ABI = FloatABI::Hard;
828 case llvm::Triple::FreeBSD:
829 switch (Triple.getEnvironment()) {
830 case llvm::Triple::GNUEABIHF:
831 ABI = FloatABI::Hard;
834 // FreeBSD defaults to soft float
835 ABI = FloatABI::Soft;
841 switch (Triple.getEnvironment()) {
842 case llvm::Triple::GNUEABIHF:
843 case llvm::Triple::MuslEABIHF:
844 case llvm::Triple::EABIHF:
845 ABI = FloatABI::Hard;
847 case llvm::Triple::GNUEABI:
848 case llvm::Triple::MuslEABI:
849 case llvm::Triple::EABI:
850 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
851 ABI = FloatABI::SoftFP;
853 case llvm::Triple::Android:
854 ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
857 // Assume "soft", but warn the user we are guessing.
858 if (Triple.isOSBinFormatMachO() &&
859 Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
860 ABI = FloatABI::Hard;
862 ABI = FloatABI::Soft;
864 if (Triple.getOS() != llvm::Triple::UnknownOS ||
865 !Triple.isOSBinFormatMachO())
866 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
872 assert(ABI != FloatABI::Invalid && "must select an ABI");
876 static void getARMTargetFeatures(const ToolChain &TC,
877 const llvm::Triple &Triple,
879 std::vector<const char *> &Features,
881 const Driver &D = TC.getDriver();
884 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
885 arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
886 const Arg *WaCPU = nullptr, *WaFPU = nullptr;
887 const Arg *WaHDiv = nullptr, *WaArch = nullptr;
890 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
891 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
892 // stripped out by the ARM target. We should probably pass this a new
893 // -target-option, which is handled by the -cc1/-cc1as invocation.
895 // FIXME2: For consistency, it would be ideal if we set up the target
896 // machine state the same when using the frontend or the assembler. We don't
897 // currently do that for the assembler, we pass the options directly to the
898 // backend and never even instantiate the frontend TargetInfo. If we did,
899 // and used its handleTargetFeatures hook, then we could ensure the
900 // assembler and the frontend behave the same.
902 // Use software floating point operations?
903 if (ABI == arm::FloatABI::Soft)
904 Features.push_back("+soft-float");
906 // Use software floating point argument passing?
907 if (ABI != arm::FloatABI::Hard)
908 Features.push_back("+soft-float-abi");
910 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
911 // to the assembler correctly.
913 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
914 StringRef Value = A->getValue();
915 if (Value.startswith("-mfpu=")) {
917 } else if (Value.startswith("-mcpu=")) {
919 } else if (Value.startswith("-mhwdiv=")) {
921 } else if (Value.startswith("-march=")) {
927 // Check -march. ClangAs gives preference to -Wa,-march=.
928 const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
932 D.Diag(clang::diag::warn_drv_unused_argument)
933 << ArchArg->getAsString(Args);
934 ArchName = StringRef(WaArch->getValue()).substr(7);
935 checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
937 D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
938 } else if (ArchArg) {
939 ArchName = ArchArg->getValue();
940 checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
943 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
944 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
948 D.Diag(clang::diag::warn_drv_unused_argument)
949 << CPUArg->getAsString(Args);
950 CPUName = StringRef(WaCPU->getValue()).substr(6);
951 checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
953 CPUName = CPUArg->getValue();
954 checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
957 // Add CPU features for generic CPUs
958 if (CPUName == "native") {
959 llvm::StringMap<bool> HostFeatures;
960 if (llvm::sys::getHostCPUFeatures(HostFeatures))
961 for (auto &F : HostFeatures)
963 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
966 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
967 const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
970 D.Diag(clang::diag::warn_drv_unused_argument)
971 << FPUArg->getAsString(Args);
972 getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
975 getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
978 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
979 const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
982 D.Diag(clang::diag::warn_drv_unused_argument)
983 << HDivArg->getAsString(Args);
984 getARMHWDivFeatures(D, WaHDiv, Args,
985 StringRef(WaHDiv->getValue()).substr(8), Features);
987 getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
989 // Setting -msoft-float effectively disables NEON because of the GCC
990 // implementation, although the same isn't true of VFP or VFP3.
991 if (ABI == arm::FloatABI::Soft) {
992 Features.push_back("-neon");
993 // Also need to explicitly disable features which imply NEON.
994 Features.push_back("-crypto");
997 // En/disable crc code generation.
998 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
999 if (A->getOption().matches(options::OPT_mcrc))
1000 Features.push_back("+crc");
1002 Features.push_back("-crc");
1005 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
1006 // neither options are specified, see if we are compiling for kernel/kext and
1007 // decide whether to pass "+long-calls" based on the OS and its version.
1008 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
1009 options::OPT_mno_long_calls)) {
1010 if (A->getOption().matches(options::OPT_mlong_calls))
1011 Features.push_back("+long-calls");
1012 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
1013 !Triple.isWatchOS()) {
1014 Features.push_back("+long-calls");
1017 // Kernel code has more strict alignment requirements.
1019 Features.push_back("+strict-align");
1020 else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
1021 options::OPT_munaligned_access)) {
1022 if (A->getOption().matches(options::OPT_munaligned_access)) {
1023 // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
1024 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1025 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
1026 // v8M Baseline follows on from v6M, so doesn't support unaligned memory
1028 else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
1029 D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
1031 Features.push_back("+strict-align");
1033 // Assume pre-ARMv6 doesn't support unaligned accesses.
1035 // ARMv6 may or may not support unaligned accesses depending on the
1036 // SCTLR.U bit, which is architecture-specific. We assume ARMv6
1037 // Darwin and NetBSD targets support unaligned accesses, and others don't.
1039 // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
1040 // which raises an alignment fault on unaligned accesses. Linux
1041 // defaults this bit to 0 and handles it as a system-wide (not
1042 // per-process) setting. It is therefore safe to assume that ARMv7+
1043 // Linux targets support unaligned accesses. The same goes for NaCl.
1045 // The above behavior is consistent with GCC.
1046 int VersionNum = getARMSubArchVersionNumber(Triple);
1047 if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
1048 if (VersionNum < 6 ||
1049 Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1050 Features.push_back("+strict-align");
1051 } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
1053 Features.push_back("+strict-align");
1055 Features.push_back("+strict-align");
1058 // llvm does not support reserving registers in general. There is support
1059 // for reserving r9 on ARM though (defined as a platform-specific register
1061 if (Args.hasArg(options::OPT_ffixed_r9))
1062 Features.push_back("+reserve-r9");
1064 // The kext linker doesn't know how to deal with movw/movt.
1065 if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
1066 Features.push_back("+no-movt");
1069 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1070 ArgStringList &CmdArgs, bool KernelOrKext) const {
1071 // Select the ABI to use.
1072 // FIXME: Support -meabi.
1073 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1074 const char *ABIName = nullptr;
1075 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1076 ABIName = A->getValue();
1077 } else if (Triple.isOSBinFormatMachO()) {
1078 if (useAAPCSForMachO(Triple)) {
1080 } else if (Triple.isWatchABI()) {
1081 ABIName = "aapcs16";
1083 ABIName = "apcs-gnu";
1085 } else if (Triple.isOSWindows()) {
1086 // FIXME: this is invalid for WindowsCE
1089 // Select the default based on the platform.
1090 switch (Triple.getEnvironment()) {
1091 case llvm::Triple::Android:
1092 case llvm::Triple::GNUEABI:
1093 case llvm::Triple::GNUEABIHF:
1094 case llvm::Triple::MuslEABI:
1095 case llvm::Triple::MuslEABIHF:
1096 ABIName = "aapcs-linux";
1098 case llvm::Triple::EABIHF:
1099 case llvm::Triple::EABI:
1103 if (Triple.getOS() == llvm::Triple::NetBSD)
1104 ABIName = "apcs-gnu";
1110 CmdArgs.push_back("-target-abi");
1111 CmdArgs.push_back(ABIName);
1113 // Determine floating point ABI from the options & target defaults.
1114 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1115 if (ABI == arm::FloatABI::Soft) {
1116 // Floating point operations and argument passing are soft.
1117 // FIXME: This changes CPP defines, we need -target-soft-float.
1118 CmdArgs.push_back("-msoft-float");
1119 CmdArgs.push_back("-mfloat-abi");
1120 CmdArgs.push_back("soft");
1121 } else if (ABI == arm::FloatABI::SoftFP) {
1122 // Floating point operations are hard, but argument passing is soft.
1123 CmdArgs.push_back("-mfloat-abi");
1124 CmdArgs.push_back("soft");
1126 // Floating point operations and argument passing are hard.
1127 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1128 CmdArgs.push_back("-mfloat-abi");
1129 CmdArgs.push_back("hard");
1132 // Forward the -mglobal-merge option for explicit control over the pass.
1133 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1134 options::OPT_mno_global_merge)) {
1135 CmdArgs.push_back("-backend-option");
1136 if (A->getOption().matches(options::OPT_mno_global_merge))
1137 CmdArgs.push_back("-arm-global-merge=false");
1139 CmdArgs.push_back("-arm-global-merge=true");
1142 if (!Args.hasFlag(options::OPT_mimplicit_float,
1143 options::OPT_mno_implicit_float, true))
1144 CmdArgs.push_back("-no-implicit-float");
1148 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1150 static std::string getAArch64TargetCPU(const ArgList &Args) {
1153 // If we have -mtune or -mcpu, use that.
1154 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1155 CPU = StringRef(A->getValue()).lower();
1156 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1157 StringRef Mcpu = A->getValue();
1158 CPU = Mcpu.split("+").first.lower();
1161 // Handle CPU name is 'native'.
1162 if (CPU == "native")
1163 return llvm::sys::getHostCPUName();
1164 else if (CPU.size())
1167 // Make sure we pick "cyclone" if -arch is used.
1168 // FIXME: Should this be picked by checking the target triple instead?
1169 if (Args.getLastArg(options::OPT_arch))
1175 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1176 ArgStringList &CmdArgs) const {
1177 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1178 llvm::Triple Triple(TripleStr);
1180 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1181 Args.hasArg(options::OPT_mkernel) ||
1182 Args.hasArg(options::OPT_fapple_kext))
1183 CmdArgs.push_back("-disable-red-zone");
1185 if (!Args.hasFlag(options::OPT_mimplicit_float,
1186 options::OPT_mno_implicit_float, true))
1187 CmdArgs.push_back("-no-implicit-float");
1189 const char *ABIName = nullptr;
1190 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1191 ABIName = A->getValue();
1192 else if (Triple.isOSDarwin())
1193 ABIName = "darwinpcs";
1197 CmdArgs.push_back("-target-abi");
1198 CmdArgs.push_back(ABIName);
1200 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1201 options::OPT_mno_fix_cortex_a53_835769)) {
1202 CmdArgs.push_back("-backend-option");
1203 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1204 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1206 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1207 } else if (Triple.isAndroid()) {
1208 // Enabled A53 errata (835769) workaround by default on android
1209 CmdArgs.push_back("-backend-option");
1210 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1213 // Forward the -mglobal-merge option for explicit control over the pass.
1214 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1215 options::OPT_mno_global_merge)) {
1216 CmdArgs.push_back("-backend-option");
1217 if (A->getOption().matches(options::OPT_mno_global_merge))
1218 CmdArgs.push_back("-aarch64-global-merge=false");
1220 CmdArgs.push_back("-aarch64-global-merge=true");
1224 // Get CPU and ABI names. They are not independent
1225 // so we have to calculate them together.
1226 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1227 StringRef &CPUName, StringRef &ABIName) {
1228 const char *DefMips32CPU = "mips32r2";
1229 const char *DefMips64CPU = "mips64r2";
1231 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1232 // default for mips64(el)?-img-linux-gnu.
1233 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1234 Triple.getEnvironment() == llvm::Triple::GNU) {
1235 DefMips32CPU = "mips32r6";
1236 DefMips64CPU = "mips64r6";
1239 // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1240 if (Triple.isAndroid()) {
1241 DefMips32CPU = "mips32";
1242 DefMips64CPU = "mips64r6";
1245 // MIPS3 is the default for mips64*-unknown-openbsd.
1246 if (Triple.getOS() == llvm::Triple::OpenBSD)
1247 DefMips64CPU = "mips3";
1249 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1250 CPUName = A->getValue();
1252 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1253 ABIName = A->getValue();
1254 // Convert a GNU style Mips ABI name to the name
1255 // accepted by LLVM Mips backend.
1256 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1262 // Setup default CPU and ABI names.
1263 if (CPUName.empty() && ABIName.empty()) {
1264 switch (Triple.getArch()) {
1266 llvm_unreachable("Unexpected triple arch name");
1267 case llvm::Triple::mips:
1268 case llvm::Triple::mipsel:
1269 CPUName = DefMips32CPU;
1271 case llvm::Triple::mips64:
1272 case llvm::Triple::mips64el:
1273 CPUName = DefMips64CPU;
1278 if (ABIName.empty() &&
1279 (Triple.getVendor() == llvm::Triple::MipsTechnologies ||
1280 Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) {
1281 ABIName = llvm::StringSwitch<const char *>(CPUName)
1282 .Case("mips1", "o32")
1283 .Case("mips2", "o32")
1284 .Case("mips3", "n64")
1285 .Case("mips4", "n64")
1286 .Case("mips5", "n64")
1287 .Case("mips32", "o32")
1288 .Case("mips32r2", "o32")
1289 .Case("mips32r3", "o32")
1290 .Case("mips32r5", "o32")
1291 .Case("mips32r6", "o32")
1292 .Case("mips64", "n64")
1293 .Case("mips64r2", "n64")
1294 .Case("mips64r3", "n64")
1295 .Case("mips64r5", "n64")
1296 .Case("mips64r6", "n64")
1297 .Case("octeon", "n64")
1298 .Case("p5600", "o32")
1302 if (ABIName.empty()) {
1303 // Deduce ABI name from the target triple.
1304 if (Triple.getArch() == llvm::Triple::mips ||
1305 Triple.getArch() == llvm::Triple::mipsel)
1311 if (CPUName.empty()) {
1312 // Deduce CPU name from ABI name.
1313 CPUName = llvm::StringSwitch<const char *>(ABIName)
1314 .Case("o32", DefMips32CPU)
1315 .Cases("n32", "n64", DefMips64CPU)
1319 // FIXME: Warn on inconsistent use of -march and -mabi.
1322 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1323 const llvm::Triple &Triple) {
1324 StringRef CPUName, ABIName;
1325 tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1326 return llvm::StringSwitch<std::string>(ABIName)
1332 // Convert ABI name to the GNU tools acceptable variant.
1333 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1334 return llvm::StringSwitch<llvm::StringRef>(ABI)
1340 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1341 // and -mfloat-abi=.
1342 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1343 mips::FloatABI ABI = mips::FloatABI::Invalid;
1345 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1346 options::OPT_mfloat_abi_EQ)) {
1347 if (A->getOption().matches(options::OPT_msoft_float))
1348 ABI = mips::FloatABI::Soft;
1349 else if (A->getOption().matches(options::OPT_mhard_float))
1350 ABI = mips::FloatABI::Hard;
1352 ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1353 .Case("soft", mips::FloatABI::Soft)
1354 .Case("hard", mips::FloatABI::Hard)
1355 .Default(mips::FloatABI::Invalid);
1356 if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1357 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1358 ABI = mips::FloatABI::Hard;
1363 // If unspecified, choose the default based on the platform.
1364 if (ABI == mips::FloatABI::Invalid) {
1365 // Assume "hard", because it's a default value used by gcc.
1366 // When we start to recognize specific target MIPS processors,
1367 // we will be able to select the default more correctly.
1368 ABI = mips::FloatABI::Hard;
1371 assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1375 static void AddTargetFeature(const ArgList &Args,
1376 std::vector<const char *> &Features,
1377 OptSpecifier OnOpt, OptSpecifier OffOpt,
1378 StringRef FeatureName) {
1379 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1380 if (A->getOption().matches(OnOpt))
1381 Features.push_back(Args.MakeArgString("+" + FeatureName));
1383 Features.push_back(Args.MakeArgString("-" + FeatureName));
1387 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1388 const ArgList &Args,
1389 std::vector<const char *> &Features) {
1392 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1393 ABIName = getGnuCompatibleMipsABIName(ABIName);
1395 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1396 options::OPT_mabicalls, "noabicalls");
1398 mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1399 if (FloatABI == mips::FloatABI::Soft) {
1400 // FIXME: Note, this is a hack. We need to pass the selected float
1401 // mode to the MipsTargetInfoBase to define appropriate macros there.
1402 // Now it is the only method.
1403 Features.push_back("+soft-float");
1406 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1407 StringRef Val = StringRef(A->getValue());
1408 if (Val == "2008") {
1409 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1410 Features.push_back("+nan2008");
1412 Features.push_back("-nan2008");
1413 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1415 } else if (Val == "legacy") {
1416 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1417 Features.push_back("-nan2008");
1419 Features.push_back("+nan2008");
1420 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1423 D.Diag(diag::err_drv_unsupported_option_argument)
1424 << A->getOption().getName() << Val;
1427 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1428 options::OPT_mdouble_float, "single-float");
1429 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1431 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1432 options::OPT_mno_micromips, "micromips");
1433 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1435 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1437 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1440 // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
1441 // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and
1443 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1444 options::OPT_mfp64)) {
1445 if (A->getOption().matches(options::OPT_mfp32))
1446 Features.push_back(Args.MakeArgString("-fp64"));
1447 else if (A->getOption().matches(options::OPT_mfpxx)) {
1448 Features.push_back(Args.MakeArgString("+fpxx"));
1449 Features.push_back(Args.MakeArgString("+nooddspreg"));
1451 Features.push_back(Args.MakeArgString("+fp64"));
1452 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1453 Features.push_back(Args.MakeArgString("+fpxx"));
1454 Features.push_back(Args.MakeArgString("+nooddspreg"));
1455 } else if (mips::isFP64ADefault(Triple, CPUName)) {
1456 Features.push_back(Args.MakeArgString("+fp64"));
1457 Features.push_back(Args.MakeArgString("+nooddspreg"));
1460 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1461 options::OPT_modd_spreg, "nooddspreg");
1464 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1465 ArgStringList &CmdArgs) const {
1466 const Driver &D = getToolChain().getDriver();
1469 const llvm::Triple &Triple = getToolChain().getTriple();
1470 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1472 CmdArgs.push_back("-target-abi");
1473 CmdArgs.push_back(ABIName.data());
1475 mips::FloatABI ABI = getMipsFloatABI(D, Args);
1476 if (ABI == mips::FloatABI::Soft) {
1477 // Floating point operations and argument passing are soft.
1478 CmdArgs.push_back("-msoft-float");
1479 CmdArgs.push_back("-mfloat-abi");
1480 CmdArgs.push_back("soft");
1482 // Floating point operations and argument passing are hard.
1483 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1484 CmdArgs.push_back("-mfloat-abi");
1485 CmdArgs.push_back("hard");
1488 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1489 if (A->getOption().matches(options::OPT_mxgot)) {
1490 CmdArgs.push_back("-mllvm");
1491 CmdArgs.push_back("-mxgot");
1495 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1496 options::OPT_mno_ldc1_sdc1)) {
1497 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1498 CmdArgs.push_back("-mllvm");
1499 CmdArgs.push_back("-mno-ldc1-sdc1");
1503 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1504 options::OPT_mno_check_zero_division)) {
1505 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1506 CmdArgs.push_back("-mllvm");
1507 CmdArgs.push_back("-mno-check-zero-division");
1511 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1512 StringRef v = A->getValue();
1513 CmdArgs.push_back("-mllvm");
1514 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1518 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1519 StringRef Val = StringRef(A->getValue());
1520 if (mips::hasCompactBranches(CPUName)) {
1521 if (Val == "never" || Val == "always" || Val == "optimal") {
1522 CmdArgs.push_back("-mllvm");
1523 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1525 D.Diag(diag::err_drv_unsupported_option_argument)
1526 << A->getOption().getName() << Val;
1528 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1532 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1533 static std::string getPPCTargetCPU(const ArgList &Args) {
1534 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1535 StringRef CPUName = A->getValue();
1537 if (CPUName == "native") {
1538 std::string CPU = llvm::sys::getHostCPUName();
1539 if (!CPU.empty() && CPU != "generic")
1545 return llvm::StringSwitch<const char *>(CPUName)
1546 .Case("common", "generic")
1548 .Case("440fp", "440")
1553 .Case("603e", "603e")
1554 .Case("603ev", "603ev")
1556 .Case("604e", "604e")
1558 .Case("630", "pwr3")
1560 .Case("7400", "7400")
1562 .Case("7450", "7450")
1569 .Case("e500mc", "e500mc")
1570 .Case("e5500", "e5500")
1571 .Case("power3", "pwr3")
1572 .Case("power4", "pwr4")
1573 .Case("power5", "pwr5")
1574 .Case("power5x", "pwr5x")
1575 .Case("power6", "pwr6")
1576 .Case("power6x", "pwr6x")
1577 .Case("power7", "pwr7")
1578 .Case("power8", "pwr8")
1579 .Case("power9", "pwr9")
1580 .Case("pwr3", "pwr3")
1581 .Case("pwr4", "pwr4")
1582 .Case("pwr5", "pwr5")
1583 .Case("pwr5x", "pwr5x")
1584 .Case("pwr6", "pwr6")
1585 .Case("pwr6x", "pwr6x")
1586 .Case("pwr7", "pwr7")
1587 .Case("pwr8", "pwr8")
1588 .Case("pwr9", "pwr9")
1589 .Case("powerpc", "ppc")
1590 .Case("powerpc64", "ppc64")
1591 .Case("powerpc64le", "ppc64le")
1598 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1599 const ArgList &Args,
1600 std::vector<const char *> &Features) {
1601 handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1603 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1604 if (FloatABI == ppc::FloatABI::Soft)
1605 Features.push_back("-hard-float");
1607 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1608 AddTargetFeature(Args, Features, options::OPT_faltivec,
1609 options::OPT_fno_altivec, "altivec");
1612 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1613 ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1615 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1616 options::OPT_mfloat_abi_EQ)) {
1617 if (A->getOption().matches(options::OPT_msoft_float))
1618 ABI = ppc::FloatABI::Soft;
1619 else if (A->getOption().matches(options::OPT_mhard_float))
1620 ABI = ppc::FloatABI::Hard;
1622 ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1623 .Case("soft", ppc::FloatABI::Soft)
1624 .Case("hard", ppc::FloatABI::Hard)
1625 .Default(ppc::FloatABI::Invalid);
1626 if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1627 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1628 ABI = ppc::FloatABI::Hard;
1633 // If unspecified, choose the default based on the platform.
1634 if (ABI == ppc::FloatABI::Invalid) {
1635 ABI = ppc::FloatABI::Hard;
1641 void Clang::AddPPCTargetArgs(const ArgList &Args,
1642 ArgStringList &CmdArgs) const {
1643 // Select the ABI to use.
1644 const char *ABIName = nullptr;
1645 if (getToolChain().getTriple().isOSLinux())
1646 switch (getToolChain().getArch()) {
1647 case llvm::Triple::ppc64: {
1648 // When targeting a processor that supports QPX, or if QPX is
1649 // specifically enabled, default to using the ABI that supports QPX (so
1650 // long as it is not specifically disabled).
1651 bool HasQPX = false;
1652 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1653 HasQPX = A->getValue() == StringRef("a2q");
1654 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1656 ABIName = "elfv1-qpx";
1663 case llvm::Triple::ppc64le:
1670 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1671 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1672 // the option if given as we don't have backend support for any targets
1673 // that don't use the altivec abi.
1674 if (StringRef(A->getValue()) != "altivec")
1675 ABIName = A->getValue();
1677 ppc::FloatABI FloatABI =
1678 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1680 if (FloatABI == ppc::FloatABI::Soft) {
1681 // Floating point operations and argument passing are soft.
1682 CmdArgs.push_back("-msoft-float");
1683 CmdArgs.push_back("-mfloat-abi");
1684 CmdArgs.push_back("soft");
1686 // Floating point operations and argument passing are hard.
1687 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1688 CmdArgs.push_back("-mfloat-abi");
1689 CmdArgs.push_back("hard");
1693 CmdArgs.push_back("-target-abi");
1694 CmdArgs.push_back(ABIName);
1698 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1699 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1700 return A && (A->getValue() == StringRef(Value));
1703 /// Get the (LLVM) name of the R600 gpu we are targeting.
1704 static std::string getR600TargetGPU(const ArgList &Args) {
1705 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1706 const char *GPUName = A->getValue();
1707 return llvm::StringSwitch<const char *>(GPUName)
1708 .Cases("rv630", "rv635", "r600")
1709 .Cases("rv610", "rv620", "rs780", "rs880")
1710 .Case("rv740", "rv770")
1711 .Case("palm", "cedar")
1712 .Cases("sumo", "sumo2", "sumo")
1713 .Case("hemlock", "cypress")
1714 .Case("aruba", "cayman")
1720 static std::string getLanaiTargetCPU(const ArgList &Args) {
1721 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1722 return A->getValue();
1727 sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
1728 const ArgList &Args) {
1729 sparc::FloatABI ABI = sparc::FloatABI::Invalid;
1731 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1732 options::OPT_mfloat_abi_EQ)) {
1733 if (A->getOption().matches(options::OPT_msoft_float))
1734 ABI = sparc::FloatABI::Soft;
1735 else if (A->getOption().matches(options::OPT_mhard_float))
1736 ABI = sparc::FloatABI::Hard;
1738 ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
1739 .Case("soft", sparc::FloatABI::Soft)
1740 .Case("hard", sparc::FloatABI::Hard)
1741 .Default(sparc::FloatABI::Invalid);
1742 if (ABI == sparc::FloatABI::Invalid &&
1743 !StringRef(A->getValue()).empty()) {
1744 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1745 ABI = sparc::FloatABI::Hard;
1750 // If unspecified, choose the default based on the platform.
1751 // Only the hard-float ABI on Sparc is standardized, and it is the
1752 // default. GCC also supports a nonstandard soft-float ABI mode, also
1753 // implemented in LLVM. However as this is not standard we set the default
1754 // to be hard-float.
1755 if (ABI == sparc::FloatABI::Invalid) {
1756 ABI = sparc::FloatABI::Hard;
1762 static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
1763 std::vector<const char *> &Features) {
1764 sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
1765 if (FloatABI == sparc::FloatABI::Soft)
1766 Features.push_back("+soft-float");
1769 void Clang::AddSparcTargetArgs(const ArgList &Args,
1770 ArgStringList &CmdArgs) const {
1771 sparc::FloatABI FloatABI =
1772 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1774 if (FloatABI == sparc::FloatABI::Soft) {
1775 // Floating point operations and argument passing are soft.
1776 CmdArgs.push_back("-msoft-float");
1777 CmdArgs.push_back("-mfloat-abi");
1778 CmdArgs.push_back("soft");
1780 // Floating point operations and argument passing are hard.
1781 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1782 CmdArgs.push_back("-mfloat-abi");
1783 CmdArgs.push_back("hard");
1787 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1788 ArgStringList &CmdArgs) const {
1789 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1790 CmdArgs.push_back("-mbackchain");
1793 static const char *getSystemZTargetCPU(const ArgList &Args) {
1794 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1795 return A->getValue();
1799 static void getSystemZTargetFeatures(const ArgList &Args,
1800 std::vector<const char *> &Features) {
1801 // -m(no-)htm overrides use of the transactional-execution facility.
1802 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1803 if (A->getOption().matches(options::OPT_mhtm))
1804 Features.push_back("+transactional-execution");
1806 Features.push_back("-transactional-execution");
1808 // -m(no-)vx overrides use of the vector facility.
1809 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1810 if (A->getOption().matches(options::OPT_mvx))
1811 Features.push_back("+vector");
1813 Features.push_back("-vector");
1817 static const char *getX86TargetCPU(const ArgList &Args,
1818 const llvm::Triple &Triple) {
1819 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1820 if (StringRef(A->getValue()) != "native") {
1821 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1824 return A->getValue();
1827 // FIXME: Reject attempts to use -march=native unless the target matches
1830 // FIXME: We should also incorporate the detected target features for use
1832 std::string CPU = llvm::sys::getHostCPUName();
1833 if (!CPU.empty() && CPU != "generic")
1834 return Args.MakeArgString(CPU);
1837 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1838 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1839 StringRef Arch = A->getValue();
1841 if (Triple.getArch() == llvm::Triple::x86) {
1842 CPU = llvm::StringSwitch<const char *>(Arch)
1843 .Case("IA32", "i386")
1844 .Case("SSE", "pentium3")
1845 .Case("SSE2", "pentium4")
1846 .Case("AVX", "sandybridge")
1847 .Case("AVX2", "haswell")
1850 CPU = llvm::StringSwitch<const char *>(Arch)
1851 .Case("AVX", "sandybridge")
1852 .Case("AVX2", "haswell")
1859 // Select the default CPU if none was given (or detection failed).
1861 if (Triple.getArch() != llvm::Triple::x86_64 &&
1862 Triple.getArch() != llvm::Triple::x86)
1863 return nullptr; // This routine is only handling x86 targets.
1865 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1867 // FIXME: Need target hooks.
1868 if (Triple.isOSDarwin()) {
1869 if (Triple.getArchName() == "x86_64h")
1871 return Is64Bit ? "core2" : "yonah";
1874 // Set up default CPU name for PS4 compilers.
1875 if (Triple.isPS4CPU())
1878 // On Android use targets compatible with gcc
1879 if (Triple.isAndroid())
1880 return Is64Bit ? "x86-64" : "i686";
1882 // Everything else goes to x86-64 in 64-bit mode.
1886 switch (Triple.getOS()) {
1887 case llvm::Triple::FreeBSD:
1888 case llvm::Triple::NetBSD:
1889 case llvm::Triple::OpenBSD:
1891 case llvm::Triple::Haiku:
1893 case llvm::Triple::Bitrig:
1901 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
1902 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1903 // If we have -mcpu=, use that.
1904 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1905 StringRef CPU = A->getValue();
1908 // Handle "native" by examining the host. "native" isn't meaningful when
1909 // cross compiling, so only support this when the host is also WebAssembly.
1910 if (CPU == "native")
1911 return llvm::sys::getHostCPUName();
1920 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1921 bool FromAs = false) {
1922 switch (T.getArch()) {
1926 case llvm::Triple::aarch64:
1927 case llvm::Triple::aarch64_be:
1928 return getAArch64TargetCPU(Args);
1930 case llvm::Triple::arm:
1931 case llvm::Triple::armeb:
1932 case llvm::Triple::thumb:
1933 case llvm::Triple::thumbeb: {
1934 StringRef MArch, MCPU;
1935 getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1936 return arm::getARMTargetCPU(MCPU, MArch, T);
1938 case llvm::Triple::mips:
1939 case llvm::Triple::mipsel:
1940 case llvm::Triple::mips64:
1941 case llvm::Triple::mips64el: {
1944 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1948 case llvm::Triple::nvptx:
1949 case llvm::Triple::nvptx64:
1950 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1951 return A->getValue();
1954 case llvm::Triple::ppc:
1955 case llvm::Triple::ppc64:
1956 case llvm::Triple::ppc64le: {
1957 std::string TargetCPUName = getPPCTargetCPU(Args);
1958 // LLVM may default to generating code for the native CPU,
1959 // but, like gcc, we default to a more generic option for
1960 // each architecture. (except on Darwin)
1961 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1962 if (T.getArch() == llvm::Triple::ppc64)
1963 TargetCPUName = "ppc64";
1964 else if (T.getArch() == llvm::Triple::ppc64le)
1965 TargetCPUName = "ppc64le";
1967 TargetCPUName = "ppc";
1969 return TargetCPUName;
1972 case llvm::Triple::sparc:
1973 case llvm::Triple::sparcel:
1974 case llvm::Triple::sparcv9:
1975 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1976 return A->getValue();
1979 case llvm::Triple::x86:
1980 case llvm::Triple::x86_64:
1981 return getX86TargetCPU(Args, T);
1983 case llvm::Triple::hexagon:
1985 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1987 case llvm::Triple::lanai:
1988 return getLanaiTargetCPU(Args);
1990 case llvm::Triple::systemz:
1991 return getSystemZTargetCPU(Args);
1993 case llvm::Triple::r600:
1994 case llvm::Triple::amdgcn:
1995 return getR600TargetGPU(Args);
1997 case llvm::Triple::wasm32:
1998 case llvm::Triple::wasm64:
1999 return getWebAssemblyTargetCPU(Args);
2003 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
2004 ArgStringList &CmdArgs, bool IsThinLTO) {
2005 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
2006 // as gold requires -plugin to come before any -plugin-opt that -Wl might
2008 CmdArgs.push_back("-plugin");
2009 std::string Plugin =
2010 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
2011 CmdArgs.push_back(Args.MakeArgString(Plugin));
2013 // Try to pass driver level flags relevant to LTO code generation down to
2016 // Handle flags for selecting CPU variants.
2017 std::string CPU = getCPUName(Args, ToolChain.getTriple());
2019 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
2021 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2023 if (A->getOption().matches(options::OPT_O4) ||
2024 A->getOption().matches(options::OPT_Ofast))
2026 else if (A->getOption().matches(options::OPT_O))
2027 OOpt = A->getValue();
2028 else if (A->getOption().matches(options::OPT_O0))
2031 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
2035 CmdArgs.push_back("-plugin-opt=thinlto");
2037 // If an explicit debugger tuning argument appeared, pass it along.
2038 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2039 options::OPT_ggdbN_Group)) {
2040 if (A->getOption().matches(options::OPT_glldb))
2041 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
2042 else if (A->getOption().matches(options::OPT_gsce))
2043 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
2045 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
2049 /// This is a helper function for validating the optional refinement step
2050 /// parameter in reciprocal argument strings. Return false if there is an error
2051 /// parsing the refinement step. Otherwise, return true and set the Position
2052 /// of the refinement step in the input string.
2053 static bool getRefinementStep(StringRef In, const Driver &D,
2054 const Arg &A, size_t &Position) {
2055 const char RefinementStepToken = ':';
2056 Position = In.find(RefinementStepToken);
2057 if (Position != StringRef::npos) {
2058 StringRef Option = A.getOption().getName();
2059 StringRef RefStep = In.substr(Position + 1);
2060 // Allow exactly one numeric character for the additional refinement
2061 // step parameter. This is reasonable for all currently-supported
2062 // operations and architectures because we would expect that a larger value
2063 // of refinement steps would cause the estimate "optimization" to
2064 // under-perform the native operation. Also, if the estimate does not
2065 // converge quickly, it probably will not ever converge, so further
2066 // refinement steps will not produce a better answer.
2067 if (RefStep.size() != 1) {
2068 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2071 char RefStepChar = RefStep[0];
2072 if (RefStepChar < '0' || RefStepChar > '9') {
2073 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2080 /// The -mrecip flag requires processing of many optional parameters.
2081 static void ParseMRecip(const Driver &D, const ArgList &Args,
2082 ArgStringList &OutStrings) {
2083 StringRef DisabledPrefixIn = "!";
2084 StringRef DisabledPrefixOut = "!";
2085 StringRef EnabledPrefixOut = "";
2086 StringRef Out = "-mrecip=";
2088 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
2092 unsigned NumOptions = A->getNumValues();
2093 if (NumOptions == 0) {
2094 // No option is the same as "all".
2095 OutStrings.push_back(Args.MakeArgString(Out + "all"));
2099 // Pass through "all", "none", or "default" with an optional refinement step.
2100 if (NumOptions == 1) {
2101 StringRef Val = A->getValue(0);
2103 if (!getRefinementStep(Val, D, *A, RefStepLoc))
2105 StringRef ValBase = Val.slice(0, RefStepLoc);
2106 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2107 OutStrings.push_back(Args.MakeArgString(Out + Val));
2112 // Each reciprocal type may be enabled or disabled individually.
2113 // Check each input value for validity, concatenate them all back together,
2114 // and pass through.
2116 llvm::StringMap<bool> OptionStrings;
2117 OptionStrings.insert(std::make_pair("divd", false));
2118 OptionStrings.insert(std::make_pair("divf", false));
2119 OptionStrings.insert(std::make_pair("vec-divd", false));
2120 OptionStrings.insert(std::make_pair("vec-divf", false));
2121 OptionStrings.insert(std::make_pair("sqrtd", false));
2122 OptionStrings.insert(std::make_pair("sqrtf", false));
2123 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2124 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
2126 for (unsigned i = 0; i != NumOptions; ++i) {
2127 StringRef Val = A->getValue(i);
2129 bool IsDisabled = Val.startswith(DisabledPrefixIn);
2130 // Ignore the disablement token for string matching.
2132 Val = Val.substr(1);
2135 if (!getRefinementStep(Val, D, *A, RefStep))
2138 StringRef ValBase = Val.slice(0, RefStep);
2139 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2140 if (OptionIter == OptionStrings.end()) {
2141 // Try again specifying float suffix.
2142 OptionIter = OptionStrings.find(ValBase.str() + 'f');
2143 if (OptionIter == OptionStrings.end()) {
2144 // The input name did not match any known option string.
2145 D.Diag(diag::err_drv_unknown_argument) << Val;
2148 // The option was specified without a float or double suffix.
2149 // Make sure that the double entry was not already specified.
2150 // The float entry will be checked below.
2151 if (OptionStrings[ValBase.str() + 'd']) {
2152 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2157 if (OptionIter->second == true) {
2158 // Duplicate option specified.
2159 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2163 // Mark the matched option as found. Do not allow duplicate specifiers.
2164 OptionIter->second = true;
2166 // If the precision was not specified, also mark the double entry as found.
2167 if (ValBase.back() != 'f' && ValBase.back() != 'd')
2168 OptionStrings[ValBase.str() + 'd'] = true;
2170 // Build the output string.
2171 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2172 Out = Args.MakeArgString(Out + Prefix + Val);
2173 if (i != NumOptions - 1)
2174 Out = Args.MakeArgString(Out + ",");
2177 OutStrings.push_back(Args.MakeArgString(Out));
2180 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
2181 const ArgList &Args,
2182 std::vector<const char *> &Features) {
2183 // If -march=native, autodetect the feature list.
2184 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
2185 if (StringRef(A->getValue()) == "native") {
2186 llvm::StringMap<bool> HostFeatures;
2187 if (llvm::sys::getHostCPUFeatures(HostFeatures))
2188 for (auto &F : HostFeatures)
2190 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
2194 if (Triple.getArchName() == "x86_64h") {
2195 // x86_64h implies quite a few of the more modern subtarget features
2196 // for Haswell class CPUs, but not all of them. Opt-out of a few.
2197 Features.push_back("-rdrnd");
2198 Features.push_back("-aes");
2199 Features.push_back("-pclmul");
2200 Features.push_back("-rtm");
2201 Features.push_back("-hle");
2202 Features.push_back("-fsgsbase");
2205 const llvm::Triple::ArchType ArchType = Triple.getArch();
2206 // Add features to be compatible with gcc for Android.
2207 if (Triple.isAndroid()) {
2208 if (ArchType == llvm::Triple::x86_64) {
2209 Features.push_back("+sse4.2");
2210 Features.push_back("+popcnt");
2212 Features.push_back("+ssse3");
2215 // Set features according to the -arch flag on MSVC.
2216 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
2217 StringRef Arch = A->getValue();
2218 bool ArchUsed = false;
2219 // First, look for flags that are shared in x86 and x86-64.
2220 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
2221 if (Arch == "AVX" || Arch == "AVX2") {
2223 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2226 // Then, look for x86-specific flags.
2227 if (ArchType == llvm::Triple::x86) {
2228 if (Arch == "IA32") {
2230 } else if (Arch == "SSE" || Arch == "SSE2") {
2232 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2236 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2239 // Now add any that the user explicitly requested on the command line,
2240 // which may override the defaults.
2241 handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2244 void Clang::AddX86TargetArgs(const ArgList &Args,
2245 ArgStringList &CmdArgs) const {
2246 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2247 Args.hasArg(options::OPT_mkernel) ||
2248 Args.hasArg(options::OPT_fapple_kext))
2249 CmdArgs.push_back("-disable-red-zone");
2251 // Default to avoid implicit floating-point for kernel/kext code, but allow
2252 // that to be overridden with -mno-soft-float.
2253 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2254 Args.hasArg(options::OPT_fapple_kext));
2255 if (Arg *A = Args.getLastArg(
2256 options::OPT_msoft_float, options::OPT_mno_soft_float,
2257 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2258 const Option &O = A->getOption();
2259 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2260 O.matches(options::OPT_msoft_float));
2262 if (NoImplicitFloat)
2263 CmdArgs.push_back("-no-implicit-float");
2265 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2266 StringRef Value = A->getValue();
2267 if (Value == "intel" || Value == "att") {
2268 CmdArgs.push_back("-mllvm");
2269 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2271 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2272 << A->getOption().getName() << Value;
2276 // Set flags to support MCU ABI.
2277 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2278 CmdArgs.push_back("-mfloat-abi");
2279 CmdArgs.push_back("soft");
2280 CmdArgs.push_back("-mstack-alignment=4");
2284 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2285 ArgStringList &CmdArgs) const {
2286 CmdArgs.push_back("-mqdsp6-compat");
2287 CmdArgs.push_back("-Wreturn-type");
2289 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2290 std::string N = llvm::utostr(G.getValue());
2291 std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2292 CmdArgs.push_back("-mllvm");
2293 CmdArgs.push_back(Args.MakeArgString(Opt));
2296 if (!Args.hasArg(options::OPT_fno_short_enums))
2297 CmdArgs.push_back("-fshort-enums");
2298 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2299 CmdArgs.push_back("-mllvm");
2300 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2302 CmdArgs.push_back("-mllvm");
2303 CmdArgs.push_back("-machine-sink-split=0");
2306 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2307 ArgStringList &CmdArgs) const {
2308 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2309 StringRef CPUName = A->getValue();
2311 CmdArgs.push_back("-target-cpu");
2312 CmdArgs.push_back(Args.MakeArgString(CPUName));
2314 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2315 StringRef Value = A->getValue();
2316 // Only support mregparm=4 to support old usage. Report error for all other
2319 if (Value.getAsInteger(10, Mregparm)) {
2320 if (Mregparm != 4) {
2321 getToolChain().getDriver().Diag(
2322 diag::err_drv_unsupported_option_argument)
2323 << A->getOption().getName() << Value;
2329 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2330 ArgStringList &CmdArgs) const {
2331 // Default to "hidden" visibility.
2332 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2333 options::OPT_fvisibility_ms_compat)) {
2334 CmdArgs.push_back("-fvisibility");
2335 CmdArgs.push_back("hidden");
2339 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2340 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2341 std::vector<const char *> &Features) {
2342 SmallVector<StringRef, 8> Split;
2343 text.split(Split, StringRef("+"), -1, false);
2345 for (StringRef Feature : Split) {
2346 const char *result = llvm::StringSwitch<const char *>(Feature)
2347 .Case("fp", "+fp-armv8")
2348 .Case("simd", "+neon")
2349 .Case("crc", "+crc")
2350 .Case("crypto", "+crypto")
2351 .Case("fp16", "+fullfp16")
2352 .Case("profile", "+spe")
2353 .Case("ras", "+ras")
2354 .Case("nofp", "-fp-armv8")
2355 .Case("nosimd", "-neon")
2356 .Case("nocrc", "-crc")
2357 .Case("nocrypto", "-crypto")
2358 .Case("nofp16", "-fullfp16")
2359 .Case("noprofile", "-spe")
2360 .Case("noras", "-ras")
2363 Features.push_back(result);
2364 else if (Feature == "neon" || Feature == "noneon")
2365 D.Diag(diag::err_drv_no_neon_modifier);
2372 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2373 // decode CPU and feature.
2374 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2375 std::vector<const char *> &Features) {
2376 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2378 if (CPU == "cortex-a53" || CPU == "cortex-a57" ||
2379 CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1" ||
2380 CPU == "kryo" || CPU == "cortex-a73" || CPU == "vulcan") {
2381 Features.push_back("+neon");
2382 Features.push_back("+crc");
2383 Features.push_back("+crypto");
2384 } else if (CPU == "cyclone") {
2385 Features.push_back("+neon");
2386 Features.push_back("+crypto");
2387 } else if (CPU == "generic") {
2388 Features.push_back("+neon");
2393 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2400 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2401 const ArgList &Args,
2402 std::vector<const char *> &Features) {
2403 std::string MarchLowerCase = March.lower();
2404 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2406 if (Split.first == "armv8-a" || Split.first == "armv8a") {
2407 // ok, no additional features.
2408 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2409 Features.push_back("+v8.1a");
2410 } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2411 Features.push_back("+v8.2a");
2416 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2423 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2424 const ArgList &Args,
2425 std::vector<const char *> &Features) {
2427 std::string McpuLowerCase = Mcpu.lower();
2428 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2435 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2436 const ArgList &Args,
2437 std::vector<const char *> &Features) {
2438 std::string MtuneLowerCase = Mtune.lower();
2439 // Handle CPU name is 'native'.
2440 if (MtuneLowerCase == "native")
2441 MtuneLowerCase = llvm::sys::getHostCPUName();
2442 if (MtuneLowerCase == "cyclone") {
2443 Features.push_back("+zcm");
2444 Features.push_back("+zcz");
2450 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2451 const ArgList &Args,
2452 std::vector<const char *> &Features) {
2454 std::vector<const char *> DecodedFeature;
2455 std::string McpuLowerCase = Mcpu.lower();
2456 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2459 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2462 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2463 std::vector<const char *> &Features) {
2465 bool success = true;
2466 // Enable NEON by default.
2467 Features.push_back("+neon");
2468 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2469 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2470 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2471 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2472 else if (Args.hasArg(options::OPT_arch))
2473 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2476 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2478 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2479 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2481 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2482 else if (Args.hasArg(options::OPT_arch))
2483 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2487 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2489 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2490 Features.push_back("-fp-armv8");
2491 Features.push_back("-crypto");
2492 Features.push_back("-neon");
2496 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2497 if (A->getOption().matches(options::OPT_mcrc))
2498 Features.push_back("+crc");
2500 Features.push_back("-crc");
2503 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2504 options::OPT_munaligned_access))
2505 if (A->getOption().matches(options::OPT_mno_unaligned_access))
2506 Features.push_back("+strict-align");
2508 if (Args.hasArg(options::OPT_ffixed_x18))
2509 Features.push_back("+reserve-x18");
2512 static void getHexagonTargetFeatures(const ArgList &Args,
2513 std::vector<const char *> &Features) {
2514 bool HasHVX = false, HasHVXD = false;
2516 // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2517 // doing dependent option handling here rather than in initFeatureMap or a
2519 for (auto &A : Args) {
2520 auto &Opt = A->getOption();
2521 if (Opt.matches(options::OPT_mhexagon_hvx))
2523 else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2524 HasHVXD = HasHVX = false;
2525 else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2526 HasHVXD = HasHVX = true;
2527 else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2534 Features.push_back(HasHVX ? "+hvx" : "-hvx");
2535 Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2538 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2539 std::vector<const char *> &Features) {
2540 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2543 static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
2544 std::vector<const char *> &Features) {
2545 if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
2546 StringRef value = dAbi->getValue();
2547 if (value == "1.0") {
2548 Features.push_back("+amdgpu-debugger-insert-nops");
2549 Features.push_back("+amdgpu-debugger-reserve-regs");
2550 Features.push_back("+amdgpu-debugger-emit-prologue");
2552 D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
2556 handleTargetFeaturesGroup(
2557 Args, Features, options::OPT_m_amdgpu_Features_Group);
2560 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2561 const ArgList &Args, ArgStringList &CmdArgs,
2563 const Driver &D = TC.getDriver();
2564 std::vector<const char *> Features;
2565 switch (Triple.getArch()) {
2568 case llvm::Triple::mips:
2569 case llvm::Triple::mipsel:
2570 case llvm::Triple::mips64:
2571 case llvm::Triple::mips64el:
2572 getMIPSTargetFeatures(D, Triple, Args, Features);
2575 case llvm::Triple::arm:
2576 case llvm::Triple::armeb:
2577 case llvm::Triple::thumb:
2578 case llvm::Triple::thumbeb:
2579 getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2582 case llvm::Triple::ppc:
2583 case llvm::Triple::ppc64:
2584 case llvm::Triple::ppc64le:
2585 getPPCTargetFeatures(D, Triple, Args, Features);
2587 case llvm::Triple::systemz:
2588 getSystemZTargetFeatures(Args, Features);
2590 case llvm::Triple::aarch64:
2591 case llvm::Triple::aarch64_be:
2592 getAArch64TargetFeatures(D, Args, Features);
2594 case llvm::Triple::x86:
2595 case llvm::Triple::x86_64:
2596 getX86TargetFeatures(D, Triple, Args, Features);
2598 case llvm::Triple::hexagon:
2599 getHexagonTargetFeatures(Args, Features);
2601 case llvm::Triple::wasm32:
2602 case llvm::Triple::wasm64:
2603 getWebAssemblyTargetFeatures(Args, Features);
2605 case llvm::Triple::sparc:
2606 case llvm::Triple::sparcel:
2607 case llvm::Triple::sparcv9:
2608 getSparcTargetFeatures(D, Args, Features);
2610 case llvm::Triple::r600:
2611 case llvm::Triple::amdgcn:
2612 getAMDGPUTargetFeatures(D, Args, Features);
2616 // Find the last of each feature.
2617 llvm::StringMap<unsigned> LastOpt;
2618 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2619 const char *Name = Features[I];
2620 assert(Name[0] == '-' || Name[0] == '+');
2621 LastOpt[Name + 1] = I;
2624 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2625 // If this feature was overridden, ignore it.
2626 const char *Name = Features[I];
2627 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2628 assert(LastI != LastOpt.end());
2629 unsigned Last = LastI->second;
2633 CmdArgs.push_back("-target-feature");
2634 CmdArgs.push_back(Name);
2639 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2640 const llvm::Triple &Triple) {
2641 // We use the zero-cost exception tables for Objective-C if the non-fragile
2642 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2644 if (runtime.isNonFragile())
2647 if (!Triple.isMacOSX())
2650 return (!Triple.isMacOSXVersionLT(10, 5) &&
2651 (Triple.getArch() == llvm::Triple::x86_64 ||
2652 Triple.getArch() == llvm::Triple::arm));
2655 /// Adds exception related arguments to the driver command arguments. There's a
2656 /// master flag, -fexceptions and also language specific flags to enable/disable
2657 /// C++ and Objective-C exceptions. This makes it possible to for example
2658 /// disable C++ exceptions but enable Objective-C exceptions.
2659 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2660 const ToolChain &TC, bool KernelOrKext,
2661 const ObjCRuntime &objcRuntime,
2662 ArgStringList &CmdArgs) {
2663 const Driver &D = TC.getDriver();
2664 const llvm::Triple &Triple = TC.getTriple();
2667 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2668 // arguments now to avoid warnings about unused arguments.
2669 Args.ClaimAllArgs(options::OPT_fexceptions);
2670 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2671 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2672 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2673 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2674 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2678 // See if the user explicitly enabled exceptions.
2679 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2682 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2683 // is not necessarily sensible, but follows GCC.
2684 if (types::isObjC(InputType) &&
2685 Args.hasFlag(options::OPT_fobjc_exceptions,
2686 options::OPT_fno_objc_exceptions, true)) {
2687 CmdArgs.push_back("-fobjc-exceptions");
2689 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2692 if (types::isCXX(InputType)) {
2693 // Disable C++ EH by default on XCore and PS4.
2694 bool CXXExceptionsEnabled =
2695 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
2696 Arg *ExceptionArg = Args.getLastArg(
2697 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2698 options::OPT_fexceptions, options::OPT_fno_exceptions);
2700 CXXExceptionsEnabled =
2701 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2702 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2704 if (CXXExceptionsEnabled) {
2705 if (Triple.isPS4CPU()) {
2706 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2707 assert(ExceptionArg &&
2708 "On the PS4 exceptions should only be enabled if passing "
2710 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2711 const Arg *RTTIArg = TC.getRTTIArg();
2712 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2713 D.Diag(diag::err_drv_argument_not_allowed_with)
2714 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2715 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2716 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2718 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2720 CmdArgs.push_back("-fcxx-exceptions");
2727 CmdArgs.push_back("-fexceptions");
2730 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2731 bool Default = true;
2732 if (TC.getTriple().isOSDarwin()) {
2733 // The native darwin assembler doesn't support the linker_option directives,
2734 // so we disable them if we think the .s file will be passed to it.
2735 Default = TC.useIntegratedAs();
2737 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2741 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2742 const ToolChain &TC) {
2743 bool UseDwarfDirectory =
2744 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2745 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2746 return !UseDwarfDirectory;
2749 /// \brief Check whether the given input tree contains any compilation actions.
2750 static bool ContainsCompileAction(const Action *A) {
2751 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2754 for (const auto &AI : A->inputs())
2755 if (ContainsCompileAction(AI))
2761 /// \brief Check if -relax-all should be passed to the internal assembler.
2762 /// This is done by default when compiling non-assembler source with -O0.
2763 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2764 bool RelaxDefault = true;
2766 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2767 RelaxDefault = A->getOption().matches(options::OPT_O0);
2770 RelaxDefault = false;
2771 for (const auto &Act : C.getActions()) {
2772 if (ContainsCompileAction(Act)) {
2773 RelaxDefault = true;
2779 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2783 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2784 // to the corresponding DebugInfoKind.
2785 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2786 assert(A.getOption().matches(options::OPT_gN_Group) &&
2787 "Not a -g option that specifies a debug-info level");
2788 if (A.getOption().matches(options::OPT_g0) ||
2789 A.getOption().matches(options::OPT_ggdb0))
2790 return codegenoptions::NoDebugInfo;
2791 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2792 A.getOption().matches(options::OPT_ggdb1))
2793 return codegenoptions::DebugLineTablesOnly;
2794 return codegenoptions::LimitedDebugInfo;
2797 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2798 // on mismatch. The StringRef input (rather than an Arg) allows
2799 // for use by the "-Xassembler" option parser.
2800 static unsigned DwarfVersionNum(StringRef ArgValue) {
2801 return llvm::StringSwitch<unsigned>(ArgValue)
2802 .Case("-gdwarf-2", 2)
2803 .Case("-gdwarf-3", 3)
2804 .Case("-gdwarf-4", 4)
2805 .Case("-gdwarf-5", 5)
2809 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2810 codegenoptions::DebugInfoKind DebugInfoKind,
2811 unsigned DwarfVersion,
2812 llvm::DebuggerKind DebuggerTuning) {
2813 switch (DebugInfoKind) {
2814 case codegenoptions::DebugLineTablesOnly:
2815 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2817 case codegenoptions::LimitedDebugInfo:
2818 CmdArgs.push_back("-debug-info-kind=limited");
2820 case codegenoptions::FullDebugInfo:
2821 CmdArgs.push_back("-debug-info-kind=standalone");
2826 if (DwarfVersion > 0)
2828 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2829 switch (DebuggerTuning) {
2830 case llvm::DebuggerKind::GDB:
2831 CmdArgs.push_back("-debugger-tuning=gdb");
2833 case llvm::DebuggerKind::LLDB:
2834 CmdArgs.push_back("-debugger-tuning=lldb");
2836 case llvm::DebuggerKind::SCE:
2837 CmdArgs.push_back("-debugger-tuning=sce");
2844 static void CollectArgsForIntegratedAssembler(Compilation &C,
2845 const ArgList &Args,
2846 ArgStringList &CmdArgs,
2848 if (UseRelaxAll(C, Args))
2849 CmdArgs.push_back("-mrelax-all");
2851 // Only default to -mincremental-linker-compatible if we think we are
2852 // targeting the MSVC linker.
2853 bool DefaultIncrementalLinkerCompatible =
2854 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2855 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2856 options::OPT_mno_incremental_linker_compatible,
2857 DefaultIncrementalLinkerCompatible))
2858 CmdArgs.push_back("-mincremental-linker-compatible");
2860 // When passing -I arguments to the assembler we sometimes need to
2861 // unconditionally take the next argument. For example, when parsing
2862 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2863 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2864 // arg after parsing the '-I' arg.
2865 bool TakeNextArg = false;
2867 // When using an integrated assembler, translate -Wa, and -Xassembler
2869 bool CompressDebugSections = false;
2871 bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
2872 const char *MipsTargetFeature = nullptr;
2874 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2877 for (StringRef Value : A->getValues()) {
2879 CmdArgs.push_back(Value.data());
2880 TakeNextArg = false;
2884 switch (C.getDefaultToolChain().getArch()) {
2887 case llvm::Triple::mips:
2888 case llvm::Triple::mipsel:
2889 case llvm::Triple::mips64:
2890 case llvm::Triple::mips64el:
2891 if (Value == "--trap") {
2892 CmdArgs.push_back("-target-feature");
2893 CmdArgs.push_back("+use-tcc-in-div");
2896 if (Value == "--break") {
2897 CmdArgs.push_back("-target-feature");
2898 CmdArgs.push_back("-use-tcc-in-div");
2901 if (Value.startswith("-msoft-float")) {
2902 CmdArgs.push_back("-target-feature");
2903 CmdArgs.push_back("+soft-float");
2906 if (Value.startswith("-mhard-float")) {
2907 CmdArgs.push_back("-target-feature");
2908 CmdArgs.push_back("-soft-float");
2912 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2913 .Case("-mips1", "+mips1")
2914 .Case("-mips2", "+mips2")
2915 .Case("-mips3", "+mips3")
2916 .Case("-mips4", "+mips4")
2917 .Case("-mips5", "+mips5")
2918 .Case("-mips32", "+mips32")
2919 .Case("-mips32r2", "+mips32r2")
2920 .Case("-mips32r3", "+mips32r3")
2921 .Case("-mips32r5", "+mips32r5")
2922 .Case("-mips32r6", "+mips32r6")
2923 .Case("-mips64", "+mips64")
2924 .Case("-mips64r2", "+mips64r2")
2925 .Case("-mips64r3", "+mips64r3")
2926 .Case("-mips64r5", "+mips64r5")
2927 .Case("-mips64r6", "+mips64r6")
2929 if (MipsTargetFeature)
2933 if (Value == "-force_cpusubtype_ALL") {
2934 // Do nothing, this is the default and we don't support anything else.
2935 } else if (Value == "-L") {
2936 CmdArgs.push_back("-msave-temp-labels");
2937 } else if (Value == "--fatal-warnings") {
2938 CmdArgs.push_back("-massembler-fatal-warnings");
2939 } else if (Value == "--noexecstack") {
2940 CmdArgs.push_back("-mnoexecstack");
2941 } else if (Value == "-compress-debug-sections" ||
2942 Value == "--compress-debug-sections") {
2943 CompressDebugSections = true;
2944 } else if (Value == "-nocompress-debug-sections" ||
2945 Value == "--nocompress-debug-sections") {
2946 CompressDebugSections = false;
2947 } else if (Value == "-mrelax-relocations=yes" ||
2948 Value == "--mrelax-relocations=yes") {
2949 UseRelaxRelocations = true;
2950 } else if (Value == "-mrelax-relocations=no" ||
2951 Value == "--mrelax-relocations=no") {
2952 UseRelaxRelocations = false;
2953 } else if (Value.startswith("-I")) {
2954 CmdArgs.push_back(Value.data());
2955 // We need to consume the next argument if the current arg is a plain
2956 // -I. The next arg will be the include directory.
2959 } else if (Value.startswith("-gdwarf-")) {
2960 // "-gdwarf-N" options are not cc1as options.
2961 unsigned DwarfVersion = DwarfVersionNum(Value);
2962 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2963 CmdArgs.push_back(Value.data());
2965 RenderDebugEnablingArgs(Args, CmdArgs,
2966 codegenoptions::LimitedDebugInfo,
2967 DwarfVersion, llvm::DebuggerKind::Default);
2969 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2970 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2971 // Do nothing, we'll validate it later.
2973 D.Diag(diag::err_drv_unsupported_option_argument)
2974 << A->getOption().getName() << Value;
2978 if (CompressDebugSections) {
2979 if (llvm::zlib::isAvailable())
2980 CmdArgs.push_back("-compress-debug-sections");
2982 D.Diag(diag::warn_debug_compression_unavailable);
2984 if (UseRelaxRelocations)
2985 CmdArgs.push_back("--mrelax-relocations");
2986 if (MipsTargetFeature != nullptr) {
2987 CmdArgs.push_back("-target-feature");
2988 CmdArgs.push_back(MipsTargetFeature);
2992 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2993 // FIXME: Make sure we can also emit shared objects if they're requested
2994 // and available, check for possible errors, etc.
2995 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2996 ArgStringList &CmdArgs) {
2997 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
3001 enum OpenMPRuntimeKind {
3002 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
3003 /// without knowing what runtime to target.
3006 /// The LLVM OpenMP runtime. When completed and integrated, this will become
3007 /// the default for Clang.
3010 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
3011 /// this runtime but can swallow the pragmas, and find and link against the
3012 /// runtime library itself.
3015 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
3016 /// OpenMP runtime. We support this mode for users with existing dependencies
3017 /// on this runtime library name.
3022 /// Compute the desired OpenMP runtime from the flag provided.
3023 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
3024 const ArgList &Args) {
3025 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
3027 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
3029 RuntimeName = A->getValue();
3031 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
3032 .Case("libomp", OMPRT_OMP)
3033 .Case("libgomp", OMPRT_GOMP)
3034 .Case("libiomp5", OMPRT_IOMP5)
3035 .Default(OMPRT_Unknown);
3037 if (RT == OMPRT_Unknown) {
3039 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
3040 << A->getOption().getName() << A->getValue();
3042 // FIXME: We could use a nicer diagnostic here.
3043 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
3049 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
3050 const ArgList &Args) {
3051 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3052 options::OPT_fno_openmp, false))
3055 switch (getOpenMPRuntime(TC, Args)) {
3057 CmdArgs.push_back("-lomp");
3060 CmdArgs.push_back("-lgomp");
3063 CmdArgs.push_back("-liomp5");
3066 // Already diagnosed.
3071 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
3072 ArgStringList &CmdArgs, StringRef Sanitizer,
3073 bool IsShared, bool IsWhole) {
3074 // Wrap any static runtimes that must be forced into executable in
3076 if (IsWhole) CmdArgs.push_back("-whole-archive");
3077 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
3078 if (IsWhole) CmdArgs.push_back("-no-whole-archive");
3081 // Tries to use a file with the list of dynamic symbols that need to be exported
3082 // from the runtime library. Returns true if the file was found.
3083 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
3084 ArgStringList &CmdArgs,
3085 StringRef Sanitizer) {
3086 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
3087 if (llvm::sys::fs::exists(SanRT + ".syms")) {
3088 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
3094 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
3095 ArgStringList &CmdArgs) {
3096 // Force linking against the system libraries sanitizers depends on
3097 // (see PR15823 why this is necessary).
3098 CmdArgs.push_back("--no-as-needed");
3099 CmdArgs.push_back("-lpthread");
3100 CmdArgs.push_back("-lrt");
3101 CmdArgs.push_back("-lm");
3102 // There's no libdl on FreeBSD.
3103 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3104 CmdArgs.push_back("-ldl");
3108 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3109 SmallVectorImpl<StringRef> &SharedRuntimes,
3110 SmallVectorImpl<StringRef> &StaticRuntimes,
3111 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
3112 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
3113 SmallVectorImpl<StringRef> &RequiredSymbols) {
3114 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
3115 // Collect shared runtimes.
3116 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
3117 SharedRuntimes.push_back("asan");
3119 // The stats_client library is also statically linked into DSOs.
3120 if (SanArgs.needsStatsRt())
3121 StaticRuntimes.push_back("stats_client");
3123 // Collect static runtimes.
3124 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
3125 // Don't link static runtimes into DSOs or if compiling for Android.
3128 if (SanArgs.needsAsanRt()) {
3129 if (SanArgs.needsSharedAsanRt()) {
3130 HelperStaticRuntimes.push_back("asan-preinit");
3132 StaticRuntimes.push_back("asan");
3133 if (SanArgs.linkCXXRuntimes())
3134 StaticRuntimes.push_back("asan_cxx");
3137 if (SanArgs.needsDfsanRt())
3138 StaticRuntimes.push_back("dfsan");
3139 if (SanArgs.needsLsanRt())
3140 StaticRuntimes.push_back("lsan");
3141 if (SanArgs.needsMsanRt()) {
3142 StaticRuntimes.push_back("msan");
3143 if (SanArgs.linkCXXRuntimes())
3144 StaticRuntimes.push_back("msan_cxx");
3146 if (SanArgs.needsTsanRt()) {
3147 StaticRuntimes.push_back("tsan");
3148 if (SanArgs.linkCXXRuntimes())
3149 StaticRuntimes.push_back("tsan_cxx");
3151 if (SanArgs.needsUbsanRt()) {
3152 StaticRuntimes.push_back("ubsan_standalone");
3153 if (SanArgs.linkCXXRuntimes())
3154 StaticRuntimes.push_back("ubsan_standalone_cxx");
3156 if (SanArgs.needsSafeStackRt())
3157 StaticRuntimes.push_back("safestack");
3158 if (SanArgs.needsCfiRt())
3159 StaticRuntimes.push_back("cfi");
3160 if (SanArgs.needsCfiDiagRt()) {
3161 StaticRuntimes.push_back("cfi_diag");
3162 if (SanArgs.linkCXXRuntimes())
3163 StaticRuntimes.push_back("ubsan_standalone_cxx");
3165 if (SanArgs.needsStatsRt()) {
3166 NonWholeStaticRuntimes.push_back("stats");
3167 RequiredSymbols.push_back("__sanitizer_stats_register");
3169 if (SanArgs.needsEsanRt())
3170 StaticRuntimes.push_back("esan");
3173 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
3174 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
3175 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3176 ArgStringList &CmdArgs) {
3177 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
3178 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
3179 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
3180 NonWholeStaticRuntimes, HelperStaticRuntimes,
3182 for (auto RT : SharedRuntimes)
3183 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
3184 for (auto RT : HelperStaticRuntimes)
3185 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3186 bool AddExportDynamic = false;
3187 for (auto RT : StaticRuntimes) {
3188 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3189 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3191 for (auto RT : NonWholeStaticRuntimes) {
3192 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
3193 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3195 for (auto S : RequiredSymbols) {
3196 CmdArgs.push_back("-u");
3197 CmdArgs.push_back(Args.MakeArgString(S));
3199 // If there is a static runtime with no dynamic list, force all the symbols
3200 // to be dynamic to be sure we export sanitizer interface functions.
3201 if (AddExportDynamic)
3202 CmdArgs.push_back("-export-dynamic");
3203 return !StaticRuntimes.empty();
3206 static bool addXRayRuntime(const ToolChain &TC, const ArgList &Args,
3207 ArgStringList &CmdArgs) {
3208 if (Args.hasFlag(options::OPT_fxray_instrument,
3209 options::OPT_fnoxray_instrument, false)) {
3210 CmdArgs.push_back("-whole-archive");
3211 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
3212 CmdArgs.push_back("-no-whole-archive");
3218 static void linkXRayRuntimeDeps(const ToolChain &TC, const ArgList &Args,
3219 ArgStringList &CmdArgs) {
3220 CmdArgs.push_back("--no-as-needed");
3221 CmdArgs.push_back("-lpthread");
3222 CmdArgs.push_back("-lrt");
3223 CmdArgs.push_back("-lm");
3224 CmdArgs.push_back("-latomic");
3225 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3226 CmdArgs.push_back("-lc++");
3228 CmdArgs.push_back("-lstdc++");
3229 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3230 CmdArgs.push_back("-ldl");
3233 static bool areOptimizationsEnabled(const ArgList &Args) {
3234 // Find the last -O arg and see if it is non-zero.
3235 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
3236 return !A->getOption().matches(options::OPT_O0);
3241 static bool shouldUseFramePointerForTarget(const ArgList &Args,
3242 const llvm::Triple &Triple) {
3243 switch (Triple.getArch()) {
3244 case llvm::Triple::xcore:
3245 case llvm::Triple::wasm32:
3246 case llvm::Triple::wasm64:
3247 // XCore never wants frame pointers, regardless of OS.
3248 // WebAssembly never wants frame pointers.
3254 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
3255 switch (Triple.getArch()) {
3256 // Don't use a frame pointer on linux if optimizing for certain targets.
3257 case llvm::Triple::mips64:
3258 case llvm::Triple::mips64el:
3259 case llvm::Triple::mips:
3260 case llvm::Triple::mipsel:
3261 case llvm::Triple::systemz:
3262 case llvm::Triple::x86:
3263 case llvm::Triple::x86_64:
3264 return !areOptimizationsEnabled(Args);
3270 if (Triple.isOSWindows()) {
3271 switch (Triple.getArch()) {
3272 case llvm::Triple::x86:
3273 return !areOptimizationsEnabled(Args);
3274 case llvm::Triple::x86_64:
3275 return Triple.isOSBinFormatMachO();
3276 case llvm::Triple::arm:
3277 case llvm::Triple::thumb:
3278 // Windows on ARM builds with FPO disabled to aid fast stack walking
3281 // All other supported Windows ISAs use xdata unwind information, so frame
3282 // pointers are not generally useful.
3290 static bool shouldUseFramePointer(const ArgList &Args,
3291 const llvm::Triple &Triple) {
3292 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
3293 options::OPT_fomit_frame_pointer))
3294 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
3295 if (Args.hasArg(options::OPT_pg))
3298 return shouldUseFramePointerForTarget(Args, Triple);
3301 static bool shouldUseLeafFramePointer(const ArgList &Args,
3302 const llvm::Triple &Triple) {
3303 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
3304 options::OPT_momit_leaf_frame_pointer))
3305 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
3306 if (Args.hasArg(options::OPT_pg))
3309 if (Triple.isPS4CPU())
3312 return shouldUseFramePointerForTarget(Args, Triple);
3315 /// Add a CC1 option to specify the debug compilation directory.
3316 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
3317 SmallString<128> cwd;
3318 if (!llvm::sys::fs::current_path(cwd)) {
3319 CmdArgs.push_back("-fdebug-compilation-dir");
3320 CmdArgs.push_back(Args.MakeArgString(cwd));
3324 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
3325 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3326 if (FinalOutput && Args.hasArg(options::OPT_c)) {
3327 SmallString<128> T(FinalOutput->getValue());
3328 llvm::sys::path::replace_extension(T, "dwo");
3329 return Args.MakeArgString(T);
3331 // Use the compilation dir.
3333 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
3334 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
3335 llvm::sys::path::replace_extension(F, "dwo");
3337 return Args.MakeArgString(F);
3341 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
3342 const JobAction &JA, const ArgList &Args,
3343 const InputInfo &Output, const char *OutFile) {
3344 ArgStringList ExtractArgs;
3345 ExtractArgs.push_back("--extract-dwo");
3347 ArgStringList StripArgs;
3348 StripArgs.push_back("--strip-dwo");
3350 // Grabbing the output of the earlier compile step.
3351 StripArgs.push_back(Output.getFilename());
3352 ExtractArgs.push_back(Output.getFilename());
3353 ExtractArgs.push_back(OutFile);
3355 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
3356 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
3358 // First extract the dwo sections.
3359 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
3361 // Then remove them from the original .o file.
3362 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
3365 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
3366 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
3367 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3368 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3369 if (A->getOption().matches(options::OPT_O4) ||
3370 A->getOption().matches(options::OPT_Ofast))
3373 if (A->getOption().matches(options::OPT_O0))
3376 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3379 StringRef S(A->getValue());
3383 // Don't vectorize -Oz, unless it's the slp vectorizer.
3387 unsigned OptLevel = 0;
3388 if (S.getAsInteger(10, OptLevel))
3391 return OptLevel > 1;
3397 /// Add -x lang to \p CmdArgs for \p Input.
3398 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3399 ArgStringList &CmdArgs) {
3400 // When using -verify-pch, we don't want to provide the type
3401 // 'precompiled-header' if it was inferred from the file extension
3402 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3405 CmdArgs.push_back("-x");
3406 if (Args.hasArg(options::OPT_rewrite_objc))
3407 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3409 CmdArgs.push_back(types::getTypeName(Input.getType()));
3412 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3414 return VersionTuple(Version);
3416 if (Version < 10000)
3417 return VersionTuple(Version / 100, Version % 100);
3419 unsigned Build = 0, Factor = 1;
3420 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3421 Build = Build + (Version % 10) * Factor;
3422 return VersionTuple(Version / 100, Version % 100, Build);
3425 // Claim options we don't want to warn if they are unused. We do this for
3426 // options that build systems might add but are unused when assembling or only
3427 // running the preprocessor for example.
3428 static void claimNoWarnArgs(const ArgList &Args) {
3429 // Don't warn about unused -f(no-)?lto. This can happen when we're
3430 // preprocessing, precompiling or assembling.
3431 Args.ClaimAllArgs(options::OPT_flto_EQ);
3432 Args.ClaimAllArgs(options::OPT_flto);
3433 Args.ClaimAllArgs(options::OPT_fno_lto);
3436 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3438 const char *Username = getenv("LOGNAME");
3440 const char *Username = getenv("USERNAME");
3443 // Validate that LoginName can be used in a path, and get its length.
3445 for (const char *P = Username; *P; ++P, ++Len) {
3446 if (!isAlphanumeric(*P) && *P != '_') {
3452 if (Username && Len > 0) {
3453 Result.append(Username, Username + Len);
3458 // Fallback to user id.
3460 std::string UID = llvm::utostr(getuid());
3462 // FIXME: Windows seems to have an 'SID' that might work.
3463 std::string UID = "9999";
3465 Result.append(UID.begin(), UID.end());
3468 VersionTuple visualstudio::getMSVCVersion(const Driver *D, const ToolChain &TC,
3469 const llvm::Triple &Triple,
3470 const llvm::opt::ArgList &Args,
3471 bool IsWindowsMSVC) {
3472 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3474 Args.hasArg(options::OPT_fmsc_version) ||
3475 Args.hasArg(options::OPT_fms_compatibility_version)) {
3476 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3477 const Arg *MSCompatibilityVersion =
3478 Args.getLastArg(options::OPT_fms_compatibility_version);
3480 if (MSCVersion && MSCompatibilityVersion) {
3482 D->Diag(diag::err_drv_argument_not_allowed_with)
3483 << MSCVersion->getAsString(Args)
3484 << MSCompatibilityVersion->getAsString(Args);
3485 return VersionTuple();
3488 if (MSCompatibilityVersion) {
3490 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3491 D->Diag(diag::err_drv_invalid_value)
3492 << MSCompatibilityVersion->getAsString(Args)
3493 << MSCompatibilityVersion->getValue();
3498 unsigned Version = 0;
3499 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3500 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3501 << MSCVersion->getValue();
3502 return getMSCompatibilityVersion(Version);
3505 unsigned Major, Minor, Micro;
3506 Triple.getEnvironmentVersion(Major, Minor, Micro);
3507 if (Major || Minor || Micro)
3508 return VersionTuple(Major, Minor, Micro);
3510 if (IsWindowsMSVC) {
3511 VersionTuple MSVT = TC.getMSVCVersionFromExe();
3515 // FIXME: Consider bumping this to 19 (MSVC2015) soon.
3516 return VersionTuple(18);
3519 return VersionTuple();
3522 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3523 const InputInfo &Output, const ArgList &Args,
3524 ArgStringList &CmdArgs) {
3526 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
3527 options::OPT_fprofile_generate_EQ,
3528 options::OPT_fno_profile_generate);
3529 if (PGOGenerateArg &&
3530 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
3531 PGOGenerateArg = nullptr;
3533 auto *ProfileGenerateArg = Args.getLastArg(
3534 options::OPT_fprofile_instr_generate,
3535 options::OPT_fprofile_instr_generate_EQ,
3536 options::OPT_fno_profile_instr_generate);
3537 if (ProfileGenerateArg &&
3538 ProfileGenerateArg->getOption().matches(
3539 options::OPT_fno_profile_instr_generate))
3540 ProfileGenerateArg = nullptr;
3542 if (PGOGenerateArg && ProfileGenerateArg)
3543 D.Diag(diag::err_drv_argument_not_allowed_with)
3544 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
3546 auto *ProfileUseArg = Args.getLastArg(
3547 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3548 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3549 options::OPT_fno_profile_instr_use);
3550 if (ProfileUseArg &&
3551 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3552 ProfileUseArg = nullptr;
3554 if (PGOGenerateArg && ProfileUseArg)
3555 D.Diag(diag::err_drv_argument_not_allowed_with)
3556 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
3558 if (ProfileGenerateArg && ProfileUseArg)
3559 D.Diag(diag::err_drv_argument_not_allowed_with)
3560 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3562 if (ProfileGenerateArg) {
3563 if (ProfileGenerateArg->getOption().matches(
3564 options::OPT_fprofile_instr_generate_EQ))
3565 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
3566 ProfileGenerateArg->getValue()));
3567 // The default is to use Clang Instrumentation.
3568 CmdArgs.push_back("-fprofile-instrument=clang");
3571 if (PGOGenerateArg) {
3572 CmdArgs.push_back("-fprofile-instrument=llvm");
3573 if (PGOGenerateArg->getOption().matches(
3574 options::OPT_fprofile_generate_EQ)) {
3575 SmallString<128> Path(PGOGenerateArg->getValue());
3576 llvm::sys::path::append(Path, "default.profraw");
3578 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
3582 if (ProfileUseArg) {
3583 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3584 CmdArgs.push_back(Args.MakeArgString(
3585 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
3586 else if ((ProfileUseArg->getOption().matches(
3587 options::OPT_fprofile_use_EQ) ||
3588 ProfileUseArg->getOption().matches(
3589 options::OPT_fprofile_instr_use))) {
3590 SmallString<128> Path(
3591 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3592 if (Path.empty() || llvm::sys::fs::is_directory(Path))
3593 llvm::sys::path::append(Path, "default.profdata");
3595 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
3599 if (Args.hasArg(options::OPT_ftest_coverage) ||
3600 Args.hasArg(options::OPT_coverage))
3601 CmdArgs.push_back("-femit-coverage-notes");
3602 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3604 Args.hasArg(options::OPT_coverage))
3605 CmdArgs.push_back("-femit-coverage-data");
3607 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3608 options::OPT_fno_coverage_mapping, false) &&
3609 !ProfileGenerateArg)
3610 D.Diag(diag::err_drv_argument_only_allowed_with)
3611 << "-fcoverage-mapping"
3612 << "-fprofile-instr-generate";
3614 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3615 options::OPT_fno_coverage_mapping, false))
3616 CmdArgs.push_back("-fcoverage-mapping");
3618 if (C.getArgs().hasArg(options::OPT_c) ||
3619 C.getArgs().hasArg(options::OPT_S)) {
3620 if (Output.isFilename()) {
3621 CmdArgs.push_back("-coverage-file");
3622 SmallString<128> CoverageFilename;
3623 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3624 CoverageFilename = FinalOutput->getValue();
3626 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3628 if (llvm::sys::path::is_relative(CoverageFilename)) {
3629 SmallString<128> Pwd;
3630 if (!llvm::sys::fs::current_path(Pwd)) {
3631 llvm::sys::path::append(Pwd, CoverageFilename);
3632 CoverageFilename.swap(Pwd);
3635 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3640 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3641 ArgStringList &CmdArgs) {
3642 if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3644 Args.hasFlag(options::OPT_fprofile_generate,
3645 options::OPT_fno_profile_instr_generate, false) ||
3646 Args.hasFlag(options::OPT_fprofile_generate_EQ,
3647 options::OPT_fno_profile_instr_generate, false) ||
3648 Args.hasFlag(options::OPT_fprofile_instr_generate,
3649 options::OPT_fno_profile_instr_generate, false) ||
3650 Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3651 options::OPT_fno_profile_instr_generate, false) ||
3652 Args.hasArg(options::OPT_fcreate_profile) ||
3653 Args.hasArg(options::OPT_coverage)))
3654 CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3657 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
3658 /// smooshes them together with platform defaults, to decide whether
3659 /// this compile should be using PIC mode or not. Returns a tuple of
3660 /// (RelocationModel, PICLevel, IsPIE).
3661 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3662 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3663 const ArgList &Args) {
3664 // FIXME: why does this code...and so much everywhere else, use both
3665 // ToolChain.getTriple() and Triple?
3666 bool PIE = ToolChain.isPIEDefault();
3667 bool PIC = PIE || ToolChain.isPICDefault();
3668 // The Darwin/MachO default to use PIC does not apply when using -static.
3669 if (ToolChain.getTriple().isOSBinFormatMachO() &&
3670 Args.hasArg(options::OPT_static))
3672 bool IsPICLevelTwo = PIC;
3675 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3677 // Android-specific defaults for PIC/PIE
3678 if (ToolChain.getTriple().isAndroid()) {
3679 switch (ToolChain.getArch()) {
3680 case llvm::Triple::arm:
3681 case llvm::Triple::armeb:
3682 case llvm::Triple::thumb:
3683 case llvm::Triple::thumbeb:
3684 case llvm::Triple::aarch64:
3685 case llvm::Triple::mips:
3686 case llvm::Triple::mipsel:
3687 case llvm::Triple::mips64:
3688 case llvm::Triple::mips64el:
3689 PIC = true; // "-fpic"
3692 case llvm::Triple::x86:
3693 case llvm::Triple::x86_64:
3694 PIC = true; // "-fPIC"
3695 IsPICLevelTwo = true;
3703 // OpenBSD-specific defaults for PIE
3704 if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3705 switch (ToolChain.getArch()) {
3706 case llvm::Triple::mips64:
3707 case llvm::Triple::mips64el:
3708 case llvm::Triple::sparcel:
3709 case llvm::Triple::x86:
3710 case llvm::Triple::x86_64:
3711 IsPICLevelTwo = false; // "-fpie"
3714 case llvm::Triple::ppc:
3715 case llvm::Triple::sparc:
3716 case llvm::Triple::sparcv9:
3717 IsPICLevelTwo = true; // "-fPIE"
3725 // The last argument relating to either PIC or PIE wins, and no
3726 // other argument is used. If the last argument is any flavor of the
3727 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3728 // option implicitly enables PIC at the same level.
3729 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3730 options::OPT_fpic, options::OPT_fno_pic,
3731 options::OPT_fPIE, options::OPT_fno_PIE,
3732 options::OPT_fpie, options::OPT_fno_pie);
3733 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3734 // is forced, then neither PIC nor PIE flags will have no effect.
3735 if (!ToolChain.isPICDefaultForced()) {
3737 Option O = LastPICArg->getOption();
3738 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3739 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3740 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3742 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3744 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3747 if (Triple.isPS4CPU()) {
3748 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3749 StringRef Model = ModelArg ? ModelArg->getValue() : "";
3750 if (Model != "kernel") {
3752 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3753 << LastPICArg->getSpelling();
3760 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3761 // PIC level would've been set to level 1, force it back to level 2 PIC
3763 if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3764 IsPICLevelTwo |= ToolChain.isPICDefault();
3766 // This kernel flags are a trump-card: they will disable PIC/PIE
3767 // generation, independent of the argument order.
3768 if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3769 !Triple.isWatchOS()))
3772 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3773 // This is a very special mode. It trumps the other modes, almost no one
3774 // uses it, and it isn't even valid on any OS but Darwin.
3775 if (!ToolChain.getTriple().isOSDarwin())
3776 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3777 << A->getSpelling() << ToolChain.getTriple().str();
3779 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3781 // Only a forced PIC mode can cause the actual compile to have PIC defines
3782 // etc., no flags are sufficient. This behavior was selected to closely
3783 // match that of llvm-gcc and Apple GCC before that.
3784 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3786 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3790 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3792 return std::make_tuple(llvm::Reloc::Static, 0, false);
3795 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3797 case llvm::Reloc::Static:
3799 case llvm::Reloc::PIC_:
3801 case llvm::Reloc::DynamicNoPIC:
3802 return "dynamic-no-pic";
3804 llvm_unreachable("Unknown Reloc::Model kind");
3807 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3808 ArgStringList &CmdArgs) {
3809 llvm::Reloc::Model RelocationModel;
3812 std::tie(RelocationModel, PICLevel, IsPIE) =
3813 ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3815 if (RelocationModel != llvm::Reloc::Static)
3816 CmdArgs.push_back("-KPIC");
3819 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3820 const InputInfo &Output, const InputInfoList &Inputs,
3821 const ArgList &Args, const char *LinkingOutput) const {
3822 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3823 const llvm::Triple Triple(TripleStr);
3826 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3827 const Driver &D = getToolChain().getDriver();
3828 ArgStringList CmdArgs;
3830 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3831 bool IsWindowsCygnus =
3832 getToolChain().getTriple().isWindowsCygwinEnvironment();
3833 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3834 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3835 bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
3837 // Check number of inputs for sanity. We need at least one input.
3838 assert(Inputs.size() >= 1 && "Must have at least one input.");
3839 const InputInfo &Input = Inputs[0];
3840 // CUDA compilation may have multiple inputs (source file + results of
3841 // device-side compilations). All other jobs are expected to have exactly one
3843 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3844 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3846 // C++ is not supported for IAMCU.
3847 if (IsIAMCU && types::isCXX(Input.getType()))
3848 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3850 // Invoke ourselves in -cc1 mode.
3852 // FIXME: Implement custom jobs for internal actions.
3853 CmdArgs.push_back("-cc1");
3855 // Add the "effective" target triple.
3856 CmdArgs.push_back("-triple");
3857 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3860 // We have to pass the triple of the host if compiling for a CUDA device and
3862 std::string NormalizedTriple;
3863 if (JA.isDeviceOffloading(Action::OFK_Cuda))
3864 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3868 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3872 CmdArgs.push_back("-aux-triple");
3873 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3876 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3877 Triple.getArch() == llvm::Triple::thumb)) {
3878 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3880 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3882 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3886 // Push all default warning arguments that are specific to
3887 // the given target. These come before user provided warning options
3889 getToolChain().addClangWarningOptions(CmdArgs);
3891 // Select the appropriate action.
3892 RewriteKind rewriteKind = RK_None;
3894 if (isa<AnalyzeJobAction>(JA)) {
3895 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3896 CmdArgs.push_back("-analyze");
3897 } else if (isa<MigrateJobAction>(JA)) {
3898 CmdArgs.push_back("-migrate");
3899 } else if (isa<PreprocessJobAction>(JA)) {
3900 if (Output.getType() == types::TY_Dependencies)
3901 CmdArgs.push_back("-Eonly");
3903 CmdArgs.push_back("-E");
3904 if (Args.hasArg(options::OPT_rewrite_objc) &&
3905 !Args.hasArg(options::OPT_g_Group))
3906 CmdArgs.push_back("-P");
3908 } else if (isa<AssembleJobAction>(JA)) {
3909 CmdArgs.push_back("-emit-obj");
3911 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3913 // Also ignore explicit -force_cpusubtype_ALL option.
3914 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3915 } else if (isa<PrecompileJobAction>(JA)) {
3916 // Use PCH if the user requested it.
3917 bool UsePCH = D.CCCUsePCH;
3919 if (JA.getType() == types::TY_Nothing)
3920 CmdArgs.push_back("-fsyntax-only");
3922 CmdArgs.push_back("-emit-pch");
3924 CmdArgs.push_back("-emit-pth");
3925 } else if (isa<VerifyPCHJobAction>(JA)) {
3926 CmdArgs.push_back("-verify-pch");
3928 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3929 "Invalid action for clang tool.");
3930 if (JA.getType() == types::TY_Nothing) {
3931 CmdArgs.push_back("-fsyntax-only");
3932 } else if (JA.getType() == types::TY_LLVM_IR ||
3933 JA.getType() == types::TY_LTO_IR) {
3934 CmdArgs.push_back("-emit-llvm");
3935 } else if (JA.getType() == types::TY_LLVM_BC ||
3936 JA.getType() == types::TY_LTO_BC) {
3937 CmdArgs.push_back("-emit-llvm-bc");
3938 } else if (JA.getType() == types::TY_PP_Asm) {
3939 CmdArgs.push_back("-S");
3940 } else if (JA.getType() == types::TY_AST) {
3941 CmdArgs.push_back("-emit-pch");
3942 } else if (JA.getType() == types::TY_ModuleFile) {
3943 CmdArgs.push_back("-module-file-info");
3944 } else if (JA.getType() == types::TY_RewrittenObjC) {
3945 CmdArgs.push_back("-rewrite-objc");
3946 rewriteKind = RK_NonFragile;
3947 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3948 CmdArgs.push_back("-rewrite-objc");
3949 rewriteKind = RK_Fragile;
3951 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3954 // Preserve use-list order by default when emitting bitcode, so that
3955 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3956 // same result as running passes here. For LTO, we don't need to preserve
3957 // the use-list order, since serialization to bitcode is part of the flow.
3958 if (JA.getType() == types::TY_LLVM_BC)
3959 CmdArgs.push_back("-emit-llvm-uselists");
3962 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3965 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3966 if (!types::isLLVMIR(Input.getType()))
3967 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3969 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3972 // Embed-bitcode option.
3973 if (C.getDriver().embedBitcodeEnabled() &&
3974 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3975 // Add flags implied by -fembed-bitcode.
3976 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3977 // Disable all llvm IR level optimizations.
3978 CmdArgs.push_back("-disable-llvm-optzns");
3980 if (C.getDriver().embedBitcodeMarkerOnly())
3981 CmdArgs.push_back("-fembed-bitcode=marker");
3983 // We normally speed up the clang process a bit by skipping destructors at
3984 // exit, but when we're generating diagnostics we can rely on some of the
3986 if (!C.isForDiagnostics())
3987 CmdArgs.push_back("-disable-free");
3989 // Disable the verification pass in -asserts builds.
3991 CmdArgs.push_back("-disable-llvm-verifier");
3992 // Discard LLVM value names in -asserts builds.
3993 CmdArgs.push_back("-discard-value-names");
3996 // Set the main file name, so that debug info works even with
3998 CmdArgs.push_back("-main-file-name");
3999 CmdArgs.push_back(getBaseInputName(Args, Input));
4001 // Some flags which affect the language (via preprocessor
4003 if (Args.hasArg(options::OPT_static))
4004 CmdArgs.push_back("-static-define");
4006 if (isa<AnalyzeJobAction>(JA)) {
4007 // Enable region store model by default.
4008 CmdArgs.push_back("-analyzer-store=region");
4010 // Treat blocks as analysis entry points.
4011 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
4013 CmdArgs.push_back("-analyzer-eagerly-assume");
4015 // Add default argument set.
4016 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
4017 CmdArgs.push_back("-analyzer-checker=core");
4019 if (!IsWindowsMSVC) {
4020 CmdArgs.push_back("-analyzer-checker=unix");
4022 // Enable "unix" checkers that also work on Windows.
4023 CmdArgs.push_back("-analyzer-checker=unix.API");
4024 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
4025 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
4026 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
4027 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
4028 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
4031 // Disable some unix checkers for PS4.
4033 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
4034 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
4037 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
4038 CmdArgs.push_back("-analyzer-checker=osx");
4040 CmdArgs.push_back("-analyzer-checker=deadcode");
4042 if (types::isCXX(Input.getType()))
4043 CmdArgs.push_back("-analyzer-checker=cplusplus");
4047 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
4048 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
4049 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
4050 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
4051 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
4052 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
4055 // Default nullability checks.
4056 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
4058 "-analyzer-checker=nullability.NullReturnedFromNonnull");
4061 // Set the output format. The default is plist, for (lame) historical
4063 CmdArgs.push_back("-analyzer-output");
4064 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
4065 CmdArgs.push_back(A->getValue());
4067 CmdArgs.push_back("plist");
4069 // Disable the presentation of standard compiler warnings when
4070 // using --analyze. We only want to show static analyzer diagnostics
4071 // or frontend errors.
4072 CmdArgs.push_back("-w");
4074 // Add -Xanalyzer arguments when running as analyzer.
4075 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
4078 CheckCodeGenerationOptions(D, Args);
4080 llvm::Reloc::Model RelocationModel;
4083 std::tie(RelocationModel, PICLevel, IsPIE) =
4084 ParsePICArgs(getToolChain(), Triple, Args);
4086 const char *RMName = RelocationModelName(RelocationModel);
4088 CmdArgs.push_back("-mrelocation-model");
4089 CmdArgs.push_back(RMName);
4092 CmdArgs.push_back("-pic-level");
4093 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4095 CmdArgs.push_back("-pic-is-pie");
4098 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4099 CmdArgs.push_back("-meabi");
4100 CmdArgs.push_back(A->getValue());
4103 CmdArgs.push_back("-mthread-model");
4104 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
4105 CmdArgs.push_back(A->getValue());
4107 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
4109 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4111 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
4112 options::OPT_fno_merge_all_constants))
4113 CmdArgs.push_back("-fno-merge-all-constants");
4115 // LLVM Code Generator Options.
4117 if (Args.hasArg(options::OPT_frewrite_map_file) ||
4118 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
4119 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
4120 options::OPT_frewrite_map_file_EQ)) {
4121 CmdArgs.push_back("-frewrite-map-file");
4122 CmdArgs.push_back(A->getValue());
4127 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4128 StringRef v = A->getValue();
4129 CmdArgs.push_back("-mllvm");
4130 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4134 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4136 CmdArgs.push_back("-fno-jump-tables");
4138 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4139 CmdArgs.push_back("-mregparm");
4140 CmdArgs.push_back(A->getValue());
4143 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4144 options::OPT_freg_struct_return)) {
4145 if (getToolChain().getArch() != llvm::Triple::x86) {
4146 D.Diag(diag::err_drv_unsupported_opt_for_target)
4147 << A->getSpelling() << getToolChain().getTriple().str();
4148 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4149 CmdArgs.push_back("-fpcc-struct-return");
4151 assert(A->getOption().matches(options::OPT_freg_struct_return));
4152 CmdArgs.push_back("-freg-struct-return");
4156 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4157 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4159 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
4160 CmdArgs.push_back("-mdisable-fp-elim");
4161 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4162 options::OPT_fno_zero_initialized_in_bss))
4163 CmdArgs.push_back("-mno-zero-initialized-in-bss");
4165 bool OFastEnabled = isOptimizationLevelFast(Args);
4166 // If -Ofast is the optimization level, then -fstrict-aliasing should be
4167 // enabled. This alias option is being used to simplify the hasFlag logic.
4168 OptSpecifier StrictAliasingAliasOption =
4169 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4170 // We turn strict aliasing off by default if we're in CL mode, since MSVC
4171 // doesn't do any TBAA.
4172 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
4173 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4174 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4175 CmdArgs.push_back("-relaxed-aliasing");
4176 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4177 options::OPT_fno_struct_path_tbaa))
4178 CmdArgs.push_back("-no-struct-path-tbaa");
4179 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4181 CmdArgs.push_back("-fstrict-enums");
4182 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4183 options::OPT_fno_strict_vtable_pointers,
4185 CmdArgs.push_back("-fstrict-vtable-pointers");
4186 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4187 options::OPT_fno_optimize_sibling_calls))
4188 CmdArgs.push_back("-mdisable-tail-calls");
4190 // Handle segmented stacks.
4191 if (Args.hasArg(options::OPT_fsplit_stack))
4192 CmdArgs.push_back("-split-stacks");
4194 // If -Ofast is the optimization level, then -ffast-math should be enabled.
4195 // This alias option is being used to simplify the getLastArg logic.
4196 OptSpecifier FastMathAliasOption =
4197 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
4199 // Handle various floating point optimization flags, mapping them to the
4200 // appropriate LLVM code generation flags. The pattern for all of these is to
4201 // default off the codegen optimizations, and if any flag enables them and no
4202 // flag disables them after the flag enabling them, enable the codegen
4203 // optimization. This is complicated by several "umbrella" flags.
4204 if (Arg *A = Args.getLastArg(
4205 options::OPT_ffast_math, FastMathAliasOption,
4206 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4207 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
4208 options::OPT_fno_honor_infinities))
4209 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4210 A->getOption().getID() != options::OPT_fno_finite_math_only &&
4211 A->getOption().getID() != options::OPT_fhonor_infinities)
4212 CmdArgs.push_back("-menable-no-infs");
4213 if (Arg *A = Args.getLastArg(
4214 options::OPT_ffast_math, FastMathAliasOption,
4215 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4216 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
4217 options::OPT_fno_honor_nans))
4218 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4219 A->getOption().getID() != options::OPT_fno_finite_math_only &&
4220 A->getOption().getID() != options::OPT_fhonor_nans)
4221 CmdArgs.push_back("-menable-no-nans");
4223 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
4224 bool MathErrno = getToolChain().IsMathErrnoDefault();
4226 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4227 options::OPT_fno_fast_math, options::OPT_fmath_errno,
4228 options::OPT_fno_math_errno)) {
4229 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
4230 // However, turning *off* -ffast_math merely restores the toolchain default
4231 // (which may be false).
4232 if (A->getOption().getID() == options::OPT_fno_math_errno ||
4233 A->getOption().getID() == options::OPT_ffast_math ||
4234 A->getOption().getID() == options::OPT_Ofast)
4236 else if (A->getOption().getID() == options::OPT_fmath_errno)
4240 CmdArgs.push_back("-fmath-errno");
4242 // There are several flags which require disabling very specific
4243 // optimizations. Any of these being disabled forces us to turn off the
4244 // entire set of LLVM optimizations, so collect them through all the flag
4246 bool AssociativeMath = false;
4247 if (Arg *A = Args.getLastArg(
4248 options::OPT_ffast_math, FastMathAliasOption,
4249 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4250 options::OPT_fno_unsafe_math_optimizations,
4251 options::OPT_fassociative_math, options::OPT_fno_associative_math))
4252 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4253 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4254 A->getOption().getID() != options::OPT_fno_associative_math)
4255 AssociativeMath = true;
4256 bool ReciprocalMath = false;
4257 if (Arg *A = Args.getLastArg(
4258 options::OPT_ffast_math, FastMathAliasOption,
4259 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4260 options::OPT_fno_unsafe_math_optimizations,
4261 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
4262 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4263 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4264 A->getOption().getID() != options::OPT_fno_reciprocal_math)
4265 ReciprocalMath = true;
4266 bool SignedZeros = true;
4267 if (Arg *A = Args.getLastArg(
4268 options::OPT_ffast_math, FastMathAliasOption,
4269 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4270 options::OPT_fno_unsafe_math_optimizations,
4271 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
4272 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4273 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4274 A->getOption().getID() != options::OPT_fsigned_zeros)
4275 SignedZeros = false;
4276 bool TrappingMath = true;
4277 if (Arg *A = Args.getLastArg(
4278 options::OPT_ffast_math, FastMathAliasOption,
4279 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4280 options::OPT_fno_unsafe_math_optimizations,
4281 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
4282 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4283 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4284 A->getOption().getID() != options::OPT_ftrapping_math)
4285 TrappingMath = false;
4286 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
4288 CmdArgs.push_back("-menable-unsafe-fp-math");
4291 CmdArgs.push_back("-fno-signed-zeros");
4294 CmdArgs.push_back("-freciprocal-math");
4296 // Validate and pass through -fp-contract option.
4297 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4298 options::OPT_fno_fast_math,
4299 options::OPT_ffp_contract)) {
4300 if (A->getOption().getID() == options::OPT_ffp_contract) {
4301 StringRef Val = A->getValue();
4302 if (Val == "fast" || Val == "on" || Val == "off") {
4303 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
4305 D.Diag(diag::err_drv_unsupported_option_argument)
4306 << A->getOption().getName() << Val;
4308 } else if (A->getOption().matches(options::OPT_ffast_math) ||
4309 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
4310 // If fast-math is set then set the fp-contract mode to fast.
4311 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
4315 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
4317 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
4318 // and if we find them, tell the frontend to provide the appropriate
4319 // preprocessor macros. This is distinct from enabling any optimizations as
4320 // these options induce language changes which must survive serialization
4321 // and deserialization, etc.
4322 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4323 options::OPT_fno_fast_math))
4324 if (!A->getOption().matches(options::OPT_fno_fast_math))
4325 CmdArgs.push_back("-ffast-math");
4326 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
4327 options::OPT_fno_fast_math))
4328 if (A->getOption().matches(options::OPT_ffinite_math_only))
4329 CmdArgs.push_back("-ffinite-math-only");
4331 // Decide whether to use verbose asm. Verbose assembly is the default on
4332 // toolchains which have the integrated assembler on by default.
4333 bool IsIntegratedAssemblerDefault =
4334 getToolChain().IsIntegratedAssemblerDefault();
4335 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4336 IsIntegratedAssemblerDefault) ||
4337 Args.hasArg(options::OPT_dA))
4338 CmdArgs.push_back("-masm-verbose");
4340 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
4341 IsIntegratedAssemblerDefault))
4342 CmdArgs.push_back("-no-integrated-as");
4344 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4345 CmdArgs.push_back("-mdebug-pass");
4346 CmdArgs.push_back("Structure");
4348 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4349 CmdArgs.push_back("-mdebug-pass");
4350 CmdArgs.push_back("Arguments");
4353 // Enable -mconstructor-aliases except on darwin, where we have to work around
4354 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4355 // aliases aren't supported.
4356 if (!getToolChain().getTriple().isOSDarwin() &&
4357 !getToolChain().getTriple().isNVPTX())
4358 CmdArgs.push_back("-mconstructor-aliases");
4360 // Darwin's kernel doesn't support guard variables; just die if we
4362 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
4363 CmdArgs.push_back("-fforbid-guard-variables");
4365 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4367 CmdArgs.push_back("-mms-bitfields");
4370 // This is a coarse approximation of what llvm-gcc actually does, both
4371 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4372 // complicated ways.
4373 bool AsynchronousUnwindTables =
4374 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4375 options::OPT_fno_asynchronous_unwind_tables,
4376 (getToolChain().IsUnwindTablesDefault() ||
4377 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
4379 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4380 AsynchronousUnwindTables))
4381 CmdArgs.push_back("-munwind-tables");
4383 getToolChain().addClangTargetOptions(Args, CmdArgs);
4385 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
4386 CmdArgs.push_back("-mlimit-float-precision");
4387 CmdArgs.push_back(A->getValue());
4390 // FIXME: Handle -mtune=.
4391 (void)Args.hasArg(options::OPT_mtune_EQ);
4393 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4394 CmdArgs.push_back("-mcode-model");
4395 CmdArgs.push_back(A->getValue());
4398 // Add the target cpu
4399 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4401 CmdArgs.push_back("-target-cpu");
4402 CmdArgs.push_back(Args.MakeArgString(CPU));
4405 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
4406 CmdArgs.push_back("-mfpmath");
4407 CmdArgs.push_back(A->getValue());
4410 // Add the target features
4411 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
4413 // Add target specific flags.
4414 switch (getToolChain().getArch()) {
4418 case llvm::Triple::arm:
4419 case llvm::Triple::armeb:
4420 case llvm::Triple::thumb:
4421 case llvm::Triple::thumbeb:
4422 // Use the effective triple, which takes into account the deployment target.
4423 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
4426 case llvm::Triple::aarch64:
4427 case llvm::Triple::aarch64_be:
4428 AddAArch64TargetArgs(Args, CmdArgs);
4431 case llvm::Triple::mips:
4432 case llvm::Triple::mipsel:
4433 case llvm::Triple::mips64:
4434 case llvm::Triple::mips64el:
4435 AddMIPSTargetArgs(Args, CmdArgs);
4438 case llvm::Triple::ppc:
4439 case llvm::Triple::ppc64:
4440 case llvm::Triple::ppc64le:
4441 AddPPCTargetArgs(Args, CmdArgs);
4444 case llvm::Triple::sparc:
4445 case llvm::Triple::sparcel:
4446 case llvm::Triple::sparcv9:
4447 AddSparcTargetArgs(Args, CmdArgs);
4450 case llvm::Triple::systemz:
4451 AddSystemZTargetArgs(Args, CmdArgs);
4454 case llvm::Triple::x86:
4455 case llvm::Triple::x86_64:
4456 AddX86TargetArgs(Args, CmdArgs);
4459 case llvm::Triple::lanai:
4460 AddLanaiTargetArgs(Args, CmdArgs);
4463 case llvm::Triple::hexagon:
4464 AddHexagonTargetArgs(Args, CmdArgs);
4467 case llvm::Triple::wasm32:
4468 case llvm::Triple::wasm64:
4469 AddWebAssemblyTargetArgs(Args, CmdArgs);
4473 // The 'g' groups options involve a somewhat intricate sequence of decisions
4474 // about what to pass from the driver to the frontend, but by the time they
4475 // reach cc1 they've been factored into three well-defined orthogonal choices:
4476 // * what level of debug info to generate
4477 // * what dwarf version to write
4478 // * what debugger tuning to use
4479 // This avoids having to monkey around further in cc1 other than to disable
4480 // codeview if not running in a Windows environment. Perhaps even that
4481 // decision should be made in the driver as well though.
4482 unsigned DwarfVersion = 0;
4483 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4484 // These two are potentially updated by AddClangCLArgs.
4485 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4486 bool EmitCodeView = false;
4488 // Add clang-cl arguments.
4489 types::ID InputType = Input.getType();
4490 if (getToolChain().getDriver().IsCLMode())
4491 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4493 // Pass the linker version in use.
4494 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4495 CmdArgs.push_back("-target-linker-version");
4496 CmdArgs.push_back(A->getValue());
4499 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4500 CmdArgs.push_back("-momit-leaf-frame-pointer");
4502 // Explicitly error on some things we know we don't support and can't just
4504 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4506 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4507 getToolChain().getArch() == llvm::Triple::x86) {
4508 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4509 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4510 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4511 << Unsupported->getOption().getName();
4515 Args.AddAllArgs(CmdArgs, options::OPT_v);
4516 Args.AddLastArg(CmdArgs, options::OPT_H);
4517 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4518 CmdArgs.push_back("-header-include-file");
4519 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4522 Args.AddLastArg(CmdArgs, options::OPT_P);
4523 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4525 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4526 CmdArgs.push_back("-diagnostic-log-file");
4527 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4531 Args.ClaimAllArgs(options::OPT_g_Group);
4532 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4533 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4534 // If the last option explicitly specified a debug-info level, use it.
4535 if (A->getOption().matches(options::OPT_gN_Group)) {
4536 DebugInfoKind = DebugLevelToInfoKind(*A);
4537 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4538 // But -gsplit-dwarf is not a g_group option, hence we have to check the
4539 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4540 if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
4541 A->getIndex() > SplitDwarfArg->getIndex())
4542 SplitDwarfArg = nullptr;
4544 // For any other 'g' option, use Limited.
4545 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4548 // If a debugger tuning argument appeared, remember it.
4549 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4550 options::OPT_ggdbN_Group)) {
4551 if (A->getOption().matches(options::OPT_glldb))
4552 DebuggerTuning = llvm::DebuggerKind::LLDB;
4553 else if (A->getOption().matches(options::OPT_gsce))
4554 DebuggerTuning = llvm::DebuggerKind::SCE;
4556 DebuggerTuning = llvm::DebuggerKind::GDB;
4559 // If a -gdwarf argument appeared, remember it.
4560 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4561 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4562 DwarfVersion = DwarfVersionNum(A->getSpelling());
4564 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
4565 // argument parsing.
4566 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4567 // DwarfVersion remains at 0 if no explicit choice was made.
4568 CmdArgs.push_back("-gcodeview");
4569 } else if (DwarfVersion == 0 &&
4570 DebugInfoKind != codegenoptions::NoDebugInfo) {
4571 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4574 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4575 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4577 // PS4 defaults to no column info
4578 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4579 /*Default=*/ !IsPS4CPU))
4580 CmdArgs.push_back("-dwarf-column-info");
4582 // FIXME: Move backend command line options to the module.
4583 if (Args.hasArg(options::OPT_gmodules)) {
4584 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4585 CmdArgs.push_back("-dwarf-ext-refs");
4586 CmdArgs.push_back("-fmodule-format=obj");
4589 // -gsplit-dwarf should turn on -g and enable the backend dwarf
4590 // splitting and extraction.
4591 // FIXME: Currently only works on Linux.
4592 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4593 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4594 CmdArgs.push_back("-backend-option");
4595 CmdArgs.push_back("-split-dwarf=Enable");
4598 // After we've dealt with all combinations of things that could
4599 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4600 // figure out if we need to "upgrade" it to standalone debug info.
4601 // We parse these two '-f' options whether or not they will be used,
4602 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4603 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4604 options::OPT_fno_standalone_debug,
4605 getToolChain().GetDefaultStandaloneDebug());
4606 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
4607 DebugInfoKind = codegenoptions::FullDebugInfo;
4608 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4611 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4612 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4613 CmdArgs.push_back("-backend-option");
4614 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4617 // -gdwarf-aranges turns on the emission of the aranges section in the
4619 // Always enabled on the PS4.
4620 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4621 CmdArgs.push_back("-backend-option");
4622 CmdArgs.push_back("-generate-arange-section");
4625 if (Args.hasFlag(options::OPT_fdebug_types_section,
4626 options::OPT_fno_debug_types_section, false)) {
4627 CmdArgs.push_back("-backend-option");
4628 CmdArgs.push_back("-generate-type-units");
4631 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4633 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4634 Triple.getArch() == llvm::Triple::wasm32 ||
4635 Triple.getArch() == llvm::Triple::wasm64;
4637 if (Args.hasFlag(options::OPT_ffunction_sections,
4638 options::OPT_fno_function_sections, UseSeparateSections)) {
4639 CmdArgs.push_back("-ffunction-sections");
4642 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4643 UseSeparateSections)) {
4644 CmdArgs.push_back("-fdata-sections");
4647 if (!Args.hasFlag(options::OPT_funique_section_names,
4648 options::OPT_fno_unique_section_names, true))
4649 CmdArgs.push_back("-fno-unique-section-names");
4651 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4653 if (Args.hasFlag(options::OPT_fxray_instrument,
4654 options::OPT_fnoxray_instrument, false)) {
4655 CmdArgs.push_back("-fxray-instrument");
4657 Args.getLastArg(options::OPT_fxray_instruction_threshold_,
4658 options::OPT_fxray_instruction_threshold_EQ)) {
4659 CmdArgs.push_back("-fxray-instruction-threshold");
4660 CmdArgs.push_back(A->getValue());
4664 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4666 // Add runtime flag for PS4 when PGO or Coverage are enabled.
4667 if (getToolChain().getTriple().isPS4CPU())
4668 addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4670 // Pass options for controlling the default header search paths.
4671 if (Args.hasArg(options::OPT_nostdinc)) {
4672 CmdArgs.push_back("-nostdsysteminc");
4673 CmdArgs.push_back("-nobuiltininc");
4675 if (Args.hasArg(options::OPT_nostdlibinc))
4676 CmdArgs.push_back("-nostdsysteminc");
4677 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4678 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4681 // Pass the path to compiler resource files.
4682 CmdArgs.push_back("-resource-dir");
4683 CmdArgs.push_back(D.ResourceDir.c_str());
4685 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4687 bool ARCMTEnabled = false;
4688 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4689 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4690 options::OPT_ccc_arcmt_modify,
4691 options::OPT_ccc_arcmt_migrate)) {
4692 ARCMTEnabled = true;
4693 switch (A->getOption().getID()) {
4695 llvm_unreachable("missed a case");
4696 case options::OPT_ccc_arcmt_check:
4697 CmdArgs.push_back("-arcmt-check");
4699 case options::OPT_ccc_arcmt_modify:
4700 CmdArgs.push_back("-arcmt-modify");
4702 case options::OPT_ccc_arcmt_migrate:
4703 CmdArgs.push_back("-arcmt-migrate");
4704 CmdArgs.push_back("-mt-migrate-directory");
4705 CmdArgs.push_back(A->getValue());
4707 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4708 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4713 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4714 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4715 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4718 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4720 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4721 << "-ccc-arcmt-migrate";
4723 CmdArgs.push_back("-mt-migrate-directory");
4724 CmdArgs.push_back(A->getValue());
4726 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4727 options::OPT_objcmt_migrate_subscripting,
4728 options::OPT_objcmt_migrate_property)) {
4729 // None specified, means enable them all.
4730 CmdArgs.push_back("-objcmt-migrate-literals");
4731 CmdArgs.push_back("-objcmt-migrate-subscripting");
4732 CmdArgs.push_back("-objcmt-migrate-property");
4734 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4735 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4736 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4739 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4740 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4741 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4742 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4743 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4744 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4745 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4746 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4747 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4748 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4749 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4750 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4751 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4752 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4753 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4754 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4757 // Add preprocessing options like -I, -D, etc. if we are using the
4760 // FIXME: Support -fpreprocessed
4761 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4762 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4764 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4765 // that "The compiler can only warn and ignore the option if not recognized".
4766 // When building with ccache, it will pass -D options to clang even on
4767 // preprocessed inputs and configure concludes that -fPIC is not supported.
4768 Args.ClaimAllArgs(options::OPT_D);
4770 // Manually translate -O4 to -O3; let clang reject others.
4771 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4772 if (A->getOption().matches(options::OPT_O4)) {
4773 CmdArgs.push_back("-O3");
4774 D.Diag(diag::warn_O4_is_O3);
4776 A->render(Args, CmdArgs);
4780 // Warn about ignored options to clang.
4782 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4783 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4787 claimNoWarnArgs(Args);
4789 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4790 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4791 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4792 CmdArgs.push_back("-pedantic");
4793 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4794 Args.AddLastArg(CmdArgs, options::OPT_w);
4796 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4797 // (-ansi is equivalent to -std=c89 or -std=c++98).
4799 // If a std is supplied, only add -trigraphs if it follows the
4801 bool ImplyVCPPCXXVer = false;
4802 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4803 if (Std->getOption().matches(options::OPT_ansi))
4804 if (types::isCXX(InputType))
4805 CmdArgs.push_back("-std=c++98");
4807 CmdArgs.push_back("-std=c89");
4809 Std->render(Args, CmdArgs);
4811 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4812 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4813 options::OPT_ftrigraphs,
4814 options::OPT_fno_trigraphs))
4816 A->render(Args, CmdArgs);
4818 // Honor -std-default.
4820 // FIXME: Clang doesn't correctly handle -std= when the input language
4821 // doesn't match. For the time being just ignore this for C++ inputs;
4822 // eventually we want to do all the standard defaulting here instead of
4823 // splitting it between the driver and clang -cc1.
4824 if (!types::isCXX(InputType))
4825 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4827 else if (IsWindowsMSVC)
4828 ImplyVCPPCXXVer = true;
4830 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4831 options::OPT_fno_trigraphs);
4834 // GCC's behavior for -Wwrite-strings is a bit strange:
4835 // * In C, this "warning flag" changes the types of string literals from
4836 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4837 // for the discarded qualifier.
4838 // * In C++, this is just a normal warning flag.
4840 // Implementing this warning correctly in C is hard, so we follow GCC's
4841 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4842 // a non-const char* in C, rather than using this crude hack.
4843 if (!types::isCXX(InputType)) {
4844 // FIXME: This should behave just like a warning flag, and thus should also
4845 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4847 Args.getLastArg(options::OPT_Wwrite_strings,
4848 options::OPT_Wno_write_strings, options::OPT_w);
4850 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4851 CmdArgs.push_back("-fconst-strings");
4854 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4855 // during C++ compilation, which it is by default. GCC keeps this define even
4856 // in the presence of '-w', match this behavior bug-for-bug.
4857 if (types::isCXX(InputType) &&
4858 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4860 CmdArgs.push_back("-fdeprecated-macro");
4863 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4864 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4865 if (Asm->getOption().matches(options::OPT_fasm))
4866 CmdArgs.push_back("-fgnu-keywords");
4868 CmdArgs.push_back("-fno-gnu-keywords");
4871 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4872 CmdArgs.push_back("-fno-dwarf-directory-asm");
4874 if (ShouldDisableAutolink(Args, getToolChain()))
4875 CmdArgs.push_back("-fno-autolink");
4877 // Add in -fdebug-compilation-dir if necessary.
4878 addDebugCompDirArg(Args, CmdArgs);
4880 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4881 StringRef Map = A->getValue();
4882 if (Map.find('=') == StringRef::npos)
4883 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4885 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4889 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4890 options::OPT_ftemplate_depth_EQ)) {
4891 CmdArgs.push_back("-ftemplate-depth");
4892 CmdArgs.push_back(A->getValue());
4895 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4896 CmdArgs.push_back("-foperator-arrow-depth");
4897 CmdArgs.push_back(A->getValue());
4900 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4901 CmdArgs.push_back("-fconstexpr-depth");
4902 CmdArgs.push_back(A->getValue());
4905 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4906 CmdArgs.push_back("-fconstexpr-steps");
4907 CmdArgs.push_back(A->getValue());
4910 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4911 CmdArgs.push_back("-fbracket-depth");
4912 CmdArgs.push_back(A->getValue());
4915 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4916 options::OPT_Wlarge_by_value_copy_def)) {
4917 if (A->getNumValues()) {
4918 StringRef bytes = A->getValue();
4919 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4921 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4924 if (Args.hasArg(options::OPT_relocatable_pch))
4925 CmdArgs.push_back("-relocatable-pch");
4927 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4928 CmdArgs.push_back("-fconstant-string-class");
4929 CmdArgs.push_back(A->getValue());
4932 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4933 CmdArgs.push_back("-ftabstop");
4934 CmdArgs.push_back(A->getValue());
4937 CmdArgs.push_back("-ferror-limit");
4938 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4939 CmdArgs.push_back(A->getValue());
4941 CmdArgs.push_back("19");
4943 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4944 CmdArgs.push_back("-fmacro-backtrace-limit");
4945 CmdArgs.push_back(A->getValue());
4948 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4949 CmdArgs.push_back("-ftemplate-backtrace-limit");
4950 CmdArgs.push_back(A->getValue());
4953 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4954 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4955 CmdArgs.push_back(A->getValue());
4958 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4959 CmdArgs.push_back("-fspell-checking-limit");
4960 CmdArgs.push_back(A->getValue());
4963 // Pass -fmessage-length=.
4964 CmdArgs.push_back("-fmessage-length");
4965 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4966 CmdArgs.push_back(A->getValue());
4968 // If -fmessage-length=N was not specified, determine whether this is a
4969 // terminal and, if so, implicitly define -fmessage-length appropriately.
4970 unsigned N = llvm::sys::Process::StandardErrColumns();
4971 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4974 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4975 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4976 options::OPT_fvisibility_ms_compat)) {
4977 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4978 CmdArgs.push_back("-fvisibility");
4979 CmdArgs.push_back(A->getValue());
4981 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4982 CmdArgs.push_back("-fvisibility");
4983 CmdArgs.push_back("hidden");
4984 CmdArgs.push_back("-ftype-visibility");
4985 CmdArgs.push_back("default");
4989 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4991 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4993 // -fhosted is default.
4994 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4996 CmdArgs.push_back("-ffreestanding");
4998 // Forward -f (flag) options which we can pass directly.
4999 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
5000 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
5001 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
5002 // Emulated TLS is enabled by default on Android, and can be enabled manually
5003 // with -femulated-tls.
5004 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
5005 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
5006 EmulatedTLSDefault))
5007 CmdArgs.push_back("-femulated-tls");
5008 // AltiVec-like language extensions aren't relevant for assembling.
5009 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
5010 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
5011 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
5013 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
5014 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
5016 // Forward flags for OpenMP. We don't do this if the current action is an
5017 // device offloading action.
5019 // TODO: Allow OpenMP offload actions when they become available.
5020 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5021 options::OPT_fno_openmp, false) &&
5022 JA.isDeviceOffloading(Action::OFK_None)) {
5023 switch (getOpenMPRuntime(getToolChain(), Args)) {
5026 // Clang can generate useful OpenMP code for these two runtime libraries.
5027 CmdArgs.push_back("-fopenmp");
5029 // If no option regarding the use of TLS in OpenMP codegeneration is
5030 // given, decide a default based on the target. Otherwise rely on the
5031 // options and pass the right information to the frontend.
5032 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5033 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5034 CmdArgs.push_back("-fnoopenmp-use-tls");
5035 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5038 // By default, if Clang doesn't know how to generate useful OpenMP code
5039 // for a specific runtime library, we just don't pass the '-fopenmp' flag
5040 // down to the actual compilation.
5041 // FIXME: It would be better to have a mode which *only* omits IR
5042 // generation based on the OpenMP support so that we get consistent
5043 // semantic analysis, etc.
5048 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
5049 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
5051 // Report an error for -faltivec on anything other than PowerPC.
5052 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
5053 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5054 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
5055 Arch == llvm::Triple::ppc64le))
5056 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
5057 << "ppc/ppc64/ppc64le";
5060 // -fzvector is incompatible with -faltivec.
5061 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
5062 if (Args.hasArg(options::OPT_faltivec))
5063 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
5066 if (getToolChain().SupportsProfiling())
5067 Args.AddLastArg(CmdArgs, options::OPT_pg);
5069 // -flax-vector-conversions is default.
5070 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
5071 options::OPT_fno_lax_vector_conversions))
5072 CmdArgs.push_back("-fno-lax-vector-conversions");
5074 if (Args.getLastArg(options::OPT_fapple_kext) ||
5075 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5076 CmdArgs.push_back("-fapple-kext");
5078 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5079 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5080 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5081 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5082 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5084 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5085 CmdArgs.push_back("-ftrapv-handler");
5086 CmdArgs.push_back(A->getValue());
5089 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5091 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5092 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5093 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5094 if (A->getOption().matches(options::OPT_fwrapv))
5095 CmdArgs.push_back("-fwrapv");
5096 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5097 options::OPT_fno_strict_overflow)) {
5098 if (A->getOption().matches(options::OPT_fno_strict_overflow))
5099 CmdArgs.push_back("-fwrapv");
5102 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5103 options::OPT_fno_reroll_loops))
5104 if (A->getOption().matches(options::OPT_freroll_loops))
5105 CmdArgs.push_back("-freroll-loops");
5107 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5108 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5109 options::OPT_fno_unroll_loops);
5111 Args.AddLastArg(CmdArgs, options::OPT_pthread);
5113 // -stack-protector=0 is default.
5114 unsigned StackProtectorLevel = 0;
5115 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
5116 options::OPT_fstack_protector_all,
5117 options::OPT_fstack_protector_strong,
5118 options::OPT_fstack_protector)) {
5119 if (A->getOption().matches(options::OPT_fstack_protector)) {
5120 StackProtectorLevel = std::max<unsigned>(
5122 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
5123 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
5124 StackProtectorLevel = LangOptions::SSPStrong;
5125 else if (A->getOption().matches(options::OPT_fstack_protector_all))
5126 StackProtectorLevel = LangOptions::SSPReq;
5128 StackProtectorLevel =
5129 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
5131 if (StackProtectorLevel) {
5132 CmdArgs.push_back("-stack-protector");
5133 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
5136 // --param ssp-buffer-size=
5137 for (const Arg *A : Args.filtered(options::OPT__param)) {
5138 StringRef Str(A->getValue());
5139 if (Str.startswith("ssp-buffer-size=")) {
5140 if (StackProtectorLevel) {
5141 CmdArgs.push_back("-stack-protector-buffer-size");
5142 // FIXME: Verify the argument is a valid integer.
5143 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
5149 // Translate -mstackrealign
5150 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5152 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5154 if (Args.hasArg(options::OPT_mstack_alignment)) {
5155 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5156 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5159 if (Args.hasArg(options::OPT_mstack_probe_size)) {
5160 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5163 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5165 CmdArgs.push_back("-mstack-probe-size=0");
5168 switch (getToolChain().getArch()) {
5169 case llvm::Triple::aarch64:
5170 case llvm::Triple::aarch64_be:
5171 case llvm::Triple::arm:
5172 case llvm::Triple::armeb:
5173 case llvm::Triple::thumb:
5174 case llvm::Triple::thumbeb:
5175 CmdArgs.push_back("-fallow-half-arguments-and-returns");
5182 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5183 options::OPT_mno_restrict_it)) {
5184 if (A->getOption().matches(options::OPT_mrestrict_it)) {
5185 CmdArgs.push_back("-backend-option");
5186 CmdArgs.push_back("-arm-restrict-it");
5188 CmdArgs.push_back("-backend-option");
5189 CmdArgs.push_back("-arm-no-restrict-it");
5191 } else if (Triple.isOSWindows() &&
5192 (Triple.getArch() == llvm::Triple::arm ||
5193 Triple.getArch() == llvm::Triple::thumb)) {
5194 // Windows on ARM expects restricted IT blocks
5195 CmdArgs.push_back("-backend-option");
5196 CmdArgs.push_back("-arm-restrict-it");
5199 // Forward -cl options to -cc1
5200 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
5201 CmdArgs.push_back("-cl-opt-disable");
5203 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
5204 CmdArgs.push_back("-cl-strict-aliasing");
5206 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
5207 CmdArgs.push_back("-cl-single-precision-constant");
5209 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
5210 CmdArgs.push_back("-cl-finite-math-only");
5212 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
5213 CmdArgs.push_back("-cl-kernel-arg-info");
5215 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
5216 CmdArgs.push_back("-cl-unsafe-math-optimizations");
5218 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
5219 CmdArgs.push_back("-cl-fast-relaxed-math");
5221 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
5222 CmdArgs.push_back("-cl-mad-enable");
5224 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
5225 CmdArgs.push_back("-cl-no-signed-zeros");
5227 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
5228 std::string CLStdStr = "-cl-std=";
5229 CLStdStr += A->getValue();
5230 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
5232 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
5233 CmdArgs.push_back("-cl-denorms-are-zero");
5236 // Forward -f options with positive and negative forms; we translate
5238 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
5239 StringRef fname = A->getValue();
5240 if (!llvm::sys::fs::exists(fname))
5241 D.Diag(diag::err_drv_no_such_file) << fname;
5243 A->render(Args, CmdArgs);
5246 // -fbuiltin is default unless -mkernel is used.
5248 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
5249 !Args.hasArg(options::OPT_mkernel));
5251 CmdArgs.push_back("-fno-builtin");
5253 // -ffreestanding implies -fno-builtin.
5254 if (Args.hasArg(options::OPT_ffreestanding))
5255 UseBuiltins = false;
5257 // Process the -fno-builtin-* options.
5258 for (const auto &Arg : Args) {
5259 const Option &O = Arg->getOption();
5260 if (!O.matches(options::OPT_fno_builtin_))
5264 // If -fno-builtin is specified, then there's no need to pass the option to
5269 StringRef FuncName = Arg->getValue();
5270 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
5273 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5274 options::OPT_fno_assume_sane_operator_new))
5275 CmdArgs.push_back("-fno-assume-sane-operator-new");
5277 // -fblocks=0 is default.
5278 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
5279 getToolChain().IsBlocksDefault()) ||
5280 (Args.hasArg(options::OPT_fgnu_runtime) &&
5281 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
5282 !Args.hasArg(options::OPT_fno_blocks))) {
5283 CmdArgs.push_back("-fblocks");
5285 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
5286 !getToolChain().hasBlocksRuntime())
5287 CmdArgs.push_back("-fblocks-runtime-optional");
5290 // -fmodules enables the use of precompiled modules (off by default).
5291 // Users can pass -fno-cxx-modules to turn off modules support for
5292 // C++/Objective-C++ programs.
5293 bool HaveModules = false;
5294 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
5295 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
5296 options::OPT_fno_cxx_modules, true);
5297 if (AllowedInCXX || !types::isCXX(InputType)) {
5298 CmdArgs.push_back("-fmodules");
5303 // -fmodule-maps enables implicit reading of module map files. By default,
5304 // this is enabled if we are using precompiled modules.
5305 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
5306 options::OPT_fno_implicit_module_maps, HaveModules)) {
5307 CmdArgs.push_back("-fimplicit-module-maps");
5310 // -fmodules-decluse checks that modules used are declared so (off by
5312 if (Args.hasFlag(options::OPT_fmodules_decluse,
5313 options::OPT_fno_modules_decluse, false)) {
5314 CmdArgs.push_back("-fmodules-decluse");
5317 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
5318 // all #included headers are part of modules.
5319 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
5320 options::OPT_fno_modules_strict_decluse, false)) {
5321 CmdArgs.push_back("-fmodules-strict-decluse");
5324 // -fno-implicit-modules turns off implicitly compiling modules on demand.
5325 if (!Args.hasFlag(options::OPT_fimplicit_modules,
5326 options::OPT_fno_implicit_modules)) {
5327 CmdArgs.push_back("-fno-implicit-modules");
5328 } else if (HaveModules) {
5329 // -fmodule-cache-path specifies where our implicitly-built module files
5330 // should be written.
5331 SmallString<128> Path;
5332 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
5333 Path = A->getValue();
5334 if (C.isForDiagnostics()) {
5335 // When generating crash reports, we want to emit the modules along with
5336 // the reproduction sources, so we ignore any provided module path.
5337 Path = Output.getFilename();
5338 llvm::sys::path::replace_extension(Path, ".cache");
5339 llvm::sys::path::append(Path, "modules");
5340 } else if (Path.empty()) {
5341 // No module path was provided: use the default.
5342 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
5343 llvm::sys::path::append(Path, "org.llvm.clang.");
5344 appendUserToPath(Path);
5345 llvm::sys::path::append(Path, "ModuleCache");
5347 const char Arg[] = "-fmodules-cache-path=";
5348 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
5349 CmdArgs.push_back(Args.MakeArgString(Path));
5352 // -fmodule-name specifies the module that is currently being built (or
5353 // used for header checking by -fmodule-maps).
5354 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
5356 // -fmodule-map-file can be used to specify files containing module
5358 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
5360 // -fmodule-file can be used to specify files containing precompiled modules.
5362 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
5364 Args.ClaimAllArgs(options::OPT_fmodule_file);
5366 // When building modules and generating crashdumps, we need to dump a module
5367 // dependency VFS alongside the output.
5368 if (HaveModules && C.isForDiagnostics()) {
5369 SmallString<128> VFSDir(Output.getFilename());
5370 llvm::sys::path::replace_extension(VFSDir, ".cache");
5371 // Add the cache directory as a temp so the crash diagnostics pick it up.
5372 C.addTempFile(Args.MakeArgString(VFSDir));
5374 llvm::sys::path::append(VFSDir, "vfs");
5375 CmdArgs.push_back("-module-dependency-dir");
5376 CmdArgs.push_back(Args.MakeArgString(VFSDir));
5380 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
5382 // Pass through all -fmodules-ignore-macro arguments.
5383 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
5384 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
5385 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
5387 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
5389 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
5390 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
5391 D.Diag(diag::err_drv_argument_not_allowed_with)
5392 << A->getAsString(Args) << "-fbuild-session-timestamp";
5394 llvm::sys::fs::file_status Status;
5395 if (llvm::sys::fs::status(A->getValue(), Status))
5396 D.Diag(diag::err_drv_no_such_file) << A->getValue();
5397 CmdArgs.push_back(Args.MakeArgString(
5398 "-fbuild-session-timestamp=" +
5399 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
5402 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
5403 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
5404 options::OPT_fbuild_session_file))
5405 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
5407 Args.AddLastArg(CmdArgs,
5408 options::OPT_fmodules_validate_once_per_build_session);
5411 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
5413 // -faccess-control is default.
5414 if (Args.hasFlag(options::OPT_fno_access_control,
5415 options::OPT_faccess_control, false))
5416 CmdArgs.push_back("-fno-access-control");
5418 // -felide-constructors is the default.
5419 if (Args.hasFlag(options::OPT_fno_elide_constructors,
5420 options::OPT_felide_constructors, false))
5421 CmdArgs.push_back("-fno-elide-constructors");
5423 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
5425 if (KernelOrKext || (types::isCXX(InputType) &&
5426 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
5427 RTTIMode == ToolChain::RM_DisabledImplicitly)))
5428 CmdArgs.push_back("-fno-rtti");
5430 // -fshort-enums=0 is default for all architectures except Hexagon.
5431 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5432 getToolChain().getArch() == llvm::Triple::hexagon))
5433 CmdArgs.push_back("-fshort-enums");
5435 // -fsigned-char is default.
5436 if (Arg *A = Args.getLastArg(
5437 options::OPT_fsigned_char, options::OPT_fno_signed_char,
5438 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
5439 if (A->getOption().matches(options::OPT_funsigned_char) ||
5440 A->getOption().matches(options::OPT_fno_signed_char)) {
5441 CmdArgs.push_back("-fno-signed-char");
5443 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
5444 CmdArgs.push_back("-fno-signed-char");
5447 // -fuse-cxa-atexit is default.
5449 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
5450 !IsWindowsCygnus && !IsWindowsGNU &&
5451 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
5452 getToolChain().getArch() != llvm::Triple::hexagon &&
5453 getToolChain().getArch() != llvm::Triple::xcore &&
5454 ((getToolChain().getTriple().getVendor() !=
5455 llvm::Triple::MipsTechnologies) ||
5456 getToolChain().getTriple().hasEnvironment())) ||
5458 CmdArgs.push_back("-fno-use-cxa-atexit");
5460 // -fms-extensions=0 is default.
5461 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
5463 CmdArgs.push_back("-fms-extensions");
5465 // -fno-use-line-directives is default.
5466 if (Args.hasFlag(options::OPT_fuse_line_directives,
5467 options::OPT_fno_use_line_directives, false))
5468 CmdArgs.push_back("-fuse-line-directives");
5470 // -fms-compatibility=0 is default.
5471 if (Args.hasFlag(options::OPT_fms_compatibility,
5472 options::OPT_fno_ms_compatibility,
5474 Args.hasFlag(options::OPT_fms_extensions,
5475 options::OPT_fno_ms_extensions, true))))
5476 CmdArgs.push_back("-fms-compatibility");
5478 // -fms-compatibility-version=18.00 is default.
5479 VersionTuple MSVT = visualstudio::getMSVCVersion(
5480 &D, getToolChain(), getToolChain().getTriple(), Args, IsWindowsMSVC);
5483 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5485 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5486 if (ImplyVCPPCXXVer) {
5487 StringRef LanguageStandard;
5488 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
5489 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
5490 .Case("c++14", "-std=c++14")
5491 .Case("c++latest", "-std=c++1z")
5493 if (LanguageStandard.empty())
5494 D.Diag(clang::diag::warn_drv_unused_argument)
5495 << StdArg->getAsString(Args);
5498 if (LanguageStandard.empty()) {
5499 if (IsMSVC2015Compatible)
5500 LanguageStandard = "-std=c++14";
5502 LanguageStandard = "-std=c++11";
5505 CmdArgs.push_back(LanguageStandard.data());
5508 // -fno-borland-extensions is default.
5509 if (Args.hasFlag(options::OPT_fborland_extensions,
5510 options::OPT_fno_borland_extensions, false))
5511 CmdArgs.push_back("-fborland-extensions");
5513 // -fno-declspec is default, except for PS4.
5514 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5515 getToolChain().getTriple().isPS4()))
5516 CmdArgs.push_back("-fdeclspec");
5517 else if (Args.hasArg(options::OPT_fno_declspec))
5518 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5520 // -fthreadsafe-static is default, except for MSVC compatibility versions less
5522 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5523 options::OPT_fno_threadsafe_statics,
5524 !IsWindowsMSVC || IsMSVC2015Compatible))
5525 CmdArgs.push_back("-fno-threadsafe-statics");
5527 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5529 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5530 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5531 CmdArgs.push_back("-fdelayed-template-parsing");
5533 // -fgnu-keywords default varies depending on language; only pass if
5535 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5536 options::OPT_fno_gnu_keywords))
5537 A->render(Args, CmdArgs);
5539 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5541 CmdArgs.push_back("-fgnu89-inline");
5543 if (Args.hasArg(options::OPT_fno_inline))
5544 CmdArgs.push_back("-fno-inline");
5546 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
5547 options::OPT_finline_hint_functions,
5548 options::OPT_fno_inline_functions))
5549 InlineArg->render(Args, CmdArgs);
5551 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5553 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5554 // legacy is the default. Except for deployment taget of 10.5,
5555 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5556 // gets ignored silently.
5557 if (objcRuntime.isNonFragile()) {
5558 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5559 options::OPT_fno_objc_legacy_dispatch,
5560 objcRuntime.isLegacyDispatchDefaultForArch(
5561 getToolChain().getArch()))) {
5562 if (getToolChain().UseObjCMixedDispatch())
5563 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5565 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5569 // When ObjectiveC legacy runtime is in effect on MacOSX,
5570 // turn on the option to do Array/Dictionary subscripting
5572 if (getToolChain().getArch() == llvm::Triple::x86 &&
5573 getToolChain().getTriple().isMacOSX() &&
5574 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5575 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5576 objcRuntime.isNeXTFamily())
5577 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5579 // -fencode-extended-block-signature=1 is default.
5580 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5581 CmdArgs.push_back("-fencode-extended-block-signature");
5584 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5585 // NOTE: This logic is duplicated in ToolChains.cpp.
5586 bool ARC = isObjCAutoRefCount(Args);
5588 getToolChain().CheckObjCARC();
5590 CmdArgs.push_back("-fobjc-arc");
5592 // FIXME: It seems like this entire block, and several around it should be
5593 // wrapped in isObjC, but for now we just use it here as this is where it
5594 // was being used previously.
5595 if (types::isCXX(InputType) && types::isObjC(InputType)) {
5596 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5597 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5599 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5602 // Allow the user to enable full exceptions code emission.
5603 // We define off for Objective-CC, on for Objective-C++.
5604 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5605 options::OPT_fno_objc_arc_exceptions,
5606 /*default*/ types::isCXX(InputType)))
5607 CmdArgs.push_back("-fobjc-arc-exceptions");
5611 // -fobjc-infer-related-result-type is the default, except in the Objective-C
5613 if (rewriteKind != RK_None)
5614 CmdArgs.push_back("-fno-objc-infer-related-result-type");
5616 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5617 // takes precedence.
5618 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5620 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5623 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5624 } else if (getToolChain().SupportsObjCGC()) {
5625 GCArg->render(Args, CmdArgs);
5627 // FIXME: We should move this to a hard error.
5628 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5632 // Pass down -fobjc-weak or -fno-objc-weak if present.
5633 if (types::isObjC(InputType)) {
5634 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5635 options::OPT_fno_objc_weak);
5639 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5640 D.Diag(diag::err_objc_weak_with_gc);
5641 } else if (!objcRuntime.allowsWeak()) {
5642 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5643 D.Diag(diag::err_objc_weak_unsupported);
5645 WeakArg->render(Args, CmdArgs);
5649 if (Args.hasFlag(options::OPT_fapplication_extension,
5650 options::OPT_fno_application_extension, false))
5651 CmdArgs.push_back("-fapplication-extension");
5653 // Handle GCC-style exception args.
5654 if (!C.getDriver().IsCLMode())
5655 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5658 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
5659 getToolChain().UseSjLjExceptions(Args))
5660 CmdArgs.push_back("-fsjlj-exceptions");
5662 // C++ "sane" operator new.
5663 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5664 options::OPT_fno_assume_sane_operator_new))
5665 CmdArgs.push_back("-fno-assume-sane-operator-new");
5667 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5669 if (Args.hasFlag(options::OPT_fsized_deallocation,
5670 options::OPT_fno_sized_deallocation, false))
5671 CmdArgs.push_back("-fsized-deallocation");
5673 // -fconstant-cfstrings is default, and may be subject to argument translation
5675 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5676 options::OPT_fno_constant_cfstrings) ||
5677 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5678 options::OPT_mno_constant_cfstrings))
5679 CmdArgs.push_back("-fno-constant-cfstrings");
5681 // -fshort-wchar default varies depending on platform; only
5682 // pass if specified.
5683 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5684 options::OPT_fno_short_wchar))
5685 A->render(Args, CmdArgs);
5687 // -fno-pascal-strings is default, only pass non-default.
5688 if (Args.hasFlag(options::OPT_fpascal_strings,
5689 options::OPT_fno_pascal_strings, false))
5690 CmdArgs.push_back("-fpascal-strings");
5692 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5693 // -fno-pack-struct doesn't apply to -fpack-struct=.
5694 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5695 std::string PackStructStr = "-fpack-struct=";
5696 PackStructStr += A->getValue();
5697 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5698 } else if (Args.hasFlag(options::OPT_fpack_struct,
5699 options::OPT_fno_pack_struct, false)) {
5700 CmdArgs.push_back("-fpack-struct=1");
5703 // Handle -fmax-type-align=N and -fno-type-align
5704 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5705 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5706 if (!SkipMaxTypeAlign) {
5707 std::string MaxTypeAlignStr = "-fmax-type-align=";
5708 MaxTypeAlignStr += A->getValue();
5709 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5711 } else if (getToolChain().getTriple().isOSDarwin()) {
5712 if (!SkipMaxTypeAlign) {
5713 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5714 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5718 // -fcommon is the default unless compiling kernel code or the target says so
5719 bool NoCommonDefault =
5720 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5721 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5723 CmdArgs.push_back("-fno-common");
5725 // -fsigned-bitfields is default, and clang doesn't yet support
5726 // -funsigned-bitfields.
5727 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5728 options::OPT_funsigned_bitfields))
5729 D.Diag(diag::warn_drv_clang_unsupported)
5730 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5732 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5733 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5734 D.Diag(diag::err_drv_clang_unsupported)
5735 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5737 // -finput_charset=UTF-8 is default. Reject others
5738 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5739 StringRef value = inputCharset->getValue();
5740 if (value != "UTF-8")
5741 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5745 // -fexec_charset=UTF-8 is default. Reject others
5746 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5747 StringRef value = execCharset->getValue();
5748 if (value != "UTF-8")
5749 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5753 // -fcaret-diagnostics is default.
5754 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5755 options::OPT_fno_caret_diagnostics, true))
5756 CmdArgs.push_back("-fno-caret-diagnostics");
5758 // -fdiagnostics-fixit-info is default, only pass non-default.
5759 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5760 options::OPT_fno_diagnostics_fixit_info))
5761 CmdArgs.push_back("-fno-diagnostics-fixit-info");
5763 // Enable -fdiagnostics-show-option by default.
5764 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5765 options::OPT_fno_diagnostics_show_option))
5766 CmdArgs.push_back("-fdiagnostics-show-option");
5769 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5770 CmdArgs.push_back("-fdiagnostics-show-category");
5771 CmdArgs.push_back(A->getValue());
5774 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5775 CmdArgs.push_back("-fdiagnostics-format");
5776 CmdArgs.push_back(A->getValue());
5779 if (Arg *A = Args.getLastArg(
5780 options::OPT_fdiagnostics_show_note_include_stack,
5781 options::OPT_fno_diagnostics_show_note_include_stack)) {
5782 if (A->getOption().matches(
5783 options::OPT_fdiagnostics_show_note_include_stack))
5784 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5786 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5789 // Color diagnostics are parsed by the driver directly from argv
5790 // and later re-parsed to construct this job; claim any possible
5791 // color diagnostic here to avoid warn_drv_unused_argument and
5792 // diagnose bad OPT_fdiagnostics_color_EQ values.
5793 for (Arg *A : Args) {
5794 const Option &O = A->getOption();
5795 if (!O.matches(options::OPT_fcolor_diagnostics) &&
5796 !O.matches(options::OPT_fdiagnostics_color) &&
5797 !O.matches(options::OPT_fno_color_diagnostics) &&
5798 !O.matches(options::OPT_fno_diagnostics_color) &&
5799 !O.matches(options::OPT_fdiagnostics_color_EQ))
5801 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
5802 StringRef Value(A->getValue());
5803 if (Value != "always" && Value != "never" && Value != "auto")
5804 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5805 << ("-fdiagnostics-color=" + Value).str();
5809 if (D.getDiags().getDiagnosticOptions().ShowColors)
5810 CmdArgs.push_back("-fcolor-diagnostics");
5812 if (Args.hasArg(options::OPT_fansi_escape_codes))
5813 CmdArgs.push_back("-fansi-escape-codes");
5815 if (!Args.hasFlag(options::OPT_fshow_source_location,
5816 options::OPT_fno_show_source_location))
5817 CmdArgs.push_back("-fno-show-source-location");
5819 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5821 CmdArgs.push_back("-fno-show-column");
5823 if (!Args.hasFlag(options::OPT_fspell_checking,
5824 options::OPT_fno_spell_checking))
5825 CmdArgs.push_back("-fno-spell-checking");
5827 // -fno-asm-blocks is default.
5828 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5830 CmdArgs.push_back("-fasm-blocks");
5832 // -fgnu-inline-asm is default.
5833 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5834 options::OPT_fno_gnu_inline_asm, true))
5835 CmdArgs.push_back("-fno-gnu-inline-asm");
5837 // Enable vectorization per default according to the optimization level
5838 // selected. For optimization levels that want vectorization we use the alias
5839 // option to simplify the hasFlag logic.
5840 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5841 OptSpecifier VectorizeAliasOption =
5842 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5843 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5844 options::OPT_fno_vectorize, EnableVec))
5845 CmdArgs.push_back("-vectorize-loops");
5847 // -fslp-vectorize is enabled based on the optimization level selected.
5848 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5849 OptSpecifier SLPVectAliasOption =
5850 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5851 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5852 options::OPT_fno_slp_vectorize, EnableSLPVec))
5853 CmdArgs.push_back("-vectorize-slp");
5855 // -fno-slp-vectorize-aggressive is default.
5856 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5857 options::OPT_fno_slp_vectorize_aggressive, false))
5858 CmdArgs.push_back("-vectorize-slp-aggressive");
5860 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5861 A->render(Args, CmdArgs);
5863 if (Arg *A = Args.getLastArg(
5864 options::OPT_fsanitize_undefined_strip_path_components_EQ))
5865 A->render(Args, CmdArgs);
5867 // -fdollars-in-identifiers default varies depending on platform and
5868 // language; only pass if specified.
5869 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5870 options::OPT_fno_dollars_in_identifiers)) {
5871 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5872 CmdArgs.push_back("-fdollars-in-identifiers");
5874 CmdArgs.push_back("-fno-dollars-in-identifiers");
5877 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5878 // practical purposes.
5879 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5880 options::OPT_fno_unit_at_a_time)) {
5881 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5882 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5885 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5886 options::OPT_fno_apple_pragma_pack, false))
5887 CmdArgs.push_back("-fapple-pragma-pack");
5889 // le32-specific flags:
5890 // -fno-math-builtin: clang should not convert math builtins to intrinsics
5892 if (getToolChain().getArch() == llvm::Triple::le32) {
5893 CmdArgs.push_back("-fno-math-builtin");
5896 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5898 // FIXME: Now that PR4941 has been fixed this can be enabled.
5900 if (getToolChain().getTriple().isOSDarwin() &&
5901 (getToolChain().getArch() == llvm::Triple::arm ||
5902 getToolChain().getArch() == llvm::Triple::thumb)) {
5903 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5904 CmdArgs.push_back("-fno-builtin-strcat");
5905 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5906 CmdArgs.push_back("-fno-builtin-strcpy");
5910 // Enable rewrite includes if the user's asked for it or if we're generating
5912 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5913 // nice to enable this when doing a crashdump for modules as well.
5914 if (Args.hasFlag(options::OPT_frewrite_includes,
5915 options::OPT_fno_rewrite_includes, false) ||
5916 (C.isForDiagnostics() && !HaveModules))
5917 CmdArgs.push_back("-frewrite-includes");
5919 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5920 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5921 options::OPT_traditional_cpp)) {
5922 if (isa<PreprocessJobAction>(JA))
5923 CmdArgs.push_back("-traditional-cpp");
5925 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5928 Args.AddLastArg(CmdArgs, options::OPT_dM);
5929 Args.AddLastArg(CmdArgs, options::OPT_dD);
5931 // Handle serialized diagnostics.
5932 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5933 CmdArgs.push_back("-serialize-diagnostic-file");
5934 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5937 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5938 CmdArgs.push_back("-fretain-comments-from-system-headers");
5940 // Forward -fcomment-block-commands to -cc1.
5941 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5942 // Forward -fparse-all-comments to -cc1.
5943 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5945 // Turn -fplugin=name.so into -load name.so
5946 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5947 CmdArgs.push_back("-load");
5948 CmdArgs.push_back(A->getValue());
5952 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5954 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5955 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5958 // We translate this by hand to the -cc1 argument, since nightly test uses
5959 // it and developers have been trained to spell it with -mllvm.
5960 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5961 CmdArgs.push_back("-disable-llvm-optzns");
5963 A->render(Args, CmdArgs);
5966 // With -save-temps, we want to save the unoptimized bitcode output from the
5967 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5969 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5970 // has slightly different breakdown between stages.
5971 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5972 // pristine IR generated by the frontend. Ideally, a new compile action should
5973 // be added so both IR can be captured.
5974 if (C.getDriver().isSaveTempsEnabled() &&
5975 !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
5976 CmdArgs.push_back("-disable-llvm-passes");
5978 if (Output.getType() == types::TY_Dependencies) {
5979 // Handled with other dependency code.
5980 } else if (Output.isFilename()) {
5981 CmdArgs.push_back("-o");
5982 CmdArgs.push_back(Output.getFilename());
5984 assert(Output.isNothing() && "Invalid output.");
5987 addDashXForInput(Args, Input, CmdArgs);
5989 if (Input.isFilename())
5990 CmdArgs.push_back(Input.getFilename());
5992 Input.getInputArg().renderAsInput(Args, CmdArgs);
5994 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5996 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5998 // Optionally embed the -cc1 level arguments into the debug info, for build
6000 if (getToolChain().UseDwarfDebugFlags()) {
6001 ArgStringList OriginalArgs;
6002 for (const auto &Arg : Args)
6003 Arg->render(Args, OriginalArgs);
6005 SmallString<256> Flags;
6007 for (const char *OriginalArg : OriginalArgs) {
6008 SmallString<128> EscapedArg;
6009 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6011 Flags += EscapedArg;
6013 CmdArgs.push_back("-dwarf-debug-flags");
6014 CmdArgs.push_back(Args.MakeArgString(Flags));
6017 // Add the split debug info name to the command lines here so we
6018 // can propagate it to the backend.
6019 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
6020 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
6021 isa<BackendJobAction>(JA));
6022 const char *SplitDwarfOut;
6024 CmdArgs.push_back("-split-dwarf-file");
6025 SplitDwarfOut = SplitDebugName(Args, Input);
6026 CmdArgs.push_back(SplitDwarfOut);
6029 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
6030 // Include them with -fcuda-include-gpubinary.
6031 if (IsCuda && Inputs.size() > 1)
6032 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
6033 CmdArgs.push_back("-fcuda-include-gpubinary");
6034 CmdArgs.push_back(I->getFilename());
6037 bool WholeProgramVTables =
6038 Args.hasFlag(options::OPT_fwhole_program_vtables,
6039 options::OPT_fno_whole_program_vtables, false);
6040 if (WholeProgramVTables) {
6041 if (!D.isUsingLTO())
6042 D.Diag(diag::err_drv_argument_only_allowed_with)
6043 << "-fwhole-program-vtables"
6045 CmdArgs.push_back("-fwhole-program-vtables");
6048 // Finally add the compile command to the compilation.
6049 if (Args.hasArg(options::OPT__SLASH_fallback) &&
6050 Output.getType() == types::TY_Object &&
6051 (InputType == types::TY_C || InputType == types::TY_CXX)) {
6053 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
6054 C.addCommand(llvm::make_unique<FallbackCommand>(
6055 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
6056 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
6057 isa<PrecompileJobAction>(JA)) {
6058 // In /fallback builds, run the main compilation even if the pch generation
6059 // fails, so that the main compilation's fallback to cl.exe runs.
6060 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
6063 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6066 // Handle the debug info splitting at object creation time if we're
6067 // creating an object.
6068 // TODO: Currently only works on linux with newer objcopy.
6069 if (SplitDwarf && Output.getType() == types::TY_Object)
6070 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
6072 if (Arg *A = Args.getLastArg(options::OPT_pg))
6073 if (Args.hasArg(options::OPT_fomit_frame_pointer))
6074 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6075 << A->getAsString(Args);
6077 // Claim some arguments which clang supports automatically.
6079 // -fpch-preprocess is used with gcc to add a special marker in the output to
6080 // include the PCH file. Clang's PTH solution is completely transparent, so we
6081 // do not need to deal with it at all.
6082 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6084 // Claim some arguments which clang doesn't support, but we don't
6085 // care to warn the user about.
6086 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6087 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6089 // Disable warnings for clang -E -emit-llvm foo.c
6090 Args.ClaimAllArgs(options::OPT_emit_llvm);
6093 /// Add options related to the Objective-C runtime/ABI.
6095 /// Returns true if the runtime is non-fragile.
6096 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6097 ArgStringList &cmdArgs,
6098 RewriteKind rewriteKind) const {
6099 // Look for the controlling runtime option.
6101 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6102 options::OPT_fobjc_runtime_EQ);
6104 // Just forward -fobjc-runtime= to the frontend. This supercedes
6105 // options about fragility.
6107 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6108 ObjCRuntime runtime;
6109 StringRef value = runtimeArg->getValue();
6110 if (runtime.tryParse(value)) {
6111 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6115 runtimeArg->render(args, cmdArgs);
6119 // Otherwise, we'll need the ABI "version". Version numbers are
6120 // slightly confusing for historical reasons:
6121 // 1 - Traditional "fragile" ABI
6122 // 2 - Non-fragile ABI, version 1
6123 // 3 - Non-fragile ABI, version 2
6124 unsigned objcABIVersion = 1;
6125 // If -fobjc-abi-version= is present, use that to set the version.
6126 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6127 StringRef value = abiArg->getValue();
6130 else if (value == "2")
6132 else if (value == "3")
6135 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6137 // Otherwise, determine if we are using the non-fragile ABI.
6138 bool nonFragileABIIsDefault =
6139 (rewriteKind == RK_NonFragile ||
6140 (rewriteKind == RK_None &&
6141 getToolChain().IsObjCNonFragileABIDefault()));
6142 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6143 options::OPT_fno_objc_nonfragile_abi,
6144 nonFragileABIIsDefault)) {
6145 // Determine the non-fragile ABI version to use.
6146 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6147 unsigned nonFragileABIVersion = 1;
6149 unsigned nonFragileABIVersion = 2;
6153 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6154 StringRef value = abiArg->getValue();
6156 nonFragileABIVersion = 1;
6157 else if (value == "2")
6158 nonFragileABIVersion = 2;
6160 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6164 objcABIVersion = 1 + nonFragileABIVersion;
6170 // We don't actually care about the ABI version other than whether
6171 // it's non-fragile.
6172 bool isNonFragile = objcABIVersion != 1;
6174 // If we have no runtime argument, ask the toolchain for its default runtime.
6175 // However, the rewriter only really supports the Mac runtime, so assume that.
6176 ObjCRuntime runtime;
6178 switch (rewriteKind) {
6180 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6183 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
6186 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6191 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
6192 // On Darwin, make this use the default behavior for the toolchain.
6193 if (getToolChain().getTriple().isOSDarwin()) {
6194 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6196 // Otherwise, build for a generic macosx port.
6198 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6203 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
6204 // Legacy behaviour is to target the gnustep runtime if we are in
6205 // non-fragile mode or the GCC runtime in fragile mode.
6207 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
6209 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
6213 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
6217 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
6218 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
6226 bool Asynch = false;
6227 bool NoUnwindC = false;
6229 } // end anonymous namespace
6231 /// /EH controls whether to run destructor cleanups when exceptions are
6232 /// thrown. There are three modifiers:
6233 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
6234 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
6235 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
6236 /// - c: Assume that extern "C" functions are implicitly nounwind.
6237 /// The default is /EHs-c-, meaning cleanups are disabled.
6238 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
6241 std::vector<std::string> EHArgs =
6242 Args.getAllArgValues(options::OPT__SLASH_EH);
6243 for (auto EHVal : EHArgs) {
6244 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
6247 EH.Asynch = maybeConsumeDash(EHVal, I);
6252 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
6255 EH.Synch = maybeConsumeDash(EHVal, I);
6262 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
6266 // The /GX, /GX- flags are only processed if there are not /EH flags.
6267 // The default is that /GX is not specified.
6268 if (EHArgs.empty() &&
6269 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
6270 /*default=*/false)) {
6272 EH.NoUnwindC = true;
6278 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
6279 ArgStringList &CmdArgs,
6280 codegenoptions::DebugInfoKind *DebugInfoKind,
6281 bool *EmitCodeView) const {
6282 unsigned RTOptionID = options::OPT__SLASH_MT;
6284 if (Args.hasArg(options::OPT__SLASH_LDd))
6285 // The /LDd option implies /MTd. The dependent lib part can be overridden,
6286 // but defining _DEBUG is sticky.
6287 RTOptionID = options::OPT__SLASH_MTd;
6289 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
6290 RTOptionID = A->getOption().getID();
6292 StringRef FlagForCRT;
6293 switch (RTOptionID) {
6294 case options::OPT__SLASH_MD:
6295 if (Args.hasArg(options::OPT__SLASH_LDd))
6296 CmdArgs.push_back("-D_DEBUG");
6297 CmdArgs.push_back("-D_MT");
6298 CmdArgs.push_back("-D_DLL");
6299 FlagForCRT = "--dependent-lib=msvcrt";
6301 case options::OPT__SLASH_MDd:
6302 CmdArgs.push_back("-D_DEBUG");
6303 CmdArgs.push_back("-D_MT");
6304 CmdArgs.push_back("-D_DLL");
6305 FlagForCRT = "--dependent-lib=msvcrtd";
6307 case options::OPT__SLASH_MT:
6308 if (Args.hasArg(options::OPT__SLASH_LDd))
6309 CmdArgs.push_back("-D_DEBUG");
6310 CmdArgs.push_back("-D_MT");
6311 CmdArgs.push_back("-flto-visibility-public-std");
6312 FlagForCRT = "--dependent-lib=libcmt";
6314 case options::OPT__SLASH_MTd:
6315 CmdArgs.push_back("-D_DEBUG");
6316 CmdArgs.push_back("-D_MT");
6317 CmdArgs.push_back("-flto-visibility-public-std");
6318 FlagForCRT = "--dependent-lib=libcmtd";
6321 llvm_unreachable("Unexpected option ID.");
6324 if (Args.hasArg(options::OPT__SLASH_Zl)) {
6325 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
6327 CmdArgs.push_back(FlagForCRT.data());
6329 // This provides POSIX compatibility (maps 'open' to '_open'), which most
6330 // users want. The /Za flag to cl.exe turns this off, but it's not
6331 // implemented in clang.
6332 CmdArgs.push_back("--dependent-lib=oldnames");
6335 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
6336 // would produce interleaved output, so ignore /showIncludes in such cases.
6337 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
6338 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
6339 A->render(Args, CmdArgs);
6341 // This controls whether or not we emit RTTI data for polymorphic types.
6342 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
6344 CmdArgs.push_back("-fno-rtti-data");
6346 // This controls whether or not we emit stack-protector instrumentation.
6347 // In MSVC, Buffer Security Check (/GS) is on by default.
6348 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
6349 /*default=*/true)) {
6350 CmdArgs.push_back("-stack-protector");
6351 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
6354 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
6355 if (Arg *DebugInfoArg =
6356 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
6357 options::OPT_gline_tables_only)) {
6358 *EmitCodeView = true;
6359 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
6360 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
6362 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
6363 CmdArgs.push_back("-gcodeview");
6365 *EmitCodeView = false;
6368 const Driver &D = getToolChain().getDriver();
6369 EHFlags EH = parseClangCLEHFlags(D, Args);
6370 if (EH.Synch || EH.Asynch) {
6371 if (types::isCXX(InputType))
6372 CmdArgs.push_back("-fcxx-exceptions");
6373 CmdArgs.push_back("-fexceptions");
6375 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
6376 CmdArgs.push_back("-fexternc-nounwind");
6378 // /EP should expand to -E -P.
6379 if (Args.hasArg(options::OPT__SLASH_EP)) {
6380 CmdArgs.push_back("-E");
6381 CmdArgs.push_back("-P");
6384 unsigned VolatileOptionID;
6385 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
6386 getToolChain().getArch() == llvm::Triple::x86)
6387 VolatileOptionID = options::OPT__SLASH_volatile_ms;
6389 VolatileOptionID = options::OPT__SLASH_volatile_iso;
6391 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
6392 VolatileOptionID = A->getOption().getID();
6394 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
6395 CmdArgs.push_back("-fms-volatile");
6397 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
6398 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
6399 if (MostGeneralArg && BestCaseArg)
6400 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6401 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
6403 if (MostGeneralArg) {
6404 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
6405 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
6406 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
6408 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
6409 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
6410 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
6411 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6412 << FirstConflict->getAsString(Args)
6413 << SecondConflict->getAsString(Args);
6416 CmdArgs.push_back("-fms-memptr-rep=single");
6417 else if (MultipleArg)
6418 CmdArgs.push_back("-fms-memptr-rep=multiple");
6420 CmdArgs.push_back("-fms-memptr-rep=virtual");
6423 if (Args.getLastArg(options::OPT__SLASH_Gd))
6424 CmdArgs.push_back("-fdefault-calling-conv=cdecl");
6425 else if (Args.getLastArg(options::OPT__SLASH_Gr))
6426 CmdArgs.push_back("-fdefault-calling-conv=fastcall");
6427 else if (Args.getLastArg(options::OPT__SLASH_Gz))
6428 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6429 else if (Args.getLastArg(options::OPT__SLASH_Gv))
6430 CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
6432 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
6433 A->render(Args, CmdArgs);
6435 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6436 CmdArgs.push_back("-fdiagnostics-format");
6437 if (Args.hasArg(options::OPT__SLASH_fallback))
6438 CmdArgs.push_back("msvc-fallback");
6440 CmdArgs.push_back("msvc");
6444 visualstudio::Compiler *Clang::getCLFallback() const {
6446 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6447 return CLFallback.get();
6450 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6451 ArgStringList &CmdArgs) const {
6454 const llvm::Triple &Triple = getToolChain().getTriple();
6455 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6457 CmdArgs.push_back("-target-abi");
6458 CmdArgs.push_back(ABIName.data());
6461 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6462 const InputInfo &Output, const InputInfoList &Inputs,
6463 const ArgList &Args,
6464 const char *LinkingOutput) const {
6465 ArgStringList CmdArgs;
6467 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6468 const InputInfo &Input = Inputs[0];
6470 std::string TripleStr =
6471 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
6472 const llvm::Triple Triple(TripleStr);
6474 // Don't warn about "clang -w -c foo.s"
6475 Args.ClaimAllArgs(options::OPT_w);
6476 // and "clang -emit-llvm -c foo.s"
6477 Args.ClaimAllArgs(options::OPT_emit_llvm);
6479 claimNoWarnArgs(Args);
6481 // Invoke ourselves in -cc1as mode.
6483 // FIXME: Implement custom jobs for internal actions.
6484 CmdArgs.push_back("-cc1as");
6486 // Add the "effective" target triple.
6487 CmdArgs.push_back("-triple");
6488 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6490 // Set the output mode, we currently only expect to be used as a real
6492 CmdArgs.push_back("-filetype");
6493 CmdArgs.push_back("obj");
6495 // Set the main file name, so that debug info works even with
6496 // -save-temps or preprocessed assembly.
6497 CmdArgs.push_back("-main-file-name");
6498 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6500 // Add the target cpu
6501 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6503 CmdArgs.push_back("-target-cpu");
6504 CmdArgs.push_back(Args.MakeArgString(CPU));
6507 // Add the target features
6508 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6510 // Ignore explicit -force_cpusubtype_ALL option.
6511 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6513 // Pass along any -I options so we get proper .include search paths.
6514 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6516 // Determine the original source input.
6517 const Action *SourceAction = &JA;
6518 while (SourceAction->getKind() != Action::InputClass) {
6519 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6520 SourceAction = SourceAction->getInputs()[0];
6523 // Forward -g and handle debug info related flags, assuming we are dealing
6524 // with an actual assembly file.
6525 bool WantDebug = false;
6526 unsigned DwarfVersion = 0;
6527 Args.ClaimAllArgs(options::OPT_g_Group);
6528 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6529 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6530 !A->getOption().matches(options::OPT_ggdb0);
6532 DwarfVersion = DwarfVersionNum(A->getSpelling());
6534 if (DwarfVersion == 0)
6535 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6537 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6539 if (SourceAction->getType() == types::TY_Asm ||
6540 SourceAction->getType() == types::TY_PP_Asm) {
6541 // You might think that it would be ok to set DebugInfoKind outside of
6542 // the guard for source type, however there is a test which asserts
6543 // that some assembler invocation receives no -debug-info-kind,
6544 // and it's not clear whether that test is just overly restrictive.
6545 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6546 : codegenoptions::NoDebugInfo);
6547 // Add the -fdebug-compilation-dir flag if needed.
6548 addDebugCompDirArg(Args, CmdArgs);
6550 // Set the AT_producer to the clang version when using the integrated
6551 // assembler on assembly source files.
6552 CmdArgs.push_back("-dwarf-debug-producer");
6553 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6555 // And pass along -I options
6556 Args.AddAllArgs(CmdArgs, options::OPT_I);
6558 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6559 llvm::DebuggerKind::Default);
6561 // Handle -fPIC et al -- the relocation-model affects the assembler
6562 // for some targets.
6563 llvm::Reloc::Model RelocationModel;
6566 std::tie(RelocationModel, PICLevel, IsPIE) =
6567 ParsePICArgs(getToolChain(), Triple, Args);
6569 const char *RMName = RelocationModelName(RelocationModel);
6571 CmdArgs.push_back("-mrelocation-model");
6572 CmdArgs.push_back(RMName);
6575 // Optionally embed the -cc1as level arguments into the debug info, for build
6577 if (getToolChain().UseDwarfDebugFlags()) {
6578 ArgStringList OriginalArgs;
6579 for (const auto &Arg : Args)
6580 Arg->render(Args, OriginalArgs);
6582 SmallString<256> Flags;
6583 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6585 for (const char *OriginalArg : OriginalArgs) {
6586 SmallString<128> EscapedArg;
6587 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6589 Flags += EscapedArg;
6591 CmdArgs.push_back("-dwarf-debug-flags");
6592 CmdArgs.push_back(Args.MakeArgString(Flags));
6595 // FIXME: Add -static support, once we have it.
6597 // Add target specific flags.
6598 switch (getToolChain().getArch()) {
6602 case llvm::Triple::mips:
6603 case llvm::Triple::mipsel:
6604 case llvm::Triple::mips64:
6605 case llvm::Triple::mips64el:
6606 AddMIPSTargetArgs(Args, CmdArgs);
6610 // Consume all the warning flags. Usually this would be handled more
6611 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6612 // doesn't handle that so rather than warning about unused flags that are
6613 // actually used, we'll lie by omission instead.
6614 // FIXME: Stop lying and consume only the appropriate driver flags
6615 Args.ClaimAllArgs(options::OPT_W_Group);
6617 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6618 getToolChain().getDriver());
6620 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6622 assert(Output.isFilename() && "Unexpected lipo output.");
6623 CmdArgs.push_back("-o");
6624 CmdArgs.push_back(Output.getFilename());
6626 assert(Input.isFilename() && "Invalid input.");
6627 CmdArgs.push_back(Input.getFilename());
6629 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6630 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6632 // Handle the debug info splitting at object creation time if we're
6633 // creating an object.
6634 // TODO: Currently only works on linux with newer objcopy.
6635 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6636 getToolChain().getTriple().isOSLinux())
6637 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6638 SplitDebugName(Args, Input));
6641 void GnuTool::anchor() {}
6643 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6644 const InputInfo &Output,
6645 const InputInfoList &Inputs, const ArgList &Args,
6646 const char *LinkingOutput) const {
6647 const Driver &D = getToolChain().getDriver();
6648 ArgStringList CmdArgs;
6650 for (const auto &A : Args) {
6651 if (forwardToGCC(A->getOption())) {
6652 // It is unfortunate that we have to claim here, as this means
6653 // we will basically never report anything interesting for
6654 // platforms using a generic gcc, even if we are just using gcc
6655 // to get to the assembler.
6658 // Don't forward any -g arguments to assembly steps.
6659 if (isa<AssembleJobAction>(JA) &&
6660 A->getOption().matches(options::OPT_g_Group))
6663 // Don't forward any -W arguments to assembly and link steps.
6664 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6665 A->getOption().matches(options::OPT_W_Group))
6668 A->render(Args, CmdArgs);
6672 RenderExtraToolArgs(JA, CmdArgs);
6674 // If using a driver driver, force the arch.
6675 if (getToolChain().getTriple().isOSDarwin()) {
6676 CmdArgs.push_back("-arch");
6678 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6681 // Try to force gcc to match the tool chain we want, if we recognize
6684 // FIXME: The triple class should directly provide the information we want
6686 switch (getToolChain().getArch()) {
6689 case llvm::Triple::x86:
6690 case llvm::Triple::ppc:
6691 CmdArgs.push_back("-m32");
6693 case llvm::Triple::x86_64:
6694 case llvm::Triple::ppc64:
6695 case llvm::Triple::ppc64le:
6696 CmdArgs.push_back("-m64");
6698 case llvm::Triple::sparcel:
6699 CmdArgs.push_back("-EL");
6703 if (Output.isFilename()) {
6704 CmdArgs.push_back("-o");
6705 CmdArgs.push_back(Output.getFilename());
6707 assert(Output.isNothing() && "Unexpected output");
6708 CmdArgs.push_back("-fsyntax-only");
6711 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6713 // Only pass -x if gcc will understand it; otherwise hope gcc
6714 // understands the suffix correctly. The main use case this would go
6715 // wrong in is for linker inputs if they happened to have an odd
6716 // suffix; really the only way to get this to happen is a command
6717 // like '-x foobar a.c' which will treat a.c like a linker input.
6719 // FIXME: For the linker case specifically, can we safely convert
6720 // inputs into '-Wl,' options?
6721 for (const auto &II : Inputs) {
6722 // Don't try to pass LLVM or AST inputs to a generic gcc.
6723 if (types::isLLVMIR(II.getType()))
6724 D.Diag(diag::err_drv_no_linker_llvm_support)
6725 << getToolChain().getTripleString();
6726 else if (II.getType() == types::TY_AST)
6727 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6728 else if (II.getType() == types::TY_ModuleFile)
6729 D.Diag(diag::err_drv_no_module_support)
6730 << getToolChain().getTripleString();
6732 if (types::canTypeBeUserSpecified(II.getType())) {
6733 CmdArgs.push_back("-x");
6734 CmdArgs.push_back(types::getTypeName(II.getType()));
6737 if (II.isFilename())
6738 CmdArgs.push_back(II.getFilename());
6740 const Arg &A = II.getInputArg();
6742 // Reverse translate some rewritten options.
6743 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6744 CmdArgs.push_back("-lstdc++");
6748 // Don't render as input, we need gcc to do the translations.
6749 A.render(Args, CmdArgs);
6753 const std::string &customGCCName = D.getCCCGenericGCCName();
6754 const char *GCCName;
6755 if (!customGCCName.empty())
6756 GCCName = customGCCName.c_str();
6757 else if (D.CCCIsCXX()) {
6762 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6763 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6766 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6767 ArgStringList &CmdArgs) const {
6768 CmdArgs.push_back("-E");
6771 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6772 ArgStringList &CmdArgs) const {
6773 const Driver &D = getToolChain().getDriver();
6775 switch (JA.getType()) {
6776 // If -flto, etc. are present then make sure not to force assembly output.
6777 case types::TY_LLVM_IR:
6778 case types::TY_LTO_IR:
6779 case types::TY_LLVM_BC:
6780 case types::TY_LTO_BC:
6781 CmdArgs.push_back("-c");
6783 // We assume we've got an "integrated" assembler in that gcc will produce an
6784 // object file itself.
6785 case types::TY_Object:
6786 CmdArgs.push_back("-c");
6788 case types::TY_PP_Asm:
6789 CmdArgs.push_back("-S");
6791 case types::TY_Nothing:
6792 CmdArgs.push_back("-fsyntax-only");
6795 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6799 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6800 ArgStringList &CmdArgs) const {
6801 // The types are (hopefully) good enough.
6804 // Hexagon tools start.
6805 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6806 ArgStringList &CmdArgs) const {
6809 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6810 const InputInfo &Output,
6811 const InputInfoList &Inputs,
6812 const ArgList &Args,
6813 const char *LinkingOutput) const {
6814 claimNoWarnArgs(Args);
6816 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6817 const Driver &D = HTC.getDriver();
6818 ArgStringList CmdArgs;
6820 std::string MArchString = "-march=hexagon";
6821 CmdArgs.push_back(Args.MakeArgString(MArchString));
6823 RenderExtraToolArgs(JA, CmdArgs);
6825 std::string AsName = "hexagon-llvm-mc";
6826 std::string MCpuString = "-mcpu=hexagon" +
6827 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6828 CmdArgs.push_back("-filetype=obj");
6829 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6831 if (Output.isFilename()) {
6832 CmdArgs.push_back("-o");
6833 CmdArgs.push_back(Output.getFilename());
6835 assert(Output.isNothing() && "Unexpected output");
6836 CmdArgs.push_back("-fsyntax-only");
6839 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6840 std::string N = llvm::utostr(G.getValue());
6841 CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6844 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6846 // Only pass -x if gcc will understand it; otherwise hope gcc
6847 // understands the suffix correctly. The main use case this would go
6848 // wrong in is for linker inputs if they happened to have an odd
6849 // suffix; really the only way to get this to happen is a command
6850 // like '-x foobar a.c' which will treat a.c like a linker input.
6852 // FIXME: For the linker case specifically, can we safely convert
6853 // inputs into '-Wl,' options?
6854 for (const auto &II : Inputs) {
6855 // Don't try to pass LLVM or AST inputs to a generic gcc.
6856 if (types::isLLVMIR(II.getType()))
6857 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6858 << HTC.getTripleString();
6859 else if (II.getType() == types::TY_AST)
6860 D.Diag(clang::diag::err_drv_no_ast_support)
6861 << HTC.getTripleString();
6862 else if (II.getType() == types::TY_ModuleFile)
6863 D.Diag(diag::err_drv_no_module_support)
6864 << HTC.getTripleString();
6866 if (II.isFilename())
6867 CmdArgs.push_back(II.getFilename());
6869 // Don't render as input, we need gcc to do the translations.
6870 // FIXME: What is this?
6871 II.getInputArg().render(Args, CmdArgs);
6874 auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6875 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6878 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6879 ArgStringList &CmdArgs) const {
6883 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6884 const toolchains::HexagonToolChain &HTC,
6885 const InputInfo &Output, const InputInfoList &Inputs,
6886 const ArgList &Args, ArgStringList &CmdArgs,
6887 const char *LinkingOutput) {
6889 const Driver &D = HTC.getDriver();
6891 //----------------------------------------------------------------------------
6893 //----------------------------------------------------------------------------
6894 bool IsStatic = Args.hasArg(options::OPT_static);
6895 bool IsShared = Args.hasArg(options::OPT_shared);
6896 bool IsPIE = Args.hasArg(options::OPT_pie);
6897 bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6898 bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6899 bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6901 bool UseShared = IsShared && !IsStatic;
6903 //----------------------------------------------------------------------------
6904 // Silence warnings for various options
6905 //----------------------------------------------------------------------------
6906 Args.ClaimAllArgs(options::OPT_g_Group);
6907 Args.ClaimAllArgs(options::OPT_emit_llvm);
6908 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6909 // handled somewhere else.
6910 Args.ClaimAllArgs(options::OPT_static_libgcc);
6912 //----------------------------------------------------------------------------
6914 //----------------------------------------------------------------------------
6915 if (Args.hasArg(options::OPT_s))
6916 CmdArgs.push_back("-s");
6918 if (Args.hasArg(options::OPT_r))
6919 CmdArgs.push_back("-r");
6921 for (const auto &Opt : HTC.ExtraOpts)
6922 CmdArgs.push_back(Opt.c_str());
6924 CmdArgs.push_back("-march=hexagon");
6925 std::string CpuVer =
6926 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6927 std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6928 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6931 CmdArgs.push_back("-shared");
6932 // The following should be the default, but doing as hexagon-gcc does.
6933 CmdArgs.push_back("-call_shared");
6937 CmdArgs.push_back("-static");
6939 if (IsPIE && !IsShared)
6940 CmdArgs.push_back("-pie");
6942 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6943 std::string N = llvm::utostr(G.getValue());
6944 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6945 UseG0 = G.getValue() == 0;
6948 //----------------------------------------------------------------------------
6950 //----------------------------------------------------------------------------
6951 CmdArgs.push_back("-o");
6952 CmdArgs.push_back(Output.getFilename());
6954 //----------------------------------------------------------------------------
6956 //----------------------------------------------------------------------------
6957 std::vector<std::string> OsLibs;
6958 bool HasStandalone = false;
6960 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6962 OsLibs.emplace_back(A->getValue());
6963 HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6965 if (OsLibs.empty()) {
6966 OsLibs.push_back("standalone");
6967 HasStandalone = true;
6970 //----------------------------------------------------------------------------
6972 //----------------------------------------------------------------------------
6973 const std::string MCpuSuffix = "/" + CpuVer;
6974 const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6975 const std::string RootDir =
6976 HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6977 const std::string StartSubDir =
6978 "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6980 auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6981 const char *Name) -> std::string {
6982 std::string RelName = SubDir + Name;
6983 std::string P = HTC.GetFilePath(RelName.c_str());
6984 if (llvm::sys::fs::exists(P))
6986 return RootDir + RelName;
6989 if (IncStdLib && IncStartFiles) {
6991 if (HasStandalone) {
6992 std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6993 CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6995 std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6996 CmdArgs.push_back(Args.MakeArgString(Crt0));
6998 std::string Init = UseShared
6999 ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
7000 : Find(RootDir, StartSubDir, "/init.o");
7001 CmdArgs.push_back(Args.MakeArgString(Init));
7004 //----------------------------------------------------------------------------
7005 // Library Search Paths
7006 //----------------------------------------------------------------------------
7007 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
7008 for (const auto &LibPath : LibPaths)
7009 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
7011 //----------------------------------------------------------------------------
7013 //----------------------------------------------------------------------------
7014 Args.AddAllArgs(CmdArgs,
7015 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7016 options::OPT_t, options::OPT_u_Group});
7018 AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
7020 //----------------------------------------------------------------------------
7022 //----------------------------------------------------------------------------
7023 if (IncStdLib && IncDefLibs) {
7025 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
7026 CmdArgs.push_back("-lm");
7029 CmdArgs.push_back("--start-group");
7032 for (const std::string &Lib : OsLibs)
7033 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
7034 CmdArgs.push_back("-lc");
7036 CmdArgs.push_back("-lgcc");
7038 CmdArgs.push_back("--end-group");
7041 //----------------------------------------------------------------------------
7043 //----------------------------------------------------------------------------
7044 if (IncStdLib && IncStartFiles) {
7045 std::string Fini = UseShared
7046 ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
7047 : Find(RootDir, StartSubDir, "/fini.o");
7048 CmdArgs.push_back(Args.MakeArgString(Fini));
7052 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7053 const InputInfo &Output,
7054 const InputInfoList &Inputs,
7055 const ArgList &Args,
7056 const char *LinkingOutput) const {
7057 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
7059 ArgStringList CmdArgs;
7060 constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
7063 std::string Linker = HTC.GetProgramPath("hexagon-link");
7064 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7067 // Hexagon tools end.
7069 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7070 const InputInfo &Output,
7071 const InputInfoList &Inputs,
7072 const ArgList &Args,
7073 const char *LinkingOutput) const {
7075 std::string Linker = getToolChain().GetProgramPath(getShortName());
7076 ArgStringList CmdArgs;
7077 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7078 CmdArgs.push_back("-shared");
7079 CmdArgs.push_back("-o");
7080 CmdArgs.push_back(Output.getFilename());
7081 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7084 // AMDGPU tools end.
7086 wasm::Linker::Linker(const ToolChain &TC)
7087 : GnuTool("wasm::Linker", "lld", TC) {}
7089 bool wasm::Linker::isLinkJob() const {
7093 bool wasm::Linker::hasIntegratedCPP() const {
7097 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7098 const InputInfo &Output,
7099 const InputInfoList &Inputs,
7100 const ArgList &Args,
7101 const char *LinkingOutput) const {
7103 const ToolChain &ToolChain = getToolChain();
7104 const Driver &D = ToolChain.getDriver();
7105 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
7106 ArgStringList CmdArgs;
7107 CmdArgs.push_back("-flavor");
7108 CmdArgs.push_back("ld");
7110 // Enable garbage collection of unused input sections by default, since code
7111 // size is of particular importance. This is significantly facilitated by
7112 // the enabling of -ffunction-sections and -fdata-sections in
7113 // Clang::ConstructJob.
7114 if (areOptimizationsEnabled(Args))
7115 CmdArgs.push_back("--gc-sections");
7117 if (Args.hasArg(options::OPT_rdynamic))
7118 CmdArgs.push_back("-export-dynamic");
7119 if (Args.hasArg(options::OPT_s))
7120 CmdArgs.push_back("--strip-all");
7121 if (Args.hasArg(options::OPT_shared))
7122 CmdArgs.push_back("-shared");
7123 if (Args.hasArg(options::OPT_static))
7124 CmdArgs.push_back("-Bstatic");
7126 Args.AddAllArgs(CmdArgs, options::OPT_L);
7127 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7129 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7130 if (Args.hasArg(options::OPT_shared))
7131 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
7132 else if (Args.hasArg(options::OPT_pie))
7133 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
7135 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
7137 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7140 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7142 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7144 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7146 if (Args.hasArg(options::OPT_pthread))
7147 CmdArgs.push_back("-lpthread");
7149 CmdArgs.push_back("-lc");
7150 CmdArgs.push_back("-lcompiler_rt");
7153 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7154 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7156 CmdArgs.push_back("-o");
7157 CmdArgs.push_back(Output.getFilename());
7159 C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
7162 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
7167 MArch = Triple.getArchName();
7168 MArch = StringRef(MArch).split("+").first.lower();
7170 // Handle -march=native.
7171 if (MArch == "native") {
7172 std::string CPU = llvm::sys::getHostCPUName();
7173 if (CPU != "generic") {
7174 // Translate the native cpu into the architecture suffix for that CPU.
7175 StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
7176 // If there is no valid architecture suffix for this CPU we don't know how
7177 // to handle it, so return no architecture.
7181 MArch = std::string("arm") + Suffix.str();
7188 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
7189 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
7190 std::string MArch = getARMArch(Arch, Triple);
7191 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
7192 // here means an -march=native that we can't handle, so instead return no CPU.
7196 // We need to return an empty string here on invalid MArch values as the
7197 // various places that call this function can't cope with a null result.
7198 return Triple.getARMCPUForArch(MArch);
7201 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
7202 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
7203 const llvm::Triple &Triple) {
7204 // FIXME: Warn on inconsistent use of -mcpu and -march.
7205 // If we have -mcpu=, use that.
7207 std::string MCPU = StringRef(CPU).split("+").first.lower();
7208 // Handle -mcpu=native.
7209 if (MCPU == "native")
7210 return llvm::sys::getHostCPUName();
7215 return getARMCPUForMArch(Arch, Triple);
7218 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
7219 /// CPU (or Arch, if CPU is generic).
7220 // FIXME: This is redundant with -mcpu, why does LLVM use this.
7221 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
7222 const llvm::Triple &Triple) {
7224 if (CPU == "generic") {
7225 std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
7226 ArchKind = llvm::ARM::parseArch(ARMArch);
7227 if (ArchKind == llvm::ARM::AK_INVALID)
7228 // In case of generic Arch, i.e. "arm",
7229 // extract arch from default cpu of the Triple
7230 ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
7232 // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
7233 // armv7k triple if it's actually been specified via "-arch armv7k".
7234 ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
7235 ? (unsigned)llvm::ARM::AK_ARMV7K
7236 : llvm::ARM::parseCPUArch(CPU);
7238 if (ArchKind == llvm::ARM::AK_INVALID)
7240 return llvm::ARM::getSubArch(ArchKind);
7243 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
7244 const llvm::Triple &Triple) {
7245 if (Args.hasArg(options::OPT_r))
7248 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
7249 // to generate BE-8 executables.
7250 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
7251 CmdArgs.push_back("--be8");
7254 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
7255 // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
7256 // was first introduced in Release 3. However, other compilers have
7257 // traditionally allowed it for Release 2 so we should do the same.
7258 return (NanEncoding)llvm::StringSwitch<int>(CPU)
7259 .Case("mips1", NanLegacy)
7260 .Case("mips2", NanLegacy)
7261 .Case("mips3", NanLegacy)
7262 .Case("mips4", NanLegacy)
7263 .Case("mips5", NanLegacy)
7264 .Case("mips32", NanLegacy)
7265 .Case("mips32r2", NanLegacy | Nan2008)
7266 .Case("mips32r3", NanLegacy | Nan2008)
7267 .Case("mips32r5", NanLegacy | Nan2008)
7268 .Case("mips32r6", Nan2008)
7269 .Case("mips64", NanLegacy)
7270 .Case("mips64r2", NanLegacy | Nan2008)
7271 .Case("mips64r3", NanLegacy | Nan2008)
7272 .Case("mips64r5", NanLegacy | Nan2008)
7273 .Case("mips64r6", Nan2008)
7274 .Default(NanLegacy);
7277 bool mips::hasCompactBranches(StringRef &CPU) {
7278 // mips32r6 and mips64r6 have compact branches.
7279 return llvm::StringSwitch<bool>(CPU)
7280 .Case("mips32r6", true)
7281 .Case("mips64r6", true)
7285 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
7286 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
7287 return A && (A->getValue() == StringRef(Value));
7290 bool mips::isUCLibc(const ArgList &Args) {
7291 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
7292 return A && A->getOption().matches(options::OPT_muclibc);
7295 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
7296 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
7297 return llvm::StringSwitch<bool>(NaNArg->getValue())
7299 .Case("legacy", false)
7302 // NaN2008 is the default for MIPS32r6/MIPS64r6.
7303 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
7304 .Cases("mips32r6", "mips64r6", true)
7310 bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
7311 if (!Triple.isAndroid())
7314 // Android MIPS32R6 defaults to FP64A.
7315 return llvm::StringSwitch<bool>(CPUName)
7316 .Case("mips32r6", true)
7320 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
7321 StringRef ABIName, mips::FloatABI FloatABI) {
7322 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
7323 Triple.getVendor() != llvm::Triple::MipsTechnologies &&
7324 !Triple.isAndroid())
7327 if (ABIName != "32")
7330 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
7332 if (FloatABI == mips::FloatABI::Soft)
7335 return llvm::StringSwitch<bool>(CPUName)
7336 .Cases("mips2", "mips3", "mips4", "mips5", true)
7337 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
7338 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
7342 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
7343 StringRef CPUName, StringRef ABIName,
7344 mips::FloatABI FloatABI) {
7345 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
7347 // FPXX shouldn't be used if -msingle-float is present.
7348 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
7349 options::OPT_mdouble_float))
7350 if (A->getOption().matches(options::OPT_msingle_float))
7356 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
7357 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
7358 // archs which Darwin doesn't use.
7360 // The matching this routine does is fairly pointless, since it is neither the
7361 // complete architecture list, nor a reasonable subset. The problem is that
7362 // historically the driver driver accepts this and also ties its -march=
7363 // handling to the architecture name, so we need to be careful before removing
7366 // This code must be kept in sync with Clang's Darwin specific argument
7369 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
7370 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
7371 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
7372 .Case("ppc64", llvm::Triple::ppc64)
7373 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
7374 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
7376 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
7377 // This is derived from the driver driver.
7378 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
7379 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
7380 .Cases("armv7s", "xscale", llvm::Triple::arm)
7381 .Case("arm64", llvm::Triple::aarch64)
7382 .Case("r600", llvm::Triple::r600)
7383 .Case("amdgcn", llvm::Triple::amdgcn)
7384 .Case("nvptx", llvm::Triple::nvptx)
7385 .Case("nvptx64", llvm::Triple::nvptx64)
7386 .Case("amdil", llvm::Triple::amdil)
7387 .Case("spir", llvm::Triple::spir)
7388 .Default(llvm::Triple::UnknownArch);
7391 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
7392 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
7395 if (Str == "x86_64h")
7397 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
7398 T.setOS(llvm::Triple::UnknownOS);
7399 T.setObjectFormat(llvm::Triple::MachO);
7403 const char *Clang::getBaseInputName(const ArgList &Args,
7404 const InputInfo &Input) {
7405 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7408 const char *Clang::getBaseInputStem(const ArgList &Args,
7409 const InputInfoList &Inputs) {
7410 const char *Str = getBaseInputName(Args, Inputs[0]);
7412 if (const char *End = strrchr(Str, '.'))
7413 return Args.MakeArgString(std::string(Str, End));
7418 const char *Clang::getDependencyFileName(const ArgList &Args,
7419 const InputInfoList &Inputs) {
7420 // FIXME: Think about this more.
7423 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7424 std::string Str(OutputOpt->getValue());
7425 Res = Str.substr(0, Str.rfind('.'));
7427 Res = getBaseInputStem(Args, Inputs);
7429 return Args.MakeArgString(Res + ".d");
7432 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7433 const InputInfo &Output,
7434 const InputInfoList &Inputs,
7435 const ArgList &Args,
7436 const char *LinkingOutput) const {
7437 const ToolChain &ToolChain = getToolChain();
7438 const Driver &D = ToolChain.getDriver();
7439 ArgStringList CmdArgs;
7441 // Silence warning for "clang -g foo.o -o foo"
7442 Args.ClaimAllArgs(options::OPT_g_Group);
7443 // and "clang -emit-llvm foo.o -o foo"
7444 Args.ClaimAllArgs(options::OPT_emit_llvm);
7445 // and for "clang -w foo.o -o foo". Other warning options are already
7446 // handled somewhere else.
7447 Args.ClaimAllArgs(options::OPT_w);
7449 if (!D.SysRoot.empty())
7450 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7452 // CloudABI only supports static linkage.
7453 CmdArgs.push_back("-Bstatic");
7454 CmdArgs.push_back("--no-dynamic-linker");
7456 // Provide PIE linker flags in case PIE is default for the architecture.
7457 if (ToolChain.isPIEDefault()) {
7458 CmdArgs.push_back("-pie");
7459 CmdArgs.push_back("-zrelro");
7462 CmdArgs.push_back("--eh-frame-hdr");
7463 CmdArgs.push_back("--gc-sections");
7465 if (Output.isFilename()) {
7466 CmdArgs.push_back("-o");
7467 CmdArgs.push_back(Output.getFilename());
7469 assert(Output.isNothing() && "Invalid output.");
7472 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7473 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
7474 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
7477 Args.AddAllArgs(CmdArgs, options::OPT_L);
7478 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7479 Args.AddAllArgs(CmdArgs,
7480 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7481 options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
7484 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7486 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7488 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7490 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7491 CmdArgs.push_back("-lc");
7492 CmdArgs.push_back("-lcompiler_rt");
7495 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7496 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7498 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
7499 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7502 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7503 const InputInfo &Output,
7504 const InputInfoList &Inputs,
7505 const ArgList &Args,
7506 const char *LinkingOutput) const {
7507 ArgStringList CmdArgs;
7509 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7510 const InputInfo &Input = Inputs[0];
7512 // Determine the original source input.
7513 const Action *SourceAction = &JA;
7514 while (SourceAction->getKind() != Action::InputClass) {
7515 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7516 SourceAction = SourceAction->getInputs()[0];
7519 // If -fno-integrated-as is used add -Q to the darwin assember driver to make
7520 // sure it runs its system assembler not clang's integrated assembler.
7521 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
7522 // FIXME: at run-time detect assembler capabilities or rely on version
7523 // information forwarded by -target-assembler-version.
7524 if (Args.hasArg(options::OPT_fno_integrated_as)) {
7525 const llvm::Triple &T(getToolChain().getTriple());
7526 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
7527 CmdArgs.push_back("-Q");
7530 // Forward -g, assuming we are dealing with an actual assembly file.
7531 if (SourceAction->getType() == types::TY_Asm ||
7532 SourceAction->getType() == types::TY_PP_Asm) {
7533 if (Args.hasArg(options::OPT_gstabs))
7534 CmdArgs.push_back("--gstabs");
7535 else if (Args.hasArg(options::OPT_g_Group))
7536 CmdArgs.push_back("-g");
7539 // Derived from asm spec.
7540 AddMachOArch(Args, CmdArgs);
7542 // Use -force_cpusubtype_ALL on x86 by default.
7543 if (getToolChain().getArch() == llvm::Triple::x86 ||
7544 getToolChain().getArch() == llvm::Triple::x86_64 ||
7545 Args.hasArg(options::OPT_force__cpusubtype__ALL))
7546 CmdArgs.push_back("-force_cpusubtype_ALL");
7548 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
7549 (((Args.hasArg(options::OPT_mkernel) ||
7550 Args.hasArg(options::OPT_fapple_kext)) &&
7551 getMachOToolChain().isKernelStatic()) ||
7552 Args.hasArg(options::OPT_static)))
7553 CmdArgs.push_back("-static");
7555 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7557 assert(Output.isFilename() && "Unexpected lipo output.");
7558 CmdArgs.push_back("-o");
7559 CmdArgs.push_back(Output.getFilename());
7561 assert(Input.isFilename() && "Invalid input.");
7562 CmdArgs.push_back(Input.getFilename());
7564 // asm_final spec is empty.
7566 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7567 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7570 void darwin::MachOTool::anchor() {}
7572 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
7573 ArgStringList &CmdArgs) const {
7574 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
7576 // Derived from darwin_arch spec.
7577 CmdArgs.push_back("-arch");
7578 CmdArgs.push_back(Args.MakeArgString(ArchName));
7580 // FIXME: Is this needed anymore?
7581 if (ArchName == "arm")
7582 CmdArgs.push_back("-force_cpusubtype_ALL");
7585 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
7586 // We only need to generate a temp path for LTO if we aren't compiling object
7587 // files. When compiling source files, we run 'dsymutil' after linking. We
7588 // don't run 'dsymutil' when compiling object files.
7589 for (const auto &Input : Inputs)
7590 if (Input.getType() != types::TY_Object)
7596 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
7597 ArgStringList &CmdArgs,
7598 const InputInfoList &Inputs) const {
7599 const Driver &D = getToolChain().getDriver();
7600 const toolchains::MachO &MachOTC = getMachOToolChain();
7602 unsigned Version[5] = {0, 0, 0, 0, 0};
7603 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
7604 if (!Driver::GetReleaseVersion(A->getValue(), Version))
7605 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
7608 // Newer linkers support -demangle. Pass it if supported and not disabled by
7610 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7611 CmdArgs.push_back("-demangle");
7613 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7614 CmdArgs.push_back("-export_dynamic");
7616 // If we are using App Extension restrictions, pass a flag to the linker
7617 // telling it that the compiled code has been audited.
7618 if (Args.hasFlag(options::OPT_fapplication_extension,
7619 options::OPT_fno_application_extension, false))
7620 CmdArgs.push_back("-application_extension");
7622 if (D.isUsingLTO()) {
7623 // If we are using LTO, then automatically create a temporary file path for
7624 // the linker to use, so that it's lifetime will extend past a possible
7626 if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7627 const char *TmpPath = C.getArgs().MakeArgString(
7628 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7629 C.addTempFile(TmpPath);
7630 CmdArgs.push_back("-object_path_lto");
7631 CmdArgs.push_back(TmpPath);
7634 // Use -lto_library option to specify the libLTO.dylib path. Try to find
7635 // it in clang installed libraries. If not found, the option is not used
7636 // and 'ld' will use its default mechanism to search for libLTO.dylib.
7637 if (Version[0] >= 133) {
7638 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7639 StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7640 SmallString<128> LibLTOPath(P);
7641 llvm::sys::path::append(LibLTOPath, "lib");
7642 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7643 if (llvm::sys::fs::exists(LibLTOPath)) {
7644 CmdArgs.push_back("-lto_library");
7645 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7647 D.Diag(diag::warn_drv_lto_libpath);
7652 // Derived from the "link" spec.
7653 Args.AddAllArgs(CmdArgs, options::OPT_static);
7654 if (!Args.hasArg(options::OPT_static))
7655 CmdArgs.push_back("-dynamic");
7656 if (Args.hasArg(options::OPT_fgnu_runtime)) {
7657 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7658 // here. How do we wish to handle such things?
7661 if (!Args.hasArg(options::OPT_dynamiclib)) {
7662 AddMachOArch(Args, CmdArgs);
7663 // FIXME: Why do this only on this path?
7664 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7666 Args.AddLastArg(CmdArgs, options::OPT_bundle);
7667 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7668 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7671 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7672 (A = Args.getLastArg(options::OPT_current__version)) ||
7673 (A = Args.getLastArg(options::OPT_install__name)))
7674 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7677 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7678 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7679 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7681 CmdArgs.push_back("-dylib");
7684 if ((A = Args.getLastArg(options::OPT_bundle)) ||
7685 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7686 (A = Args.getLastArg(options::OPT_client__name)) ||
7687 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7688 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7689 (A = Args.getLastArg(options::OPT_private__bundle)))
7690 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7693 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7694 "-dylib_compatibility_version");
7695 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7696 "-dylib_current_version");
7698 AddMachOArch(Args, CmdArgs);
7700 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7701 "-dylib_install_name");
7704 Args.AddLastArg(CmdArgs, options::OPT_all__load);
7705 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7706 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7707 if (MachOTC.isTargetIOSBased())
7708 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7709 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7710 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7711 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7712 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7713 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7714 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7715 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7716 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7717 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7718 Args.AddAllArgs(CmdArgs, options::OPT_init);
7720 // Add the deployment target.
7721 MachOTC.addMinVersionArgs(Args, CmdArgs);
7723 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7724 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7725 Args.AddLastArg(CmdArgs, options::OPT_single__module);
7726 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7727 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7730 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7731 options::OPT_fno_pie, options::OPT_fno_PIE)) {
7732 if (A->getOption().matches(options::OPT_fpie) ||
7733 A->getOption().matches(options::OPT_fPIE))
7734 CmdArgs.push_back("-pie");
7736 CmdArgs.push_back("-no_pie");
7738 // for embed-bitcode, use -bitcode_bundle in linker command
7739 if (C.getDriver().embedBitcodeEnabled() ||
7740 C.getDriver().embedBitcodeMarkerOnly()) {
7741 // Check if the toolchain supports bitcode build flow.
7742 if (MachOTC.SupportsEmbeddedBitcode())
7743 CmdArgs.push_back("-bitcode_bundle");
7745 D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
7748 Args.AddLastArg(CmdArgs, options::OPT_prebind);
7749 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7750 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7751 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7752 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7753 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7754 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7755 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7756 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7757 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7758 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7759 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7760 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7761 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7762 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7763 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7765 // Give --sysroot= preference, over the Apple specific behavior to also use
7766 // --isysroot as the syslibroot.
7767 StringRef sysroot = C.getSysRoot();
7768 if (sysroot != "") {
7769 CmdArgs.push_back("-syslibroot");
7770 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7771 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7772 CmdArgs.push_back("-syslibroot");
7773 CmdArgs.push_back(A->getValue());
7776 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7777 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7778 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7779 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7780 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7781 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7782 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7783 Args.AddAllArgs(CmdArgs, options::OPT_y);
7784 Args.AddLastArg(CmdArgs, options::OPT_w);
7785 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7786 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7787 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7788 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7789 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7790 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7791 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7792 Args.AddLastArg(CmdArgs, options::OPT_whyload);
7793 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7794 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7795 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7796 Args.AddLastArg(CmdArgs, options::OPT_Mach);
7799 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7800 const InputInfo &Output,
7801 const InputInfoList &Inputs,
7802 const ArgList &Args,
7803 const char *LinkingOutput) const {
7804 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7806 // If the number of arguments surpasses the system limits, we will encode the
7807 // input files in a separate file, shortening the command line. To this end,
7808 // build a list of input file names that can be passed via a file with the
7809 // -filelist linker option.
7810 llvm::opt::ArgStringList InputFileList;
7812 // The logic here is derived from gcc's behavior; most of which
7813 // comes from specs (starting with link_command). Consult gcc for
7814 // more information.
7815 ArgStringList CmdArgs;
7817 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7818 if (Args.hasArg(options::OPT_ccc_arcmt_check,
7819 options::OPT_ccc_arcmt_migrate)) {
7820 for (const auto &Arg : Args)
7823 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7824 CmdArgs.push_back(Output.getFilename());
7825 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7829 // I'm not sure why this particular decomposition exists in gcc, but
7830 // we follow suite for ease of comparison.
7831 AddLinkArgs(C, Args, CmdArgs, Inputs);
7833 // It seems that the 'e' option is completely ignored for dynamic executables
7834 // (the default), and with static executables, the last one wins, as expected.
7835 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7836 options::OPT_Z_Flag, options::OPT_u_Group,
7837 options::OPT_e, options::OPT_r});
7839 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7840 // members of static archive libraries which implement Objective-C classes or
7842 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7843 CmdArgs.push_back("-ObjC");
7845 CmdArgs.push_back("-o");
7846 CmdArgs.push_back(Output.getFilename());
7848 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7849 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7851 // SafeStack requires its own runtime libraries
7852 // These libraries should be linked first, to make sure the
7853 // __safestack_init constructor executes before everything else
7854 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7855 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7856 "libclang_rt.safestack_osx.a",
7857 /*AlwaysLink=*/true);
7860 Args.AddAllArgs(CmdArgs, options::OPT_L);
7862 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7863 // Build the input file for -filelist (list of linker input files) in case we
7865 for (const auto &II : Inputs) {
7866 if (!II.isFilename()) {
7867 // This is a linker input argument.
7868 // We cannot mix input arguments and file names in a -filelist input, thus
7869 // we prematurely stop our list (remaining files shall be passed as
7871 if (InputFileList.size() > 0)
7877 InputFileList.push_back(II.getFilename());
7880 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7881 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7883 if (isObjCRuntimeLinked(Args) &&
7884 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7885 // We use arclite library for both ARC and subscripting support.
7886 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7888 CmdArgs.push_back("-framework");
7889 CmdArgs.push_back("Foundation");
7891 CmdArgs.push_back("-lobjc");
7894 if (LinkingOutput) {
7895 CmdArgs.push_back("-arch_multiple");
7896 CmdArgs.push_back("-final_output");
7897 CmdArgs.push_back(LinkingOutput);
7900 if (Args.hasArg(options::OPT_fnested_functions))
7901 CmdArgs.push_back("-allow_stack_execute");
7903 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7905 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7906 if (getToolChain().getDriver().CCCIsCXX())
7907 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7909 // link_ssp spec is empty.
7911 // Let the tool chain choose which runtime library to link.
7912 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7915 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7916 // endfile_spec is empty.
7919 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7920 Args.AddAllArgs(CmdArgs, options::OPT_F);
7922 // -iframework should be forwarded as -F.
7923 for (const Arg *A : Args.filtered(options::OPT_iframework))
7924 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7926 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7927 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7928 if (A->getValue() == StringRef("Accelerate")) {
7929 CmdArgs.push_back("-framework");
7930 CmdArgs.push_back("Accelerate");
7935 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7936 std::unique_ptr<Command> Cmd =
7937 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7938 Cmd->setInputFileList(std::move(InputFileList));
7939 C.addCommand(std::move(Cmd));
7942 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7943 const InputInfo &Output,
7944 const InputInfoList &Inputs,
7945 const ArgList &Args,
7946 const char *LinkingOutput) const {
7947 ArgStringList CmdArgs;
7949 CmdArgs.push_back("-create");
7950 assert(Output.isFilename() && "Unexpected lipo output.");
7952 CmdArgs.push_back("-output");
7953 CmdArgs.push_back(Output.getFilename());
7955 for (const auto &II : Inputs) {
7956 assert(II.isFilename() && "Unexpected lipo input.");
7957 CmdArgs.push_back(II.getFilename());
7960 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7961 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7964 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7965 const InputInfo &Output,
7966 const InputInfoList &Inputs,
7967 const ArgList &Args,
7968 const char *LinkingOutput) const {
7969 ArgStringList CmdArgs;
7971 CmdArgs.push_back("-o");
7972 CmdArgs.push_back(Output.getFilename());
7974 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7975 const InputInfo &Input = Inputs[0];
7976 assert(Input.isFilename() && "Unexpected dsymutil input.");
7977 CmdArgs.push_back(Input.getFilename());
7980 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7981 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7984 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7985 const InputInfo &Output,
7986 const InputInfoList &Inputs,
7987 const ArgList &Args,
7988 const char *LinkingOutput) const {
7989 ArgStringList CmdArgs;
7990 CmdArgs.push_back("--verify");
7991 CmdArgs.push_back("--debug-info");
7992 CmdArgs.push_back("--eh-frame");
7993 CmdArgs.push_back("--quiet");
7995 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7996 const InputInfo &Input = Inputs[0];
7997 assert(Input.isFilename() && "Unexpected verify input");
7999 // Grabbing the output of the earlier dsymutil run.
8000 CmdArgs.push_back(Input.getFilename());
8003 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
8004 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8007 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8008 const InputInfo &Output,
8009 const InputInfoList &Inputs,
8010 const ArgList &Args,
8011 const char *LinkingOutput) const {
8012 claimNoWarnArgs(Args);
8013 ArgStringList CmdArgs;
8015 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8017 CmdArgs.push_back("-o");
8018 CmdArgs.push_back(Output.getFilename());
8020 for (const auto &II : Inputs)
8021 CmdArgs.push_back(II.getFilename());
8023 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8024 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8027 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8028 const InputInfo &Output,
8029 const InputInfoList &Inputs,
8030 const ArgList &Args,
8031 const char *LinkingOutput) const {
8032 ArgStringList CmdArgs;
8034 // Demangle C++ names in errors
8035 CmdArgs.push_back("-C");
8037 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8038 CmdArgs.push_back("-e");
8039 CmdArgs.push_back("_start");
8042 if (Args.hasArg(options::OPT_static)) {
8043 CmdArgs.push_back("-Bstatic");
8044 CmdArgs.push_back("-dn");
8046 CmdArgs.push_back("-Bdynamic");
8047 if (Args.hasArg(options::OPT_shared)) {
8048 CmdArgs.push_back("-shared");
8050 CmdArgs.push_back("--dynamic-linker");
8052 Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
8056 if (Output.isFilename()) {
8057 CmdArgs.push_back("-o");
8058 CmdArgs.push_back(Output.getFilename());
8060 assert(Output.isNothing() && "Invalid output.");
8063 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8064 if (!Args.hasArg(options::OPT_shared))
8066 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8068 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8070 Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
8072 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8075 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
8077 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8078 options::OPT_e, options::OPT_r});
8080 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8082 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8083 if (getToolChain().getDriver().CCCIsCXX())
8084 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8085 CmdArgs.push_back("-lgcc_s");
8086 CmdArgs.push_back("-lc");
8087 if (!Args.hasArg(options::OPT_shared)) {
8088 CmdArgs.push_back("-lgcc");
8089 CmdArgs.push_back("-lm");
8093 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8095 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8097 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8099 getToolChain().addProfileRTLibs(Args, CmdArgs);
8101 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8102 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8105 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8106 const InputInfo &Output,
8107 const InputInfoList &Inputs,
8108 const ArgList &Args,
8109 const char *LinkingOutput) const {
8110 claimNoWarnArgs(Args);
8111 ArgStringList CmdArgs;
8113 switch (getToolChain().getArch()) {
8114 case llvm::Triple::x86:
8115 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
8116 // instruct as in the base system to assemble 32-bit code.
8117 CmdArgs.push_back("--32");
8120 case llvm::Triple::ppc:
8121 CmdArgs.push_back("-mppc");
8122 CmdArgs.push_back("-many");
8125 case llvm::Triple::sparc:
8126 case llvm::Triple::sparcel: {
8127 CmdArgs.push_back("-32");
8128 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8129 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8130 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8134 case llvm::Triple::sparcv9: {
8135 CmdArgs.push_back("-64");
8136 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8137 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8138 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8142 case llvm::Triple::mips64:
8143 case llvm::Triple::mips64el: {
8146 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8148 CmdArgs.push_back("-mabi");
8149 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8151 if (getToolChain().getArch() == llvm::Triple::mips64)
8152 CmdArgs.push_back("-EB");
8154 CmdArgs.push_back("-EL");
8156 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8164 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8166 CmdArgs.push_back("-o");
8167 CmdArgs.push_back(Output.getFilename());
8169 for (const auto &II : Inputs)
8170 CmdArgs.push_back(II.getFilename());
8172 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8173 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8176 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8177 const InputInfo &Output,
8178 const InputInfoList &Inputs,
8179 const ArgList &Args,
8180 const char *LinkingOutput) const {
8181 const Driver &D = getToolChain().getDriver();
8182 ArgStringList CmdArgs;
8184 // Silence warning for "clang -g foo.o -o foo"
8185 Args.ClaimAllArgs(options::OPT_g_Group);
8186 // and "clang -emit-llvm foo.o -o foo"
8187 Args.ClaimAllArgs(options::OPT_emit_llvm);
8188 // and for "clang -w foo.o -o foo". Other warning options are already
8189 // handled somewhere else.
8190 Args.ClaimAllArgs(options::OPT_w);
8192 if (getToolChain().getArch() == llvm::Triple::mips64)
8193 CmdArgs.push_back("-EB");
8194 else if (getToolChain().getArch() == llvm::Triple::mips64el)
8195 CmdArgs.push_back("-EL");
8197 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8198 CmdArgs.push_back("-e");
8199 CmdArgs.push_back("__start");
8202 if (Args.hasArg(options::OPT_static)) {
8203 CmdArgs.push_back("-Bstatic");
8205 if (Args.hasArg(options::OPT_rdynamic))
8206 CmdArgs.push_back("-export-dynamic");
8207 CmdArgs.push_back("--eh-frame-hdr");
8208 CmdArgs.push_back("-Bdynamic");
8209 if (Args.hasArg(options::OPT_shared)) {
8210 CmdArgs.push_back("-shared");
8212 CmdArgs.push_back("-dynamic-linker");
8213 CmdArgs.push_back("/usr/libexec/ld.so");
8217 if (Args.hasArg(options::OPT_nopie))
8218 CmdArgs.push_back("-nopie");
8220 if (Output.isFilename()) {
8221 CmdArgs.push_back("-o");
8222 CmdArgs.push_back(Output.getFilename());
8224 assert(Output.isNothing() && "Invalid output.");
8227 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8228 if (!Args.hasArg(options::OPT_shared)) {
8229 if (Args.hasArg(options::OPT_pg))
8231 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8234 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8236 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8239 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8243 std::string Triple = getToolChain().getTripleString();
8244 if (Triple.substr(0, 6) == "x86_64")
8245 Triple.replace(0, 6, "amd64");
8247 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
8249 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8250 options::OPT_e, options::OPT_s, options::OPT_t,
8251 options::OPT_Z_Flag, options::OPT_r});
8253 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8255 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8257 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8258 if (Args.hasArg(options::OPT_pg))
8259 CmdArgs.push_back("-lm_p");
8261 CmdArgs.push_back("-lm");
8264 // FIXME: For some reason GCC passes -lgcc before adding
8265 // the default system libraries. Just mimic this for now.
8266 CmdArgs.push_back("-lgcc");
8268 if (Args.hasArg(options::OPT_pthread)) {
8269 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8270 CmdArgs.push_back("-lpthread_p");
8272 CmdArgs.push_back("-lpthread");
8275 if (!Args.hasArg(options::OPT_shared)) {
8276 if (Args.hasArg(options::OPT_pg))
8277 CmdArgs.push_back("-lc_p");
8279 CmdArgs.push_back("-lc");
8282 CmdArgs.push_back("-lgcc");
8285 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8286 if (!Args.hasArg(options::OPT_shared))
8288 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8291 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8294 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8295 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8298 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8299 const InputInfo &Output,
8300 const InputInfoList &Inputs,
8301 const ArgList &Args,
8302 const char *LinkingOutput) const {
8303 claimNoWarnArgs(Args);
8304 ArgStringList CmdArgs;
8306 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8308 CmdArgs.push_back("-o");
8309 CmdArgs.push_back(Output.getFilename());
8311 for (const auto &II : Inputs)
8312 CmdArgs.push_back(II.getFilename());
8314 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8315 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8318 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8319 const InputInfo &Output,
8320 const InputInfoList &Inputs,
8321 const ArgList &Args,
8322 const char *LinkingOutput) const {
8323 const Driver &D = getToolChain().getDriver();
8324 ArgStringList CmdArgs;
8326 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8327 CmdArgs.push_back("-e");
8328 CmdArgs.push_back("__start");
8331 if (Args.hasArg(options::OPT_static)) {
8332 CmdArgs.push_back("-Bstatic");
8334 if (Args.hasArg(options::OPT_rdynamic))
8335 CmdArgs.push_back("-export-dynamic");
8336 CmdArgs.push_back("--eh-frame-hdr");
8337 CmdArgs.push_back("-Bdynamic");
8338 if (Args.hasArg(options::OPT_shared)) {
8339 CmdArgs.push_back("-shared");
8341 CmdArgs.push_back("-dynamic-linker");
8342 CmdArgs.push_back("/usr/libexec/ld.so");
8346 if (Output.isFilename()) {
8347 CmdArgs.push_back("-o");
8348 CmdArgs.push_back(Output.getFilename());
8350 assert(Output.isNothing() && "Invalid output.");
8353 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8354 if (!Args.hasArg(options::OPT_shared)) {
8355 if (Args.hasArg(options::OPT_pg))
8357 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8360 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8362 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8365 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8369 Args.AddAllArgs(CmdArgs,
8370 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
8372 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8374 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8376 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8377 if (Args.hasArg(options::OPT_pg))
8378 CmdArgs.push_back("-lm_p");
8380 CmdArgs.push_back("-lm");
8383 if (Args.hasArg(options::OPT_pthread)) {
8384 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8385 CmdArgs.push_back("-lpthread_p");
8387 CmdArgs.push_back("-lpthread");
8390 if (!Args.hasArg(options::OPT_shared)) {
8391 if (Args.hasArg(options::OPT_pg))
8392 CmdArgs.push_back("-lc_p");
8394 CmdArgs.push_back("-lc");
8398 switch (getToolChain().getArch()) {
8399 case llvm::Triple::arm:
8402 case llvm::Triple::x86:
8405 case llvm::Triple::x86_64:
8409 llvm_unreachable("Unsupported architecture");
8411 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
8414 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8415 if (!Args.hasArg(options::OPT_shared))
8417 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8420 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8423 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8424 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8427 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8428 const InputInfo &Output,
8429 const InputInfoList &Inputs,
8430 const ArgList &Args,
8431 const char *LinkingOutput) const {
8432 claimNoWarnArgs(Args);
8433 ArgStringList CmdArgs;
8435 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8436 // instruct as in the base system to assemble 32-bit code.
8437 switch (getToolChain().getArch()) {
8440 case llvm::Triple::x86:
8441 CmdArgs.push_back("--32");
8443 case llvm::Triple::ppc:
8444 CmdArgs.push_back("-a32");
8446 case llvm::Triple::mips:
8447 case llvm::Triple::mipsel:
8448 case llvm::Triple::mips64:
8449 case llvm::Triple::mips64el: {
8452 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8454 CmdArgs.push_back("-march");
8455 CmdArgs.push_back(CPUName.data());
8457 CmdArgs.push_back("-mabi");
8458 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8460 if (getToolChain().getArch() == llvm::Triple::mips ||
8461 getToolChain().getArch() == llvm::Triple::mips64)
8462 CmdArgs.push_back("-EB");
8464 CmdArgs.push_back("-EL");
8466 if (Arg *A = Args.getLastArg(options::OPT_G)) {
8467 StringRef v = A->getValue();
8468 CmdArgs.push_back(Args.MakeArgString("-G" + v));
8472 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8475 case llvm::Triple::arm:
8476 case llvm::Triple::armeb:
8477 case llvm::Triple::thumb:
8478 case llvm::Triple::thumbeb: {
8479 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
8481 if (ABI == arm::FloatABI::Hard)
8482 CmdArgs.push_back("-mfpu=vfp");
8484 CmdArgs.push_back("-mfpu=softvfp");
8486 switch (getToolChain().getTriple().getEnvironment()) {
8487 case llvm::Triple::GNUEABIHF:
8488 case llvm::Triple::GNUEABI:
8489 case llvm::Triple::EABI:
8490 CmdArgs.push_back("-meabi=5");
8494 CmdArgs.push_back("-matpcs");
8498 case llvm::Triple::sparc:
8499 case llvm::Triple::sparcel:
8500 case llvm::Triple::sparcv9: {
8501 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8502 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8503 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8508 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8510 CmdArgs.push_back("-o");
8511 CmdArgs.push_back(Output.getFilename());
8513 for (const auto &II : Inputs)
8514 CmdArgs.push_back(II.getFilename());
8516 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8517 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8520 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8521 const InputInfo &Output,
8522 const InputInfoList &Inputs,
8523 const ArgList &Args,
8524 const char *LinkingOutput) const {
8525 const toolchains::FreeBSD &ToolChain =
8526 static_cast<const toolchains::FreeBSD &>(getToolChain());
8527 const Driver &D = ToolChain.getDriver();
8528 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8530 !Args.hasArg(options::OPT_shared) &&
8531 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8532 ArgStringList CmdArgs;
8534 // Silence warning for "clang -g foo.o -o foo"
8535 Args.ClaimAllArgs(options::OPT_g_Group);
8536 // and "clang -emit-llvm foo.o -o foo"
8537 Args.ClaimAllArgs(options::OPT_emit_llvm);
8538 // and for "clang -w foo.o -o foo". Other warning options are already
8539 // handled somewhere else.
8540 Args.ClaimAllArgs(options::OPT_w);
8542 if (!D.SysRoot.empty())
8543 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8546 CmdArgs.push_back("-pie");
8548 CmdArgs.push_back("--eh-frame-hdr");
8549 if (Args.hasArg(options::OPT_static)) {
8550 CmdArgs.push_back("-Bstatic");
8552 if (Args.hasArg(options::OPT_rdynamic))
8553 CmdArgs.push_back("-export-dynamic");
8554 if (Args.hasArg(options::OPT_shared)) {
8555 CmdArgs.push_back("-Bshareable");
8557 CmdArgs.push_back("-dynamic-linker");
8558 CmdArgs.push_back("/libexec/ld-elf.so.1");
8560 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
8561 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
8562 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
8563 CmdArgs.push_back("--hash-style=both");
8566 CmdArgs.push_back("--enable-new-dtags");
8569 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8570 // instruct ld in the base system to link 32-bit code.
8571 if (Arch == llvm::Triple::x86) {
8572 CmdArgs.push_back("-m");
8573 CmdArgs.push_back("elf_i386_fbsd");
8576 if (Arch == llvm::Triple::ppc) {
8577 CmdArgs.push_back("-m");
8578 CmdArgs.push_back("elf32ppc_fbsd");
8581 if (Arg *A = Args.getLastArg(options::OPT_G)) {
8582 if (ToolChain.getArch() == llvm::Triple::mips ||
8583 ToolChain.getArch() == llvm::Triple::mipsel ||
8584 ToolChain.getArch() == llvm::Triple::mips64 ||
8585 ToolChain.getArch() == llvm::Triple::mips64el) {
8586 StringRef v = A->getValue();
8587 CmdArgs.push_back(Args.MakeArgString("-G" + v));
8592 if (Output.isFilename()) {
8593 CmdArgs.push_back("-o");
8594 CmdArgs.push_back(Output.getFilename());
8596 assert(Output.isNothing() && "Invalid output.");
8599 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8600 const char *crt1 = nullptr;
8601 if (!Args.hasArg(options::OPT_shared)) {
8602 if (Args.hasArg(options::OPT_pg))
8610 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8612 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8614 const char *crtbegin = nullptr;
8615 if (Args.hasArg(options::OPT_static))
8616 crtbegin = "crtbeginT.o";
8617 else if (Args.hasArg(options::OPT_shared) || IsPIE)
8618 crtbegin = "crtbeginS.o";
8620 crtbegin = "crtbegin.o";
8622 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8625 Args.AddAllArgs(CmdArgs, options::OPT_L);
8626 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8627 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8628 Args.AddAllArgs(CmdArgs, options::OPT_e);
8629 Args.AddAllArgs(CmdArgs, options::OPT_s);
8630 Args.AddAllArgs(CmdArgs, options::OPT_t);
8631 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8632 Args.AddAllArgs(CmdArgs, options::OPT_r);
8635 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8637 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8638 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8640 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8641 addOpenMPRuntime(CmdArgs, ToolChain, Args);
8643 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8644 if (Args.hasArg(options::OPT_pg))
8645 CmdArgs.push_back("-lm_p");
8647 CmdArgs.push_back("-lm");
8649 if (NeedsSanitizerDeps)
8650 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8651 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8652 // the default system libraries. Just mimic this for now.
8653 if (Args.hasArg(options::OPT_pg))
8654 CmdArgs.push_back("-lgcc_p");
8656 CmdArgs.push_back("-lgcc");
8657 if (Args.hasArg(options::OPT_static)) {
8658 CmdArgs.push_back("-lgcc_eh");
8659 } else if (Args.hasArg(options::OPT_pg)) {
8660 CmdArgs.push_back("-lgcc_eh_p");
8662 CmdArgs.push_back("--as-needed");
8663 CmdArgs.push_back("-lgcc_s");
8664 CmdArgs.push_back("--no-as-needed");
8667 if (Args.hasArg(options::OPT_pthread)) {
8668 if (Args.hasArg(options::OPT_pg))
8669 CmdArgs.push_back("-lpthread_p");
8671 CmdArgs.push_back("-lpthread");
8674 if (Args.hasArg(options::OPT_pg)) {
8675 if (Args.hasArg(options::OPT_shared))
8676 CmdArgs.push_back("-lc");
8678 CmdArgs.push_back("-lc_p");
8679 CmdArgs.push_back("-lgcc_p");
8681 CmdArgs.push_back("-lc");
8682 CmdArgs.push_back("-lgcc");
8685 if (Args.hasArg(options::OPT_static)) {
8686 CmdArgs.push_back("-lgcc_eh");
8687 } else if (Args.hasArg(options::OPT_pg)) {
8688 CmdArgs.push_back("-lgcc_eh_p");
8690 CmdArgs.push_back("--as-needed");
8691 CmdArgs.push_back("-lgcc_s");
8692 CmdArgs.push_back("--no-as-needed");
8696 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8697 if (Args.hasArg(options::OPT_shared) || IsPIE)
8698 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8700 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8701 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8704 ToolChain.addProfileRTLibs(Args, CmdArgs);
8706 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8707 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8710 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8711 const InputInfo &Output,
8712 const InputInfoList &Inputs,
8713 const ArgList &Args,
8714 const char *LinkingOutput) const {
8715 claimNoWarnArgs(Args);
8716 ArgStringList CmdArgs;
8718 // GNU as needs different flags for creating the correct output format
8719 // on architectures with different ABIs or optional feature sets.
8720 switch (getToolChain().getArch()) {
8721 case llvm::Triple::x86:
8722 CmdArgs.push_back("--32");
8724 case llvm::Triple::arm:
8725 case llvm::Triple::armeb:
8726 case llvm::Triple::thumb:
8727 case llvm::Triple::thumbeb: {
8728 StringRef MArch, MCPU;
8729 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8731 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8732 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8736 case llvm::Triple::mips:
8737 case llvm::Triple::mipsel:
8738 case llvm::Triple::mips64:
8739 case llvm::Triple::mips64el: {
8742 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8744 CmdArgs.push_back("-march");
8745 CmdArgs.push_back(CPUName.data());
8747 CmdArgs.push_back("-mabi");
8748 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8750 if (getToolChain().getArch() == llvm::Triple::mips ||
8751 getToolChain().getArch() == llvm::Triple::mips64)
8752 CmdArgs.push_back("-EB");
8754 CmdArgs.push_back("-EL");
8756 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8760 case llvm::Triple::sparc:
8761 case llvm::Triple::sparcel: {
8762 CmdArgs.push_back("-32");
8763 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8764 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8765 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8769 case llvm::Triple::sparcv9: {
8770 CmdArgs.push_back("-64");
8771 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8772 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8773 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8781 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8783 CmdArgs.push_back("-o");
8784 CmdArgs.push_back(Output.getFilename());
8786 for (const auto &II : Inputs)
8787 CmdArgs.push_back(II.getFilename());
8789 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8790 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8793 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8794 const InputInfo &Output,
8795 const InputInfoList &Inputs,
8796 const ArgList &Args,
8797 const char *LinkingOutput) const {
8798 const Driver &D = getToolChain().getDriver();
8799 ArgStringList CmdArgs;
8801 if (!D.SysRoot.empty())
8802 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8804 CmdArgs.push_back("--eh-frame-hdr");
8805 if (Args.hasArg(options::OPT_static)) {
8806 CmdArgs.push_back("-Bstatic");
8808 if (Args.hasArg(options::OPT_rdynamic))
8809 CmdArgs.push_back("-export-dynamic");
8810 if (Args.hasArg(options::OPT_shared)) {
8811 CmdArgs.push_back("-Bshareable");
8813 Args.AddAllArgs(CmdArgs, options::OPT_pie);
8814 CmdArgs.push_back("-dynamic-linker");
8815 CmdArgs.push_back("/libexec/ld.elf_so");
8819 // Many NetBSD architectures support more than one ABI.
8820 // Determine the correct emulation for ld.
8821 switch (getToolChain().getArch()) {
8822 case llvm::Triple::x86:
8823 CmdArgs.push_back("-m");
8824 CmdArgs.push_back("elf_i386");
8826 case llvm::Triple::arm:
8827 case llvm::Triple::thumb:
8828 CmdArgs.push_back("-m");
8829 switch (getToolChain().getTriple().getEnvironment()) {
8830 case llvm::Triple::EABI:
8831 case llvm::Triple::GNUEABI:
8832 CmdArgs.push_back("armelf_nbsd_eabi");
8834 case llvm::Triple::EABIHF:
8835 case llvm::Triple::GNUEABIHF:
8836 CmdArgs.push_back("armelf_nbsd_eabihf");
8839 CmdArgs.push_back("armelf_nbsd");
8843 case llvm::Triple::armeb:
8844 case llvm::Triple::thumbeb:
8845 arm::appendEBLinkFlags(
8847 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8848 CmdArgs.push_back("-m");
8849 switch (getToolChain().getTriple().getEnvironment()) {
8850 case llvm::Triple::EABI:
8851 case llvm::Triple::GNUEABI:
8852 CmdArgs.push_back("armelfb_nbsd_eabi");
8854 case llvm::Triple::EABIHF:
8855 case llvm::Triple::GNUEABIHF:
8856 CmdArgs.push_back("armelfb_nbsd_eabihf");
8859 CmdArgs.push_back("armelfb_nbsd");
8863 case llvm::Triple::mips64:
8864 case llvm::Triple::mips64el:
8865 if (mips::hasMipsAbiArg(Args, "32")) {
8866 CmdArgs.push_back("-m");
8867 if (getToolChain().getArch() == llvm::Triple::mips64)
8868 CmdArgs.push_back("elf32btsmip");
8870 CmdArgs.push_back("elf32ltsmip");
8871 } else if (mips::hasMipsAbiArg(Args, "64")) {
8872 CmdArgs.push_back("-m");
8873 if (getToolChain().getArch() == llvm::Triple::mips64)
8874 CmdArgs.push_back("elf64btsmip");
8876 CmdArgs.push_back("elf64ltsmip");
8879 case llvm::Triple::ppc:
8880 CmdArgs.push_back("-m");
8881 CmdArgs.push_back("elf32ppc_nbsd");
8884 case llvm::Triple::ppc64:
8885 case llvm::Triple::ppc64le:
8886 CmdArgs.push_back("-m");
8887 CmdArgs.push_back("elf64ppc");
8890 case llvm::Triple::sparc:
8891 CmdArgs.push_back("-m");
8892 CmdArgs.push_back("elf32_sparc");
8895 case llvm::Triple::sparcv9:
8896 CmdArgs.push_back("-m");
8897 CmdArgs.push_back("elf64_sparc");
8904 if (Output.isFilename()) {
8905 CmdArgs.push_back("-o");
8906 CmdArgs.push_back(Output.getFilename());
8908 assert(Output.isNothing() && "Invalid output.");
8911 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8912 if (!Args.hasArg(options::OPT_shared)) {
8914 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8917 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8918 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
8920 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8923 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8927 Args.AddAllArgs(CmdArgs, options::OPT_L);
8928 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8929 Args.AddAllArgs(CmdArgs, options::OPT_e);
8930 Args.AddAllArgs(CmdArgs, options::OPT_s);
8931 Args.AddAllArgs(CmdArgs, options::OPT_t);
8932 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8933 Args.AddAllArgs(CmdArgs, options::OPT_r);
8935 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8937 unsigned Major, Minor, Micro;
8938 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8939 bool useLibgcc = true;
8940 if (Major >= 7 || Major == 0) {
8941 switch (getToolChain().getArch()) {
8942 case llvm::Triple::aarch64:
8943 case llvm::Triple::arm:
8944 case llvm::Triple::armeb:
8945 case llvm::Triple::thumb:
8946 case llvm::Triple::thumbeb:
8947 case llvm::Triple::ppc:
8948 case llvm::Triple::ppc64:
8949 case llvm::Triple::ppc64le:
8950 case llvm::Triple::sparc:
8951 case llvm::Triple::sparcv9:
8952 case llvm::Triple::x86:
8953 case llvm::Triple::x86_64:
8961 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8962 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8964 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8965 CmdArgs.push_back("-lm");
8967 if (Args.hasArg(options::OPT_pthread))
8968 CmdArgs.push_back("-lpthread");
8969 CmdArgs.push_back("-lc");
8972 if (Args.hasArg(options::OPT_static)) {
8973 // libgcc_eh depends on libc, so resolve as much as possible,
8974 // pull in any new requirements from libc and then get the rest
8976 CmdArgs.push_back("-lgcc_eh");
8977 CmdArgs.push_back("-lc");
8978 CmdArgs.push_back("-lgcc");
8980 CmdArgs.push_back("-lgcc");
8981 CmdArgs.push_back("--as-needed");
8982 CmdArgs.push_back("-lgcc_s");
8983 CmdArgs.push_back("--no-as-needed");
8988 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8989 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8991 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8994 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8995 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8998 getToolChain().addProfileRTLibs(Args, CmdArgs);
9000 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9001 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9004 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9005 const InputInfo &Output,
9006 const InputInfoList &Inputs,
9007 const ArgList &Args,
9008 const char *LinkingOutput) const {
9009 claimNoWarnArgs(Args);
9011 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9012 llvm::Triple Triple = llvm::Triple(TripleStr);
9014 ArgStringList CmdArgs;
9016 llvm::Reloc::Model RelocationModel;
9019 std::tie(RelocationModel, PICLevel, IsPIE) =
9020 ParsePICArgs(getToolChain(), Triple, Args);
9022 switch (getToolChain().getArch()) {
9025 // Add --32/--64 to make sure we get the format we want.
9026 // This is incomplete
9027 case llvm::Triple::x86:
9028 CmdArgs.push_back("--32");
9030 case llvm::Triple::x86_64:
9031 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
9032 CmdArgs.push_back("--x32");
9034 CmdArgs.push_back("--64");
9036 case llvm::Triple::ppc:
9037 CmdArgs.push_back("-a32");
9038 CmdArgs.push_back("-mppc");
9039 CmdArgs.push_back("-many");
9041 case llvm::Triple::ppc64:
9042 CmdArgs.push_back("-a64");
9043 CmdArgs.push_back("-mppc64");
9044 CmdArgs.push_back("-many");
9046 case llvm::Triple::ppc64le:
9047 CmdArgs.push_back("-a64");
9048 CmdArgs.push_back("-mppc64");
9049 CmdArgs.push_back("-many");
9050 CmdArgs.push_back("-mlittle-endian");
9052 case llvm::Triple::sparc:
9053 case llvm::Triple::sparcel: {
9054 CmdArgs.push_back("-32");
9055 std::string CPU = getCPUName(Args, getToolChain().getTriple());
9056 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9057 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9060 case llvm::Triple::sparcv9: {
9061 CmdArgs.push_back("-64");
9062 std::string CPU = getCPUName(Args, getToolChain().getTriple());
9063 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9064 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9067 case llvm::Triple::arm:
9068 case llvm::Triple::armeb:
9069 case llvm::Triple::thumb:
9070 case llvm::Triple::thumbeb: {
9071 const llvm::Triple &Triple2 = getToolChain().getTriple();
9072 switch (Triple2.getSubArch()) {
9073 case llvm::Triple::ARMSubArch_v7:
9074 CmdArgs.push_back("-mfpu=neon");
9076 case llvm::Triple::ARMSubArch_v8:
9077 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
9083 switch (arm::getARMFloatABI(getToolChain(), Args)) {
9084 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
9085 case arm::FloatABI::Soft:
9086 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
9088 case arm::FloatABI::SoftFP:
9089 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
9091 case arm::FloatABI::Hard:
9092 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
9096 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
9098 // FIXME: remove krait check when GNU tools support krait cpu
9099 // for now replace it with -mcpu=cortex-a15 to avoid a lower
9100 // march from being picked in the absence of a cpu flag.
9102 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
9103 StringRef(A->getValue()).lower() == "krait")
9104 CmdArgs.push_back("-mcpu=cortex-a15");
9106 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
9107 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
9110 case llvm::Triple::mips:
9111 case llvm::Triple::mipsel:
9112 case llvm::Triple::mips64:
9113 case llvm::Triple::mips64el: {
9116 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9117 ABIName = getGnuCompatibleMipsABIName(ABIName);
9119 CmdArgs.push_back("-march");
9120 CmdArgs.push_back(CPUName.data());
9122 CmdArgs.push_back("-mabi");
9123 CmdArgs.push_back(ABIName.data());
9125 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
9126 // or -mshared (not implemented) is in effect.
9127 if (RelocationModel == llvm::Reloc::Static)
9128 CmdArgs.push_back("-mno-shared");
9130 // LLVM doesn't support -mplt yet and acts as if it is always given.
9131 // However, -mplt has no effect with the N64 ABI.
9132 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
9134 if (getToolChain().getArch() == llvm::Triple::mips ||
9135 getToolChain().getArch() == llvm::Triple::mips64)
9136 CmdArgs.push_back("-EB");
9138 CmdArgs.push_back("-EL");
9140 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
9141 if (StringRef(A->getValue()) == "2008")
9142 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
9145 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
9146 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
9147 options::OPT_mfp64)) {
9149 A->render(Args, CmdArgs);
9150 } else if (mips::shouldUseFPXX(
9151 Args, getToolChain().getTriple(), CPUName, ABIName,
9152 getMipsFloatABI(getToolChain().getDriver(), Args)))
9153 CmdArgs.push_back("-mfpxx");
9155 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
9156 // -mno-mips16 is actually -no-mips16.
9158 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
9159 if (A->getOption().matches(options::OPT_mips16)) {
9161 A->render(Args, CmdArgs);
9164 CmdArgs.push_back("-no-mips16");
9168 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
9169 options::OPT_mno_micromips);
9170 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
9171 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
9173 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
9174 // Do not use AddLastArg because not all versions of MIPS assembler
9175 // support -mmsa / -mno-msa options.
9176 if (A->getOption().matches(options::OPT_mmsa))
9177 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
9180 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
9181 options::OPT_msoft_float);
9183 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
9184 options::OPT_msingle_float);
9186 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
9187 options::OPT_mno_odd_spreg);
9189 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9192 case llvm::Triple::systemz: {
9193 // Always pass an -march option, since our default of z10 is later
9194 // than the GNU assembler's default.
9195 StringRef CPUName = getSystemZTargetCPU(Args);
9196 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
9201 Args.AddAllArgs(CmdArgs, options::OPT_I);
9202 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9204 CmdArgs.push_back("-o");
9205 CmdArgs.push_back(Output.getFilename());
9207 for (const auto &II : Inputs)
9208 CmdArgs.push_back(II.getFilename());
9210 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9211 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9213 // Handle the debug info splitting at object creation time if we're
9214 // creating an object.
9215 // TODO: Currently only works on linux with newer objcopy.
9216 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
9217 getToolChain().getTriple().isOSLinux())
9218 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9219 SplitDebugName(Args, Inputs[0]));
9222 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
9223 ArgStringList &CmdArgs, const ArgList &Args) {
9224 bool isAndroid = Triple.isAndroid();
9225 bool isCygMing = Triple.isOSCygMing();
9226 bool IsIAMCU = Triple.isOSIAMCU();
9227 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
9228 Args.hasArg(options::OPT_static);
9230 CmdArgs.push_back("-lgcc");
9232 if (StaticLibgcc || isAndroid) {
9234 CmdArgs.push_back("-lgcc");
9236 if (!D.CCCIsCXX() && !isCygMing)
9237 CmdArgs.push_back("--as-needed");
9238 CmdArgs.push_back("-lgcc_s");
9239 if (!D.CCCIsCXX() && !isCygMing)
9240 CmdArgs.push_back("--no-as-needed");
9243 if (StaticLibgcc && !isAndroid && !IsIAMCU)
9244 CmdArgs.push_back("-lgcc_eh");
9245 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
9246 CmdArgs.push_back("-lgcc");
9248 // According to Android ABI, we have to link with libdl if we are
9249 // linking with non-static libgcc.
9251 // NOTE: This fixes a link error on Android MIPS as well. The non-static
9252 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
9253 if (isAndroid && !StaticLibgcc)
9254 CmdArgs.push_back("-ldl");
9257 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
9258 ArgStringList &CmdArgs, const ArgList &Args) {
9259 // Make use of compiler-rt if --rtlib option is used
9260 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
9263 case ToolChain::RLT_CompilerRT:
9264 switch (TC.getTriple().getOS()) {
9266 llvm_unreachable("unsupported OS");
9267 case llvm::Triple::Win32:
9268 case llvm::Triple::Linux:
9269 addClangRT(TC, Args, CmdArgs);
9273 case ToolChain::RLT_Libgcc:
9274 // Make sure libgcc is not used under MSVC environment by default
9275 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
9276 // Issue error diagnostic if libgcc is explicitly specified
9277 // through command line as --rtlib option argument.
9278 if (Args.hasArg(options::OPT_rtlib_EQ)) {
9279 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
9280 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
9283 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
9288 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
9289 switch (T.getArch()) {
9290 case llvm::Triple::x86:
9294 case llvm::Triple::aarch64:
9295 return "aarch64linux";
9296 case llvm::Triple::aarch64_be:
9297 return "aarch64_be_linux";
9298 case llvm::Triple::arm:
9299 case llvm::Triple::thumb:
9300 return "armelf_linux_eabi";
9301 case llvm::Triple::armeb:
9302 case llvm::Triple::thumbeb:
9303 return "armelfb_linux_eabi";
9304 case llvm::Triple::ppc:
9305 return "elf32ppclinux";
9306 case llvm::Triple::ppc64:
9308 case llvm::Triple::ppc64le:
9310 case llvm::Triple::sparc:
9311 case llvm::Triple::sparcel:
9312 return "elf32_sparc";
9313 case llvm::Triple::sparcv9:
9314 return "elf64_sparc";
9315 case llvm::Triple::mips:
9316 return "elf32btsmip";
9317 case llvm::Triple::mipsel:
9318 return "elf32ltsmip";
9319 case llvm::Triple::mips64:
9320 if (mips::hasMipsAbiArg(Args, "n32"))
9321 return "elf32btsmipn32";
9322 return "elf64btsmip";
9323 case llvm::Triple::mips64el:
9324 if (mips::hasMipsAbiArg(Args, "n32"))
9325 return "elf32ltsmipn32";
9326 return "elf64ltsmip";
9327 case llvm::Triple::systemz:
9328 return "elf64_s390";
9329 case llvm::Triple::x86_64:
9330 if (T.getEnvironment() == llvm::Triple::GNUX32)
9331 return "elf32_x86_64";
9332 return "elf_x86_64";
9334 llvm_unreachable("Unexpected arch");
9338 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9339 const InputInfo &Output,
9340 const InputInfoList &Inputs,
9341 const ArgList &Args,
9342 const char *LinkingOutput) const {
9343 const toolchains::Linux &ToolChain =
9344 static_cast<const toolchains::Linux &>(getToolChain());
9345 const Driver &D = ToolChain.getDriver();
9347 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9348 llvm::Triple Triple = llvm::Triple(TripleStr);
9350 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9351 const bool isAndroid = ToolChain.getTriple().isAndroid();
9352 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
9354 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
9355 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
9356 const bool HasCRTBeginEndFiles =
9357 ToolChain.getTriple().hasEnvironment() ||
9358 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
9360 ArgStringList CmdArgs;
9362 // Silence warning for "clang -g foo.o -o foo"
9363 Args.ClaimAllArgs(options::OPT_g_Group);
9364 // and "clang -emit-llvm foo.o -o foo"
9365 Args.ClaimAllArgs(options::OPT_emit_llvm);
9366 // and for "clang -w foo.o -o foo". Other warning options are already
9367 // handled somewhere else.
9368 Args.ClaimAllArgs(options::OPT_w);
9370 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9371 if (llvm::sys::path::filename(Exec) == "lld") {
9372 CmdArgs.push_back("-flavor");
9373 CmdArgs.push_back("old-gnu");
9374 CmdArgs.push_back("-target");
9375 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
9378 if (!D.SysRoot.empty())
9379 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9382 CmdArgs.push_back("-pie");
9384 if (Args.hasArg(options::OPT_rdynamic))
9385 CmdArgs.push_back("-export-dynamic");
9387 if (Args.hasArg(options::OPT_s))
9388 CmdArgs.push_back("-s");
9390 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
9391 arm::appendEBLinkFlags(Args, CmdArgs, Triple);
9393 for (const auto &Opt : ToolChain.ExtraOpts)
9394 CmdArgs.push_back(Opt.c_str());
9396 if (!Args.hasArg(options::OPT_static)) {
9397 CmdArgs.push_back("--eh-frame-hdr");
9400 CmdArgs.push_back("-m");
9401 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
9403 if (Args.hasArg(options::OPT_static)) {
9404 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
9405 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
9406 CmdArgs.push_back("-Bstatic");
9408 CmdArgs.push_back("-static");
9409 } else if (Args.hasArg(options::OPT_shared)) {
9410 CmdArgs.push_back("-shared");
9413 if (!Args.hasArg(options::OPT_static)) {
9414 if (Args.hasArg(options::OPT_rdynamic))
9415 CmdArgs.push_back("-export-dynamic");
9417 if (!Args.hasArg(options::OPT_shared)) {
9418 const std::string Loader =
9419 D.DyldPrefix + ToolChain.getDynamicLinker(Args);
9420 CmdArgs.push_back("-dynamic-linker");
9421 CmdArgs.push_back(Args.MakeArgString(Loader));
9425 CmdArgs.push_back("-o");
9426 CmdArgs.push_back(Output.getFilename());
9428 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9429 if (!isAndroid && !IsIAMCU) {
9430 const char *crt1 = nullptr;
9431 if (!Args.hasArg(options::OPT_shared)) {
9432 if (Args.hasArg(options::OPT_pg))
9440 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
9442 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9446 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
9448 const char *crtbegin;
9449 if (Args.hasArg(options::OPT_static))
9450 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
9451 else if (Args.hasArg(options::OPT_shared))
9452 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
9454 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
9456 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
9458 if (HasCRTBeginEndFiles)
9459 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9462 // Add crtfastmath.o if available and fast math is enabled.
9463 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9466 Args.AddAllArgs(CmdArgs, options::OPT_L);
9467 Args.AddAllArgs(CmdArgs, options::OPT_u);
9469 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9472 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
9474 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9475 CmdArgs.push_back("--no-demangle");
9477 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
9478 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
9479 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9480 // The profile runtime also needs access to system libraries.
9481 getToolChain().addProfileRTLibs(Args, CmdArgs);
9484 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9485 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9486 !Args.hasArg(options::OPT_static);
9487 if (OnlyLibstdcxxStatic)
9488 CmdArgs.push_back("-Bstatic");
9489 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9490 if (OnlyLibstdcxxStatic)
9491 CmdArgs.push_back("-Bdynamic");
9492 CmdArgs.push_back("-lm");
9494 // Silence warnings when linking C code with a C++ '-stdlib' argument.
9495 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
9497 if (!Args.hasArg(options::OPT_nostdlib)) {
9498 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9499 if (Args.hasArg(options::OPT_static))
9500 CmdArgs.push_back("--start-group");
9502 if (NeedsSanitizerDeps)
9503 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
9506 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
9508 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
9509 Args.hasArg(options::OPT_pthreads);
9511 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9512 options::OPT_fno_openmp, false)) {
9513 // OpenMP runtimes implies pthreads when using the GNU toolchain.
9514 // FIXME: Does this really make sense for all GNU toolchains?
9517 // Also link the particular OpenMP runtimes.
9518 switch (getOpenMPRuntime(ToolChain, Args)) {
9520 CmdArgs.push_back("-lomp");
9523 CmdArgs.push_back("-lgomp");
9525 // FIXME: Exclude this for platforms with libgomp that don't require
9526 // librt. Most modern Linux platforms require it, but some may not.
9527 CmdArgs.push_back("-lrt");
9530 CmdArgs.push_back("-liomp5");
9533 // Already diagnosed.
9538 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9540 if (WantPthread && !isAndroid)
9541 CmdArgs.push_back("-lpthread");
9543 if (Args.hasArg(options::OPT_fsplit_stack))
9544 CmdArgs.push_back("--wrap=pthread_create");
9546 CmdArgs.push_back("-lc");
9548 // Add IAMCU specific libs, if needed.
9550 CmdArgs.push_back("-lgloss");
9552 if (Args.hasArg(options::OPT_static))
9553 CmdArgs.push_back("--end-group");
9555 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9557 // Add IAMCU specific libs (outside the group), if needed.
9559 CmdArgs.push_back("--as-needed");
9560 CmdArgs.push_back("-lsoftfp");
9561 CmdArgs.push_back("--no-as-needed");
9565 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
9567 if (Args.hasArg(options::OPT_shared))
9568 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
9570 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
9572 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
9574 if (HasCRTBeginEndFiles)
9575 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9577 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9581 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9584 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
9585 // for the various SFI requirements like register masking. The assembly tool
9586 // inserts the file containing the macros as an input into all the assembly
9588 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
9589 const InputInfo &Output,
9590 const InputInfoList &Inputs,
9591 const ArgList &Args,
9592 const char *LinkingOutput) const {
9593 const toolchains::NaClToolChain &ToolChain =
9594 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9595 InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9596 "nacl-arm-macros.s");
9597 InputInfoList NewInputs;
9598 NewInputs.push_back(NaClMacros);
9599 NewInputs.append(Inputs.begin(), Inputs.end());
9600 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9604 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9605 // we use static by default, do not yet support sanitizers or LTO, and a few
9606 // others. Eventually we can support more of that and hopefully migrate back
9607 // to gnutools::Linker.
9608 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9609 const InputInfo &Output,
9610 const InputInfoList &Inputs,
9611 const ArgList &Args,
9612 const char *LinkingOutput) const {
9614 const toolchains::NaClToolChain &ToolChain =
9615 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9616 const Driver &D = ToolChain.getDriver();
9617 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9618 const bool IsStatic =
9619 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9621 ArgStringList CmdArgs;
9623 // Silence warning for "clang -g foo.o -o foo"
9624 Args.ClaimAllArgs(options::OPT_g_Group);
9625 // and "clang -emit-llvm foo.o -o foo"
9626 Args.ClaimAllArgs(options::OPT_emit_llvm);
9627 // and for "clang -w foo.o -o foo". Other warning options are already
9628 // handled somewhere else.
9629 Args.ClaimAllArgs(options::OPT_w);
9631 if (!D.SysRoot.empty())
9632 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9634 if (Args.hasArg(options::OPT_rdynamic))
9635 CmdArgs.push_back("-export-dynamic");
9637 if (Args.hasArg(options::OPT_s))
9638 CmdArgs.push_back("-s");
9640 // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9641 // from there is --build-id, which we do want.
9642 CmdArgs.push_back("--build-id");
9645 CmdArgs.push_back("--eh-frame-hdr");
9647 CmdArgs.push_back("-m");
9648 if (Arch == llvm::Triple::x86)
9649 CmdArgs.push_back("elf_i386_nacl");
9650 else if (Arch == llvm::Triple::arm)
9651 CmdArgs.push_back("armelf_nacl");
9652 else if (Arch == llvm::Triple::x86_64)
9653 CmdArgs.push_back("elf_x86_64_nacl");
9654 else if (Arch == llvm::Triple::mipsel)
9655 CmdArgs.push_back("mipselelf_nacl");
9657 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9661 CmdArgs.push_back("-static");
9662 else if (Args.hasArg(options::OPT_shared))
9663 CmdArgs.push_back("-shared");
9665 CmdArgs.push_back("-o");
9666 CmdArgs.push_back(Output.getFilename());
9667 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9668 if (!Args.hasArg(options::OPT_shared))
9669 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9670 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9672 const char *crtbegin;
9674 crtbegin = "crtbeginT.o";
9675 else if (Args.hasArg(options::OPT_shared))
9676 crtbegin = "crtbeginS.o";
9678 crtbegin = "crtbegin.o";
9679 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9682 Args.AddAllArgs(CmdArgs, options::OPT_L);
9683 Args.AddAllArgs(CmdArgs, options::OPT_u);
9685 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9687 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9688 CmdArgs.push_back("--no-demangle");
9690 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9693 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9694 bool OnlyLibstdcxxStatic =
9695 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9696 if (OnlyLibstdcxxStatic)
9697 CmdArgs.push_back("-Bstatic");
9698 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9699 if (OnlyLibstdcxxStatic)
9700 CmdArgs.push_back("-Bdynamic");
9701 CmdArgs.push_back("-lm");
9704 if (!Args.hasArg(options::OPT_nostdlib)) {
9705 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9706 // Always use groups, since it has no effect on dynamic libraries.
9707 CmdArgs.push_back("--start-group");
9708 CmdArgs.push_back("-lc");
9709 // NaCl's libc++ currently requires libpthread, so just always include it
9710 // in the group for C++.
9711 if (Args.hasArg(options::OPT_pthread) ||
9712 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9713 // Gold, used by Mips, handles nested groups differently than ld, and
9714 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9715 // which is not a desired behaviour here.
9716 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9717 if (getToolChain().getArch() == llvm::Triple::mipsel)
9718 CmdArgs.push_back("-lnacl");
9720 CmdArgs.push_back("-lpthread");
9723 CmdArgs.push_back("-lgcc");
9724 CmdArgs.push_back("--as-needed");
9726 CmdArgs.push_back("-lgcc_eh");
9728 CmdArgs.push_back("-lgcc_s");
9729 CmdArgs.push_back("--no-as-needed");
9731 // Mips needs to create and use pnacl_legacy library that contains
9732 // definitions from bitcode/pnaclmm.c and definitions for
9733 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9734 if (getToolChain().getArch() == llvm::Triple::mipsel)
9735 CmdArgs.push_back("-lpnacl_legacy");
9737 CmdArgs.push_back("--end-group");
9740 if (!Args.hasArg(options::OPT_nostartfiles)) {
9742 if (Args.hasArg(options::OPT_shared))
9743 crtend = "crtendS.o";
9745 crtend = "crtend.o";
9747 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9748 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9752 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9753 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9756 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9757 const InputInfo &Output,
9758 const InputInfoList &Inputs,
9759 const ArgList &Args,
9760 const char *LinkingOutput) const {
9761 claimNoWarnArgs(Args);
9762 ArgStringList CmdArgs;
9764 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9766 CmdArgs.push_back("-o");
9767 CmdArgs.push_back(Output.getFilename());
9769 for (const auto &II : Inputs)
9770 CmdArgs.push_back(II.getFilename());
9772 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9773 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9776 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9777 const InputInfo &Output,
9778 const InputInfoList &Inputs,
9779 const ArgList &Args,
9780 const char *LinkingOutput) const {
9781 const Driver &D = getToolChain().getDriver();
9782 ArgStringList CmdArgs;
9784 if (Output.isFilename()) {
9785 CmdArgs.push_back("-o");
9786 CmdArgs.push_back(Output.getFilename());
9788 assert(Output.isNothing() && "Invalid output.");
9791 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9792 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9793 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9795 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9796 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9799 Args.AddAllArgs(CmdArgs,
9800 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9802 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9804 getToolChain().addProfileRTLibs(Args, CmdArgs);
9806 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9808 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9809 CmdArgs.push_back("-lm");
9813 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9814 if (Args.hasArg(options::OPT_pthread))
9815 CmdArgs.push_back("-lpthread");
9816 CmdArgs.push_back("-lc");
9817 CmdArgs.push_back("-lCompilerRT-Generic");
9818 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9820 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9823 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9824 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9829 // For now, DragonFly Assemble does just about the same as for
9830 // FreeBSD, but this may change soon.
9831 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9832 const InputInfo &Output,
9833 const InputInfoList &Inputs,
9834 const ArgList &Args,
9835 const char *LinkingOutput) const {
9836 claimNoWarnArgs(Args);
9837 ArgStringList CmdArgs;
9839 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9840 // instruct as in the base system to assemble 32-bit code.
9841 if (getToolChain().getArch() == llvm::Triple::x86)
9842 CmdArgs.push_back("--32");
9844 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9846 CmdArgs.push_back("-o");
9847 CmdArgs.push_back(Output.getFilename());
9849 for (const auto &II : Inputs)
9850 CmdArgs.push_back(II.getFilename());
9852 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9853 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9856 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9857 const InputInfo &Output,
9858 const InputInfoList &Inputs,
9859 const ArgList &Args,
9860 const char *LinkingOutput) const {
9861 const Driver &D = getToolChain().getDriver();
9862 ArgStringList CmdArgs;
9864 if (!D.SysRoot.empty())
9865 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9867 CmdArgs.push_back("--eh-frame-hdr");
9868 if (Args.hasArg(options::OPT_static)) {
9869 CmdArgs.push_back("-Bstatic");
9871 if (Args.hasArg(options::OPT_rdynamic))
9872 CmdArgs.push_back("-export-dynamic");
9873 if (Args.hasArg(options::OPT_shared))
9874 CmdArgs.push_back("-Bshareable");
9876 CmdArgs.push_back("-dynamic-linker");
9877 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9879 CmdArgs.push_back("--hash-style=gnu");
9880 CmdArgs.push_back("--enable-new-dtags");
9883 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9884 // instruct ld in the base system to link 32-bit code.
9885 if (getToolChain().getArch() == llvm::Triple::x86) {
9886 CmdArgs.push_back("-m");
9887 CmdArgs.push_back("elf_i386");
9890 if (Output.isFilename()) {
9891 CmdArgs.push_back("-o");
9892 CmdArgs.push_back(Output.getFilename());
9894 assert(Output.isNothing() && "Invalid output.");
9897 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9898 if (!Args.hasArg(options::OPT_shared)) {
9899 if (Args.hasArg(options::OPT_pg))
9901 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9903 if (Args.hasArg(options::OPT_pie))
9905 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9908 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9911 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9912 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9914 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9917 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9920 Args.AddAllArgs(CmdArgs,
9921 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9923 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9925 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9926 CmdArgs.push_back("-L/usr/lib/gcc50");
9928 if (!Args.hasArg(options::OPT_static)) {
9929 CmdArgs.push_back("-rpath");
9930 CmdArgs.push_back("/usr/lib/gcc50");
9934 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9935 CmdArgs.push_back("-lm");
9938 if (Args.hasArg(options::OPT_pthread))
9939 CmdArgs.push_back("-lpthread");
9941 if (!Args.hasArg(options::OPT_nolibc)) {
9942 CmdArgs.push_back("-lc");
9945 if (Args.hasArg(options::OPT_static) ||
9946 Args.hasArg(options::OPT_static_libgcc)) {
9947 CmdArgs.push_back("-lgcc");
9948 CmdArgs.push_back("-lgcc_eh");
9950 if (Args.hasArg(options::OPT_shared_libgcc)) {
9951 CmdArgs.push_back("-lgcc_pic");
9952 if (!Args.hasArg(options::OPT_shared))
9953 CmdArgs.push_back("-lgcc");
9955 CmdArgs.push_back("-lgcc");
9956 CmdArgs.push_back("--as-needed");
9957 CmdArgs.push_back("-lgcc_pic");
9958 CmdArgs.push_back("--no-as-needed");
9963 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9964 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9966 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9969 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9970 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9973 getToolChain().addProfileRTLibs(Args, CmdArgs);
9975 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9976 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9979 // Try to find Exe from a Visual Studio distribution. This first tries to find
9980 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9981 // making sure that whatever executable that's found is not a same-named exe
9982 // from clang itself to prevent clang from falling back to itself.
9983 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9985 const char *ClangProgramPath) {
9986 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9987 std::string visualStudioBinDir;
9988 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9989 visualStudioBinDir)) {
9990 SmallString<128> FilePath(visualStudioBinDir);
9991 llvm::sys::path::append(FilePath, Exe);
9992 if (llvm::sys::fs::can_execute(FilePath.c_str()))
9993 return FilePath.str();
9999 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10000 const InputInfo &Output,
10001 const InputInfoList &Inputs,
10002 const ArgList &Args,
10003 const char *LinkingOutput) const {
10004 ArgStringList CmdArgs;
10005 const ToolChain &TC = getToolChain();
10007 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
10008 if (Output.isFilename())
10010 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
10012 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
10013 !C.getDriver().IsCLMode())
10014 CmdArgs.push_back("-defaultlib:libcmt");
10016 if (!llvm::sys::Process::GetEnv("LIB")) {
10017 // If the VC environment hasn't been configured (perhaps because the user
10018 // did not run vcvarsall), try to build a consistent link environment. If
10019 // the environment variable is set however, assume the user knows what
10021 std::string VisualStudioDir;
10022 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
10023 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
10024 SmallString<128> LibDir(VisualStudioDir);
10025 llvm::sys::path::append(LibDir, "VC", "lib");
10026 switch (MSVC.getArch()) {
10027 case llvm::Triple::x86:
10028 // x86 just puts the libraries directly in lib
10030 case llvm::Triple::x86_64:
10031 llvm::sys::path::append(LibDir, "amd64");
10033 case llvm::Triple::arm:
10034 llvm::sys::path::append(LibDir, "arm");
10040 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
10042 if (MSVC.useUniversalCRT(VisualStudioDir)) {
10043 std::string UniversalCRTLibPath;
10044 if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
10045 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10046 UniversalCRTLibPath.c_str()));
10050 std::string WindowsSdkLibPath;
10051 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
10052 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10053 WindowsSdkLibPath.c_str()));
10056 if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
10057 for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
10058 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
10060 CmdArgs.push_back("-nologo");
10062 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
10063 options::OPT__SLASH_Zd))
10064 CmdArgs.push_back("-debug");
10066 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
10067 options::OPT_shared);
10069 CmdArgs.push_back(Args.MakeArgString("-dll"));
10071 SmallString<128> ImplibName(Output.getFilename());
10072 llvm::sys::path::replace_extension(ImplibName, "lib");
10073 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
10076 if (TC.getSanitizerArgs().needsAsanRt()) {
10077 CmdArgs.push_back(Args.MakeArgString("-debug"));
10078 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
10079 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
10080 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10081 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10082 // Make sure the dynamic runtime thunk is not optimized out at link time
10083 // to ensure proper SEH handling.
10084 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
10086 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10088 for (const auto &Lib : {"asan", "asan_cxx"})
10089 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10093 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
10095 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
10096 options::OPT_fno_openmp, false)) {
10097 CmdArgs.push_back("-nodefaultlib:vcomp.lib");
10098 CmdArgs.push_back("-nodefaultlib:vcompd.lib");
10099 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10100 TC.getDriver().Dir + "/../lib"));
10101 switch (getOpenMPRuntime(getToolChain(), Args)) {
10103 CmdArgs.push_back("-defaultlib:libomp.lib");
10106 CmdArgs.push_back("-defaultlib:libiomp5md.lib");
10110 case OMPRT_Unknown:
10111 // Already diagnosed.
10116 // Add compiler-rt lib in case if it was explicitly
10117 // specified as an argument for --rtlib option.
10118 if (!Args.hasArg(options::OPT_nostdlib)) {
10119 AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
10122 // Add filenames, libraries, and other linker inputs.
10123 for (const auto &Input : Inputs) {
10124 if (Input.isFilename()) {
10125 CmdArgs.push_back(Input.getFilename());
10129 const Arg &A = Input.getInputArg();
10131 // Render -l options differently for the MSVC linker.
10132 if (A.getOption().matches(options::OPT_l)) {
10133 StringRef Lib = A.getValue();
10134 const char *LinkLibArg;
10135 if (Lib.endswith(".lib"))
10136 LinkLibArg = Args.MakeArgString(Lib);
10138 LinkLibArg = Args.MakeArgString(Lib + ".lib");
10139 CmdArgs.push_back(LinkLibArg);
10143 // Otherwise, this is some other kind of linker input option like -Wl, -z,
10144 // or -L. Render it, even if MSVC doesn't understand it.
10145 A.renderAsInput(Args, CmdArgs);
10148 TC.addProfileRTLibs(Args, CmdArgs);
10150 // We need to special case some linker paths. In the case of lld, we need to
10151 // translate 'lld' into 'lld-link', and in the case of the regular msvc
10152 // linker, we need to use a special search algorithm.
10153 llvm::SmallString<128> linkPath;
10154 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
10155 if (Linker.equals_lower("lld"))
10156 Linker = "lld-link";
10158 if (Linker.equals_lower("link")) {
10159 // If we're using the MSVC linker, it's not sufficient to just use link
10160 // from the program PATH, because other environments like GnuWin32 install
10161 // their own link.exe which may come first.
10162 linkPath = FindVisualStudioExecutable(TC, "link.exe",
10163 C.getDriver().getClangProgramPath());
10166 llvm::sys::path::replace_extension(linkPath, "exe");
10167 linkPath = TC.GetProgramPath(linkPath.c_str());
10170 const char *Exec = Args.MakeArgString(linkPath);
10171 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10174 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10175 const InputInfo &Output,
10176 const InputInfoList &Inputs,
10177 const ArgList &Args,
10178 const char *LinkingOutput) const {
10179 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
10182 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
10183 Compilation &C, const JobAction &JA, const InputInfo &Output,
10184 const InputInfoList &Inputs, const ArgList &Args,
10185 const char *LinkingOutput) const {
10186 ArgStringList CmdArgs;
10187 CmdArgs.push_back("/nologo");
10188 CmdArgs.push_back("/c"); // Compile only.
10189 CmdArgs.push_back("/W0"); // No warnings.
10191 // The goal is to be able to invoke this tool correctly based on
10192 // any flag accepted by clang-cl.
10194 // These are spelled the same way in clang and cl.exe,.
10195 Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
10197 // Optimization level.
10198 if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
10199 CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
10201 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
10202 if (A->getOption().getID() == options::OPT_O0) {
10203 CmdArgs.push_back("/Od");
10205 CmdArgs.push_back("/Og");
10207 StringRef OptLevel = A->getValue();
10208 if (OptLevel == "s" || OptLevel == "z")
10209 CmdArgs.push_back("/Os");
10211 CmdArgs.push_back("/Ot");
10213 CmdArgs.push_back("/Ob2");
10216 if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
10217 options::OPT_fno_omit_frame_pointer))
10218 CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
10221 if (!Args.hasArg(options::OPT_fwritable_strings))
10222 CmdArgs.push_back("/GF");
10224 // Flags for which clang-cl has an alias.
10225 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
10227 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
10228 /*default=*/false))
10229 CmdArgs.push_back("/GR-");
10231 if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
10232 /*default=*/false))
10233 CmdArgs.push_back("/GS-");
10235 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
10236 options::OPT_fno_function_sections))
10237 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
10240 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
10241 options::OPT_fno_data_sections))
10243 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
10244 if (Args.hasArg(options::OPT_fsyntax_only))
10245 CmdArgs.push_back("/Zs");
10246 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
10247 options::OPT__SLASH_Z7))
10248 CmdArgs.push_back("/Z7");
10250 std::vector<std::string> Includes =
10251 Args.getAllArgValues(options::OPT_include);
10252 for (const auto &Include : Includes)
10253 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
10255 // Flags that can simply be passed through.
10256 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
10257 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
10258 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
10259 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
10260 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
10261 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
10263 // The order of these flags is relevant, so pick the last one.
10264 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
10265 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
10266 A->render(Args, CmdArgs);
10268 // Pass through all unknown arguments so that the fallback command can see
10270 Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
10273 assert(Inputs.size() == 1);
10274 const InputInfo &II = Inputs[0];
10275 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
10276 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
10277 if (II.isFilename())
10278 CmdArgs.push_back(II.getFilename());
10280 II.getInputArg().renderAsInput(Args, CmdArgs);
10282 // Output filename.
10283 assert(Output.getType() == types::TY_Object);
10285 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
10286 CmdArgs.push_back(Fo);
10288 const Driver &D = getToolChain().getDriver();
10289 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
10290 D.getClangProgramPath());
10291 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10296 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10297 const InputInfo &Output,
10298 const InputInfoList &Inputs,
10299 const ArgList &Args,
10300 const char *LinkingOutput) const {
10301 claimNoWarnArgs(Args);
10302 ArgStringList CmdArgs;
10304 if (getToolChain().getArch() == llvm::Triple::x86) {
10305 CmdArgs.push_back("--32");
10306 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
10307 CmdArgs.push_back("--64");
10310 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10312 CmdArgs.push_back("-o");
10313 CmdArgs.push_back(Output.getFilename());
10315 for (const auto &II : Inputs)
10316 CmdArgs.push_back(II.getFilename());
10318 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
10319 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10321 if (Args.hasArg(options::OPT_gsplit_dwarf))
10322 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
10323 SplitDebugName(Args, Inputs[0]));
10326 void MinGW::Linker::AddLibGCC(const ArgList &Args,
10327 ArgStringList &CmdArgs) const {
10328 if (Args.hasArg(options::OPT_mthreads))
10329 CmdArgs.push_back("-lmingwthrd");
10330 CmdArgs.push_back("-lmingw32");
10332 // Make use of compiler-rt if --rtlib option is used
10333 ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
10334 if (RLT == ToolChain::RLT_Libgcc) {
10335 bool Static = Args.hasArg(options::OPT_static_libgcc) ||
10336 Args.hasArg(options::OPT_static);
10337 bool Shared = Args.hasArg(options::OPT_shared);
10338 bool CXX = getToolChain().getDriver().CCCIsCXX();
10340 if (Static || (!CXX && !Shared)) {
10341 CmdArgs.push_back("-lgcc");
10342 CmdArgs.push_back("-lgcc_eh");
10344 CmdArgs.push_back("-lgcc_s");
10345 CmdArgs.push_back("-lgcc");
10348 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
10351 CmdArgs.push_back("-lmoldname");
10352 CmdArgs.push_back("-lmingwex");
10353 CmdArgs.push_back("-lmsvcrt");
10356 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10357 const InputInfo &Output,
10358 const InputInfoList &Inputs,
10359 const ArgList &Args,
10360 const char *LinkingOutput) const {
10361 const ToolChain &TC = getToolChain();
10362 const Driver &D = TC.getDriver();
10363 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
10365 ArgStringList CmdArgs;
10367 // Silence warning for "clang -g foo.o -o foo"
10368 Args.ClaimAllArgs(options::OPT_g_Group);
10369 // and "clang -emit-llvm foo.o -o foo"
10370 Args.ClaimAllArgs(options::OPT_emit_llvm);
10371 // and for "clang -w foo.o -o foo". Other warning options are already
10372 // handled somewhere else.
10373 Args.ClaimAllArgs(options::OPT_w);
10375 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
10376 if (LinkerName.equals_lower("lld")) {
10377 CmdArgs.push_back("-flavor");
10378 CmdArgs.push_back("gnu");
10379 } else if (!LinkerName.equals_lower("ld")) {
10380 D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
10383 if (!D.SysRoot.empty())
10384 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10386 if (Args.hasArg(options::OPT_s))
10387 CmdArgs.push_back("-s");
10389 CmdArgs.push_back("-m");
10390 if (TC.getArch() == llvm::Triple::x86)
10391 CmdArgs.push_back("i386pe");
10392 if (TC.getArch() == llvm::Triple::x86_64)
10393 CmdArgs.push_back("i386pep");
10394 if (TC.getArch() == llvm::Triple::arm)
10395 CmdArgs.push_back("thumb2pe");
10397 if (Args.hasArg(options::OPT_mwindows)) {
10398 CmdArgs.push_back("--subsystem");
10399 CmdArgs.push_back("windows");
10400 } else if (Args.hasArg(options::OPT_mconsole)) {
10401 CmdArgs.push_back("--subsystem");
10402 CmdArgs.push_back("console");
10405 if (Args.hasArg(options::OPT_static))
10406 CmdArgs.push_back("-Bstatic");
10408 if (Args.hasArg(options::OPT_mdll))
10409 CmdArgs.push_back("--dll");
10410 else if (Args.hasArg(options::OPT_shared))
10411 CmdArgs.push_back("--shared");
10412 CmdArgs.push_back("-Bdynamic");
10413 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
10414 CmdArgs.push_back("-e");
10415 if (TC.getArch() == llvm::Triple::x86)
10416 CmdArgs.push_back("_DllMainCRTStartup@12");
10418 CmdArgs.push_back("DllMainCRTStartup");
10419 CmdArgs.push_back("--enable-auto-image-base");
10423 CmdArgs.push_back("-o");
10424 CmdArgs.push_back(Output.getFilename());
10426 Args.AddAllArgs(CmdArgs, options::OPT_e);
10427 // FIXME: add -N, -n flags
10428 Args.AddLastArg(CmdArgs, options::OPT_r);
10429 Args.AddLastArg(CmdArgs, options::OPT_s);
10430 Args.AddLastArg(CmdArgs, options::OPT_t);
10431 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
10432 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
10434 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10435 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
10436 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
10438 if (Args.hasArg(options::OPT_municode))
10439 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
10441 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
10443 if (Args.hasArg(options::OPT_pg))
10444 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
10445 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10448 Args.AddAllArgs(CmdArgs, options::OPT_L);
10449 TC.AddFilePathLibArgs(Args, CmdArgs);
10450 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10452 // TODO: Add ASan stuff here
10454 // TODO: Add profile stuff here
10456 if (D.CCCIsCXX() &&
10457 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10458 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
10459 !Args.hasArg(options::OPT_static);
10460 if (OnlyLibstdcxxStatic)
10461 CmdArgs.push_back("-Bstatic");
10462 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10463 if (OnlyLibstdcxxStatic)
10464 CmdArgs.push_back("-Bdynamic");
10467 if (!Args.hasArg(options::OPT_nostdlib)) {
10468 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10469 if (Args.hasArg(options::OPT_static))
10470 CmdArgs.push_back("--start-group");
10472 if (Args.hasArg(options::OPT_fstack_protector) ||
10473 Args.hasArg(options::OPT_fstack_protector_strong) ||
10474 Args.hasArg(options::OPT_fstack_protector_all)) {
10475 CmdArgs.push_back("-lssp_nonshared");
10476 CmdArgs.push_back("-lssp");
10478 if (Args.hasArg(options::OPT_fopenmp))
10479 CmdArgs.push_back("-lgomp");
10481 AddLibGCC(Args, CmdArgs);
10483 if (Args.hasArg(options::OPT_pg))
10484 CmdArgs.push_back("-lgmon");
10486 if (Args.hasArg(options::OPT_pthread))
10487 CmdArgs.push_back("-lpthread");
10489 // add system libraries
10490 if (Args.hasArg(options::OPT_mwindows)) {
10491 CmdArgs.push_back("-lgdi32");
10492 CmdArgs.push_back("-lcomdlg32");
10494 CmdArgs.push_back("-ladvapi32");
10495 CmdArgs.push_back("-lshell32");
10496 CmdArgs.push_back("-luser32");
10497 CmdArgs.push_back("-lkernel32");
10499 if (Args.hasArg(options::OPT_static))
10500 CmdArgs.push_back("--end-group");
10501 else if (!LinkerName.equals_lower("lld"))
10502 AddLibGCC(Args, CmdArgs);
10505 if (!Args.hasArg(options::OPT_nostartfiles)) {
10506 // Add crtfastmath.o if available and fast math is enabled.
10507 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
10509 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10512 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
10513 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10517 // We pass assemble and link construction to the xcc tool.
10519 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10520 const InputInfo &Output,
10521 const InputInfoList &Inputs,
10522 const ArgList &Args,
10523 const char *LinkingOutput) const {
10524 claimNoWarnArgs(Args);
10525 ArgStringList CmdArgs;
10527 CmdArgs.push_back("-o");
10528 CmdArgs.push_back(Output.getFilename());
10530 CmdArgs.push_back("-c");
10532 if (Args.hasArg(options::OPT_v))
10533 CmdArgs.push_back("-v");
10535 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
10536 if (!A->getOption().matches(options::OPT_g0))
10537 CmdArgs.push_back("-g");
10539 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
10541 CmdArgs.push_back("-fverbose-asm");
10543 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10545 for (const auto &II : Inputs)
10546 CmdArgs.push_back(II.getFilename());
10548 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10549 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10552 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10553 const InputInfo &Output,
10554 const InputInfoList &Inputs,
10555 const ArgList &Args,
10556 const char *LinkingOutput) const {
10557 ArgStringList CmdArgs;
10559 if (Output.isFilename()) {
10560 CmdArgs.push_back("-o");
10561 CmdArgs.push_back(Output.getFilename());
10563 assert(Output.isNothing() && "Invalid output.");
10566 if (Args.hasArg(options::OPT_v))
10567 CmdArgs.push_back("-v");
10569 // Pass -fexceptions through to the linker if it was present.
10570 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
10572 CmdArgs.push_back("-fexceptions");
10574 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10576 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10577 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10580 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10581 const InputInfo &Output,
10582 const InputInfoList &Inputs,
10583 const ArgList &Args,
10584 const char *LinkingOutput) const {
10585 claimNoWarnArgs(Args);
10587 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10588 ArgStringList CmdArgs;
10591 switch (TC.getArch()) {
10593 llvm_unreachable("unsupported architecture");
10594 case llvm::Triple::arm:
10595 case llvm::Triple::thumb:
10597 case llvm::Triple::x86:
10598 CmdArgs.push_back("--32");
10600 case llvm::Triple::x86_64:
10601 CmdArgs.push_back("--64");
10605 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10607 CmdArgs.push_back("-o");
10608 CmdArgs.push_back(Output.getFilename());
10610 for (const auto &Input : Inputs)
10611 CmdArgs.push_back(Input.getFilename());
10613 const std::string Assembler = TC.GetProgramPath("as");
10614 Exec = Args.MakeArgString(Assembler);
10616 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10619 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10620 const InputInfo &Output,
10621 const InputInfoList &Inputs,
10622 const ArgList &Args,
10623 const char *LinkingOutput) const {
10625 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10626 const llvm::Triple &T = TC.getTriple();
10627 const Driver &D = TC.getDriver();
10628 SmallString<128> EntryPoint;
10629 ArgStringList CmdArgs;
10632 // Silence warning for "clang -g foo.o -o foo"
10633 Args.ClaimAllArgs(options::OPT_g_Group);
10634 // and "clang -emit-llvm foo.o -o foo"
10635 Args.ClaimAllArgs(options::OPT_emit_llvm);
10636 // and for "clang -w foo.o -o foo"
10637 Args.ClaimAllArgs(options::OPT_w);
10638 // Other warning options are already handled somewhere else.
10640 if (!D.SysRoot.empty())
10641 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10643 if (Args.hasArg(options::OPT_pie))
10644 CmdArgs.push_back("-pie");
10645 if (Args.hasArg(options::OPT_rdynamic))
10646 CmdArgs.push_back("-export-dynamic");
10647 if (Args.hasArg(options::OPT_s))
10648 CmdArgs.push_back("--strip-all");
10650 CmdArgs.push_back("-m");
10651 switch (TC.getArch()) {
10653 llvm_unreachable("unsupported architecture");
10654 case llvm::Triple::arm:
10655 case llvm::Triple::thumb:
10656 // FIXME: this is incorrect for WinCE
10657 CmdArgs.push_back("thumb2pe");
10659 case llvm::Triple::x86:
10660 CmdArgs.push_back("i386pe");
10661 EntryPoint.append("_");
10663 case llvm::Triple::x86_64:
10664 CmdArgs.push_back("i386pep");
10668 if (Args.hasArg(options::OPT_shared)) {
10669 switch (T.getArch()) {
10671 llvm_unreachable("unsupported architecture");
10672 case llvm::Triple::arm:
10673 case llvm::Triple::thumb:
10674 case llvm::Triple::x86_64:
10675 EntryPoint.append("_DllMainCRTStartup");
10677 case llvm::Triple::x86:
10678 EntryPoint.append("_DllMainCRTStartup@12");
10682 CmdArgs.push_back("-shared");
10683 CmdArgs.push_back("-Bdynamic");
10685 CmdArgs.push_back("--enable-auto-image-base");
10687 CmdArgs.push_back("--entry");
10688 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10690 EntryPoint.append("mainCRTStartup");
10692 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10695 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10696 CmdArgs.push_back("--entry");
10697 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10700 // FIXME: handle subsystem
10703 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10704 CmdArgs.push_back("--allow-multiple-definition");
10706 CmdArgs.push_back("-o");
10707 CmdArgs.push_back(Output.getFilename());
10709 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10710 SmallString<261> ImpLib(Output.getFilename());
10711 llvm::sys::path::replace_extension(ImpLib, ".lib");
10713 CmdArgs.push_back("--out-implib");
10714 CmdArgs.push_back(Args.MakeArgString(ImpLib));
10717 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10718 const std::string CRTPath(D.SysRoot + "/usr/lib/");
10719 const char *CRTBegin;
10722 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10723 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10726 Args.AddAllArgs(CmdArgs, options::OPT_L);
10727 TC.AddFilePathLibArgs(Args, CmdArgs);
10728 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10730 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10731 !Args.hasArg(options::OPT_nodefaultlibs)) {
10732 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10733 !Args.hasArg(options::OPT_static);
10735 CmdArgs.push_back("-Bstatic");
10736 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10738 CmdArgs.push_back("-Bdynamic");
10741 if (!Args.hasArg(options::OPT_nostdlib)) {
10742 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10743 // TODO handle /MT[d] /MD[d]
10744 CmdArgs.push_back("-lmsvcrt");
10745 AddRunTimeLibs(TC, D, CmdArgs, Args);
10749 if (TC.getSanitizerArgs().needsAsanRt()) {
10750 // TODO handle /MT[d] /MD[d]
10751 if (Args.hasArg(options::OPT_shared)) {
10752 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10754 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10755 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10756 // Make sure the dynamic runtime thunk is not optimized out at link time
10757 // to ensure proper SEH handling.
10758 CmdArgs.push_back(Args.MakeArgString("--undefined"));
10759 CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10760 ? "___asan_seh_interceptor"
10761 : "__asan_seh_interceptor"));
10765 Exec = Args.MakeArgString(TC.GetLinkerPath());
10767 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10770 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10771 const InputInfo &Output,
10772 const InputInfoList &Inputs,
10773 const ArgList &Args,
10774 const char *LinkingOutput) const {
10775 ArgStringList CmdArgs;
10776 assert(Inputs.size() == 1);
10777 const InputInfo &II = Inputs[0];
10778 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10779 II.getType() == types::TY_PP_CXX);
10781 if (JA.getKind() == Action::PreprocessJobClass) {
10782 Args.ClaimAllArgs();
10783 CmdArgs.push_back("-E");
10785 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10786 CmdArgs.push_back("-S");
10787 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10789 CmdArgs.push_back("-DMYRIAD2");
10791 // Append all -I, -iquote, -isystem paths, defines/undefines,
10792 // 'f' flags, optimize flags, and warning options.
10793 // These are spelled the same way in clang and moviCompile.
10794 Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10795 options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10796 options::OPT_f_Group, options::OPT_f_clang_Group,
10797 options::OPT_g_Group, options::OPT_M_Group,
10798 options::OPT_O_Group, options::OPT_W_Group,
10799 options::OPT_mcpu_EQ});
10801 // If we're producing a dependency file, and assembly is the final action,
10802 // then the name of the target in the dependency file should be the '.o'
10803 // file, not the '.s' file produced by this step. For example, instead of
10804 // /tmp/mumble.s: mumble.c .../someheader.h
10805 // the filename on the lefthand side should be "mumble.o"
10806 if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10807 C.getActions().size() == 1 &&
10808 C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10809 Arg *A = Args.getLastArg(options::OPT_o);
10811 CmdArgs.push_back("-MT");
10812 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10816 CmdArgs.push_back(II.getFilename());
10817 CmdArgs.push_back("-o");
10818 CmdArgs.push_back(Output.getFilename());
10821 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10822 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10826 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10827 const InputInfo &Output,
10828 const InputInfoList &Inputs,
10829 const ArgList &Args,
10830 const char *LinkingOutput) const {
10831 ArgStringList CmdArgs;
10833 assert(Inputs.size() == 1);
10834 const InputInfo &II = Inputs[0];
10835 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10836 assert(Output.getType() == types::TY_Object);
10838 CmdArgs.push_back("-no6thSlotCompression");
10839 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
10842 Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
10843 CmdArgs.push_back("-noSPrefixing");
10844 CmdArgs.push_back("-a"); // Mystery option.
10845 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10846 for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10849 Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10851 CmdArgs.push_back("-elf"); // Output format.
10852 CmdArgs.push_back(II.getFilename());
10854 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10857 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10858 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10862 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10863 const InputInfo &Output,
10864 const InputInfoList &Inputs,
10865 const ArgList &Args,
10866 const char *LinkingOutput) const {
10868 static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10869 const llvm::Triple &T = TC.getTriple();
10870 ArgStringList CmdArgs;
10871 bool UseStartfiles =
10872 !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10873 bool UseDefaultLibs =
10874 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10876 if (T.getArch() == llvm::Triple::sparc)
10877 CmdArgs.push_back("-EB");
10878 else // SHAVE assumes little-endian, and sparcel is expressly so.
10879 CmdArgs.push_back("-EL");
10881 // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10882 // but we never pass through a --sysroot option and various other bits.
10883 // For example, there are no sanitizers (yet) nor gold linker.
10885 // Eat some arguments that may be present but have no effect.
10886 Args.ClaimAllArgs(options::OPT_g_Group);
10887 Args.ClaimAllArgs(options::OPT_w);
10888 Args.ClaimAllArgs(options::OPT_static_libgcc);
10890 if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10891 CmdArgs.push_back("-s");
10893 CmdArgs.push_back("-o");
10894 CmdArgs.push_back(Output.getFilename());
10896 if (UseStartfiles) {
10897 // If you want startfiles, it means you want the builtin crti and crtbegin,
10898 // but not crt0. Myriad link commands provide their own crt0.o as needed.
10899 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10900 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10903 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10904 options::OPT_e, options::OPT_s, options::OPT_t,
10905 options::OPT_Z_Flag, options::OPT_r});
10907 TC.AddFilePathLibArgs(Args, CmdArgs);
10909 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10911 if (UseDefaultLibs) {
10912 if (C.getDriver().CCCIsCXX())
10913 CmdArgs.push_back("-lstdc++");
10914 if (T.getOS() == llvm::Triple::RTEMS) {
10915 CmdArgs.push_back("--start-group");
10916 CmdArgs.push_back("-lc");
10917 // You must provide your own "-L" option to enable finding these.
10918 CmdArgs.push_back("-lrtemscpu");
10919 CmdArgs.push_back("-lrtemsbsp");
10920 CmdArgs.push_back("--end-group");
10922 CmdArgs.push_back("-lc");
10924 CmdArgs.push_back("-lgcc");
10926 if (UseStartfiles) {
10927 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10928 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10932 Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10933 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10937 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10938 const InputInfo &Output,
10939 const InputInfoList &Inputs,
10940 const ArgList &Args,
10941 const char *LinkingOutput) const {
10942 claimNoWarnArgs(Args);
10943 ArgStringList CmdArgs;
10945 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10947 CmdArgs.push_back("-o");
10948 CmdArgs.push_back(Output.getFilename());
10950 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10951 const InputInfo &Input = Inputs[0];
10952 assert(Input.isFilename() && "Invalid input.");
10953 CmdArgs.push_back(Input.getFilename());
10956 Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
10957 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10960 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10961 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10962 if (SanArgs.needsUbsanRt()) {
10963 CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10965 if (SanArgs.needsAsanRt()) {
10966 CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10970 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10971 const JobAction &JA, const InputInfo &Output,
10972 const InputInfoList &Inputs,
10973 const ArgList &Args,
10974 const char *LinkingOutput) {
10975 const toolchains::FreeBSD &ToolChain =
10976 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10977 const Driver &D = ToolChain.getDriver();
10978 ArgStringList CmdArgs;
10980 // Silence warning for "clang -g foo.o -o foo"
10981 Args.ClaimAllArgs(options::OPT_g_Group);
10982 // and "clang -emit-llvm foo.o -o foo"
10983 Args.ClaimAllArgs(options::OPT_emit_llvm);
10984 // and for "clang -w foo.o -o foo". Other warning options are already
10985 // handled somewhere else.
10986 Args.ClaimAllArgs(options::OPT_w);
10988 if (!D.SysRoot.empty())
10989 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10991 if (Args.hasArg(options::OPT_pie))
10992 CmdArgs.push_back("-pie");
10994 if (Args.hasArg(options::OPT_rdynamic))
10995 CmdArgs.push_back("-export-dynamic");
10996 if (Args.hasArg(options::OPT_shared))
10997 CmdArgs.push_back("--oformat=so");
10999 if (Output.isFilename()) {
11000 CmdArgs.push_back("-o");
11001 CmdArgs.push_back(Output.getFilename());
11003 assert(Output.isNothing() && "Invalid output.");
11006 AddPS4SanitizerArgs(ToolChain, CmdArgs);
11008 Args.AddAllArgs(CmdArgs, options::OPT_L);
11009 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11010 Args.AddAllArgs(CmdArgs, options::OPT_e);
11011 Args.AddAllArgs(CmdArgs, options::OPT_s);
11012 Args.AddAllArgs(CmdArgs, options::OPT_t);
11013 Args.AddAllArgs(CmdArgs, options::OPT_r);
11015 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11016 CmdArgs.push_back("--no-demangle");
11018 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11020 if (Args.hasArg(options::OPT_pthread)) {
11021 CmdArgs.push_back("-lpthread");
11024 const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11026 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11029 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
11030 const JobAction &JA, const InputInfo &Output,
11031 const InputInfoList &Inputs,
11032 const ArgList &Args,
11033 const char *LinkingOutput) {
11034 const toolchains::FreeBSD &ToolChain =
11035 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
11036 const Driver &D = ToolChain.getDriver();
11037 ArgStringList CmdArgs;
11039 // Silence warning for "clang -g foo.o -o foo"
11040 Args.ClaimAllArgs(options::OPT_g_Group);
11041 // and "clang -emit-llvm foo.o -o foo"
11042 Args.ClaimAllArgs(options::OPT_emit_llvm);
11043 // and for "clang -w foo.o -o foo". Other warning options are already
11044 // handled somewhere else.
11045 Args.ClaimAllArgs(options::OPT_w);
11047 if (!D.SysRoot.empty())
11048 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11050 if (Args.hasArg(options::OPT_pie))
11051 CmdArgs.push_back("-pie");
11053 if (Args.hasArg(options::OPT_static)) {
11054 CmdArgs.push_back("-Bstatic");
11056 if (Args.hasArg(options::OPT_rdynamic))
11057 CmdArgs.push_back("-export-dynamic");
11058 CmdArgs.push_back("--eh-frame-hdr");
11059 if (Args.hasArg(options::OPT_shared)) {
11060 CmdArgs.push_back("-Bshareable");
11062 CmdArgs.push_back("-dynamic-linker");
11063 CmdArgs.push_back("/libexec/ld-elf.so.1");
11065 CmdArgs.push_back("--enable-new-dtags");
11068 if (Output.isFilename()) {
11069 CmdArgs.push_back("-o");
11070 CmdArgs.push_back(Output.getFilename());
11072 assert(Output.isNothing() && "Invalid output.");
11075 AddPS4SanitizerArgs(ToolChain, CmdArgs);
11077 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11078 const char *crt1 = nullptr;
11079 if (!Args.hasArg(options::OPT_shared)) {
11080 if (Args.hasArg(options::OPT_pg))
11082 else if (Args.hasArg(options::OPT_pie))
11088 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
11090 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
11092 const char *crtbegin = nullptr;
11093 if (Args.hasArg(options::OPT_static))
11094 crtbegin = "crtbeginT.o";
11095 else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11096 crtbegin = "crtbeginS.o";
11098 crtbegin = "crtbegin.o";
11100 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
11103 Args.AddAllArgs(CmdArgs, options::OPT_L);
11104 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
11105 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11106 Args.AddAllArgs(CmdArgs, options::OPT_e);
11107 Args.AddAllArgs(CmdArgs, options::OPT_s);
11108 Args.AddAllArgs(CmdArgs, options::OPT_t);
11109 Args.AddAllArgs(CmdArgs, options::OPT_r);
11111 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11112 CmdArgs.push_back("--no-demangle");
11114 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11116 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
11117 // For PS4, we always want to pass libm, libstdc++ and libkernel
11118 // libraries for both C and C++ compilations.
11119 CmdArgs.push_back("-lkernel");
11120 if (D.CCCIsCXX()) {
11121 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
11122 if (Args.hasArg(options::OPT_pg))
11123 CmdArgs.push_back("-lm_p");
11125 CmdArgs.push_back("-lm");
11127 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
11128 // the default system libraries. Just mimic this for now.
11129 if (Args.hasArg(options::OPT_pg))
11130 CmdArgs.push_back("-lgcc_p");
11132 CmdArgs.push_back("-lcompiler_rt");
11133 if (Args.hasArg(options::OPT_static)) {
11134 CmdArgs.push_back("-lstdc++");
11135 } else if (Args.hasArg(options::OPT_pg)) {
11136 CmdArgs.push_back("-lgcc_eh_p");
11138 CmdArgs.push_back("--as-needed");
11139 CmdArgs.push_back("-lstdc++");
11140 CmdArgs.push_back("--no-as-needed");
11143 if (Args.hasArg(options::OPT_pthread)) {
11144 if (Args.hasArg(options::OPT_pg))
11145 CmdArgs.push_back("-lpthread_p");
11147 CmdArgs.push_back("-lpthread");
11150 if (Args.hasArg(options::OPT_pg)) {
11151 if (Args.hasArg(options::OPT_shared))
11152 CmdArgs.push_back("-lc");
11154 if (Args.hasArg(options::OPT_static)) {
11155 CmdArgs.push_back("--start-group");
11156 CmdArgs.push_back("-lc_p");
11157 CmdArgs.push_back("-lpthread_p");
11158 CmdArgs.push_back("--end-group");
11160 CmdArgs.push_back("-lc_p");
11163 CmdArgs.push_back("-lgcc_p");
11165 if (Args.hasArg(options::OPT_static)) {
11166 CmdArgs.push_back("--start-group");
11167 CmdArgs.push_back("-lc");
11168 CmdArgs.push_back("-lpthread");
11169 CmdArgs.push_back("--end-group");
11171 CmdArgs.push_back("-lc");
11173 CmdArgs.push_back("-lcompiler_rt");
11176 if (Args.hasArg(options::OPT_static)) {
11177 CmdArgs.push_back("-lstdc++");
11178 } else if (Args.hasArg(options::OPT_pg)) {
11179 CmdArgs.push_back("-lgcc_eh_p");
11181 CmdArgs.push_back("--as-needed");
11182 CmdArgs.push_back("-lstdc++");
11183 CmdArgs.push_back("--no-as-needed");
11187 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11188 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11189 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
11191 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
11192 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
11196 #ifdef LLVM_ON_WIN32
11197 Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
11199 Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11202 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11205 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
11206 const InputInfo &Output,
11207 const InputInfoList &Inputs,
11208 const ArgList &Args,
11209 const char *LinkingOutput) const {
11210 const toolchains::FreeBSD &ToolChain =
11211 static_cast<const toolchains::FreeBSD &>(getToolChain());
11212 const Driver &D = ToolChain.getDriver();
11214 StringRef LinkerOptName;
11215 if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
11216 LinkerOptName = A->getValue();
11217 if (LinkerOptName != "ps4" && LinkerOptName != "gold")
11218 D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
11221 if (LinkerOptName == "gold")
11223 else if (LinkerOptName == "ps4")
11226 PS4Linker = !Args.hasArg(options::OPT_shared);
11229 ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11231 ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11234 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11235 const InputInfo &Output,
11236 const InputInfoList &Inputs,
11237 const ArgList &Args,
11238 const char *LinkingOutput) const {
11240 static_cast<const toolchains::CudaToolChain &>(getToolChain());
11241 assert(TC.getTriple().isNVPTX() && "Wrong platform");
11243 // Obtain architecture from the action.
11244 CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch());
11245 assert(gpu_arch != CudaArch::UNKNOWN &&
11246 "Device action expected to have an architecture.");
11248 // Check that our installation's ptxas supports gpu_arch.
11249 if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
11250 TC.cudaInstallation().CheckCudaVersionSupportsArch(gpu_arch);
11253 ArgStringList CmdArgs;
11254 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
11255 if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
11256 options::OPT_no_cuda_noopt_device_debug, false)) {
11257 // ptxas does not accept -g option if optimization is enabled, so
11258 // we ignore the compiler's -O* options if we want debug info.
11259 CmdArgs.push_back("-g");
11260 CmdArgs.push_back("--dont-merge-basicblocks");
11261 CmdArgs.push_back("--return-at-end");
11262 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
11263 // Map the -O we received to -O{0,1,2,3}.
11265 // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
11266 // default, so it may correspond more closely to the spirit of clang -O2.
11268 // -O3 seems like the least-bad option when -Osomething is specified to
11269 // clang but it isn't handled below.
11270 StringRef OOpt = "3";
11271 if (A->getOption().matches(options::OPT_O4) ||
11272 A->getOption().matches(options::OPT_Ofast))
11274 else if (A->getOption().matches(options::OPT_O0))
11276 else if (A->getOption().matches(options::OPT_O)) {
11277 // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
11278 OOpt = llvm::StringSwitch<const char *>(A->getValue())
11286 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
11288 // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
11289 // to no optimizations, but ptxas's default is -O3.
11290 CmdArgs.push_back("-O0");
11293 CmdArgs.push_back("--gpu-name");
11294 CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
11295 CmdArgs.push_back("--output-file");
11296 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11297 for (const auto& II : Inputs)
11298 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
11300 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
11301 CmdArgs.push_back(Args.MakeArgString(A));
11303 const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
11304 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11307 // All inputs to this linker must be from CudaDeviceActions, as we need to look
11308 // at the Inputs' Actions in order to figure out which GPU architecture they
11310 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11311 const InputInfo &Output,
11312 const InputInfoList &Inputs,
11313 const ArgList &Args,
11314 const char *LinkingOutput) const {
11316 static_cast<const toolchains::CudaToolChain &>(getToolChain());
11317 assert(TC.getTriple().isNVPTX() && "Wrong platform");
11319 ArgStringList CmdArgs;
11320 CmdArgs.push_back("--cuda");
11321 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
11322 CmdArgs.push_back(Args.MakeArgString("--create"));
11323 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11325 for (const auto& II : Inputs) {
11326 auto *A = II.getAction();
11327 assert(A->getInputs().size() == 1 &&
11328 "Device offload action is expected to have a single input");
11329 const char *gpu_arch_str = A->getOffloadingArch();
11330 assert(gpu_arch_str &&
11331 "Device action expected to have associated a GPU architecture!");
11332 CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
11334 // We need to pass an Arch of the form "sm_XX" for cubin files and
11335 // "compute_XX" for ptx.
11337 (II.getType() == types::TY_PP_Asm)
11338 ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
11340 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
11341 Arch + ",file=" + II.getFilename()));
11344 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
11345 CmdArgs.push_back(Args.MakeArgString(A));
11347 const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
11348 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));