1 //===--- Tools.cpp - Tools Implementations --------------------------------===//
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/TargetParser.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"
46 #include <unistd.h> // For getuid().
49 using namespace clang::driver;
50 using namespace clang::driver::tools;
51 using namespace clang;
52 using namespace llvm::opt;
54 static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
55 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
56 options::OPT_fpic, options::OPT_fno_pic,
57 options::OPT_fPIE, options::OPT_fno_PIE,
58 options::OPT_fpie, options::OPT_fno_pie);
61 if (LastPICArg->getOption().matches(options::OPT_fPIC) ||
62 LastPICArg->getOption().matches(options::OPT_fpic) ||
63 LastPICArg->getOption().matches(options::OPT_fPIE) ||
64 LastPICArg->getOption().matches(options::OPT_fpie)) {
65 CmdArgs.push_back("-KPIC");
69 /// CheckPreprocessingOptions - Perform some validation of preprocessing
70 /// arguments that is shared with gcc.
71 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
72 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
73 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
74 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
75 D.Diag(diag::err_drv_argument_only_allowed_with)
76 << A->getBaseArg().getAsString(Args)
77 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
82 /// CheckCodeGenerationOptions - Perform some validation of code generation
83 /// arguments that is shared with gcc.
84 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
85 // In gcc, only ARM checks this, but it seems reasonable to check universally.
86 if (Args.hasArg(options::OPT_static))
88 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
89 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
93 // Add backslashes to escape spaces and other backslashes.
94 // This is used for the space-separated argument list specified with
95 // the -dwarf-debug-flags option.
96 static void EscapeSpacesAndBackslashes(const char *Arg,
97 SmallVectorImpl<char> &Res) {
111 // Quote target names for inclusion in GNU Make dependency files.
112 // Only the characters '$', '#', ' ', '\t' are quoted.
113 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
114 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
118 // Escape the preceding backslashes
119 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
122 // Escape the space/tab
135 Res.push_back(Target[i]);
139 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
140 const char *ArgName, const char *EnvVar) {
141 const char *DirList = ::getenv(EnvVar);
142 bool CombinedArg = false;
145 return; // Nothing to do.
147 StringRef Name(ArgName);
148 if (Name.equals("-I") || Name.equals("-L"))
151 StringRef Dirs(DirList);
152 if (Dirs.empty()) // Empty string should not add '.'.
155 StringRef::size_type Delim;
156 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
157 if (Delim == 0) { // Leading colon.
159 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
161 CmdArgs.push_back(ArgName);
162 CmdArgs.push_back(".");
167 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
169 CmdArgs.push_back(ArgName);
170 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
173 Dirs = Dirs.substr(Delim + 1);
176 if (Dirs.empty()) { // Trailing colon.
178 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
180 CmdArgs.push_back(ArgName);
181 CmdArgs.push_back(".");
183 } else { // Add the last path.
185 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
187 CmdArgs.push_back(ArgName);
188 CmdArgs.push_back(Args.MakeArgString(Dirs));
193 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
194 const ArgList &Args, ArgStringList &CmdArgs) {
195 const Driver &D = TC.getDriver();
197 // Add extra linker input arguments which are not treated as inputs
198 // (constructed via -Xarch_).
199 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
201 for (const auto &II : Inputs) {
202 if (!TC.HasNativeLLVMSupport()) {
203 // Don't try to pass LLVM inputs unless we have native support.
204 if (II.getType() == types::TY_LLVM_IR ||
205 II.getType() == types::TY_LTO_IR ||
206 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
207 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
210 // Add filenames immediately.
211 if (II.isFilename()) {
212 CmdArgs.push_back(II.getFilename());
216 // Otherwise, this is a linker input argument.
217 const Arg &A = II.getInputArg();
219 // Handle reserved library options.
220 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
221 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
222 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
223 TC.AddCCKextLibArgs(Args, CmdArgs);
224 else if (A.getOption().matches(options::OPT_z)) {
225 // Pass -z prefix for gcc linker compatibility.
227 A.render(Args, CmdArgs);
229 A.renderAsInput(Args, CmdArgs);
233 // LIBRARY_PATH - included following the user specified library paths.
234 // and only supported on native toolchains.
235 if (!TC.isCrossCompiling())
236 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
239 /// \brief Determine whether Objective-C automated reference counting is
241 static bool isObjCAutoRefCount(const ArgList &Args) {
242 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
245 /// \brief Determine whether we are linking the ObjC runtime.
246 static bool isObjCRuntimeLinked(const ArgList &Args) {
247 if (isObjCAutoRefCount(Args)) {
248 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
251 return Args.hasArg(options::OPT_fobjc_link_runtime);
254 static bool forwardToGCC(const Option &O) {
255 // Don't forward inputs from the original command line. They are added from
257 return O.getKind() != Option::InputClass &&
258 !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
261 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
262 const Driver &D, const ArgList &Args,
263 ArgStringList &CmdArgs,
264 const InputInfo &Output,
265 const InputInfoList &Inputs) const {
268 CheckPreprocessingOptions(D, Args);
270 Args.AddLastArg(CmdArgs, options::OPT_C);
271 Args.AddLastArg(CmdArgs, options::OPT_CC);
273 // Handle dependency file generation.
274 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
275 (A = Args.getLastArg(options::OPT_MD)) ||
276 (A = Args.getLastArg(options::OPT_MMD))) {
277 // Determine the output location.
279 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
280 DepFile = MF->getValue();
281 C.addFailureResultFile(DepFile, &JA);
282 } else if (Output.getType() == types::TY_Dependencies) {
283 DepFile = Output.getFilename();
284 } else if (A->getOption().matches(options::OPT_M) ||
285 A->getOption().matches(options::OPT_MM)) {
288 DepFile = getDependencyFileName(Args, Inputs);
289 C.addFailureResultFile(DepFile, &JA);
291 CmdArgs.push_back("-dependency-file");
292 CmdArgs.push_back(DepFile);
294 // Add a default target if one wasn't specified.
295 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
296 const char *DepTarget;
298 // If user provided -o, that is the dependency target, except
299 // when we are only generating a dependency file.
300 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
301 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
302 DepTarget = OutputOpt->getValue();
304 // Otherwise derive from the base input.
306 // FIXME: This should use the computed output file location.
307 SmallString<128> P(Inputs[0].getBaseInput());
308 llvm::sys::path::replace_extension(P, "o");
309 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
312 CmdArgs.push_back("-MT");
313 SmallString<128> Quoted;
314 QuoteTarget(DepTarget, Quoted);
315 CmdArgs.push_back(Args.MakeArgString(Quoted));
318 if (A->getOption().matches(options::OPT_M) ||
319 A->getOption().matches(options::OPT_MD))
320 CmdArgs.push_back("-sys-header-deps");
321 if ((isa<PrecompileJobAction>(JA) &&
322 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
323 Args.hasArg(options::OPT_fmodule_file_deps))
324 CmdArgs.push_back("-module-file-deps");
327 if (Args.hasArg(options::OPT_MG)) {
328 if (!A || A->getOption().matches(options::OPT_MD) ||
329 A->getOption().matches(options::OPT_MMD))
330 D.Diag(diag::err_drv_mg_requires_m_or_mm);
331 CmdArgs.push_back("-MG");
334 Args.AddLastArg(CmdArgs, options::OPT_MP);
335 Args.AddLastArg(CmdArgs, options::OPT_MV);
337 // Convert all -MQ <target> args to -MT <quoted target>
338 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
341 if (A->getOption().matches(options::OPT_MQ)) {
342 CmdArgs.push_back("-MT");
343 SmallString<128> Quoted;
344 QuoteTarget(A->getValue(), Quoted);
345 CmdArgs.push_back(Args.MakeArgString(Quoted));
347 // -MT flag - no change
349 A->render(Args, CmdArgs);
353 // Add -i* options, and automatically translate to
354 // -include-pch/-include-pth for transparent PCH support. It's
355 // wonky, but we include looking for .gch so we can support seamless
356 // replacement into a build system already set up to be generating
358 bool RenderedImplicitInclude = false;
359 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
360 if (A->getOption().matches(options::OPT_include)) {
361 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
362 RenderedImplicitInclude = true;
364 // Use PCH if the user requested it.
365 bool UsePCH = D.CCCUsePCH;
367 bool FoundPTH = false;
368 bool FoundPCH = false;
369 SmallString<128> P(A->getValue());
370 // We want the files to have a name like foo.h.pch. Add a dummy extension
371 // so that replace_extension does the right thing.
374 llvm::sys::path::replace_extension(P, "pch");
375 if (llvm::sys::fs::exists(P))
380 llvm::sys::path::replace_extension(P, "pth");
381 if (llvm::sys::fs::exists(P))
385 if (!FoundPCH && !FoundPTH) {
386 llvm::sys::path::replace_extension(P, "gch");
387 if (llvm::sys::fs::exists(P)) {
393 if (FoundPCH || FoundPTH) {
394 if (IsFirstImplicitInclude) {
397 CmdArgs.push_back("-include-pch");
399 CmdArgs.push_back("-include-pth");
400 CmdArgs.push_back(Args.MakeArgString(P));
403 // Ignore the PCH if not first on command line and emit warning.
404 D.Diag(diag::warn_drv_pch_not_first_include) << P
405 << A->getAsString(Args);
410 // Not translated, render as usual.
412 A->render(Args, CmdArgs);
415 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
416 Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
417 options::OPT_index_header_map);
419 // Add -Wp, and -Xassembler if using the preprocessor.
421 // FIXME: There is a very unfortunate problem here, some troubled
422 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
423 // really support that we would have to parse and then translate
425 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
426 options::OPT_Xpreprocessor);
428 // -I- is a deprecated GCC feature, reject it.
429 if (Arg *A = Args.getLastArg(options::OPT_I_))
430 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
432 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
433 // -isysroot to the CC1 invocation.
434 StringRef sysroot = C.getSysRoot();
436 if (!Args.hasArg(options::OPT_isysroot)) {
437 CmdArgs.push_back("-isysroot");
438 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
442 // Parse additional include paths from environment variables.
443 // FIXME: We should probably sink the logic for handling these from the
444 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
445 // CPATH - included following the user specified includes (but prior to
446 // builtin and standard includes).
447 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
448 // C_INCLUDE_PATH - system includes enabled when compiling C.
449 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
450 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
451 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
452 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
453 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
454 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
455 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
457 // Add C++ include arguments, if needed.
458 if (types::isCXX(Inputs[0].getType()))
459 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
461 // Add system include arguments.
462 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
465 // FIXME: Move to target hook.
466 static bool isSignedCharDefault(const llvm::Triple &Triple) {
467 switch (Triple.getArch()) {
471 case llvm::Triple::aarch64:
472 case llvm::Triple::aarch64_be:
473 case llvm::Triple::arm:
474 case llvm::Triple::armeb:
475 case llvm::Triple::thumb:
476 case llvm::Triple::thumbeb:
477 if (Triple.isOSDarwin() || Triple.isOSWindows())
481 case llvm::Triple::ppc:
482 case llvm::Triple::ppc64:
483 if (Triple.isOSDarwin())
487 case llvm::Triple::hexagon:
488 case llvm::Triple::ppc64le:
489 case llvm::Triple::systemz:
490 case llvm::Triple::xcore:
495 static bool isNoCommonDefault(const llvm::Triple &Triple) {
496 switch (Triple.getArch()) {
500 case llvm::Triple::xcore:
508 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
509 llvm::StringRef Arch = Triple.getArchName();
510 return llvm::ARMTargetParser::parseArchVersion(Arch);
513 // True if M-profile.
514 static bool isARMMProfile(const llvm::Triple &Triple) {
515 llvm::StringRef Arch = Triple.getArchName();
516 unsigned Profile = llvm::ARMTargetParser::parseArchProfile(Arch);
517 return Profile == llvm::ARM::PK_M;
520 // Get Arch/CPU from args.
521 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
522 llvm::StringRef &CPU, bool FromAs = false) {
523 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
525 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
526 Arch = A->getValue();
531 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
532 StringRef Value = A->getValue();
533 if (Value.startswith("-mcpu="))
534 CPU = Value.substr(6);
535 if (Value.startswith("-march="))
536 Arch = Value.substr(7);
541 // FIXME: Use ARMTargetParser.
542 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
543 const ArgList &Args, StringRef HWDiv,
544 std::vector<const char *> &Features) {
545 if (HWDiv == "arm") {
546 Features.push_back("+hwdiv-arm");
547 Features.push_back("-hwdiv");
548 } else if (HWDiv == "thumb") {
549 Features.push_back("-hwdiv-arm");
550 Features.push_back("+hwdiv");
551 } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
552 Features.push_back("+hwdiv-arm");
553 Features.push_back("+hwdiv");
554 } else if (HWDiv == "none") {
555 Features.push_back("-hwdiv-arm");
556 Features.push_back("-hwdiv");
558 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
562 static void getARMFPUFeatures(const Driver &D, const Arg *A,
563 const ArgList &Args, StringRef FPU,
564 std::vector<const char *> &Features) {
565 unsigned FPUID = llvm::ARMTargetParser::parseFPU(FPU);
566 if (!llvm::ARMTargetParser::getFPUFeatures(FPUID, Features))
567 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
570 // Check if -march is valid by checking if it can be canonicalised and parsed.
571 // getARMArch is used here instead of just checking the -march value in order
572 // to handle -march=native correctly.
573 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
574 llvm::StringRef ArchName,
575 const llvm::Triple &Triple) {
576 std::string MArch = arm::getARMArch(ArchName, Triple);
577 if (llvm::ARMTargetParser::parseArch(MArch) == llvm::ARM::AK_INVALID)
578 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
581 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
582 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
583 llvm::StringRef CPUName, llvm::StringRef ArchName,
584 const llvm::Triple &Triple) {
585 std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
586 std::string Arch = arm::getARMArch(ArchName, Triple);
587 if (strcmp(arm::getLLVMArchSuffixForARM(CPU, Arch), "") == 0)
588 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
591 // Select the float ABI as determined by -msoft-float, -mhard-float, and
593 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
594 const llvm::Triple &Triple) {
597 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
598 options::OPT_mfloat_abi_EQ)) {
599 if (A->getOption().matches(options::OPT_msoft_float))
601 else if (A->getOption().matches(options::OPT_mhard_float))
604 FloatABI = A->getValue();
605 if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
606 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
612 // If unspecified, choose the default based on the platform.
613 if (FloatABI.empty()) {
614 switch (Triple.getOS()) {
615 case llvm::Triple::Darwin:
616 case llvm::Triple::MacOSX:
617 case llvm::Triple::IOS: {
618 // Darwin defaults to "softfp" for v6 and v7.
620 if (getARMSubArchVersionNumber(Triple) == 6 ||
621 getARMSubArchVersionNumber(Triple) == 7)
628 // FIXME: this is invalid for WindowsCE
629 case llvm::Triple::Win32:
633 case llvm::Triple::FreeBSD:
634 switch (Triple.getEnvironment()) {
635 case llvm::Triple::GNUEABIHF:
639 // FreeBSD defaults to soft float
646 switch (Triple.getEnvironment()) {
647 case llvm::Triple::GNUEABIHF:
650 case llvm::Triple::GNUEABI:
653 case llvm::Triple::EABIHF:
656 case llvm::Triple::EABI:
657 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
660 case llvm::Triple::Android: {
661 if (getARMSubArchVersionNumber(Triple) == 7)
668 // Assume "soft", but warn the user we are guessing.
670 if (Triple.getOS() != llvm::Triple::UnknownOS ||
671 !Triple.isOSBinFormatMachO())
672 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
681 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
683 std::vector<const char *> &Features,
686 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
687 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
688 const Arg *WaCPU = nullptr, *WaFPU = nullptr;
689 const Arg *WaHDiv = nullptr, *WaArch = nullptr;
692 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
693 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
694 // stripped out by the ARM target. We should probably pass this a new
695 // -target-option, which is handled by the -cc1/-cc1as invocation.
697 // FIXME2: For consistency, it would be ideal if we set up the target
698 // machine state the same when using the frontend or the assembler. We don't
699 // currently do that for the assembler, we pass the options directly to the
700 // backend and never even instantiate the frontend TargetInfo. If we did,
701 // and used its handleTargetFeatures hook, then we could ensure the
702 // assembler and the frontend behave the same.
704 // Use software floating point operations?
705 if (FloatABI == "soft")
706 Features.push_back("+soft-float");
708 // Use software floating point argument passing?
709 if (FloatABI != "hard")
710 Features.push_back("+soft-float-abi");
712 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
713 // to the assembler correctly.
715 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
716 StringRef Value = A->getValue();
717 if (Value.startswith("-mfpu=")) {
719 } else if (Value.startswith("-mcpu=")) {
721 } else if (Value.startswith("-mhwdiv=")) {
723 } else if (Value.startswith("-march=")) {
729 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
730 const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
733 D.Diag(clang::diag::warn_drv_unused_argument)
734 << FPUArg->getAsString(Args);
735 getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
738 getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
741 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
742 const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
745 D.Diag(clang::diag::warn_drv_unused_argument)
746 << HDivArg->getAsString(Args);
747 getARMHWDivFeatures(D, WaHDiv, Args,
748 StringRef(WaHDiv->getValue()).substr(8), Features);
750 getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
752 // Check -march. ClangAs gives preference to -Wa,-march=.
753 const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
757 D.Diag(clang::diag::warn_drv_unused_argument)
758 << ArchArg->getAsString(Args);
759 ArchName = StringRef(WaArch->getValue()).substr(7);
760 checkARMArchName(D, WaArch, Args, ArchName, Triple);
762 D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
763 } else if (ArchArg) {
764 ArchName = ArchArg->getValue();
765 checkARMArchName(D, ArchArg, Args, ArchName, Triple);
768 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
769 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
773 D.Diag(clang::diag::warn_drv_unused_argument)
774 << CPUArg->getAsString(Args);
775 CPUName = StringRef(WaCPU->getValue()).substr(6);
776 checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Triple);
778 CPUName = CPUArg->getValue();
779 checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Triple);
782 // Setting -msoft-float effectively disables NEON because of the GCC
783 // implementation, although the same isn't true of VFP or VFP3.
784 if (FloatABI == "soft") {
785 Features.push_back("-neon");
786 // Also need to explicitly disable features which imply NEON.
787 Features.push_back("-crypto");
790 // En/disable crc code generation.
791 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
792 if (A->getOption().matches(options::OPT_mcrc))
793 Features.push_back("+crc");
795 Features.push_back("-crc");
798 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
799 Features.insert(Features.begin(), "+v8.1a");
802 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
803 // neither options are specified, see if we are compiling for kernel/kext and
804 // decide whether to pass "+long-calls" based on the OS and its version.
805 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
806 options::OPT_mno_long_calls)) {
807 if (A->getOption().matches(options::OPT_mlong_calls))
808 Features.push_back("+long-calls");
809 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6))) {
810 Features.push_back("+long-calls");
814 void Clang::AddARMTargetArgs(const ArgList &Args, ArgStringList &CmdArgs,
815 bool KernelOrKext) const {
816 const Driver &D = getToolChain().getDriver();
817 // Get the effective triple, which takes into account the deployment target.
818 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
819 llvm::Triple Triple(TripleStr);
821 // Select the ABI to use.
823 // FIXME: Support -meabi.
824 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
825 const char *ABIName = nullptr;
826 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
827 ABIName = A->getValue();
828 } else if (Triple.isOSBinFormatMachO()) {
829 // The backend is hardwired to assume AAPCS for M-class processors, ensure
830 // the frontend matches that.
831 if (Triple.getEnvironment() == llvm::Triple::EABI ||
832 Triple.getOS() == llvm::Triple::UnknownOS || isARMMProfile(Triple)) {
835 ABIName = "apcs-gnu";
837 } else if (Triple.isOSWindows()) {
838 // FIXME: this is invalid for WindowsCE
841 // Select the default based on the platform.
842 switch (Triple.getEnvironment()) {
843 case llvm::Triple::Android:
844 case llvm::Triple::GNUEABI:
845 case llvm::Triple::GNUEABIHF:
846 ABIName = "aapcs-linux";
848 case llvm::Triple::EABIHF:
849 case llvm::Triple::EABI:
853 if (Triple.getOS() == llvm::Triple::NetBSD)
854 ABIName = "apcs-gnu";
860 CmdArgs.push_back("-target-abi");
861 CmdArgs.push_back(ABIName);
863 // Determine floating point ABI from the options & target defaults.
864 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
865 if (FloatABI == "soft") {
866 // Floating point operations and argument passing are soft.
868 // FIXME: This changes CPP defines, we need -target-soft-float.
869 CmdArgs.push_back("-msoft-float");
870 CmdArgs.push_back("-mfloat-abi");
871 CmdArgs.push_back("soft");
872 } else if (FloatABI == "softfp") {
873 // Floating point operations are hard, but argument passing is soft.
874 CmdArgs.push_back("-mfloat-abi");
875 CmdArgs.push_back("soft");
877 // Floating point operations and argument passing are hard.
878 assert(FloatABI == "hard" && "Invalid float abi!");
879 CmdArgs.push_back("-mfloat-abi");
880 CmdArgs.push_back("hard");
883 // Kernel code has more strict alignment requirements.
885 CmdArgs.push_back("-backend-option");
886 CmdArgs.push_back("-arm-strict-align");
888 // The kext linker doesn't know how to deal with movw/movt.
889 CmdArgs.push_back("-backend-option");
890 CmdArgs.push_back("-arm-use-movt=0");
893 // -mkernel implies -mstrict-align; don't add the redundant option.
895 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
896 options::OPT_munaligned_access)) {
897 CmdArgs.push_back("-backend-option");
898 if (A->getOption().matches(options::OPT_mno_unaligned_access))
899 CmdArgs.push_back("-arm-strict-align");
901 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
902 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
903 CmdArgs.push_back("-arm-no-strict-align");
908 // Forward the -mglobal-merge option for explicit control over the pass.
909 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
910 options::OPT_mno_global_merge)) {
911 CmdArgs.push_back("-backend-option");
912 if (A->getOption().matches(options::OPT_mno_global_merge))
913 CmdArgs.push_back("-arm-global-merge=false");
915 CmdArgs.push_back("-arm-global-merge=true");
918 if (!Args.hasFlag(options::OPT_mimplicit_float,
919 options::OPT_mno_implicit_float, true))
920 CmdArgs.push_back("-no-implicit-float");
922 // llvm does not support reserving registers in general. There is support
923 // for reserving r9 on ARM though (defined as a platform-specific register
925 if (Args.hasArg(options::OPT_ffixed_r9)) {
926 CmdArgs.push_back("-backend-option");
927 CmdArgs.push_back("-arm-reserve-r9");
932 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
934 static std::string getAArch64TargetCPU(const ArgList &Args) {
937 // If we have -mtune or -mcpu, use that.
938 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
940 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
941 StringRef Mcpu = A->getValue();
942 CPU = Mcpu.split("+").first.lower();
945 // Handle CPU name is 'native'.
947 return llvm::sys::getHostCPUName();
951 // Make sure we pick "cyclone" if -arch is used.
952 // FIXME: Should this be picked by checking the target triple instead?
953 if (Args.getLastArg(options::OPT_arch))
959 void Clang::AddAArch64TargetArgs(const ArgList &Args,
960 ArgStringList &CmdArgs) const {
961 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
962 llvm::Triple Triple(TripleStr);
964 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
965 Args.hasArg(options::OPT_mkernel) ||
966 Args.hasArg(options::OPT_fapple_kext))
967 CmdArgs.push_back("-disable-red-zone");
969 if (!Args.hasFlag(options::OPT_mimplicit_float,
970 options::OPT_mno_implicit_float, true))
971 CmdArgs.push_back("-no-implicit-float");
973 const char *ABIName = nullptr;
974 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
975 ABIName = A->getValue();
976 else if (Triple.isOSDarwin())
977 ABIName = "darwinpcs";
981 CmdArgs.push_back("-target-abi");
982 CmdArgs.push_back(ABIName);
984 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
985 options::OPT_munaligned_access)) {
986 CmdArgs.push_back("-backend-option");
987 if (A->getOption().matches(options::OPT_mno_unaligned_access))
988 CmdArgs.push_back("-aarch64-strict-align");
990 CmdArgs.push_back("-aarch64-no-strict-align");
993 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
994 options::OPT_mno_fix_cortex_a53_835769)) {
995 CmdArgs.push_back("-backend-option");
996 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
997 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
999 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1000 } else if (Triple.getEnvironment() == llvm::Triple::Android) {
1001 // Enabled A53 errata (835769) workaround by default on android
1002 CmdArgs.push_back("-backend-option");
1003 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1006 // Forward the -mglobal-merge option for explicit control over the pass.
1007 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1008 options::OPT_mno_global_merge)) {
1009 CmdArgs.push_back("-backend-option");
1010 if (A->getOption().matches(options::OPT_mno_global_merge))
1011 CmdArgs.push_back("-aarch64-global-merge=false");
1013 CmdArgs.push_back("-aarch64-global-merge=true");
1016 if (Args.hasArg(options::OPT_ffixed_x18)) {
1017 CmdArgs.push_back("-backend-option");
1018 CmdArgs.push_back("-aarch64-reserve-x18");
1022 // Get CPU and ABI names. They are not independent
1023 // so we have to calculate them together.
1024 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1025 StringRef &CPUName, StringRef &ABIName) {
1026 const char *DefMips32CPU = "mips32r2";
1027 const char *DefMips64CPU = "mips64r2";
1029 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1030 // default for mips64(el)?-img-linux-gnu.
1031 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1032 Triple.getEnvironment() == llvm::Triple::GNU) {
1033 DefMips32CPU = "mips32r6";
1034 DefMips64CPU = "mips64r6";
1037 // MIPS3 is the default for mips64*-unknown-openbsd.
1038 if (Triple.getOS() == llvm::Triple::OpenBSD)
1039 DefMips64CPU = "mips3";
1041 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1042 CPUName = A->getValue();
1044 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1045 ABIName = A->getValue();
1046 // Convert a GNU style Mips ABI name to the name
1047 // accepted by LLVM Mips backend.
1048 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1054 // Setup default CPU and ABI names.
1055 if (CPUName.empty() && ABIName.empty()) {
1056 switch (Triple.getArch()) {
1058 llvm_unreachable("Unexpected triple arch name");
1059 case llvm::Triple::mips:
1060 case llvm::Triple::mipsel:
1061 CPUName = DefMips32CPU;
1063 case llvm::Triple::mips64:
1064 case llvm::Triple::mips64el:
1065 CPUName = DefMips64CPU;
1070 if (ABIName.empty()) {
1071 // Deduce ABI name from the target triple.
1072 if (Triple.getArch() == llvm::Triple::mips ||
1073 Triple.getArch() == llvm::Triple::mipsel)
1079 if (CPUName.empty()) {
1080 // Deduce CPU name from ABI name.
1081 CPUName = llvm::StringSwitch<const char *>(ABIName)
1082 .Cases("o32", "eabi", DefMips32CPU)
1083 .Cases("n32", "n64", DefMips64CPU)
1087 // FIXME: Warn on inconsistent use of -march and -mabi.
1090 // Convert ABI name to the GNU tools acceptable variant.
1091 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1092 return llvm::StringSwitch<llvm::StringRef>(ABI)
1098 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1099 // and -mfloat-abi=.
1100 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
1103 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1104 options::OPT_mfloat_abi_EQ)) {
1105 if (A->getOption().matches(options::OPT_msoft_float))
1107 else if (A->getOption().matches(options::OPT_mhard_float))
1110 FloatABI = A->getValue();
1111 if (FloatABI != "soft" && FloatABI != "hard") {
1112 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1118 // If unspecified, choose the default based on the platform.
1119 if (FloatABI.empty()) {
1120 // Assume "hard", because it's a default value used by gcc.
1121 // When we start to recognize specific target MIPS processors,
1122 // we will be able to select the default more correctly.
1129 static void AddTargetFeature(const ArgList &Args,
1130 std::vector<const char *> &Features,
1131 OptSpecifier OnOpt, OptSpecifier OffOpt,
1132 StringRef FeatureName) {
1133 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1134 if (A->getOption().matches(OnOpt))
1135 Features.push_back(Args.MakeArgString("+" + FeatureName));
1137 Features.push_back(Args.MakeArgString("-" + FeatureName));
1141 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1142 const ArgList &Args,
1143 std::vector<const char *> &Features) {
1146 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1147 ABIName = getGnuCompatibleMipsABIName(ABIName);
1149 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1150 options::OPT_mabicalls, "noabicalls");
1152 StringRef FloatABI = getMipsFloatABI(D, Args);
1153 if (FloatABI == "soft") {
1154 // FIXME: Note, this is a hack. We need to pass the selected float
1155 // mode to the MipsTargetInfoBase to define appropriate macros there.
1156 // Now it is the only method.
1157 Features.push_back("+soft-float");
1160 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1161 StringRef Val = StringRef(A->getValue());
1162 if (Val == "2008") {
1163 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1164 Features.push_back("+nan2008");
1166 Features.push_back("-nan2008");
1167 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1169 } else if (Val == "legacy") {
1170 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1171 Features.push_back("-nan2008");
1173 Features.push_back("+nan2008");
1174 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1177 D.Diag(diag::err_drv_unsupported_option_argument)
1178 << A->getOption().getName() << Val;
1181 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1182 options::OPT_mdouble_float, "single-float");
1183 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1185 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1186 options::OPT_mno_micromips, "micromips");
1187 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1189 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1191 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1194 // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1196 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1197 options::OPT_mfp64)) {
1198 if (A->getOption().matches(options::OPT_mfp32))
1199 Features.push_back(Args.MakeArgString("-fp64"));
1200 else if (A->getOption().matches(options::OPT_mfpxx)) {
1201 Features.push_back(Args.MakeArgString("+fpxx"));
1202 Features.push_back(Args.MakeArgString("+nooddspreg"));
1204 Features.push_back(Args.MakeArgString("+fp64"));
1205 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1206 Features.push_back(Args.MakeArgString("+fpxx"));
1207 Features.push_back(Args.MakeArgString("+nooddspreg"));
1210 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1211 options::OPT_modd_spreg, "nooddspreg");
1214 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1215 ArgStringList &CmdArgs) const {
1216 const Driver &D = getToolChain().getDriver();
1219 const llvm::Triple &Triple = getToolChain().getTriple();
1220 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1222 CmdArgs.push_back("-target-abi");
1223 CmdArgs.push_back(ABIName.data());
1225 StringRef FloatABI = getMipsFloatABI(D, Args);
1227 if (FloatABI == "soft") {
1228 // Floating point operations and argument passing are soft.
1229 CmdArgs.push_back("-msoft-float");
1230 CmdArgs.push_back("-mfloat-abi");
1231 CmdArgs.push_back("soft");
1233 // Floating point operations and argument passing are hard.
1234 assert(FloatABI == "hard" && "Invalid float abi!");
1235 CmdArgs.push_back("-mfloat-abi");
1236 CmdArgs.push_back("hard");
1239 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1240 if (A->getOption().matches(options::OPT_mxgot)) {
1241 CmdArgs.push_back("-mllvm");
1242 CmdArgs.push_back("-mxgot");
1246 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1247 options::OPT_mno_ldc1_sdc1)) {
1248 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1249 CmdArgs.push_back("-mllvm");
1250 CmdArgs.push_back("-mno-ldc1-sdc1");
1254 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1255 options::OPT_mno_check_zero_division)) {
1256 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1257 CmdArgs.push_back("-mllvm");
1258 CmdArgs.push_back("-mno-check-zero-division");
1262 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1263 StringRef v = A->getValue();
1264 CmdArgs.push_back("-mllvm");
1265 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1270 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1271 static std::string getPPCTargetCPU(const ArgList &Args) {
1272 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1273 StringRef CPUName = A->getValue();
1275 if (CPUName == "native") {
1276 std::string CPU = llvm::sys::getHostCPUName();
1277 if (!CPU.empty() && CPU != "generic")
1283 return llvm::StringSwitch<const char *>(CPUName)
1284 .Case("common", "generic")
1286 .Case("440fp", "440")
1291 .Case("603e", "603e")
1292 .Case("603ev", "603ev")
1294 .Case("604e", "604e")
1296 .Case("630", "pwr3")
1298 .Case("7400", "7400")
1300 .Case("7450", "7450")
1307 .Case("e500mc", "e500mc")
1308 .Case("e5500", "e5500")
1309 .Case("power3", "pwr3")
1310 .Case("power4", "pwr4")
1311 .Case("power5", "pwr5")
1312 .Case("power5x", "pwr5x")
1313 .Case("power6", "pwr6")
1314 .Case("power6x", "pwr6x")
1315 .Case("power7", "pwr7")
1316 .Case("power8", "pwr8")
1317 .Case("pwr3", "pwr3")
1318 .Case("pwr4", "pwr4")
1319 .Case("pwr5", "pwr5")
1320 .Case("pwr5x", "pwr5x")
1321 .Case("pwr6", "pwr6")
1322 .Case("pwr6x", "pwr6x")
1323 .Case("pwr7", "pwr7")
1324 .Case("pwr8", "pwr8")
1325 .Case("powerpc", "ppc")
1326 .Case("powerpc64", "ppc64")
1327 .Case("powerpc64le", "ppc64le")
1334 static void getPPCTargetFeatures(const ArgList &Args,
1335 std::vector<const char *> &Features) {
1336 for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
1337 StringRef Name = A->getOption().getName();
1341 assert(Name.startswith("m") && "Invalid feature name.");
1342 Name = Name.substr(1);
1344 bool IsNegative = Name.startswith("no-");
1346 Name = Name.substr(3);
1348 // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1349 // pass the correct option to the backend while calling the frontend
1351 // TODO: Change the LLVM backend option maybe?
1352 if (Name == "mfcrf")
1355 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1358 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1359 AddTargetFeature(Args, Features, options::OPT_faltivec,
1360 options::OPT_fno_altivec, "altivec");
1363 void Clang::AddPPCTargetArgs(const ArgList &Args,
1364 ArgStringList &CmdArgs) const {
1365 // Select the ABI to use.
1366 const char *ABIName = nullptr;
1367 if (getToolChain().getTriple().isOSLinux())
1368 switch (getToolChain().getArch()) {
1369 case llvm::Triple::ppc64: {
1370 // When targeting a processor that supports QPX, or if QPX is
1371 // specifically enabled, default to using the ABI that supports QPX (so
1372 // long as it is not specifically disabled).
1373 bool HasQPX = false;
1374 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1375 HasQPX = A->getValue() == StringRef("a2q");
1376 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1378 ABIName = "elfv1-qpx";
1385 case llvm::Triple::ppc64le:
1392 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1393 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1394 // the option if given as we don't have backend support for any targets
1395 // that don't use the altivec abi.
1396 if (StringRef(A->getValue()) != "altivec")
1397 ABIName = A->getValue();
1400 CmdArgs.push_back("-target-abi");
1401 CmdArgs.push_back(ABIName);
1405 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1406 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1407 return A && (A->getValue() == StringRef(Value));
1410 /// Get the (LLVM) name of the R600 gpu we are targeting.
1411 static std::string getR600TargetGPU(const ArgList &Args) {
1412 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1413 const char *GPUName = A->getValue();
1414 return llvm::StringSwitch<const char *>(GPUName)
1415 .Cases("rv630", "rv635", "r600")
1416 .Cases("rv610", "rv620", "rs780", "rs880")
1417 .Case("rv740", "rv770")
1418 .Case("palm", "cedar")
1419 .Cases("sumo", "sumo2", "sumo")
1420 .Case("hemlock", "cypress")
1421 .Case("aruba", "cayman")
1427 void Clang::AddSparcTargetArgs(const ArgList &Args,
1428 ArgStringList &CmdArgs) const {
1429 const Driver &D = getToolChain().getDriver();
1430 std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1432 bool SoftFloatABI = false;
1434 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1435 if (A->getOption().matches(options::OPT_msoft_float))
1436 SoftFloatABI = true;
1439 // Only the hard-float ABI on Sparc is standardized, and it is the
1440 // default. GCC also supports a nonstandard soft-float ABI mode, and
1441 // perhaps LLVM should implement that, too. However, since llvm
1442 // currently does not support Sparc soft-float, at all, display an
1443 // error if it's requested.
1445 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1450 static const char *getSystemZTargetCPU(const ArgList &Args) {
1451 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1452 return A->getValue();
1456 static void getSystemZTargetFeatures(const ArgList &Args,
1457 std::vector<const char *> &Features) {
1458 // -m(no-)htm overrides use of the transactional-execution facility.
1459 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1460 if (A->getOption().matches(options::OPT_mhtm))
1461 Features.push_back("+transactional-execution");
1463 Features.push_back("-transactional-execution");
1465 // -m(no-)vx overrides use of the vector facility.
1466 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1467 if (A->getOption().matches(options::OPT_mvx))
1468 Features.push_back("+vector");
1470 Features.push_back("-vector");
1474 static const char *getX86TargetCPU(const ArgList &Args,
1475 const llvm::Triple &Triple) {
1476 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1477 if (StringRef(A->getValue()) != "native") {
1478 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1481 return A->getValue();
1484 // FIXME: Reject attempts to use -march=native unless the target matches
1487 // FIXME: We should also incorporate the detected target features for use
1489 std::string CPU = llvm::sys::getHostCPUName();
1490 if (!CPU.empty() && CPU != "generic")
1491 return Args.MakeArgString(CPU);
1494 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1495 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1496 StringRef Arch = A->getValue();
1498 if (Triple.getArch() == llvm::Triple::x86) {
1499 CPU = llvm::StringSwitch<const char *>(Arch)
1500 .Case("IA32", "i386")
1501 .Case("SSE", "pentium3")
1502 .Case("SSE2", "pentium4")
1503 .Case("AVX", "sandybridge")
1504 .Case("AVX2", "haswell")
1507 CPU = llvm::StringSwitch<const char *>(Arch)
1508 .Case("AVX", "sandybridge")
1509 .Case("AVX2", "haswell")
1516 // Select the default CPU if none was given (or detection failed).
1518 if (Triple.getArch() != llvm::Triple::x86_64 &&
1519 Triple.getArch() != llvm::Triple::x86)
1520 return nullptr; // This routine is only handling x86 targets.
1522 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1524 // FIXME: Need target hooks.
1525 if (Triple.isOSDarwin()) {
1526 if (Triple.getArchName() == "x86_64h")
1528 return Is64Bit ? "core2" : "yonah";
1531 // Set up default CPU name for PS4 compilers.
1532 if (Triple.isPS4CPU())
1535 // On Android use targets compatible with gcc
1536 if (Triple.getEnvironment() == llvm::Triple::Android)
1537 return Is64Bit ? "x86-64" : "i686";
1539 // Everything else goes to x86-64 in 64-bit mode.
1543 switch (Triple.getOS()) {
1544 case llvm::Triple::FreeBSD:
1545 case llvm::Triple::NetBSD:
1546 case llvm::Triple::OpenBSD:
1548 case llvm::Triple::Haiku:
1550 case llvm::Triple::Bitrig:
1558 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1559 bool FromAs = false) {
1560 switch (T.getArch()) {
1564 case llvm::Triple::aarch64:
1565 case llvm::Triple::aarch64_be:
1566 return getAArch64TargetCPU(Args);
1568 case llvm::Triple::arm:
1569 case llvm::Triple::armeb:
1570 case llvm::Triple::thumb:
1571 case llvm::Triple::thumbeb: {
1572 StringRef MArch, MCPU;
1573 getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1574 return arm::getARMTargetCPU(MCPU, MArch, T);
1576 case llvm::Triple::mips:
1577 case llvm::Triple::mipsel:
1578 case llvm::Triple::mips64:
1579 case llvm::Triple::mips64el: {
1582 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1586 case llvm::Triple::nvptx:
1587 case llvm::Triple::nvptx64:
1588 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1589 return A->getValue();
1592 case llvm::Triple::ppc:
1593 case llvm::Triple::ppc64:
1594 case llvm::Triple::ppc64le: {
1595 std::string TargetCPUName = getPPCTargetCPU(Args);
1596 // LLVM may default to generating code for the native CPU,
1597 // but, like gcc, we default to a more generic option for
1598 // each architecture. (except on Darwin)
1599 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1600 if (T.getArch() == llvm::Triple::ppc64)
1601 TargetCPUName = "ppc64";
1602 else if (T.getArch() == llvm::Triple::ppc64le)
1603 TargetCPUName = "ppc64le";
1605 TargetCPUName = "ppc";
1607 return TargetCPUName;
1610 case llvm::Triple::sparc:
1611 case llvm::Triple::sparcel:
1612 case llvm::Triple::sparcv9:
1613 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1614 return A->getValue();
1617 case llvm::Triple::x86:
1618 case llvm::Triple::x86_64:
1619 return getX86TargetCPU(Args, T);
1621 case llvm::Triple::hexagon:
1622 return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1624 case llvm::Triple::systemz:
1625 return getSystemZTargetCPU(Args);
1627 case llvm::Triple::r600:
1628 case llvm::Triple::amdgcn:
1629 return getR600TargetGPU(Args);
1633 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1634 ArgStringList &CmdArgs) {
1635 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1636 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1638 CmdArgs.push_back("-plugin");
1639 std::string Plugin =
1640 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1641 CmdArgs.push_back(Args.MakeArgString(Plugin));
1643 // Try to pass driver level flags relevant to LTO code generation down to
1646 // Handle flags for selecting CPU variants.
1647 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1649 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1652 /// This is a helper function for validating the optional refinement step
1653 /// parameter in reciprocal argument strings. Return false if there is an error
1654 /// parsing the refinement step. Otherwise, return true and set the Position
1655 /// of the refinement step in the input string.
1656 static bool getRefinementStep(const StringRef &In, const Driver &D,
1657 const Arg &A, size_t &Position) {
1658 const char RefinementStepToken = ':';
1659 Position = In.find(RefinementStepToken);
1660 if (Position != StringRef::npos) {
1661 StringRef Option = A.getOption().getName();
1662 StringRef RefStep = In.substr(Position + 1);
1663 // Allow exactly one numeric character for the additional refinement
1664 // step parameter. This is reasonable for all currently-supported
1665 // operations and architectures because we would expect that a larger value
1666 // of refinement steps would cause the estimate "optimization" to
1667 // under-perform the native operation. Also, if the estimate does not
1668 // converge quickly, it probably will not ever converge, so further
1669 // refinement steps will not produce a better answer.
1670 if (RefStep.size() != 1) {
1671 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1674 char RefStepChar = RefStep[0];
1675 if (RefStepChar < '0' || RefStepChar > '9') {
1676 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1683 /// The -mrecip flag requires processing of many optional parameters.
1684 static void ParseMRecip(const Driver &D, const ArgList &Args,
1685 ArgStringList &OutStrings) {
1686 StringRef DisabledPrefixIn = "!";
1687 StringRef DisabledPrefixOut = "!";
1688 StringRef EnabledPrefixOut = "";
1689 StringRef Out = "-mrecip=";
1691 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1695 unsigned NumOptions = A->getNumValues();
1696 if (NumOptions == 0) {
1697 // No option is the same as "all".
1698 OutStrings.push_back(Args.MakeArgString(Out + "all"));
1702 // Pass through "all", "none", or "default" with an optional refinement step.
1703 if (NumOptions == 1) {
1704 StringRef Val = A->getValue(0);
1706 if (!getRefinementStep(Val, D, *A, RefStepLoc))
1708 StringRef ValBase = Val.slice(0, RefStepLoc);
1709 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1710 OutStrings.push_back(Args.MakeArgString(Out + Val));
1715 // Each reciprocal type may be enabled or disabled individually.
1716 // Check each input value for validity, concatenate them all back together,
1717 // and pass through.
1719 llvm::StringMap<bool> OptionStrings;
1720 OptionStrings.insert(std::make_pair("divd", false));
1721 OptionStrings.insert(std::make_pair("divf", false));
1722 OptionStrings.insert(std::make_pair("vec-divd", false));
1723 OptionStrings.insert(std::make_pair("vec-divf", false));
1724 OptionStrings.insert(std::make_pair("sqrtd", false));
1725 OptionStrings.insert(std::make_pair("sqrtf", false));
1726 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1727 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1729 for (unsigned i = 0; i != NumOptions; ++i) {
1730 StringRef Val = A->getValue(i);
1732 bool IsDisabled = Val.startswith(DisabledPrefixIn);
1733 // Ignore the disablement token for string matching.
1735 Val = Val.substr(1);
1738 if (!getRefinementStep(Val, D, *A, RefStep))
1741 StringRef ValBase = Val.slice(0, RefStep);
1742 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1743 if (OptionIter == OptionStrings.end()) {
1744 // Try again specifying float suffix.
1745 OptionIter = OptionStrings.find(ValBase.str() + 'f');
1746 if (OptionIter == OptionStrings.end()) {
1747 // The input name did not match any known option string.
1748 D.Diag(diag::err_drv_unknown_argument) << Val;
1751 // The option was specified without a float or double suffix.
1752 // Make sure that the double entry was not already specified.
1753 // The float entry will be checked below.
1754 if (OptionStrings[ValBase.str() + 'd']) {
1755 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1760 if (OptionIter->second == true) {
1761 // Duplicate option specified.
1762 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1766 // Mark the matched option as found. Do not allow duplicate specifiers.
1767 OptionIter->second = true;
1769 // If the precision was not specified, also mark the double entry as found.
1770 if (ValBase.back() != 'f' && ValBase.back() != 'd')
1771 OptionStrings[ValBase.str() + 'd'] = true;
1773 // Build the output string.
1774 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1775 Out = Args.MakeArgString(Out + Prefix + Val);
1776 if (i != NumOptions - 1)
1777 Out = Args.MakeArgString(Out + ",");
1780 OutStrings.push_back(Args.MakeArgString(Out));
1783 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1784 const ArgList &Args,
1785 std::vector<const char *> &Features) {
1786 // If -march=native, autodetect the feature list.
1787 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1788 if (StringRef(A->getValue()) == "native") {
1789 llvm::StringMap<bool> HostFeatures;
1790 if (llvm::sys::getHostCPUFeatures(HostFeatures))
1791 for (auto &F : HostFeatures)
1793 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1797 if (Triple.getArchName() == "x86_64h") {
1798 // x86_64h implies quite a few of the more modern subtarget features
1799 // for Haswell class CPUs, but not all of them. Opt-out of a few.
1800 Features.push_back("-rdrnd");
1801 Features.push_back("-aes");
1802 Features.push_back("-pclmul");
1803 Features.push_back("-rtm");
1804 Features.push_back("-hle");
1805 Features.push_back("-fsgsbase");
1808 const llvm::Triple::ArchType ArchType = Triple.getArch();
1809 // Add features to be compatible with gcc for Android.
1810 if (Triple.getEnvironment() == llvm::Triple::Android) {
1811 if (ArchType == llvm::Triple::x86_64) {
1812 Features.push_back("+sse4.2");
1813 Features.push_back("+popcnt");
1815 Features.push_back("+ssse3");
1818 // Set features according to the -arch flag on MSVC.
1819 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1820 StringRef Arch = A->getValue();
1821 bool ArchUsed = false;
1822 // First, look for flags that are shared in x86 and x86-64.
1823 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1824 if (Arch == "AVX" || Arch == "AVX2") {
1826 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1829 // Then, look for x86-specific flags.
1830 if (ArchType == llvm::Triple::x86) {
1831 if (Arch == "IA32") {
1833 } else if (Arch == "SSE" || Arch == "SSE2") {
1835 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1839 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
1842 // Now add any that the user explicitly requested on the command line,
1843 // which may override the defaults.
1844 for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
1845 StringRef Name = A->getOption().getName();
1849 assert(Name.startswith("m") && "Invalid feature name.");
1850 Name = Name.substr(1);
1852 bool IsNegative = Name.startswith("no-");
1854 Name = Name.substr(3);
1856 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1860 void Clang::AddX86TargetArgs(const ArgList &Args,
1861 ArgStringList &CmdArgs) const {
1862 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1863 Args.hasArg(options::OPT_mkernel) ||
1864 Args.hasArg(options::OPT_fapple_kext))
1865 CmdArgs.push_back("-disable-red-zone");
1867 // Default to avoid implicit floating-point for kernel/kext code, but allow
1868 // that to be overridden with -mno-soft-float.
1869 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1870 Args.hasArg(options::OPT_fapple_kext));
1871 if (Arg *A = Args.getLastArg(
1872 options::OPT_msoft_float, options::OPT_mno_soft_float,
1873 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1874 const Option &O = A->getOption();
1875 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1876 O.matches(options::OPT_msoft_float));
1878 if (NoImplicitFloat)
1879 CmdArgs.push_back("-no-implicit-float");
1881 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1882 StringRef Value = A->getValue();
1883 if (Value == "intel" || Value == "att") {
1884 CmdArgs.push_back("-mllvm");
1885 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1887 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1888 << A->getOption().getName() << Value;
1893 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1894 ArgStringList &CmdArgs) const {
1895 CmdArgs.push_back("-mqdsp6-compat");
1896 CmdArgs.push_back("-Wreturn-type");
1898 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
1899 std::string SmallDataThreshold = "-hexagon-small-data-threshold=";
1900 SmallDataThreshold += v;
1901 CmdArgs.push_back("-mllvm");
1902 CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
1905 if (!Args.hasArg(options::OPT_fno_short_enums))
1906 CmdArgs.push_back("-fshort-enums");
1907 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1908 CmdArgs.push_back("-mllvm");
1909 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1911 CmdArgs.push_back("-mllvm");
1912 CmdArgs.push_back("-machine-sink-split=0");
1915 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
1916 static bool DecodeAArch64Features(const Driver &D, StringRef text,
1917 std::vector<const char *> &Features) {
1918 SmallVector<StringRef, 8> Split;
1919 text.split(Split, StringRef("+"), -1, false);
1921 for (const StringRef Feature : Split) {
1922 const char *result = llvm::StringSwitch<const char *>(Feature)
1923 .Case("fp", "+fp-armv8")
1924 .Case("simd", "+neon")
1925 .Case("crc", "+crc")
1926 .Case("crypto", "+crypto")
1927 .Case("nofp", "-fp-armv8")
1928 .Case("nosimd", "-neon")
1929 .Case("nocrc", "-crc")
1930 .Case("nocrypto", "-crypto")
1933 Features.push_back(result);
1934 else if (Feature == "neon" || Feature == "noneon")
1935 D.Diag(diag::err_drv_no_neon_modifier);
1942 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
1943 // decode CPU and feature.
1944 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
1945 std::vector<const char *> &Features) {
1946 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
1948 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
1949 CPU == "cortex-a72") {
1950 Features.push_back("+neon");
1951 Features.push_back("+crc");
1952 Features.push_back("+crypto");
1953 } else if (CPU == "generic") {
1954 Features.push_back("+neon");
1959 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1966 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
1967 const ArgList &Args,
1968 std::vector<const char *> &Features) {
1969 std::string MarchLowerCase = March.lower();
1970 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
1972 if (Split.first == "armv8-a" || Split.first == "armv8a") {
1973 // ok, no additional features.
1974 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
1975 Features.push_back("+v8.1a");
1980 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1987 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1988 const ArgList &Args,
1989 std::vector<const char *> &Features) {
1991 std::string McpuLowerCase = Mcpu.lower();
1992 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
1999 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2000 const ArgList &Args,
2001 std::vector<const char *> &Features) {
2002 // Handle CPU name is 'native'.
2003 if (Mtune == "native")
2004 Mtune = llvm::sys::getHostCPUName();
2005 if (Mtune == "cyclone") {
2006 Features.push_back("+zcm");
2007 Features.push_back("+zcz");
2013 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2014 const ArgList &Args,
2015 std::vector<const char *> &Features) {
2017 std::vector<const char *> DecodedFeature;
2018 std::string McpuLowerCase = Mcpu.lower();
2019 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2022 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2025 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2026 std::vector<const char *> &Features) {
2028 bool success = true;
2029 // Enable NEON by default.
2030 Features.push_back("+neon");
2031 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2032 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2033 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2034 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2035 else if (Args.hasArg(options::OPT_arch))
2036 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2039 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2041 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2042 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2044 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2045 else if (Args.hasArg(options::OPT_arch))
2046 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2050 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2052 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2053 Features.push_back("-fp-armv8");
2054 Features.push_back("-crypto");
2055 Features.push_back("-neon");
2059 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2060 if (A->getOption().matches(options::OPT_mcrc))
2061 Features.push_back("+crc");
2063 Features.push_back("-crc");
2067 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
2068 const ArgList &Args, ArgStringList &CmdArgs,
2070 std::vector<const char *> Features;
2071 switch (Triple.getArch()) {
2074 case llvm::Triple::mips:
2075 case llvm::Triple::mipsel:
2076 case llvm::Triple::mips64:
2077 case llvm::Triple::mips64el:
2078 getMIPSTargetFeatures(D, Triple, Args, Features);
2081 case llvm::Triple::arm:
2082 case llvm::Triple::armeb:
2083 case llvm::Triple::thumb:
2084 case llvm::Triple::thumbeb:
2085 getARMTargetFeatures(D, Triple, Args, Features, ForAS);
2088 case llvm::Triple::ppc:
2089 case llvm::Triple::ppc64:
2090 case llvm::Triple::ppc64le:
2091 getPPCTargetFeatures(Args, Features);
2093 case llvm::Triple::systemz:
2094 getSystemZTargetFeatures(Args, Features);
2096 case llvm::Triple::aarch64:
2097 case llvm::Triple::aarch64_be:
2098 getAArch64TargetFeatures(D, Args, Features);
2100 case llvm::Triple::x86:
2101 case llvm::Triple::x86_64:
2102 getX86TargetFeatures(D, Triple, Args, Features);
2106 // Find the last of each feature.
2107 llvm::StringMap<unsigned> LastOpt;
2108 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2109 const char *Name = Features[I];
2110 assert(Name[0] == '-' || Name[0] == '+');
2111 LastOpt[Name + 1] = I;
2114 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2115 // If this feature was overridden, ignore it.
2116 const char *Name = Features[I];
2117 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2118 assert(LastI != LastOpt.end());
2119 unsigned Last = LastI->second;
2123 CmdArgs.push_back("-target-feature");
2124 CmdArgs.push_back(Name);
2129 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2130 const llvm::Triple &Triple) {
2131 // We use the zero-cost exception tables for Objective-C if the non-fragile
2132 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2134 if (runtime.isNonFragile())
2137 if (!Triple.isMacOSX())
2140 return (!Triple.isMacOSXVersionLT(10, 5) &&
2141 (Triple.getArch() == llvm::Triple::x86_64 ||
2142 Triple.getArch() == llvm::Triple::arm));
2145 /// Adds exception related arguments to the driver command arguments. There's a
2146 /// master flag, -fexceptions and also language specific flags to enable/disable
2147 /// C++ and Objective-C exceptions. This makes it possible to for example
2148 /// disable C++ exceptions but enable Objective-C exceptions.
2149 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2150 const ToolChain &TC, bool KernelOrKext,
2151 const ObjCRuntime &objcRuntime,
2152 ArgStringList &CmdArgs) {
2153 const Driver &D = TC.getDriver();
2154 const llvm::Triple &Triple = TC.getTriple();
2157 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2158 // arguments now to avoid warnings about unused arguments.
2159 Args.ClaimAllArgs(options::OPT_fexceptions);
2160 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2161 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2162 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2163 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2164 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2168 // See if the user explicitly enabled exceptions.
2169 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2172 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2173 // is not necessarily sensible, but follows GCC.
2174 if (types::isObjC(InputType) &&
2175 Args.hasFlag(options::OPT_fobjc_exceptions,
2176 options::OPT_fno_objc_exceptions, true)) {
2177 CmdArgs.push_back("-fobjc-exceptions");
2179 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2182 if (types::isCXX(InputType)) {
2183 // Disable C++ EH by default on XCore, PS4, and MSVC.
2184 // FIXME: Remove MSVC from this list once things work.
2185 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2186 !Triple.isPS4CPU() &&
2187 !Triple.isWindowsMSVCEnvironment();
2188 Arg *ExceptionArg = Args.getLastArg(
2189 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2190 options::OPT_fexceptions, options::OPT_fno_exceptions);
2192 CXXExceptionsEnabled =
2193 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2194 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2196 if (CXXExceptionsEnabled) {
2197 if (Triple.isPS4CPU()) {
2198 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2199 assert(ExceptionArg &&
2200 "On the PS4 exceptions should only be enabled if passing "
2202 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2203 const Arg *RTTIArg = TC.getRTTIArg();
2204 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2205 D.Diag(diag::err_drv_argument_not_allowed_with)
2206 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2207 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2208 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2210 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2212 CmdArgs.push_back("-fcxx-exceptions");
2219 CmdArgs.push_back("-fexceptions");
2222 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2223 bool Default = true;
2224 if (TC.getTriple().isOSDarwin()) {
2225 // The native darwin assembler doesn't support the linker_option directives,
2226 // so we disable them if we think the .s file will be passed to it.
2227 Default = TC.useIntegratedAs();
2229 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2233 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2234 const ToolChain &TC) {
2235 bool UseDwarfDirectory =
2236 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2237 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2238 return !UseDwarfDirectory;
2241 /// \brief Check whether the given input tree contains any compilation actions.
2242 static bool ContainsCompileAction(const Action *A) {
2243 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2246 for (const auto &Act : *A)
2247 if (ContainsCompileAction(Act))
2253 /// \brief Check if -relax-all should be passed to the internal assembler.
2254 /// This is done by default when compiling non-assembler source with -O0.
2255 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2256 bool RelaxDefault = true;
2258 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2259 RelaxDefault = A->getOption().matches(options::OPT_O0);
2262 RelaxDefault = false;
2263 for (const auto &Act : C.getActions()) {
2264 if (ContainsCompileAction(Act)) {
2265 RelaxDefault = true;
2271 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2275 static void CollectArgsForIntegratedAssembler(Compilation &C,
2276 const ArgList &Args,
2277 ArgStringList &CmdArgs,
2279 if (UseRelaxAll(C, Args))
2280 CmdArgs.push_back("-mrelax-all");
2282 // When passing -I arguments to the assembler we sometimes need to
2283 // unconditionally take the next argument. For example, when parsing
2284 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2285 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2286 // arg after parsing the '-I' arg.
2287 bool TakeNextArg = false;
2289 // When using an integrated assembler, translate -Wa, and -Xassembler
2291 bool CompressDebugSections = false;
2293 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2296 for (const StringRef Value : A->getValues()) {
2298 CmdArgs.push_back(Value.data());
2299 TakeNextArg = false;
2303 if (Value == "-force_cpusubtype_ALL") {
2304 // Do nothing, this is the default and we don't support anything else.
2305 } else if (Value == "-L") {
2306 CmdArgs.push_back("-msave-temp-labels");
2307 } else if (Value == "--fatal-warnings") {
2308 CmdArgs.push_back("-massembler-fatal-warnings");
2309 } else if (Value == "--noexecstack") {
2310 CmdArgs.push_back("-mnoexecstack");
2311 } else if (Value == "-compress-debug-sections" ||
2312 Value == "--compress-debug-sections") {
2313 CompressDebugSections = true;
2314 } else if (Value == "-nocompress-debug-sections" ||
2315 Value == "--nocompress-debug-sections") {
2316 CompressDebugSections = false;
2317 } else if (Value.startswith("-I")) {
2318 CmdArgs.push_back(Value.data());
2319 // We need to consume the next argument if the current arg is a plain
2320 // -I. The next arg will be the include directory.
2323 } else if (Value.startswith("-gdwarf-")) {
2324 CmdArgs.push_back(Value.data());
2325 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2326 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2327 // Do nothing, we'll validate it later.
2329 D.Diag(diag::err_drv_unsupported_option_argument)
2330 << A->getOption().getName() << Value;
2334 if (CompressDebugSections) {
2335 if (llvm::zlib::isAvailable())
2336 CmdArgs.push_back("-compress-debug-sections");
2338 D.Diag(diag::warn_debug_compression_unavailable);
2342 // Until ARM libraries are build separately, we have them all in one library
2343 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
2344 if (TC.getTriple().isWindowsMSVCEnvironment() &&
2345 TC.getArch() == llvm::Triple::x86)
2347 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
2349 return TC.getArchName();
2352 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
2353 // The runtimes are located in the OS-specific resource directory.
2354 SmallString<128> Res(TC.getDriver().ResourceDir);
2355 const llvm::Triple &Triple = TC.getTriple();
2356 // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
2357 StringRef OSLibName =
2358 (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
2359 llvm::sys::path::append(Res, "lib", OSLibName);
2363 SmallString<128> tools::getCompilerRT(const ToolChain &TC, StringRef Component,
2365 const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
2369 bool IsOSWindows = TC.getTriple().isOSWindows();
2370 bool IsITANMSVCWindows = TC.getTriple().isWindowsMSVCEnvironment() ||
2371 TC.getTriple().isWindowsItaniumEnvironment();
2372 StringRef Arch = getArchNameForCompilerRTLib(TC);
2373 const char *Prefix = IsITANMSVCWindows ? "" : "lib";
2374 const char *Suffix =
2375 Shared ? (IsOSWindows ? ".dll" : ".so") : (IsITANMSVCWindows ? ".lib" : ".a");
2377 SmallString<128> Path = getCompilerRTLibDir(TC);
2378 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
2379 Arch + Env + Suffix);
2384 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2385 // FIXME: Make sure we can also emit shared objects if they're requested
2386 // and available, check for possible errors, etc.
2387 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2388 ArgStringList &CmdArgs) {
2389 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
2391 if (!TC.getTriple().isOSWindows()) {
2392 // FIXME: why do we link against gcc when we are using compiler-rt?
2393 CmdArgs.push_back("-lgcc_s");
2394 if (TC.getDriver().CCCIsCXX())
2395 CmdArgs.push_back("-lgcc_eh");
2399 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
2400 ArgStringList &CmdArgs) {
2401 if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2403 Args.hasArg(options::OPT_fprofile_generate) ||
2404 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
2405 Args.hasArg(options::OPT_fprofile_instr_generate) ||
2406 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
2407 Args.hasArg(options::OPT_fcreate_profile) ||
2408 Args.hasArg(options::OPT_coverage)))
2411 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
2415 enum OpenMPRuntimeKind {
2416 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2417 /// without knowing what runtime to target.
2420 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2421 /// the default for Clang.
2424 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2425 /// this runtime but can swallow the pragmas, and find and link against the
2426 /// runtime library itself.
2429 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2430 /// OpenMP runtime. We support this mode for users with existing dependencies
2431 /// on this runtime library name.
2436 /// Compute the desired OpenMP runtime from the flag provided.
2437 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2438 const ArgList &Args) {
2439 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2441 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2443 RuntimeName = A->getValue();
2445 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2446 .Case("libomp", OMPRT_OMP)
2447 .Case("libgomp", OMPRT_GOMP)
2448 .Case("libiomp5", OMPRT_IOMP5)
2449 .Default(OMPRT_Unknown);
2451 if (RT == OMPRT_Unknown) {
2453 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2454 << A->getOption().getName() << A->getValue();
2456 // FIXME: We could use a nicer diagnostic here.
2457 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2463 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2464 const ArgList &Args) {
2465 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2466 options::OPT_fno_openmp, false))
2469 switch (getOpenMPRuntime(TC, Args)) {
2471 CmdArgs.push_back("-lomp");
2474 CmdArgs.push_back("-lgomp");
2477 CmdArgs.push_back("-liomp5");
2480 // Already diagnosed.
2485 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2486 ArgStringList &CmdArgs, StringRef Sanitizer,
2488 // Static runtimes must be forced into executable, so we wrap them in
2491 CmdArgs.push_back("-whole-archive");
2492 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared)));
2494 CmdArgs.push_back("-no-whole-archive");
2497 // Tries to use a file with the list of dynamic symbols that need to be exported
2498 // from the runtime library. Returns true if the file was found.
2499 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2500 ArgStringList &CmdArgs,
2501 StringRef Sanitizer) {
2502 SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
2503 if (llvm::sys::fs::exists(SanRT + ".syms")) {
2504 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2510 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2511 ArgStringList &CmdArgs) {
2512 // Force linking against the system libraries sanitizers depends on
2513 // (see PR15823 why this is necessary).
2514 CmdArgs.push_back("--no-as-needed");
2515 CmdArgs.push_back("-lpthread");
2516 CmdArgs.push_back("-lrt");
2517 CmdArgs.push_back("-lm");
2518 // There's no libdl on FreeBSD.
2519 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2520 CmdArgs.push_back("-ldl");
2524 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2525 SmallVectorImpl<StringRef> &SharedRuntimes,
2526 SmallVectorImpl<StringRef> &StaticRuntimes,
2527 SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2528 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2529 // Collect shared runtimes.
2530 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2531 SharedRuntimes.push_back("asan");
2534 // Collect static runtimes.
2535 if (Args.hasArg(options::OPT_shared) ||
2536 (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
2537 // Don't link static runtimes into DSOs or if compiling for Android.
2540 if (SanArgs.needsAsanRt()) {
2541 if (SanArgs.needsSharedAsanRt()) {
2542 HelperStaticRuntimes.push_back("asan-preinit");
2544 StaticRuntimes.push_back("asan");
2545 if (SanArgs.linkCXXRuntimes())
2546 StaticRuntimes.push_back("asan_cxx");
2549 if (SanArgs.needsDfsanRt())
2550 StaticRuntimes.push_back("dfsan");
2551 if (SanArgs.needsLsanRt())
2552 StaticRuntimes.push_back("lsan");
2553 if (SanArgs.needsMsanRt()) {
2554 StaticRuntimes.push_back("msan");
2555 if (SanArgs.linkCXXRuntimes())
2556 StaticRuntimes.push_back("msan_cxx");
2558 if (SanArgs.needsTsanRt()) {
2559 StaticRuntimes.push_back("tsan");
2560 if (SanArgs.linkCXXRuntimes())
2561 StaticRuntimes.push_back("tsan_cxx");
2563 if (SanArgs.needsUbsanRt()) {
2564 StaticRuntimes.push_back("ubsan_standalone");
2565 if (SanArgs.linkCXXRuntimes())
2566 StaticRuntimes.push_back("ubsan_standalone_cxx");
2568 if (SanArgs.needsSafeStackRt())
2569 StaticRuntimes.push_back("safestack");
2572 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2573 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2574 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2575 ArgStringList &CmdArgs) {
2576 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2577 HelperStaticRuntimes;
2578 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2579 HelperStaticRuntimes);
2580 for (auto RT : SharedRuntimes)
2581 addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2582 for (auto RT : HelperStaticRuntimes)
2583 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2584 bool AddExportDynamic = false;
2585 for (auto RT : StaticRuntimes) {
2586 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2587 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2589 // If there is a static runtime with no dynamic list, force all the symbols
2590 // to be dynamic to be sure we export sanitizer interface functions.
2591 if (AddExportDynamic)
2592 CmdArgs.push_back("-export-dynamic");
2593 return !StaticRuntimes.empty();
2596 static bool areOptimizationsEnabled(const ArgList &Args) {
2597 // Find the last -O arg and see if it is non-zero.
2598 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2599 return !A->getOption().matches(options::OPT_O0);
2604 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2605 const llvm::Triple &Triple) {
2606 // XCore never wants frame pointers, regardless of OS.
2607 if (Triple.getArch() == llvm::Triple::xcore) {
2611 if (Triple.isOSLinux()) {
2612 switch (Triple.getArch()) {
2613 // Don't use a frame pointer on linux if optimizing for certain targets.
2614 case llvm::Triple::mips64:
2615 case llvm::Triple::mips64el:
2616 case llvm::Triple::mips:
2617 case llvm::Triple::mipsel:
2618 case llvm::Triple::systemz:
2619 case llvm::Triple::x86:
2620 case llvm::Triple::x86_64:
2621 return !areOptimizationsEnabled(Args);
2627 if (Triple.isOSWindows()) {
2628 switch (Triple.getArch()) {
2629 case llvm::Triple::x86:
2630 return !areOptimizationsEnabled(Args);
2632 // All other supported Windows ISAs use xdata unwind information, so frame
2633 // pointers are not generally useful.
2641 static bool shouldUseFramePointer(const ArgList &Args,
2642 const llvm::Triple &Triple) {
2643 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2644 options::OPT_fomit_frame_pointer))
2645 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2647 return shouldUseFramePointerForTarget(Args, Triple);
2650 static bool shouldUseLeafFramePointer(const ArgList &Args,
2651 const llvm::Triple &Triple) {
2652 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2653 options::OPT_momit_leaf_frame_pointer))
2654 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2656 if (Triple.isPS4CPU())
2659 return shouldUseFramePointerForTarget(Args, Triple);
2662 /// Add a CC1 option to specify the debug compilation directory.
2663 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2664 SmallString<128> cwd;
2665 if (!llvm::sys::fs::current_path(cwd)) {
2666 CmdArgs.push_back("-fdebug-compilation-dir");
2667 CmdArgs.push_back(Args.MakeArgString(cwd));
2671 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2672 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2673 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2674 SmallString<128> T(FinalOutput->getValue());
2675 llvm::sys::path::replace_extension(T, "dwo");
2676 return Args.MakeArgString(T);
2678 // Use the compilation dir.
2680 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2681 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2682 llvm::sys::path::replace_extension(F, "dwo");
2684 return Args.MakeArgString(F);
2688 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2689 const JobAction &JA, const ArgList &Args,
2690 const InputInfo &Output, const char *OutFile) {
2691 ArgStringList ExtractArgs;
2692 ExtractArgs.push_back("--extract-dwo");
2694 ArgStringList StripArgs;
2695 StripArgs.push_back("--strip-dwo");
2697 // Grabbing the output of the earlier compile step.
2698 StripArgs.push_back(Output.getFilename());
2699 ExtractArgs.push_back(Output.getFilename());
2700 ExtractArgs.push_back(OutFile);
2702 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2704 // First extract the dwo sections.
2705 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
2707 // Then remove them from the original .o file.
2708 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
2711 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2712 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2713 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2714 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2715 if (A->getOption().matches(options::OPT_O4) ||
2716 A->getOption().matches(options::OPT_Ofast))
2719 if (A->getOption().matches(options::OPT_O0))
2722 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2725 StringRef S(A->getValue());
2729 // Don't vectorize -Oz, unless it's the slp vectorizer.
2733 unsigned OptLevel = 0;
2734 if (S.getAsInteger(10, OptLevel))
2737 return OptLevel > 1;
2743 /// Add -x lang to \p CmdArgs for \p Input.
2744 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
2745 ArgStringList &CmdArgs) {
2746 // When using -verify-pch, we don't want to provide the type
2747 // 'precompiled-header' if it was inferred from the file extension
2748 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
2751 CmdArgs.push_back("-x");
2752 if (Args.hasArg(options::OPT_rewrite_objc))
2753 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
2755 CmdArgs.push_back(types::getTypeName(Input.getType()));
2758 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
2760 return VersionTuple(Version);
2762 if (Version < 10000)
2763 return VersionTuple(Version / 100, Version % 100);
2765 unsigned Build = 0, Factor = 1;
2766 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
2767 Build = Build + (Version % 10) * Factor;
2768 return VersionTuple(Version / 100, Version % 100, Build);
2771 // Claim options we don't want to warn if they are unused. We do this for
2772 // options that build systems might add but are unused when assembling or only
2773 // running the preprocessor for example.
2774 static void claimNoWarnArgs(const ArgList &Args) {
2775 // Don't warn about unused -f(no-)?lto. This can happen when we're
2776 // preprocessing, precompiling or assembling.
2777 Args.ClaimAllArgs(options::OPT_flto);
2778 Args.ClaimAllArgs(options::OPT_fno_lto);
2781 static void appendUserToPath(SmallVectorImpl<char> &Result) {
2783 const char *Username = getenv("LOGNAME");
2785 const char *Username = getenv("USERNAME");
2788 // Validate that LoginName can be used in a path, and get its length.
2790 for (const char *P = Username; *P; ++P, ++Len) {
2791 if (!isAlphanumeric(*P) && *P != '_') {
2797 if (Username && Len > 0) {
2798 Result.append(Username, Username + Len);
2803 // Fallback to user id.
2805 std::string UID = llvm::utostr(getuid());
2807 // FIXME: Windows seems to have an 'SID' that might work.
2808 std::string UID = "9999";
2810 Result.append(UID.begin(), UID.end());
2813 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
2814 const llvm::Triple &Triple,
2815 const llvm::opt::ArgList &Args,
2816 bool IsWindowsMSVC) {
2817 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2819 Args.hasArg(options::OPT_fmsc_version) ||
2820 Args.hasArg(options::OPT_fms_compatibility_version)) {
2821 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
2822 const Arg *MSCompatibilityVersion =
2823 Args.getLastArg(options::OPT_fms_compatibility_version);
2825 if (MSCVersion && MSCompatibilityVersion) {
2827 D->Diag(diag::err_drv_argument_not_allowed_with)
2828 << MSCVersion->getAsString(Args)
2829 << MSCompatibilityVersion->getAsString(Args);
2830 return VersionTuple();
2833 if (MSCompatibilityVersion) {
2835 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
2836 D->Diag(diag::err_drv_invalid_value)
2837 << MSCompatibilityVersion->getAsString(Args)
2838 << MSCompatibilityVersion->getValue();
2843 unsigned Version = 0;
2844 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
2845 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
2846 << MSCVersion->getValue();
2847 return getMSCompatibilityVersion(Version);
2850 unsigned Major, Minor, Micro;
2851 Triple.getEnvironmentVersion(Major, Minor, Micro);
2852 if (Major || Minor || Micro)
2853 return VersionTuple(Major, Minor, Micro);
2855 return VersionTuple(18);
2857 return VersionTuple();
2860 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
2861 const InputInfo &Output, const ArgList &Args,
2862 ArgStringList &CmdArgs) {
2863 auto *ProfileGenerateArg = Args.getLastArg(
2864 options::OPT_fprofile_instr_generate,
2865 options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
2866 options::OPT_fprofile_generate_EQ);
2868 auto *ProfileUseArg = Args.getLastArg(
2869 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
2870 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
2872 if (ProfileGenerateArg && ProfileUseArg)
2873 D.Diag(diag::err_drv_argument_not_allowed_with)
2874 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
2876 if (ProfileGenerateArg &&
2877 ProfileGenerateArg->getOption().matches(
2878 options::OPT_fprofile_instr_generate_EQ))
2879 ProfileGenerateArg->render(Args, CmdArgs);
2880 else if (ProfileGenerateArg &&
2881 ProfileGenerateArg->getOption().matches(
2882 options::OPT_fprofile_generate_EQ)) {
2883 SmallString<128> Path(ProfileGenerateArg->getValue());
2884 llvm::sys::path::append(Path, "default.profraw");
2886 Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
2888 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
2890 if (ProfileUseArg &&
2891 ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
2892 ProfileUseArg->render(Args, CmdArgs);
2893 else if (ProfileUseArg &&
2894 (ProfileUseArg->getOption().matches(options::OPT_fprofile_use_EQ) ||
2895 ProfileUseArg->getOption().matches(
2896 options::OPT_fprofile_instr_use))) {
2897 SmallString<128> Path(
2898 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
2899 if (Path.empty() || llvm::sys::fs::is_directory(Path))
2900 llvm::sys::path::append(Path, "default.profdata");
2901 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
2904 if (Args.hasArg(options::OPT_ftest_coverage) ||
2905 Args.hasArg(options::OPT_coverage))
2906 CmdArgs.push_back("-femit-coverage-notes");
2907 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2909 Args.hasArg(options::OPT_coverage))
2910 CmdArgs.push_back("-femit-coverage-data");
2912 if (Args.hasArg(options::OPT_fcoverage_mapping) && !ProfileGenerateArg)
2913 D.Diag(diag::err_drv_argument_only_allowed_with)
2914 << "-fcoverage-mapping"
2915 << "-fprofile-instr-generate";
2917 if (Args.hasArg(options::OPT_fcoverage_mapping))
2918 CmdArgs.push_back("-fcoverage-mapping");
2920 if (C.getArgs().hasArg(options::OPT_c) ||
2921 C.getArgs().hasArg(options::OPT_S)) {
2922 if (Output.isFilename()) {
2923 CmdArgs.push_back("-coverage-file");
2924 SmallString<128> CoverageFilename;
2925 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
2926 CoverageFilename = FinalOutput->getValue();
2928 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
2930 if (llvm::sys::path::is_relative(CoverageFilename)) {
2931 SmallString<128> Pwd;
2932 if (!llvm::sys::fs::current_path(Pwd)) {
2933 llvm::sys::path::append(Pwd, CoverageFilename);
2934 CoverageFilename.swap(Pwd);
2937 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
2942 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2943 const InputInfo &Output, const InputInfoList &Inputs,
2944 const ArgList &Args, const char *LinkingOutput) const {
2946 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
2947 const Driver &D = getToolChain().getDriver();
2948 ArgStringList CmdArgs;
2950 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
2951 bool IsWindowsCygnus =
2952 getToolChain().getTriple().isWindowsCygwinEnvironment();
2953 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
2955 // Check number of inputs for sanity. We need at least one input.
2956 assert(Inputs.size() >= 1 && "Must have at least one input.");
2957 const InputInfo &Input = Inputs[0];
2958 // CUDA compilation may have multiple inputs (source file + results of
2959 // device-side compilations). All other jobs are expected to have exactly one
2961 bool IsCuda = types::isCuda(Input.getType());
2962 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
2964 // Invoke ourselves in -cc1 mode.
2966 // FIXME: Implement custom jobs for internal actions.
2967 CmdArgs.push_back("-cc1");
2969 // Add the "effective" target triple.
2970 CmdArgs.push_back("-triple");
2971 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2972 CmdArgs.push_back(Args.MakeArgString(TripleStr));
2974 const llvm::Triple TT(TripleStr);
2975 if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
2976 TT.getArch() == llvm::Triple::thumb)) {
2977 unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
2979 TT.getArchName().substr(Offset).getAsInteger(10, Version);
2981 D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
2985 // Push all default warning arguments that are specific to
2986 // the given target. These come before user provided warning options
2988 getToolChain().addClangWarningOptions(CmdArgs);
2990 // Select the appropriate action.
2991 RewriteKind rewriteKind = RK_None;
2993 if (isa<AnalyzeJobAction>(JA)) {
2994 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2995 CmdArgs.push_back("-analyze");
2996 } else if (isa<MigrateJobAction>(JA)) {
2997 CmdArgs.push_back("-migrate");
2998 } else if (isa<PreprocessJobAction>(JA)) {
2999 if (Output.getType() == types::TY_Dependencies)
3000 CmdArgs.push_back("-Eonly");
3002 CmdArgs.push_back("-E");
3003 if (Args.hasArg(options::OPT_rewrite_objc) &&
3004 !Args.hasArg(options::OPT_g_Group))
3005 CmdArgs.push_back("-P");
3007 } else if (isa<AssembleJobAction>(JA)) {
3008 CmdArgs.push_back("-emit-obj");
3010 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3012 // Also ignore explicit -force_cpusubtype_ALL option.
3013 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3014 } else if (isa<PrecompileJobAction>(JA)) {
3015 // Use PCH if the user requested it.
3016 bool UsePCH = D.CCCUsePCH;
3018 if (JA.getType() == types::TY_Nothing)
3019 CmdArgs.push_back("-fsyntax-only");
3021 CmdArgs.push_back("-emit-pch");
3023 CmdArgs.push_back("-emit-pth");
3024 } else if (isa<VerifyPCHJobAction>(JA)) {
3025 CmdArgs.push_back("-verify-pch");
3027 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3028 "Invalid action for clang tool.");
3030 if (JA.getType() == types::TY_LTO_IR || JA.getType() == types::TY_LTO_BC) {
3031 CmdArgs.push_back("-flto");
3033 if (JA.getType() == types::TY_Nothing) {
3034 CmdArgs.push_back("-fsyntax-only");
3035 } else if (JA.getType() == types::TY_LLVM_IR ||
3036 JA.getType() == types::TY_LTO_IR) {
3037 CmdArgs.push_back("-emit-llvm");
3038 } else if (JA.getType() == types::TY_LLVM_BC ||
3039 JA.getType() == types::TY_LTO_BC) {
3040 CmdArgs.push_back("-emit-llvm-bc");
3041 } else if (JA.getType() == types::TY_PP_Asm) {
3042 CmdArgs.push_back("-S");
3043 } else if (JA.getType() == types::TY_AST) {
3044 CmdArgs.push_back("-emit-pch");
3045 } else if (JA.getType() == types::TY_ModuleFile) {
3046 CmdArgs.push_back("-module-file-info");
3047 } else if (JA.getType() == types::TY_RewrittenObjC) {
3048 CmdArgs.push_back("-rewrite-objc");
3049 rewriteKind = RK_NonFragile;
3050 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3051 CmdArgs.push_back("-rewrite-objc");
3052 rewriteKind = RK_Fragile;
3054 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3057 // Preserve use-list order by default when emitting bitcode, so that
3058 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3059 // same result as running passes here. For LTO, we don't need to preserve
3060 // the use-list order, since serialization to bitcode is part of the flow.
3061 if (JA.getType() == types::TY_LLVM_BC)
3062 CmdArgs.push_back("-emit-llvm-uselists");
3065 // We normally speed up the clang process a bit by skipping destructors at
3066 // exit, but when we're generating diagnostics we can rely on some of the
3068 if (!C.isForDiagnostics())
3069 CmdArgs.push_back("-disable-free");
3071 // Disable the verification pass in -asserts builds.
3073 CmdArgs.push_back("-disable-llvm-verifier");
3076 // Set the main file name, so that debug info works even with
3078 CmdArgs.push_back("-main-file-name");
3079 CmdArgs.push_back(getBaseInputName(Args, Input));
3081 // Some flags which affect the language (via preprocessor
3083 if (Args.hasArg(options::OPT_static))
3084 CmdArgs.push_back("-static-define");
3086 if (isa<AnalyzeJobAction>(JA)) {
3087 // Enable region store model by default.
3088 CmdArgs.push_back("-analyzer-store=region");
3090 // Treat blocks as analysis entry points.
3091 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3093 CmdArgs.push_back("-analyzer-eagerly-assume");
3095 // Add default argument set.
3096 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3097 CmdArgs.push_back("-analyzer-checker=core");
3100 CmdArgs.push_back("-analyzer-checker=unix");
3102 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3103 CmdArgs.push_back("-analyzer-checker=osx");
3105 CmdArgs.push_back("-analyzer-checker=deadcode");
3107 if (types::isCXX(Input.getType()))
3108 CmdArgs.push_back("-analyzer-checker=cplusplus");
3110 // Enable the following experimental checkers for testing.
3112 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3113 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3114 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3115 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3116 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3117 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3120 // Set the output format. The default is plist, for (lame) historical
3122 CmdArgs.push_back("-analyzer-output");
3123 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3124 CmdArgs.push_back(A->getValue());
3126 CmdArgs.push_back("plist");
3128 // Disable the presentation of standard compiler warnings when
3129 // using --analyze. We only want to show static analyzer diagnostics
3130 // or frontend errors.
3131 CmdArgs.push_back("-w");
3133 // Add -Xanalyzer arguments when running as analyzer.
3134 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3137 CheckCodeGenerationOptions(D, Args);
3139 bool PIE = getToolChain().isPIEDefault();
3140 bool PIC = PIE || getToolChain().isPICDefault();
3141 bool IsPICLevelTwo = PIC;
3143 // Android-specific defaults for PIC/PIE
3144 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
3145 switch (getToolChain().getArch()) {
3146 case llvm::Triple::arm:
3147 case llvm::Triple::armeb:
3148 case llvm::Triple::thumb:
3149 case llvm::Triple::thumbeb:
3150 case llvm::Triple::aarch64:
3151 case llvm::Triple::mips:
3152 case llvm::Triple::mipsel:
3153 case llvm::Triple::mips64:
3154 case llvm::Triple::mips64el:
3155 PIC = true; // "-fpic"
3158 case llvm::Triple::x86:
3159 case llvm::Triple::x86_64:
3160 PIC = true; // "-fPIC"
3161 IsPICLevelTwo = true;
3169 // OpenBSD-specific defaults for PIE
3170 if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
3171 switch (getToolChain().getArch()) {
3172 case llvm::Triple::mips64:
3173 case llvm::Triple::mips64el:
3174 case llvm::Triple::sparcel:
3175 case llvm::Triple::x86:
3176 case llvm::Triple::x86_64:
3177 IsPICLevelTwo = false; // "-fpie"
3180 case llvm::Triple::ppc:
3181 case llvm::Triple::sparc:
3182 case llvm::Triple::sparcv9:
3183 IsPICLevelTwo = true; // "-fPIE"
3191 // For the PIC and PIE flag options, this logic is different from the
3192 // legacy logic in very old versions of GCC, as that logic was just
3193 // a bug no one had ever fixed. This logic is both more rational and
3194 // consistent with GCC's new logic now that the bugs are fixed. The last
3195 // argument relating to either PIC or PIE wins, and no other argument is
3196 // used. If the last argument is any flavor of the '-fno-...' arguments,
3197 // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
3198 // at the same level.
3199 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3200 options::OPT_fpic, options::OPT_fno_pic,
3201 options::OPT_fPIE, options::OPT_fno_PIE,
3202 options::OPT_fpie, options::OPT_fno_pie);
3203 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3204 // is forced, then neither PIC nor PIE flags will have no effect.
3205 if (!getToolChain().isPICDefaultForced()) {
3207 Option O = LastPICArg->getOption();
3208 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3209 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3210 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3212 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3214 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3221 // Introduce a Darwin-specific hack. If the default is PIC but the flags
3222 // specified while enabling PIC enabled level 1 PIC, just force it back to
3223 // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
3224 // informal testing).
3225 if (PIC && getToolChain().getTriple().isOSDarwin())
3226 IsPICLevelTwo |= getToolChain().isPICDefault();
3228 // Note that these flags are trump-cards. Regardless of the order w.r.t. the
3229 // PIC or PIE options above, if these show up, PIC is disabled.
3230 llvm::Triple Triple(TripleStr);
3231 if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
3233 if (Args.hasArg(options::OPT_static))
3236 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3237 // This is a very special mode. It trumps the other modes, almost no one
3238 // uses it, and it isn't even valid on any OS but Darwin.
3239 if (!getToolChain().getTriple().isOSDarwin())
3240 D.Diag(diag::err_drv_unsupported_opt_for_target)
3241 << A->getSpelling() << getToolChain().getTriple().str();
3243 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3245 CmdArgs.push_back("-mrelocation-model");
3246 CmdArgs.push_back("dynamic-no-pic");
3248 // Only a forced PIC mode can cause the actual compile to have PIC defines
3249 // etc., no flags are sufficient. This behavior was selected to closely
3250 // match that of llvm-gcc and Apple GCC before that.
3251 if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
3252 CmdArgs.push_back("-pic-level");
3253 CmdArgs.push_back("2");
3256 // Currently, LLVM only knows about PIC vs. static; the PIE differences are
3257 // handled in Clang's IRGen by the -pie-level flag.
3258 CmdArgs.push_back("-mrelocation-model");
3259 CmdArgs.push_back(PIC ? "pic" : "static");
3262 CmdArgs.push_back("-pic-level");
3263 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3265 CmdArgs.push_back("-pie-level");
3266 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3271 CmdArgs.push_back("-mthread-model");
3272 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3273 CmdArgs.push_back(A->getValue());
3275 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3277 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3279 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3280 options::OPT_fno_merge_all_constants))
3281 CmdArgs.push_back("-fno-merge-all-constants");
3283 // LLVM Code Generator Options.
3285 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3286 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3287 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3288 options::OPT_frewrite_map_file_EQ)) {
3289 CmdArgs.push_back("-frewrite-map-file");
3290 CmdArgs.push_back(A->getValue());
3295 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3296 StringRef v = A->getValue();
3297 CmdArgs.push_back("-mllvm");
3298 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3302 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3303 CmdArgs.push_back("-mregparm");
3304 CmdArgs.push_back(A->getValue());
3307 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3308 options::OPT_freg_struct_return)) {
3309 if (getToolChain().getArch() != llvm::Triple::x86) {
3310 D.Diag(diag::err_drv_unsupported_opt_for_target)
3311 << A->getSpelling() << getToolChain().getTriple().str();
3312 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3313 CmdArgs.push_back("-fpcc-struct-return");
3315 assert(A->getOption().matches(options::OPT_freg_struct_return));
3316 CmdArgs.push_back("-freg-struct-return");
3320 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3321 CmdArgs.push_back("-mrtd");
3323 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3324 CmdArgs.push_back("-mdisable-fp-elim");
3325 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3326 options::OPT_fno_zero_initialized_in_bss))
3327 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3329 bool OFastEnabled = isOptimizationLevelFast(Args);
3330 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3331 // enabled. This alias option is being used to simplify the hasFlag logic.
3332 OptSpecifier StrictAliasingAliasOption =
3333 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3334 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3335 // doesn't do any TBAA.
3336 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3337 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3338 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3339 CmdArgs.push_back("-relaxed-aliasing");
3340 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3341 options::OPT_fno_struct_path_tbaa))
3342 CmdArgs.push_back("-no-struct-path-tbaa");
3343 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3345 CmdArgs.push_back("-fstrict-enums");
3346 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3347 options::OPT_fno_optimize_sibling_calls))
3348 CmdArgs.push_back("-mdisable-tail-calls");
3350 // Handle segmented stacks.
3351 if (Args.hasArg(options::OPT_fsplit_stack))
3352 CmdArgs.push_back("-split-stacks");
3354 // If -Ofast is the optimization level, then -ffast-math should be enabled.
3355 // This alias option is being used to simplify the getLastArg logic.
3356 OptSpecifier FastMathAliasOption =
3357 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3359 // Handle various floating point optimization flags, mapping them to the
3360 // appropriate LLVM code generation flags. The pattern for all of these is to
3361 // default off the codegen optimizations, and if any flag enables them and no
3362 // flag disables them after the flag enabling them, enable the codegen
3363 // optimization. This is complicated by several "umbrella" flags.
3364 if (Arg *A = Args.getLastArg(
3365 options::OPT_ffast_math, FastMathAliasOption,
3366 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3367 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3368 options::OPT_fno_honor_infinities))
3369 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3370 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3371 A->getOption().getID() != options::OPT_fhonor_infinities)
3372 CmdArgs.push_back("-menable-no-infs");
3373 if (Arg *A = Args.getLastArg(
3374 options::OPT_ffast_math, FastMathAliasOption,
3375 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3376 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3377 options::OPT_fno_honor_nans))
3378 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3379 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3380 A->getOption().getID() != options::OPT_fhonor_nans)
3381 CmdArgs.push_back("-menable-no-nans");
3383 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3384 bool MathErrno = getToolChain().IsMathErrnoDefault();
3386 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3387 options::OPT_fno_fast_math, options::OPT_fmath_errno,
3388 options::OPT_fno_math_errno)) {
3389 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3390 // However, turning *off* -ffast_math merely restores the toolchain default
3391 // (which may be false).
3392 if (A->getOption().getID() == options::OPT_fno_math_errno ||
3393 A->getOption().getID() == options::OPT_ffast_math ||
3394 A->getOption().getID() == options::OPT_Ofast)
3396 else if (A->getOption().getID() == options::OPT_fmath_errno)
3400 CmdArgs.push_back("-fmath-errno");
3402 // There are several flags which require disabling very specific
3403 // optimizations. Any of these being disabled forces us to turn off the
3404 // entire set of LLVM optimizations, so collect them through all the flag
3406 bool AssociativeMath = false;
3407 if (Arg *A = Args.getLastArg(
3408 options::OPT_ffast_math, FastMathAliasOption,
3409 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3410 options::OPT_fno_unsafe_math_optimizations,
3411 options::OPT_fassociative_math, options::OPT_fno_associative_math))
3412 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3413 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3414 A->getOption().getID() != options::OPT_fno_associative_math)
3415 AssociativeMath = true;
3416 bool ReciprocalMath = false;
3417 if (Arg *A = Args.getLastArg(
3418 options::OPT_ffast_math, FastMathAliasOption,
3419 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3420 options::OPT_fno_unsafe_math_optimizations,
3421 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3422 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3423 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3424 A->getOption().getID() != options::OPT_fno_reciprocal_math)
3425 ReciprocalMath = true;
3426 bool SignedZeros = true;
3427 if (Arg *A = Args.getLastArg(
3428 options::OPT_ffast_math, FastMathAliasOption,
3429 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3430 options::OPT_fno_unsafe_math_optimizations,
3431 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3432 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3433 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3434 A->getOption().getID() != options::OPT_fsigned_zeros)
3435 SignedZeros = false;
3436 bool TrappingMath = true;
3437 if (Arg *A = Args.getLastArg(
3438 options::OPT_ffast_math, FastMathAliasOption,
3439 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3440 options::OPT_fno_unsafe_math_optimizations,
3441 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3442 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3443 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3444 A->getOption().getID() != options::OPT_ftrapping_math)
3445 TrappingMath = false;
3446 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3448 CmdArgs.push_back("-menable-unsafe-fp-math");
3451 CmdArgs.push_back("-fno-signed-zeros");
3454 CmdArgs.push_back("-freciprocal-math");
3456 // Validate and pass through -fp-contract option.
3457 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3458 options::OPT_fno_fast_math,
3459 options::OPT_ffp_contract)) {
3460 if (A->getOption().getID() == options::OPT_ffp_contract) {
3461 StringRef Val = A->getValue();
3462 if (Val == "fast" || Val == "on" || Val == "off") {
3463 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3465 D.Diag(diag::err_drv_unsupported_option_argument)
3466 << A->getOption().getName() << Val;
3468 } else if (A->getOption().matches(options::OPT_ffast_math) ||
3469 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3470 // If fast-math is set then set the fp-contract mode to fast.
3471 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3475 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3477 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3478 // and if we find them, tell the frontend to provide the appropriate
3479 // preprocessor macros. This is distinct from enabling any optimizations as
3480 // these options induce language changes which must survive serialization
3481 // and deserialization, etc.
3482 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3483 options::OPT_fno_fast_math))
3484 if (!A->getOption().matches(options::OPT_fno_fast_math))
3485 CmdArgs.push_back("-ffast-math");
3486 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3487 options::OPT_fno_fast_math))
3488 if (A->getOption().matches(options::OPT_ffinite_math_only))
3489 CmdArgs.push_back("-ffinite-math-only");
3491 // Decide whether to use verbose asm. Verbose assembly is the default on
3492 // toolchains which have the integrated assembler on by default.
3493 bool IsIntegratedAssemblerDefault =
3494 getToolChain().IsIntegratedAssemblerDefault();
3495 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3496 IsIntegratedAssemblerDefault) ||
3497 Args.hasArg(options::OPT_dA))
3498 CmdArgs.push_back("-masm-verbose");
3500 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3501 IsIntegratedAssemblerDefault))
3502 CmdArgs.push_back("-no-integrated-as");
3504 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3505 CmdArgs.push_back("-mdebug-pass");
3506 CmdArgs.push_back("Structure");
3508 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3509 CmdArgs.push_back("-mdebug-pass");
3510 CmdArgs.push_back("Arguments");
3513 // Enable -mconstructor-aliases except on darwin, where we have to
3514 // work around a linker bug; see <rdar://problem/7651567>.
3515 if (!getToolChain().getTriple().isOSDarwin())
3516 CmdArgs.push_back("-mconstructor-aliases");
3518 // Darwin's kernel doesn't support guard variables; just die if we
3520 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3521 CmdArgs.push_back("-fforbid-guard-variables");
3523 if (Args.hasArg(options::OPT_mms_bitfields)) {
3524 CmdArgs.push_back("-mms-bitfields");
3527 // This is a coarse approximation of what llvm-gcc actually does, both
3528 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3529 // complicated ways.
3530 bool AsynchronousUnwindTables =
3531 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3532 options::OPT_fno_asynchronous_unwind_tables,
3533 (getToolChain().IsUnwindTablesDefault() ||
3534 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3536 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3537 AsynchronousUnwindTables))
3538 CmdArgs.push_back("-munwind-tables");
3540 getToolChain().addClangTargetOptions(Args, CmdArgs);
3542 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3543 CmdArgs.push_back("-mlimit-float-precision");
3544 CmdArgs.push_back(A->getValue());
3547 // FIXME: Handle -mtune=.
3548 (void)Args.hasArg(options::OPT_mtune_EQ);
3550 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3551 CmdArgs.push_back("-mcode-model");
3552 CmdArgs.push_back(A->getValue());
3555 // Add the target cpu
3556 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3558 CmdArgs.push_back("-target-cpu");
3559 CmdArgs.push_back(Args.MakeArgString(CPU));
3562 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3563 CmdArgs.push_back("-mfpmath");
3564 CmdArgs.push_back(A->getValue());
3567 // Add the target features
3568 getTargetFeatures(D, Triple, Args, CmdArgs, false);
3570 // Add target specific flags.
3571 switch (getToolChain().getArch()) {
3575 case llvm::Triple::arm:
3576 case llvm::Triple::armeb:
3577 case llvm::Triple::thumb:
3578 case llvm::Triple::thumbeb:
3579 AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
3582 case llvm::Triple::aarch64:
3583 case llvm::Triple::aarch64_be:
3584 AddAArch64TargetArgs(Args, CmdArgs);
3587 case llvm::Triple::mips:
3588 case llvm::Triple::mipsel:
3589 case llvm::Triple::mips64:
3590 case llvm::Triple::mips64el:
3591 AddMIPSTargetArgs(Args, CmdArgs);
3594 case llvm::Triple::ppc:
3595 case llvm::Triple::ppc64:
3596 case llvm::Triple::ppc64le:
3597 AddPPCTargetArgs(Args, CmdArgs);
3600 case llvm::Triple::sparc:
3601 case llvm::Triple::sparcel:
3602 case llvm::Triple::sparcv9:
3603 AddSparcTargetArgs(Args, CmdArgs);
3606 case llvm::Triple::x86:
3607 case llvm::Triple::x86_64:
3608 AddX86TargetArgs(Args, CmdArgs);
3611 case llvm::Triple::hexagon:
3612 AddHexagonTargetArgs(Args, CmdArgs);
3616 // Add clang-cl arguments.
3617 if (getToolChain().getDriver().IsCLMode())
3618 AddClangCLArgs(Args, CmdArgs);
3620 // Pass the linker version in use.
3621 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3622 CmdArgs.push_back("-target-linker-version");
3623 CmdArgs.push_back(A->getValue());
3626 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
3627 CmdArgs.push_back("-momit-leaf-frame-pointer");
3629 // Explicitly error on some things we know we don't support and can't just
3631 types::ID InputType = Input.getType();
3632 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3634 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
3635 getToolChain().getArch() == llvm::Triple::x86) {
3636 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3637 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3638 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3639 << Unsupported->getOption().getName();
3643 Args.AddAllArgs(CmdArgs, options::OPT_v);
3644 Args.AddLastArg(CmdArgs, options::OPT_H);
3645 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3646 CmdArgs.push_back("-header-include-file");
3647 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3650 Args.AddLastArg(CmdArgs, options::OPT_P);
3651 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3653 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3654 CmdArgs.push_back("-diagnostic-log-file");
3655 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3659 // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
3660 // are preserved, all other debug options are substituted with "-g".
3661 Args.ClaimAllArgs(options::OPT_g_Group);
3662 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3663 if (A->getOption().matches(options::OPT_gline_tables_only) ||
3664 A->getOption().matches(options::OPT_g1)) {
3665 // FIXME: we should support specifying dwarf version with
3666 // -gline-tables-only.
3667 CmdArgs.push_back("-gline-tables-only");
3668 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3669 const llvm::Triple &Triple = getToolChain().getTriple();
3670 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3671 Triple.getOS() == llvm::Triple::FreeBSD ||
3672 Triple.getOS() == llvm::Triple::Solaris)
3673 CmdArgs.push_back("-gdwarf-2");
3674 } else if (A->getOption().matches(options::OPT_gdwarf_2))
3675 CmdArgs.push_back("-gdwarf-2");
3676 else if (A->getOption().matches(options::OPT_gdwarf_3))
3677 CmdArgs.push_back("-gdwarf-3");
3678 else if (A->getOption().matches(options::OPT_gdwarf_4))
3679 CmdArgs.push_back("-gdwarf-4");
3680 else if (!A->getOption().matches(options::OPT_g0) &&
3681 !A->getOption().matches(options::OPT_ggdb0)) {
3682 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3683 const llvm::Triple &Triple = getToolChain().getTriple();
3684 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3685 Triple.getOS() == llvm::Triple::FreeBSD ||
3686 Triple.getOS() == llvm::Triple::Solaris)
3687 CmdArgs.push_back("-gdwarf-2");
3689 CmdArgs.push_back("-g");
3693 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
3694 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3695 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3697 CmdArgs.push_back("-dwarf-column-info");
3699 // FIXME: Move backend command line options to the module.
3700 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3701 // splitting and extraction.
3702 // FIXME: Currently only works on Linux.
3703 if (getToolChain().getTriple().isOSLinux() &&
3704 Args.hasArg(options::OPT_gsplit_dwarf)) {
3705 CmdArgs.push_back("-g");
3706 CmdArgs.push_back("-backend-option");
3707 CmdArgs.push_back("-split-dwarf=Enable");
3710 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3711 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
3712 CmdArgs.push_back("-backend-option");
3713 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
3716 // -gdwarf-aranges turns on the emission of the aranges section in the
3718 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
3719 CmdArgs.push_back("-backend-option");
3720 CmdArgs.push_back("-generate-arange-section");
3723 if (Args.hasFlag(options::OPT_fdebug_types_section,
3724 options::OPT_fno_debug_types_section, false)) {
3725 CmdArgs.push_back("-backend-option");
3726 CmdArgs.push_back("-generate-type-units");
3729 // CloudABI uses -ffunction-sections and -fdata-sections by default.
3730 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
3732 if (Args.hasFlag(options::OPT_ffunction_sections,
3733 options::OPT_fno_function_sections, UseSeparateSections)) {
3734 CmdArgs.push_back("-ffunction-sections");
3737 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3738 UseSeparateSections)) {
3739 CmdArgs.push_back("-fdata-sections");
3742 if (!Args.hasFlag(options::OPT_funique_section_names,
3743 options::OPT_fno_unique_section_names, true))
3744 CmdArgs.push_back("-fno-unique-section-names");
3746 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
3748 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
3750 // Pass options for controlling the default header search paths.
3751 if (Args.hasArg(options::OPT_nostdinc)) {
3752 CmdArgs.push_back("-nostdsysteminc");
3753 CmdArgs.push_back("-nobuiltininc");
3755 if (Args.hasArg(options::OPT_nostdlibinc))
3756 CmdArgs.push_back("-nostdsysteminc");
3757 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3758 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3761 // Pass the path to compiler resource files.
3762 CmdArgs.push_back("-resource-dir");
3763 CmdArgs.push_back(D.ResourceDir.c_str());
3765 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3767 bool ARCMTEnabled = false;
3768 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3769 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3770 options::OPT_ccc_arcmt_modify,
3771 options::OPT_ccc_arcmt_migrate)) {
3772 ARCMTEnabled = true;
3773 switch (A->getOption().getID()) {
3775 llvm_unreachable("missed a case");
3776 case options::OPT_ccc_arcmt_check:
3777 CmdArgs.push_back("-arcmt-check");
3779 case options::OPT_ccc_arcmt_modify:
3780 CmdArgs.push_back("-arcmt-modify");
3782 case options::OPT_ccc_arcmt_migrate:
3783 CmdArgs.push_back("-arcmt-migrate");
3784 CmdArgs.push_back("-mt-migrate-directory");
3785 CmdArgs.push_back(A->getValue());
3787 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3788 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3793 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3794 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3795 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3798 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3800 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
3801 << "-ccc-arcmt-migrate";
3803 CmdArgs.push_back("-mt-migrate-directory");
3804 CmdArgs.push_back(A->getValue());
3806 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3807 options::OPT_objcmt_migrate_subscripting,
3808 options::OPT_objcmt_migrate_property)) {
3809 // None specified, means enable them all.
3810 CmdArgs.push_back("-objcmt-migrate-literals");
3811 CmdArgs.push_back("-objcmt-migrate-subscripting");
3812 CmdArgs.push_back("-objcmt-migrate-property");
3814 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3815 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3816 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3819 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3820 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3821 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3822 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3823 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3824 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3825 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3826 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3827 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3828 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3829 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3830 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3831 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3832 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3833 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3834 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3837 // Add preprocessing options like -I, -D, etc. if we are using the
3840 // FIXME: Support -fpreprocessed
3841 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3842 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3844 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3845 // that "The compiler can only warn and ignore the option if not recognized".
3846 // When building with ccache, it will pass -D options to clang even on
3847 // preprocessed inputs and configure concludes that -fPIC is not supported.
3848 Args.ClaimAllArgs(options::OPT_D);
3850 // Manually translate -O4 to -O3; let clang reject others.
3851 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3852 if (A->getOption().matches(options::OPT_O4)) {
3853 CmdArgs.push_back("-O3");
3854 D.Diag(diag::warn_O4_is_O3);
3856 A->render(Args, CmdArgs);
3860 // Warn about ignored options to clang.
3862 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3863 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3866 claimNoWarnArgs(Args);
3868 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3869 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3870 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3871 CmdArgs.push_back("-pedantic");
3872 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3873 Args.AddLastArg(CmdArgs, options::OPT_w);
3875 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3876 // (-ansi is equivalent to -std=c89 or -std=c++98).
3878 // If a std is supplied, only add -trigraphs if it follows the
3880 bool ImplyVCPPCXXVer = false;
3881 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3882 if (Std->getOption().matches(options::OPT_ansi))
3883 if (types::isCXX(InputType))
3884 CmdArgs.push_back("-std=c++98");
3886 CmdArgs.push_back("-std=c89");
3888 Std->render(Args, CmdArgs);
3890 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3891 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3892 options::OPT_ftrigraphs,
3893 options::OPT_fno_trigraphs))
3895 A->render(Args, CmdArgs);
3897 // Honor -std-default.
3899 // FIXME: Clang doesn't correctly handle -std= when the input language
3900 // doesn't match. For the time being just ignore this for C++ inputs;
3901 // eventually we want to do all the standard defaulting here instead of
3902 // splitting it between the driver and clang -cc1.
3903 if (!types::isCXX(InputType))
3904 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3906 else if (IsWindowsMSVC)
3907 ImplyVCPPCXXVer = true;
3909 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3910 options::OPT_fno_trigraphs);
3913 // GCC's behavior for -Wwrite-strings is a bit strange:
3914 // * In C, this "warning flag" changes the types of string literals from
3915 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3916 // for the discarded qualifier.
3917 // * In C++, this is just a normal warning flag.
3919 // Implementing this warning correctly in C is hard, so we follow GCC's
3920 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3921 // a non-const char* in C, rather than using this crude hack.
3922 if (!types::isCXX(InputType)) {
3923 // FIXME: This should behave just like a warning flag, and thus should also
3924 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3926 Args.getLastArg(options::OPT_Wwrite_strings,
3927 options::OPT_Wno_write_strings, options::OPT_w);
3929 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3930 CmdArgs.push_back("-fconst-strings");
3933 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3934 // during C++ compilation, which it is by default. GCC keeps this define even
3935 // in the presence of '-w', match this behavior bug-for-bug.
3936 if (types::isCXX(InputType) &&
3937 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3939 CmdArgs.push_back("-fdeprecated-macro");
3942 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3943 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3944 if (Asm->getOption().matches(options::OPT_fasm))
3945 CmdArgs.push_back("-fgnu-keywords");
3947 CmdArgs.push_back("-fno-gnu-keywords");
3950 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3951 CmdArgs.push_back("-fno-dwarf-directory-asm");
3953 if (ShouldDisableAutolink(Args, getToolChain()))
3954 CmdArgs.push_back("-fno-autolink");
3956 // Add in -fdebug-compilation-dir if necessary.
3957 addDebugCompDirArg(Args, CmdArgs);
3959 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3960 options::OPT_ftemplate_depth_EQ)) {
3961 CmdArgs.push_back("-ftemplate-depth");
3962 CmdArgs.push_back(A->getValue());
3965 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3966 CmdArgs.push_back("-foperator-arrow-depth");
3967 CmdArgs.push_back(A->getValue());
3970 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3971 CmdArgs.push_back("-fconstexpr-depth");
3972 CmdArgs.push_back(A->getValue());
3975 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3976 CmdArgs.push_back("-fconstexpr-steps");
3977 CmdArgs.push_back(A->getValue());
3980 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3981 CmdArgs.push_back("-fbracket-depth");
3982 CmdArgs.push_back(A->getValue());
3985 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3986 options::OPT_Wlarge_by_value_copy_def)) {
3987 if (A->getNumValues()) {
3988 StringRef bytes = A->getValue();
3989 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3991 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3994 if (Args.hasArg(options::OPT_relocatable_pch))
3995 CmdArgs.push_back("-relocatable-pch");
3997 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3998 CmdArgs.push_back("-fconstant-string-class");
3999 CmdArgs.push_back(A->getValue());
4002 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4003 CmdArgs.push_back("-ftabstop");
4004 CmdArgs.push_back(A->getValue());
4007 CmdArgs.push_back("-ferror-limit");
4008 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4009 CmdArgs.push_back(A->getValue());
4011 CmdArgs.push_back("19");
4013 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4014 CmdArgs.push_back("-fmacro-backtrace-limit");
4015 CmdArgs.push_back(A->getValue());
4018 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4019 CmdArgs.push_back("-ftemplate-backtrace-limit");
4020 CmdArgs.push_back(A->getValue());
4023 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4024 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4025 CmdArgs.push_back(A->getValue());
4028 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4029 CmdArgs.push_back("-fspell-checking-limit");
4030 CmdArgs.push_back(A->getValue());
4033 // Pass -fmessage-length=.
4034 CmdArgs.push_back("-fmessage-length");
4035 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4036 CmdArgs.push_back(A->getValue());
4038 // If -fmessage-length=N was not specified, determine whether this is a
4039 // terminal and, if so, implicitly define -fmessage-length appropriately.
4040 unsigned N = llvm::sys::Process::StandardErrColumns();
4041 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4044 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4045 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4046 options::OPT_fvisibility_ms_compat)) {
4047 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4048 CmdArgs.push_back("-fvisibility");
4049 CmdArgs.push_back(A->getValue());
4051 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4052 CmdArgs.push_back("-fvisibility");
4053 CmdArgs.push_back("hidden");
4054 CmdArgs.push_back("-ftype-visibility");
4055 CmdArgs.push_back("default");
4059 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4061 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4063 // -fhosted is default.
4064 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4066 CmdArgs.push_back("-ffreestanding");
4068 // Forward -f (flag) options which we can pass directly.
4069 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4070 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4071 Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
4072 Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
4073 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4074 // AltiVec-like language extensions aren't relevant for assembling.
4075 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4076 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4077 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4079 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4080 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4082 // Forward flags for OpenMP
4083 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4084 options::OPT_fno_openmp, false))
4085 switch (getOpenMPRuntime(getToolChain(), Args)) {
4088 // Clang can generate useful OpenMP code for these two runtime libraries.
4089 CmdArgs.push_back("-fopenmp");
4091 // If no option regarding the use of TLS in OpenMP codegeneration is
4092 // given, decide a default based on the target. Otherwise rely on the
4093 // options and pass the right information to the frontend.
4094 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4095 options::OPT_fnoopenmp_use_tls,
4096 getToolChain().getArch() == llvm::Triple::ppc ||
4097 getToolChain().getArch() == llvm::Triple::ppc64 ||
4098 getToolChain().getArch() == llvm::Triple::ppc64le))
4099 CmdArgs.push_back("-fnoopenmp-use-tls");
4102 // By default, if Clang doesn't know how to generate useful OpenMP code
4103 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4104 // down to the actual compilation.
4105 // FIXME: It would be better to have a mode which *only* omits IR
4106 // generation based on the OpenMP support so that we get consistent
4107 // semantic analysis, etc.
4111 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4112 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4114 // Report an error for -faltivec on anything other than PowerPC.
4115 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4116 const llvm::Triple::ArchType Arch = getToolChain().getArch();
4117 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4118 Arch == llvm::Triple::ppc64le))
4119 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4120 << "ppc/ppc64/ppc64le";
4123 // -fzvector is incompatible with -faltivec.
4124 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4125 if (Args.hasArg(options::OPT_faltivec))
4126 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4129 if (getToolChain().SupportsProfiling())
4130 Args.AddLastArg(CmdArgs, options::OPT_pg);
4132 // -flax-vector-conversions is default.
4133 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4134 options::OPT_fno_lax_vector_conversions))
4135 CmdArgs.push_back("-fno-lax-vector-conversions");
4137 if (Args.getLastArg(options::OPT_fapple_kext))
4138 CmdArgs.push_back("-fapple-kext");
4140 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4141 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4142 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4143 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4144 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4146 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4147 CmdArgs.push_back("-ftrapv-handler");
4148 CmdArgs.push_back(A->getValue());
4151 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4153 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4154 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4155 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4156 if (A->getOption().matches(options::OPT_fwrapv))
4157 CmdArgs.push_back("-fwrapv");
4158 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4159 options::OPT_fno_strict_overflow)) {
4160 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4161 CmdArgs.push_back("-fwrapv");
4164 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4165 options::OPT_fno_reroll_loops))
4166 if (A->getOption().matches(options::OPT_freroll_loops))
4167 CmdArgs.push_back("-freroll-loops");
4169 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4170 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4171 options::OPT_fno_unroll_loops);
4173 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4175 // -stack-protector=0 is default.
4176 unsigned StackProtectorLevel = 0;
4177 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4178 Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4179 Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4180 Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4181 Args.ClaimAllArgs(options::OPT_fstack_protector);
4182 } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4183 options::OPT_fstack_protector_all,
4184 options::OPT_fstack_protector_strong,
4185 options::OPT_fstack_protector)) {
4186 if (A->getOption().matches(options::OPT_fstack_protector)) {
4187 StackProtectorLevel = std::max<unsigned>(
4189 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4190 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4191 StackProtectorLevel = LangOptions::SSPStrong;
4192 else if (A->getOption().matches(options::OPT_fstack_protector_all))
4193 StackProtectorLevel = LangOptions::SSPReq;
4195 StackProtectorLevel =
4196 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4198 if (StackProtectorLevel) {
4199 CmdArgs.push_back("-stack-protector");
4200 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4203 // --param ssp-buffer-size=
4204 for (const Arg *A : Args.filtered(options::OPT__param)) {
4205 StringRef Str(A->getValue());
4206 if (Str.startswith("ssp-buffer-size=")) {
4207 if (StackProtectorLevel) {
4208 CmdArgs.push_back("-stack-protector-buffer-size");
4209 // FIXME: Verify the argument is a valid integer.
4210 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4216 // Translate -mstackrealign
4217 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4219 CmdArgs.push_back("-backend-option");
4220 CmdArgs.push_back("-force-align-stack");
4222 if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
4224 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4227 if (Args.hasArg(options::OPT_mstack_alignment)) {
4228 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4229 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4232 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4233 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4236 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4238 CmdArgs.push_back("-mstack-probe-size=0");
4241 if (getToolChain().getArch() == llvm::Triple::aarch64 ||
4242 getToolChain().getArch() == llvm::Triple::aarch64_be)
4243 CmdArgs.push_back("-fallow-half-arguments-and-returns");
4245 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4246 options::OPT_mno_restrict_it)) {
4247 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4248 CmdArgs.push_back("-backend-option");
4249 CmdArgs.push_back("-arm-restrict-it");
4251 CmdArgs.push_back("-backend-option");
4252 CmdArgs.push_back("-arm-no-restrict-it");
4254 } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
4255 TT.getArch() == llvm::Triple::thumb)) {
4256 // Windows on ARM expects restricted IT blocks
4257 CmdArgs.push_back("-backend-option");
4258 CmdArgs.push_back("-arm-restrict-it");
4261 // Forward -f options with positive and negative forms; we translate
4263 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4264 StringRef fname = A->getValue();
4265 if (!llvm::sys::fs::exists(fname))
4266 D.Diag(diag::err_drv_no_such_file) << fname;
4268 A->render(Args, CmdArgs);
4271 if (Args.hasArg(options::OPT_mkernel)) {
4272 if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
4273 CmdArgs.push_back("-fapple-kext");
4274 if (!Args.hasArg(options::OPT_fbuiltin))
4275 CmdArgs.push_back("-fno-builtin");
4276 Args.ClaimAllArgs(options::OPT_fno_builtin);
4278 // -fbuiltin is default.
4279 else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
4280 CmdArgs.push_back("-fno-builtin");
4282 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4283 options::OPT_fno_assume_sane_operator_new))
4284 CmdArgs.push_back("-fno-assume-sane-operator-new");
4286 // -fblocks=0 is default.
4287 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4288 getToolChain().IsBlocksDefault()) ||
4289 (Args.hasArg(options::OPT_fgnu_runtime) &&
4290 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4291 !Args.hasArg(options::OPT_fno_blocks))) {
4292 CmdArgs.push_back("-fblocks");
4294 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4295 !getToolChain().hasBlocksRuntime())
4296 CmdArgs.push_back("-fblocks-runtime-optional");
4299 // -fmodules enables the use of precompiled modules (off by default).
4300 // Users can pass -fno-cxx-modules to turn off modules support for
4301 // C++/Objective-C++ programs.
4302 bool HaveModules = false;
4303 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4304 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4305 options::OPT_fno_cxx_modules, true);
4306 if (AllowedInCXX || !types::isCXX(InputType)) {
4307 CmdArgs.push_back("-fmodules");
4312 // -fmodule-maps enables implicit reading of module map files. By default,
4313 // this is enabled if we are using precompiled modules.
4314 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4315 options::OPT_fno_implicit_module_maps, HaveModules)) {
4316 CmdArgs.push_back("-fimplicit-module-maps");
4319 // -fmodules-decluse checks that modules used are declared so (off by
4321 if (Args.hasFlag(options::OPT_fmodules_decluse,
4322 options::OPT_fno_modules_decluse, false)) {
4323 CmdArgs.push_back("-fmodules-decluse");
4326 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4327 // all #included headers are part of modules.
4328 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4329 options::OPT_fno_modules_strict_decluse, false)) {
4330 CmdArgs.push_back("-fmodules-strict-decluse");
4333 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4334 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4335 options::OPT_fno_implicit_modules)) {
4336 CmdArgs.push_back("-fno-implicit-modules");
4339 // -fmodule-name specifies the module that is currently being built (or
4340 // used for header checking by -fmodule-maps).
4341 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4343 // -fmodule-map-file can be used to specify files containing module
4345 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4347 // -fmodule-file can be used to specify files containing precompiled modules.
4348 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4350 // -fmodule-cache-path specifies where our implicitly-built module files
4351 // should be written.
4352 SmallString<128> Path;
4353 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4354 Path = A->getValue();
4356 if (C.isForDiagnostics()) {
4357 // When generating crash reports, we want to emit the modules along with
4358 // the reproduction sources, so we ignore any provided module path.
4359 Path = Output.getFilename();
4360 llvm::sys::path::replace_extension(Path, ".cache");
4361 llvm::sys::path::append(Path, "modules");
4362 } else if (Path.empty()) {
4363 // No module path was provided: use the default.
4364 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4365 llvm::sys::path::append(Path, "org.llvm.clang.");
4366 appendUserToPath(Path);
4367 llvm::sys::path::append(Path, "ModuleCache");
4369 const char Arg[] = "-fmodules-cache-path=";
4370 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4371 CmdArgs.push_back(Args.MakeArgString(Path));
4374 // When building modules and generating crashdumps, we need to dump a module
4375 // dependency VFS alongside the output.
4376 if (HaveModules && C.isForDiagnostics()) {
4377 SmallString<128> VFSDir(Output.getFilename());
4378 llvm::sys::path::replace_extension(VFSDir, ".cache");
4379 // Add the cache directory as a temp so the crash diagnostics pick it up.
4380 C.addTempFile(Args.MakeArgString(VFSDir));
4382 llvm::sys::path::append(VFSDir, "vfs");
4383 CmdArgs.push_back("-module-dependency-dir");
4384 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4388 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4390 // Pass through all -fmodules-ignore-macro arguments.
4391 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4392 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4393 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4395 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4397 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4398 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4399 D.Diag(diag::err_drv_argument_not_allowed_with)
4400 << A->getAsString(Args) << "-fbuild-session-timestamp";
4402 llvm::sys::fs::file_status Status;
4403 if (llvm::sys::fs::status(A->getValue(), Status))
4404 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4405 CmdArgs.push_back(Args.MakeArgString(
4406 "-fbuild-session-timestamp=" +
4407 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4410 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4411 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4412 options::OPT_fbuild_session_file))
4413 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4415 Args.AddLastArg(CmdArgs,
4416 options::OPT_fmodules_validate_once_per_build_session);
4419 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4421 // -faccess-control is default.
4422 if (Args.hasFlag(options::OPT_fno_access_control,
4423 options::OPT_faccess_control, false))
4424 CmdArgs.push_back("-fno-access-control");
4426 // -felide-constructors is the default.
4427 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4428 options::OPT_felide_constructors, false))
4429 CmdArgs.push_back("-fno-elide-constructors");
4431 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4433 if (KernelOrKext || (types::isCXX(InputType) &&
4434 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4435 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4436 CmdArgs.push_back("-fno-rtti");
4438 // -fshort-enums=0 is default for all architectures except Hexagon.
4439 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4440 getToolChain().getArch() == llvm::Triple::hexagon))
4441 CmdArgs.push_back("-fshort-enums");
4443 // -fsigned-char is default.
4444 if (Arg *A = Args.getLastArg(
4445 options::OPT_fsigned_char, options::OPT_fno_signed_char,
4446 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4447 if (A->getOption().matches(options::OPT_funsigned_char) ||
4448 A->getOption().matches(options::OPT_fno_signed_char)) {
4449 CmdArgs.push_back("-fno-signed-char");
4451 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4452 CmdArgs.push_back("-fno-signed-char");
4455 // -fuse-cxa-atexit is default.
4456 if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
4457 options::OPT_fno_use_cxa_atexit,
4458 !IsWindowsCygnus && !IsWindowsGNU &&
4459 getToolChain().getArch() != llvm::Triple::hexagon &&
4460 getToolChain().getArch() != llvm::Triple::xcore) ||
4462 CmdArgs.push_back("-fno-use-cxa-atexit");
4464 // -fms-extensions=0 is default.
4465 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4467 CmdArgs.push_back("-fms-extensions");
4469 // -fno-use-line-directives is default.
4470 if (Args.hasFlag(options::OPT_fuse_line_directives,
4471 options::OPT_fno_use_line_directives, false))
4472 CmdArgs.push_back("-fuse-line-directives");
4474 // -fms-compatibility=0 is default.
4475 if (Args.hasFlag(options::OPT_fms_compatibility,
4476 options::OPT_fno_ms_compatibility,
4478 Args.hasFlag(options::OPT_fms_extensions,
4479 options::OPT_fno_ms_extensions, true))))
4480 CmdArgs.push_back("-fms-compatibility");
4482 // -fms-compatibility-version=18.00 is default.
4483 VersionTuple MSVT = visualstudio::getMSVCVersion(
4484 &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4487 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4489 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4490 if (ImplyVCPPCXXVer) {
4491 if (IsMSVC2015Compatible)
4492 CmdArgs.push_back("-std=c++14");
4494 CmdArgs.push_back("-std=c++11");
4497 // -fno-borland-extensions is default.
4498 if (Args.hasFlag(options::OPT_fborland_extensions,
4499 options::OPT_fno_borland_extensions, false))
4500 CmdArgs.push_back("-fborland-extensions");
4502 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4504 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4505 options::OPT_fno_threadsafe_statics,
4506 !IsWindowsMSVC || IsMSVC2015Compatible))
4507 CmdArgs.push_back("-fno-threadsafe-statics");
4509 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4511 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4512 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4513 CmdArgs.push_back("-fdelayed-template-parsing");
4515 // -fgnu-keywords default varies depending on language; only pass if
4517 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4518 options::OPT_fno_gnu_keywords))
4519 A->render(Args, CmdArgs);
4521 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4523 CmdArgs.push_back("-fgnu89-inline");
4525 if (Args.hasArg(options::OPT_fno_inline))
4526 CmdArgs.push_back("-fno-inline");
4528 if (Args.hasArg(options::OPT_fno_inline_functions))
4529 CmdArgs.push_back("-fno-inline-functions");
4531 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4533 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
4534 // legacy is the default. Except for deployment taget of 10.5,
4535 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
4536 // gets ignored silently.
4537 if (objcRuntime.isNonFragile()) {
4538 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4539 options::OPT_fno_objc_legacy_dispatch,
4540 objcRuntime.isLegacyDispatchDefaultForArch(
4541 getToolChain().getArch()))) {
4542 if (getToolChain().UseObjCMixedDispatch())
4543 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4545 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4549 // When ObjectiveC legacy runtime is in effect on MacOSX,
4550 // turn on the option to do Array/Dictionary subscripting
4552 if (getToolChain().getArch() == llvm::Triple::x86 &&
4553 getToolChain().getTriple().isMacOSX() &&
4554 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
4555 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
4556 objcRuntime.isNeXTFamily())
4557 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4559 // -fencode-extended-block-signature=1 is default.
4560 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
4561 CmdArgs.push_back("-fencode-extended-block-signature");
4564 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4565 // NOTE: This logic is duplicated in ToolChains.cpp.
4566 bool ARC = isObjCAutoRefCount(Args);
4568 getToolChain().CheckObjCARC();
4570 CmdArgs.push_back("-fobjc-arc");
4572 // FIXME: It seems like this entire block, and several around it should be
4573 // wrapped in isObjC, but for now we just use it here as this is where it
4574 // was being used previously.
4575 if (types::isCXX(InputType) && types::isObjC(InputType)) {
4576 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4577 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4579 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4582 // Allow the user to enable full exceptions code emission.
4583 // We define off for Objective-CC, on for Objective-C++.
4584 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4585 options::OPT_fno_objc_arc_exceptions,
4586 /*default*/ types::isCXX(InputType)))
4587 CmdArgs.push_back("-fobjc-arc-exceptions");
4590 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4592 if (rewriteKind != RK_None)
4593 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4595 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
4596 // takes precedence.
4597 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
4599 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
4602 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
4603 } else if (getToolChain().SupportsObjCGC()) {
4604 GCArg->render(Args, CmdArgs);
4606 // FIXME: We should move this to a hard error.
4607 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
4611 if (Args.hasFlag(options::OPT_fapplication_extension,
4612 options::OPT_fno_application_extension, false))
4613 CmdArgs.push_back("-fapplication-extension");
4615 // Handle GCC-style exception args.
4616 if (!C.getDriver().IsCLMode())
4617 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
4620 if (getToolChain().UseSjLjExceptions())
4621 CmdArgs.push_back("-fsjlj-exceptions");
4623 // C++ "sane" operator new.
4624 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4625 options::OPT_fno_assume_sane_operator_new))
4626 CmdArgs.push_back("-fno-assume-sane-operator-new");
4628 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4630 if (Args.hasFlag(options::OPT_fsized_deallocation,
4631 options::OPT_fno_sized_deallocation, false))
4632 CmdArgs.push_back("-fsized-deallocation");
4634 // -fconstant-cfstrings is default, and may be subject to argument translation
4636 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4637 options::OPT_fno_constant_cfstrings) ||
4638 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4639 options::OPT_mno_constant_cfstrings))
4640 CmdArgs.push_back("-fno-constant-cfstrings");
4642 // -fshort-wchar default varies depending on platform; only
4643 // pass if specified.
4644 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4645 options::OPT_fno_short_wchar))
4646 A->render(Args, CmdArgs);
4648 // -fno-pascal-strings is default, only pass non-default.
4649 if (Args.hasFlag(options::OPT_fpascal_strings,
4650 options::OPT_fno_pascal_strings, false))
4651 CmdArgs.push_back("-fpascal-strings");
4653 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4654 // -fno-pack-struct doesn't apply to -fpack-struct=.
4655 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4656 std::string PackStructStr = "-fpack-struct=";
4657 PackStructStr += A->getValue();
4658 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4659 } else if (Args.hasFlag(options::OPT_fpack_struct,
4660 options::OPT_fno_pack_struct, false)) {
4661 CmdArgs.push_back("-fpack-struct=1");
4664 // Handle -fmax-type-align=N and -fno-type-align
4665 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4666 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4667 if (!SkipMaxTypeAlign) {
4668 std::string MaxTypeAlignStr = "-fmax-type-align=";
4669 MaxTypeAlignStr += A->getValue();
4670 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4672 } else if (getToolChain().getTriple().isOSDarwin()) {
4673 if (!SkipMaxTypeAlign) {
4674 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4675 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4679 if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
4680 if (!Args.hasArg(options::OPT_fcommon))
4681 CmdArgs.push_back("-fno-common");
4682 Args.ClaimAllArgs(options::OPT_fno_common);
4685 // -fcommon is default, only pass non-default.
4686 else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
4687 CmdArgs.push_back("-fno-common");
4689 // -fsigned-bitfields is default, and clang doesn't yet support
4690 // -funsigned-bitfields.
4691 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4692 options::OPT_funsigned_bitfields))
4693 D.Diag(diag::warn_drv_clang_unsupported)
4694 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4696 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4697 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4698 D.Diag(diag::err_drv_clang_unsupported)
4699 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4701 // -finput_charset=UTF-8 is default. Reject others
4702 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4703 StringRef value = inputCharset->getValue();
4704 if (value != "UTF-8")
4705 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4709 // -fexec_charset=UTF-8 is default. Reject others
4710 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4711 StringRef value = execCharset->getValue();
4712 if (value != "UTF-8")
4713 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4717 // -fcaret-diagnostics is default.
4718 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4719 options::OPT_fno_caret_diagnostics, true))
4720 CmdArgs.push_back("-fno-caret-diagnostics");
4722 // -fdiagnostics-fixit-info is default, only pass non-default.
4723 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4724 options::OPT_fno_diagnostics_fixit_info))
4725 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4727 // Enable -fdiagnostics-show-option by default.
4728 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4729 options::OPT_fno_diagnostics_show_option))
4730 CmdArgs.push_back("-fdiagnostics-show-option");
4733 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4734 CmdArgs.push_back("-fdiagnostics-show-category");
4735 CmdArgs.push_back(A->getValue());
4738 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4739 CmdArgs.push_back("-fdiagnostics-format");
4740 CmdArgs.push_back(A->getValue());
4743 if (Arg *A = Args.getLastArg(
4744 options::OPT_fdiagnostics_show_note_include_stack,
4745 options::OPT_fno_diagnostics_show_note_include_stack)) {
4746 if (A->getOption().matches(
4747 options::OPT_fdiagnostics_show_note_include_stack))
4748 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4750 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4753 // Color diagnostics are the default, unless the terminal doesn't support
4755 // Support both clang's -f[no-]color-diagnostics and gcc's
4756 // -f[no-]diagnostics-colors[=never|always|auto].
4757 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
4758 for (const auto &Arg : Args) {
4759 const Option &O = Arg->getOption();
4760 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4761 !O.matches(options::OPT_fdiagnostics_color) &&
4762 !O.matches(options::OPT_fno_color_diagnostics) &&
4763 !O.matches(options::OPT_fno_diagnostics_color) &&
4764 !O.matches(options::OPT_fdiagnostics_color_EQ))
4768 if (O.matches(options::OPT_fcolor_diagnostics) ||
4769 O.matches(options::OPT_fdiagnostics_color)) {
4770 ShowColors = Colors_On;
4771 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
4772 O.matches(options::OPT_fno_diagnostics_color)) {
4773 ShowColors = Colors_Off;
4775 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
4776 StringRef value(Arg->getValue());
4777 if (value == "always")
4778 ShowColors = Colors_On;
4779 else if (value == "never")
4780 ShowColors = Colors_Off;
4781 else if (value == "auto")
4782 ShowColors = Colors_Auto;
4784 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4785 << ("-fdiagnostics-color=" + value).str();
4788 if (ShowColors == Colors_On ||
4789 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
4790 CmdArgs.push_back("-fcolor-diagnostics");
4792 if (Args.hasArg(options::OPT_fansi_escape_codes))
4793 CmdArgs.push_back("-fansi-escape-codes");
4795 if (!Args.hasFlag(options::OPT_fshow_source_location,
4796 options::OPT_fno_show_source_location))
4797 CmdArgs.push_back("-fno-show-source-location");
4799 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4801 CmdArgs.push_back("-fno-show-column");
4803 if (!Args.hasFlag(options::OPT_fspell_checking,
4804 options::OPT_fno_spell_checking))
4805 CmdArgs.push_back("-fno-spell-checking");
4807 // -fno-asm-blocks is default.
4808 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4810 CmdArgs.push_back("-fasm-blocks");
4812 // -fgnu-inline-asm is default.
4813 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4814 options::OPT_fno_gnu_inline_asm, true))
4815 CmdArgs.push_back("-fno-gnu-inline-asm");
4817 // Enable vectorization per default according to the optimization level
4818 // selected. For optimization levels that want vectorization we use the alias
4819 // option to simplify the hasFlag logic.
4820 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4821 OptSpecifier VectorizeAliasOption =
4822 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4823 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4824 options::OPT_fno_vectorize, EnableVec))
4825 CmdArgs.push_back("-vectorize-loops");
4827 // -fslp-vectorize is enabled based on the optimization level selected.
4828 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4829 OptSpecifier SLPVectAliasOption =
4830 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4831 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4832 options::OPT_fno_slp_vectorize, EnableSLPVec))
4833 CmdArgs.push_back("-vectorize-slp");
4835 // -fno-slp-vectorize-aggressive is default.
4836 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4837 options::OPT_fno_slp_vectorize_aggressive, false))
4838 CmdArgs.push_back("-vectorize-slp-aggressive");
4840 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4841 A->render(Args, CmdArgs);
4843 // -fdollars-in-identifiers default varies depending on platform and
4844 // language; only pass if specified.
4845 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4846 options::OPT_fno_dollars_in_identifiers)) {
4847 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4848 CmdArgs.push_back("-fdollars-in-identifiers");
4850 CmdArgs.push_back("-fno-dollars-in-identifiers");
4853 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4854 // practical purposes.
4855 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4856 options::OPT_fno_unit_at_a_time)) {
4857 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4858 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4861 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4862 options::OPT_fno_apple_pragma_pack, false))
4863 CmdArgs.push_back("-fapple-pragma-pack");
4865 // le32-specific flags:
4866 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4868 if (getToolChain().getArch() == llvm::Triple::le32) {
4869 CmdArgs.push_back("-fno-math-builtin");
4872 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4874 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
4876 if (getToolChain().getTriple().isOSDarwin() &&
4877 (getToolChain().getArch() == llvm::Triple::arm ||
4878 getToolChain().getArch() == llvm::Triple::thumb)) {
4879 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4880 CmdArgs.push_back("-fno-builtin-strcat");
4881 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4882 CmdArgs.push_back("-fno-builtin-strcpy");
4886 // Enable rewrite includes if the user's asked for it or if we're generating
4888 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4889 // nice to enable this when doing a crashdump for modules as well.
4890 if (Args.hasFlag(options::OPT_frewrite_includes,
4891 options::OPT_fno_rewrite_includes, false) ||
4892 (C.isForDiagnostics() && !HaveModules))
4893 CmdArgs.push_back("-frewrite-includes");
4895 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4896 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4897 options::OPT_traditional_cpp)) {
4898 if (isa<PreprocessJobAction>(JA))
4899 CmdArgs.push_back("-traditional-cpp");
4901 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4904 Args.AddLastArg(CmdArgs, options::OPT_dM);
4905 Args.AddLastArg(CmdArgs, options::OPT_dD);
4907 // Handle serialized diagnostics.
4908 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4909 CmdArgs.push_back("-serialize-diagnostic-file");
4910 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4913 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4914 CmdArgs.push_back("-fretain-comments-from-system-headers");
4916 // Forward -fcomment-block-commands to -cc1.
4917 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4918 // Forward -fparse-all-comments to -cc1.
4919 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4921 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4923 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4924 bool OptDisabled = false;
4925 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4928 // We translate this by hand to the -cc1 argument, since nightly test uses
4929 // it and developers have been trained to spell it with -mllvm.
4930 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4931 CmdArgs.push_back("-disable-llvm-optzns");
4934 A->render(Args, CmdArgs);
4937 // With -save-temps, we want to save the unoptimized bitcode output from the
4938 // CompileJobAction, so disable optimizations if they are not already
4940 if (C.getDriver().isSaveTempsEnabled() && !OptDisabled &&
4941 isa<CompileJobAction>(JA))
4942 CmdArgs.push_back("-disable-llvm-optzns");
4944 if (Output.getType() == types::TY_Dependencies) {
4945 // Handled with other dependency code.
4946 } else if (Output.isFilename()) {
4947 CmdArgs.push_back("-o");
4948 CmdArgs.push_back(Output.getFilename());
4950 assert(Output.isNothing() && "Invalid output.");
4953 addDashXForInput(Args, Input, CmdArgs);
4955 if (Input.isFilename())
4956 CmdArgs.push_back(Input.getFilename());
4958 Input.getInputArg().renderAsInput(Args, CmdArgs);
4960 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4962 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4964 // Optionally embed the -cc1 level arguments into the debug info, for build
4966 if (getToolChain().UseDwarfDebugFlags()) {
4967 ArgStringList OriginalArgs;
4968 for (const auto &Arg : Args)
4969 Arg->render(Args, OriginalArgs);
4971 SmallString<256> Flags;
4973 for (const char *OriginalArg : OriginalArgs) {
4974 SmallString<128> EscapedArg;
4975 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4977 Flags += EscapedArg;
4979 CmdArgs.push_back("-dwarf-debug-flags");
4980 CmdArgs.push_back(Args.MakeArgString(Flags));
4983 // Add the split debug info name to the command lines here so we
4984 // can propagate it to the backend.
4985 bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
4986 getToolChain().getTriple().isOSLinux() &&
4987 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4988 isa<BackendJobAction>(JA));
4989 const char *SplitDwarfOut;
4991 CmdArgs.push_back("-split-dwarf-file");
4992 SplitDwarfOut = SplitDebugName(Args, Input);
4993 CmdArgs.push_back(SplitDwarfOut);
4996 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4997 // Include them with -fcuda-include-gpubinary.
4998 if (IsCuda && Inputs.size() > 1)
4999 for (InputInfoList::const_iterator it = std::next(Inputs.begin()),
5002 CmdArgs.push_back("-fcuda-include-gpubinary");
5003 CmdArgs.push_back(it->getFilename());
5006 // Finally add the compile command to the compilation.
5007 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5008 Output.getType() == types::TY_Object &&
5009 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5011 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5012 C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
5013 std::move(CLCommand)));
5015 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5018 // Handle the debug info splitting at object creation time if we're
5019 // creating an object.
5020 // TODO: Currently only works on linux with newer objcopy.
5021 if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5022 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5024 if (Arg *A = Args.getLastArg(options::OPT_pg))
5025 if (Args.hasArg(options::OPT_fomit_frame_pointer))
5026 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5027 << A->getAsString(Args);
5029 // Claim some arguments which clang supports automatically.
5031 // -fpch-preprocess is used with gcc to add a special marker in the output to
5032 // include the PCH file. Clang's PTH solution is completely transparent, so we
5033 // do not need to deal with it at all.
5034 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5036 // Claim some arguments which clang doesn't support, but we don't
5037 // care to warn the user about.
5038 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5039 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5041 // Disable warnings for clang -E -emit-llvm foo.c
5042 Args.ClaimAllArgs(options::OPT_emit_llvm);
5045 /// Add options related to the Objective-C runtime/ABI.
5047 /// Returns true if the runtime is non-fragile.
5048 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5049 ArgStringList &cmdArgs,
5050 RewriteKind rewriteKind) const {
5051 // Look for the controlling runtime option.
5053 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5054 options::OPT_fobjc_runtime_EQ);
5056 // Just forward -fobjc-runtime= to the frontend. This supercedes
5057 // options about fragility.
5059 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5060 ObjCRuntime runtime;
5061 StringRef value = runtimeArg->getValue();
5062 if (runtime.tryParse(value)) {
5063 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5067 runtimeArg->render(args, cmdArgs);
5071 // Otherwise, we'll need the ABI "version". Version numbers are
5072 // slightly confusing for historical reasons:
5073 // 1 - Traditional "fragile" ABI
5074 // 2 - Non-fragile ABI, version 1
5075 // 3 - Non-fragile ABI, version 2
5076 unsigned objcABIVersion = 1;
5077 // If -fobjc-abi-version= is present, use that to set the version.
5078 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5079 StringRef value = abiArg->getValue();
5082 else if (value == "2")
5084 else if (value == "3")
5087 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5089 // Otherwise, determine if we are using the non-fragile ABI.
5090 bool nonFragileABIIsDefault =
5091 (rewriteKind == RK_NonFragile ||
5092 (rewriteKind == RK_None &&
5093 getToolChain().IsObjCNonFragileABIDefault()));
5094 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5095 options::OPT_fno_objc_nonfragile_abi,
5096 nonFragileABIIsDefault)) {
5097 // Determine the non-fragile ABI version to use.
5098 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5099 unsigned nonFragileABIVersion = 1;
5101 unsigned nonFragileABIVersion = 2;
5105 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5106 StringRef value = abiArg->getValue();
5108 nonFragileABIVersion = 1;
5109 else if (value == "2")
5110 nonFragileABIVersion = 2;
5112 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5116 objcABIVersion = 1 + nonFragileABIVersion;
5122 // We don't actually care about the ABI version other than whether
5123 // it's non-fragile.
5124 bool isNonFragile = objcABIVersion != 1;
5126 // If we have no runtime argument, ask the toolchain for its default runtime.
5127 // However, the rewriter only really supports the Mac runtime, so assume that.
5128 ObjCRuntime runtime;
5130 switch (rewriteKind) {
5132 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5135 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5138 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5143 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5144 // On Darwin, make this use the default behavior for the toolchain.
5145 if (getToolChain().getTriple().isOSDarwin()) {
5146 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5148 // Otherwise, build for a generic macosx port.
5150 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5155 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5156 // Legacy behaviour is to target the gnustep runtime if we are i
5157 // non-fragile mode or the GCC runtime in fragile mode.
5159 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5161 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5165 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5169 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5170 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5176 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5182 /// /EH controls whether to run destructor cleanups when exceptions are
5183 /// thrown. There are three modifiers:
5184 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5185 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5186 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5187 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5188 /// modifier is an optimization, so we ignore it for now.
5189 /// The default is /EHs-c-, meaning cleanups are disabled.
5190 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5193 std::vector<std::string> EHArgs =
5194 Args.getAllArgValues(options::OPT__SLASH_EH);
5195 for (auto EHVal : EHArgs) {
5196 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5199 EH.Asynch = maybeConsumeDash(EHVal, I);
5202 EH.NoExceptC = maybeConsumeDash(EHVal, I);
5205 EH.Synch = maybeConsumeDash(EHVal, I);
5210 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5215 // FIXME: Disable C++ EH completely, until it becomes more reliable. Users
5216 // can use -Xclang to manually enable C++ EH until then.
5222 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
5223 unsigned RTOptionID = options::OPT__SLASH_MT;
5225 if (Args.hasArg(options::OPT__SLASH_LDd))
5226 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5227 // but defining _DEBUG is sticky.
5228 RTOptionID = options::OPT__SLASH_MTd;
5230 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5231 RTOptionID = A->getOption().getID();
5233 switch (RTOptionID) {
5234 case options::OPT__SLASH_MD:
5235 if (Args.hasArg(options::OPT__SLASH_LDd))
5236 CmdArgs.push_back("-D_DEBUG");
5237 CmdArgs.push_back("-D_MT");
5238 CmdArgs.push_back("-D_DLL");
5239 CmdArgs.push_back("--dependent-lib=msvcrt");
5241 case options::OPT__SLASH_MDd:
5242 CmdArgs.push_back("-D_DEBUG");
5243 CmdArgs.push_back("-D_MT");
5244 CmdArgs.push_back("-D_DLL");
5245 CmdArgs.push_back("--dependent-lib=msvcrtd");
5247 case options::OPT__SLASH_MT:
5248 if (Args.hasArg(options::OPT__SLASH_LDd))
5249 CmdArgs.push_back("-D_DEBUG");
5250 CmdArgs.push_back("-D_MT");
5251 CmdArgs.push_back("--dependent-lib=libcmt");
5253 case options::OPT__SLASH_MTd:
5254 CmdArgs.push_back("-D_DEBUG");
5255 CmdArgs.push_back("-D_MT");
5256 CmdArgs.push_back("--dependent-lib=libcmtd");
5259 llvm_unreachable("Unexpected option ID.");
5262 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5263 // users want. The /Za flag to cl.exe turns this off, but it's not
5264 // implemented in clang.
5265 CmdArgs.push_back("--dependent-lib=oldnames");
5267 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5268 // would produce interleaved output, so ignore /showIncludes in such cases.
5269 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5270 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5271 A->render(Args, CmdArgs);
5273 // This controls whether or not we emit RTTI data for polymorphic types.
5274 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5276 CmdArgs.push_back("-fno-rtti-data");
5278 const Driver &D = getToolChain().getDriver();
5279 EHFlags EH = parseClangCLEHFlags(D, Args);
5280 // FIXME: Do something with NoExceptC.
5281 if (EH.Synch || EH.Asynch) {
5282 CmdArgs.push_back("-fcxx-exceptions");
5283 CmdArgs.push_back("-fexceptions");
5286 // /EP should expand to -E -P.
5287 if (Args.hasArg(options::OPT__SLASH_EP)) {
5288 CmdArgs.push_back("-E");
5289 CmdArgs.push_back("-P");
5292 unsigned VolatileOptionID;
5293 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5294 getToolChain().getArch() == llvm::Triple::x86)
5295 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5297 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5299 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5300 VolatileOptionID = A->getOption().getID();
5302 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5303 CmdArgs.push_back("-fms-volatile");
5305 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5306 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5307 if (MostGeneralArg && BestCaseArg)
5308 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5309 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5311 if (MostGeneralArg) {
5312 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5313 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5314 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5316 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5317 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5318 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5319 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5320 << FirstConflict->getAsString(Args)
5321 << SecondConflict->getAsString(Args);
5324 CmdArgs.push_back("-fms-memptr-rep=single");
5325 else if (MultipleArg)
5326 CmdArgs.push_back("-fms-memptr-rep=multiple");
5328 CmdArgs.push_back("-fms-memptr-rep=virtual");
5331 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5332 A->render(Args, CmdArgs);
5334 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5335 CmdArgs.push_back("-fdiagnostics-format");
5336 if (Args.hasArg(options::OPT__SLASH_fallback))
5337 CmdArgs.push_back("msvc-fallback");
5339 CmdArgs.push_back("msvc");
5343 visualstudio::Compiler *Clang::getCLFallback() const {
5345 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5346 return CLFallback.get();
5349 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5350 ArgStringList &CmdArgs) const {
5353 const llvm::Triple &Triple = getToolChain().getTriple();
5354 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5356 CmdArgs.push_back("-target-abi");
5357 CmdArgs.push_back(ABIName.data());
5360 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5361 const InputInfo &Output, const InputInfoList &Inputs,
5362 const ArgList &Args,
5363 const char *LinkingOutput) const {
5364 ArgStringList CmdArgs;
5366 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5367 const InputInfo &Input = Inputs[0];
5369 // Don't warn about "clang -w -c foo.s"
5370 Args.ClaimAllArgs(options::OPT_w);
5371 // and "clang -emit-llvm -c foo.s"
5372 Args.ClaimAllArgs(options::OPT_emit_llvm);
5374 claimNoWarnArgs(Args);
5376 // Invoke ourselves in -cc1as mode.
5378 // FIXME: Implement custom jobs for internal actions.
5379 CmdArgs.push_back("-cc1as");
5381 // Add the "effective" target triple.
5382 CmdArgs.push_back("-triple");
5383 std::string TripleStr =
5384 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5385 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5387 // Set the output mode, we currently only expect to be used as a real
5389 CmdArgs.push_back("-filetype");
5390 CmdArgs.push_back("obj");
5392 // Set the main file name, so that debug info works even with
5393 // -save-temps or preprocessed assembly.
5394 CmdArgs.push_back("-main-file-name");
5395 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5397 // Add the target cpu
5398 const llvm::Triple Triple(TripleStr);
5399 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5401 CmdArgs.push_back("-target-cpu");
5402 CmdArgs.push_back(Args.MakeArgString(CPU));
5405 // Add the target features
5406 const Driver &D = getToolChain().getDriver();
5407 getTargetFeatures(D, Triple, Args, CmdArgs, true);
5409 // Ignore explicit -force_cpusubtype_ALL option.
5410 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5412 // Pass along any -I options so we get proper .include search paths.
5413 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5415 // Determine the original source input.
5416 const Action *SourceAction = &JA;
5417 while (SourceAction->getKind() != Action::InputClass) {
5418 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5419 SourceAction = SourceAction->getInputs()[0];
5422 // Forward -g and handle debug info related flags, assuming we are dealing
5423 // with an actual assembly file.
5424 if (SourceAction->getType() == types::TY_Asm ||
5425 SourceAction->getType() == types::TY_PP_Asm) {
5426 Args.ClaimAllArgs(options::OPT_g_Group);
5427 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
5428 if (!A->getOption().matches(options::OPT_g0))
5429 CmdArgs.push_back("-g");
5431 if (Args.hasArg(options::OPT_gdwarf_2))
5432 CmdArgs.push_back("-gdwarf-2");
5433 if (Args.hasArg(options::OPT_gdwarf_3))
5434 CmdArgs.push_back("-gdwarf-3");
5435 if (Args.hasArg(options::OPT_gdwarf_4))
5436 CmdArgs.push_back("-gdwarf-4");
5438 // Add the -fdebug-compilation-dir flag if needed.
5439 addDebugCompDirArg(Args, CmdArgs);
5441 // Set the AT_producer to the clang version when using the integrated
5442 // assembler on assembly source files.
5443 CmdArgs.push_back("-dwarf-debug-producer");
5444 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5447 // Optionally embed the -cc1as level arguments into the debug info, for build
5449 if (getToolChain().UseDwarfDebugFlags()) {
5450 ArgStringList OriginalArgs;
5451 for (const auto &Arg : Args)
5452 Arg->render(Args, OriginalArgs);
5454 SmallString<256> Flags;
5455 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5457 for (const char *OriginalArg : OriginalArgs) {
5458 SmallString<128> EscapedArg;
5459 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5461 Flags += EscapedArg;
5463 CmdArgs.push_back("-dwarf-debug-flags");
5464 CmdArgs.push_back(Args.MakeArgString(Flags));
5467 // FIXME: Add -static support, once we have it.
5469 // Add target specific flags.
5470 switch (getToolChain().getArch()) {
5474 case llvm::Triple::mips:
5475 case llvm::Triple::mipsel:
5476 case llvm::Triple::mips64:
5477 case llvm::Triple::mips64el:
5478 AddMIPSTargetArgs(Args, CmdArgs);
5482 // Consume all the warning flags. Usually this would be handled more
5483 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5484 // doesn't handle that so rather than warning about unused flags that are
5485 // actually used, we'll lie by omission instead.
5486 // FIXME: Stop lying and consume only the appropriate driver flags
5487 for (const Arg *A : Args.filtered(options::OPT_W_Group))
5490 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5491 getToolChain().getDriver());
5493 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5495 assert(Output.isFilename() && "Unexpected lipo output.");
5496 CmdArgs.push_back("-o");
5497 CmdArgs.push_back(Output.getFilename());
5499 assert(Input.isFilename() && "Invalid input.");
5500 CmdArgs.push_back(Input.getFilename());
5502 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5503 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5505 // Handle the debug info splitting at object creation time if we're
5506 // creating an object.
5507 // TODO: Currently only works on linux with newer objcopy.
5508 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5509 getToolChain().getTriple().isOSLinux())
5510 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5511 SplitDebugName(Args, Input));
5514 void GnuTool::anchor() {}
5516 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
5517 const InputInfo &Output,
5518 const InputInfoList &Inputs, const ArgList &Args,
5519 const char *LinkingOutput) const {
5520 const Driver &D = getToolChain().getDriver();
5521 ArgStringList CmdArgs;
5523 for (const auto &A : Args) {
5524 if (forwardToGCC(A->getOption())) {
5525 // Don't forward any -g arguments to assembly steps.
5526 if (isa<AssembleJobAction>(JA) &&
5527 A->getOption().matches(options::OPT_g_Group))
5530 // Don't forward any -W arguments to assembly and link steps.
5531 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
5532 A->getOption().matches(options::OPT_W_Group))
5535 // It is unfortunate that we have to claim here, as this means
5536 // we will basically never report anything interesting for
5537 // platforms using a generic gcc, even if we are just using gcc
5538 // to get to the assembler.
5540 A->render(Args, CmdArgs);
5544 RenderExtraToolArgs(JA, CmdArgs);
5546 // If using a driver driver, force the arch.
5547 if (getToolChain().getTriple().isOSDarwin()) {
5548 CmdArgs.push_back("-arch");
5550 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
5553 // Try to force gcc to match the tool chain we want, if we recognize
5556 // FIXME: The triple class should directly provide the information we want
5558 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5559 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
5560 CmdArgs.push_back("-m32");
5561 else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
5562 Arch == llvm::Triple::ppc64le)
5563 CmdArgs.push_back("-m64");
5565 if (Output.isFilename()) {
5566 CmdArgs.push_back("-o");
5567 CmdArgs.push_back(Output.getFilename());
5569 assert(Output.isNothing() && "Unexpected output");
5570 CmdArgs.push_back("-fsyntax-only");
5573 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5575 // Only pass -x if gcc will understand it; otherwise hope gcc
5576 // understands the suffix correctly. The main use case this would go
5577 // wrong in is for linker inputs if they happened to have an odd
5578 // suffix; really the only way to get this to happen is a command
5579 // like '-x foobar a.c' which will treat a.c like a linker input.
5581 // FIXME: For the linker case specifically, can we safely convert
5582 // inputs into '-Wl,' options?
5583 for (const auto &II : Inputs) {
5584 // Don't try to pass LLVM or AST inputs to a generic gcc.
5585 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5586 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5587 D.Diag(diag::err_drv_no_linker_llvm_support)
5588 << getToolChain().getTripleString();
5589 else if (II.getType() == types::TY_AST)
5590 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
5591 else if (II.getType() == types::TY_ModuleFile)
5592 D.Diag(diag::err_drv_no_module_support)
5593 << getToolChain().getTripleString();
5595 if (types::canTypeBeUserSpecified(II.getType())) {
5596 CmdArgs.push_back("-x");
5597 CmdArgs.push_back(types::getTypeName(II.getType()));
5600 if (II.isFilename())
5601 CmdArgs.push_back(II.getFilename());
5603 const Arg &A = II.getInputArg();
5605 // Reverse translate some rewritten options.
5606 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
5607 CmdArgs.push_back("-lstdc++");
5611 // Don't render as input, we need gcc to do the translations.
5612 A.render(Args, CmdArgs);
5616 const std::string customGCCName = D.getCCCGenericGCCName();
5617 const char *GCCName;
5618 if (!customGCCName.empty())
5619 GCCName = customGCCName.c_str();
5620 else if (D.CCCIsCXX()) {
5625 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5626 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5629 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
5630 ArgStringList &CmdArgs) const {
5631 CmdArgs.push_back("-E");
5634 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
5635 ArgStringList &CmdArgs) const {
5636 const Driver &D = getToolChain().getDriver();
5638 switch (JA.getType()) {
5639 // If -flto, etc. are present then make sure not to force assembly output.
5640 case types::TY_LLVM_IR:
5641 case types::TY_LTO_IR:
5642 case types::TY_LLVM_BC:
5643 case types::TY_LTO_BC:
5644 CmdArgs.push_back("-c");
5646 case types::TY_PP_Asm:
5647 CmdArgs.push_back("-S");
5649 case types::TY_Nothing:
5650 CmdArgs.push_back("-fsyntax-only");
5653 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
5657 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
5658 ArgStringList &CmdArgs) const {
5659 // The types are (hopefully) good enough.
5662 // Hexagon tools start.
5663 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
5664 ArgStringList &CmdArgs) const {}
5665 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
5666 const InputInfo &Output,
5667 const InputInfoList &Inputs,
5668 const ArgList &Args,
5669 const char *LinkingOutput) const {
5670 claimNoWarnArgs(Args);
5672 const Driver &D = getToolChain().getDriver();
5673 ArgStringList CmdArgs;
5675 std::string MarchString = "-march=";
5676 MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
5677 CmdArgs.push_back(Args.MakeArgString(MarchString));
5679 RenderExtraToolArgs(JA, CmdArgs);
5681 if (Output.isFilename()) {
5682 CmdArgs.push_back("-o");
5683 CmdArgs.push_back(Output.getFilename());
5685 assert(Output.isNothing() && "Unexpected output");
5686 CmdArgs.push_back("-fsyntax-only");
5689 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args))
5690 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5692 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5694 // Only pass -x if gcc will understand it; otherwise hope gcc
5695 // understands the suffix correctly. The main use case this would go
5696 // wrong in is for linker inputs if they happened to have an odd
5697 // suffix; really the only way to get this to happen is a command
5698 // like '-x foobar a.c' which will treat a.c like a linker input.
5700 // FIXME: For the linker case specifically, can we safely convert
5701 // inputs into '-Wl,' options?
5702 for (const auto &II : Inputs) {
5703 // Don't try to pass LLVM or AST inputs to a generic gcc.
5704 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5705 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5706 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
5707 << getToolChain().getTripleString();
5708 else if (II.getType() == types::TY_AST)
5709 D.Diag(clang::diag::err_drv_no_ast_support)
5710 << getToolChain().getTripleString();
5711 else if (II.getType() == types::TY_ModuleFile)
5712 D.Diag(diag::err_drv_no_module_support)
5713 << getToolChain().getTripleString();
5715 if (II.isFilename())
5716 CmdArgs.push_back(II.getFilename());
5718 // Don't render as input, we need gcc to do the translations.
5719 // FIXME: Pranav: What is this ?
5720 II.getInputArg().render(Args, CmdArgs);
5723 const char *GCCName = "hexagon-as";
5724 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5725 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5728 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
5729 ArgStringList &CmdArgs) const {
5730 // The types are (hopefully) good enough.
5733 static void constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
5734 const toolchains::Hexagon_TC &ToolChain,
5735 const InputInfo &Output,
5736 const InputInfoList &Inputs,
5737 const ArgList &Args,
5738 ArgStringList &CmdArgs,
5739 const char *LinkingOutput) {
5741 const Driver &D = ToolChain.getDriver();
5743 //----------------------------------------------------------------------------
5745 //----------------------------------------------------------------------------
5746 bool hasStaticArg = Args.hasArg(options::OPT_static);
5747 bool buildingLib = Args.hasArg(options::OPT_shared);
5748 bool buildPIE = Args.hasArg(options::OPT_pie);
5749 bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
5750 bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
5751 bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
5753 bool useShared = buildingLib && !hasStaticArg;
5755 //----------------------------------------------------------------------------
5756 // Silence warnings for various options
5757 //----------------------------------------------------------------------------
5759 Args.ClaimAllArgs(options::OPT_g_Group);
5760 Args.ClaimAllArgs(options::OPT_emit_llvm);
5761 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
5762 // handled somewhere else.
5763 Args.ClaimAllArgs(options::OPT_static_libgcc);
5765 //----------------------------------------------------------------------------
5767 //----------------------------------------------------------------------------
5768 for (const auto &Opt : ToolChain.ExtraOpts)
5769 CmdArgs.push_back(Opt.c_str());
5771 std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
5772 CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
5775 CmdArgs.push_back("-shared");
5776 CmdArgs.push_back("-call_shared"); // should be the default, but doing as
5781 CmdArgs.push_back("-static");
5783 if (buildPIE && !buildingLib)
5784 CmdArgs.push_back("-pie");
5786 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
5787 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5788 useG0 = toolchains::Hexagon_TC::UsesG0(v);
5791 //----------------------------------------------------------------------------
5793 //----------------------------------------------------------------------------
5794 CmdArgs.push_back("-o");
5795 CmdArgs.push_back(Output.getFilename());
5797 const std::string MarchSuffix = "/" + MarchString;
5798 const std::string G0Suffix = "/G0";
5799 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
5800 const std::string RootDir =
5801 toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
5802 const std::string StartFilesDir =
5803 RootDir + "hexagon/lib" + (useG0 ? MarchG0Suffix : MarchSuffix);
5805 //----------------------------------------------------------------------------
5807 //----------------------------------------------------------------------------
5808 std::vector<std::string> oslibs;
5809 bool hasStandalone = false;
5811 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
5813 oslibs.emplace_back(A->getValue());
5814 hasStandalone = hasStandalone || (oslibs.back() == "standalone");
5816 if (oslibs.empty()) {
5817 oslibs.push_back("standalone");
5818 hasStandalone = true;
5821 //----------------------------------------------------------------------------
5823 //----------------------------------------------------------------------------
5824 if (incStdLib && incStartFiles) {
5827 if (hasStandalone) {
5829 Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
5831 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
5833 std::string initObj = useShared ? "/initS.o" : "/init.o";
5834 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
5837 //----------------------------------------------------------------------------
5838 // Library Search Paths
5839 //----------------------------------------------------------------------------
5840 const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
5841 for (const auto &LibPath : LibPaths)
5842 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
5844 //----------------------------------------------------------------------------
5846 //----------------------------------------------------------------------------
5847 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5848 Args.AddAllArgs(CmdArgs, options::OPT_e);
5849 Args.AddAllArgs(CmdArgs, options::OPT_s);
5850 Args.AddAllArgs(CmdArgs, options::OPT_t);
5851 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5853 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5855 //----------------------------------------------------------------------------
5857 //----------------------------------------------------------------------------
5858 if (incStdLib && incDefLibs) {
5860 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5861 CmdArgs.push_back("-lm");
5864 CmdArgs.push_back("--start-group");
5867 for (const std::string &Lib : oslibs)
5868 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
5869 CmdArgs.push_back("-lc");
5871 CmdArgs.push_back("-lgcc");
5873 CmdArgs.push_back("--end-group");
5876 //----------------------------------------------------------------------------
5878 //----------------------------------------------------------------------------
5879 if (incStdLib && incStartFiles) {
5880 std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
5881 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
5885 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
5886 const InputInfo &Output,
5887 const InputInfoList &Inputs,
5888 const ArgList &Args,
5889 const char *LinkingOutput) const {
5891 const toolchains::Hexagon_TC &ToolChain =
5892 static_cast<const toolchains::Hexagon_TC &>(getToolChain());
5894 ArgStringList CmdArgs;
5895 constructHexagonLinkArgs(C, JA, ToolChain, Output, Inputs, Args, CmdArgs,
5898 std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
5899 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
5902 // Hexagon tools end.
5904 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
5909 MArch = Triple.getArchName();
5910 MArch = StringRef(MArch).lower();
5912 // Handle -march=native.
5913 if (MArch == "native") {
5914 std::string CPU = llvm::sys::getHostCPUName();
5915 if (CPU != "generic") {
5916 // Translate the native cpu into the architecture suffix for that CPU.
5917 const char *Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch);
5918 // If there is no valid architecture suffix for this CPU we don't know how
5919 // to handle it, so return no architecture.
5920 if (strcmp(Suffix, "") == 0)
5923 MArch = std::string("arm") + Suffix;
5929 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
5930 const char *arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
5931 std::string MArch = getARMArch(Arch, Triple);
5932 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
5933 // here means an -march=native that we can't handle, so instead return no CPU.
5937 // We need to return an empty string here on invalid MArch values as the
5938 // various places that call this function can't cope with a null result.
5939 const char *result = Triple.getARMCPUForArch(MArch);
5946 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
5947 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
5948 const llvm::Triple &Triple) {
5949 // FIXME: Warn on inconsistent use of -mcpu and -march.
5950 // If we have -mcpu=, use that.
5952 std::string MCPU = StringRef(CPU).lower();
5953 // Handle -mcpu=native.
5954 if (MCPU == "native")
5955 return llvm::sys::getHostCPUName();
5960 return getARMCPUForMArch(Arch, Triple);
5963 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
5964 /// CPU (or Arch, if CPU is generic).
5965 // FIXME: This is redundant with -mcpu, why does LLVM use this.
5966 const char *arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch) {
5967 if (CPU == "generic" &&
5968 llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_ARMV8_1A)
5971 unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(CPU);
5972 if (ArchKind == llvm::ARM::AK_INVALID)
5974 return llvm::ARMTargetParser::getSubArch(ArchKind);
5977 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
5978 const llvm::Triple &Triple) {
5979 if (Args.hasArg(options::OPT_r))
5982 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
5983 // to generate BE-8 executables.
5984 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
5985 CmdArgs.push_back("--be8");
5988 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
5989 return (NanEncoding)llvm::StringSwitch<int>(CPU)
5990 .Case("mips1", NanLegacy)
5991 .Case("mips2", NanLegacy)
5992 .Case("mips3", NanLegacy)
5993 .Case("mips4", NanLegacy)
5994 .Case("mips5", NanLegacy)
5995 .Case("mips32", NanLegacy)
5996 .Case("mips32r2", NanLegacy)
5997 .Case("mips32r3", NanLegacy | Nan2008)
5998 .Case("mips32r5", NanLegacy | Nan2008)
5999 .Case("mips32r6", Nan2008)
6000 .Case("mips64", NanLegacy)
6001 .Case("mips64r2", NanLegacy)
6002 .Case("mips64r3", NanLegacy | Nan2008)
6003 .Case("mips64r5", NanLegacy | Nan2008)
6004 .Case("mips64r6", Nan2008)
6005 .Default(NanLegacy);
6008 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6009 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6010 return A && (A->getValue() == StringRef(Value));
6013 bool mips::isUCLibc(const ArgList &Args) {
6014 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6015 return A && A->getOption().matches(options::OPT_muclibc);
6018 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6019 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6020 return llvm::StringSwitch<bool>(NaNArg->getValue())
6022 .Case("legacy", false)
6025 // NaN2008 is the default for MIPS32r6/MIPS64r6.
6026 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6027 .Cases("mips32r6", "mips64r6", true)
6033 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6034 StringRef ABIName, StringRef FloatABI) {
6035 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6036 Triple.getVendor() != llvm::Triple::MipsTechnologies)
6039 if (ABIName != "32")
6042 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6044 if (FloatABI == "soft")
6047 return llvm::StringSwitch<bool>(CPUName)
6048 .Cases("mips2", "mips3", "mips4", "mips5", true)
6049 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6050 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6054 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6055 StringRef CPUName, StringRef ABIName,
6056 StringRef FloatABI) {
6057 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6059 // FPXX shouldn't be used if -msingle-float is present.
6060 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6061 options::OPT_mdouble_float))
6062 if (A->getOption().matches(options::OPT_msingle_float))
6068 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6069 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6070 // archs which Darwin doesn't use.
6072 // The matching this routine does is fairly pointless, since it is neither the
6073 // complete architecture list, nor a reasonable subset. The problem is that
6074 // historically the driver driver accepts this and also ties its -march=
6075 // handling to the architecture name, so we need to be careful before removing
6078 // This code must be kept in sync with Clang's Darwin specific argument
6081 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6082 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6083 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6084 .Case("ppc64", llvm::Triple::ppc64)
6085 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6086 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6088 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6089 // This is derived from the driver driver.
6090 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6091 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6092 .Cases("armv7s", "xscale", llvm::Triple::arm)
6093 .Case("arm64", llvm::Triple::aarch64)
6094 .Case("r600", llvm::Triple::r600)
6095 .Case("amdgcn", llvm::Triple::amdgcn)
6096 .Case("nvptx", llvm::Triple::nvptx)
6097 .Case("nvptx64", llvm::Triple::nvptx64)
6098 .Case("amdil", llvm::Triple::amdil)
6099 .Case("spir", llvm::Triple::spir)
6100 .Default(llvm::Triple::UnknownArch);
6103 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6104 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6107 if (Str == "x86_64h")
6109 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6110 T.setOS(llvm::Triple::UnknownOS);
6111 T.setObjectFormat(llvm::Triple::MachO);
6115 const char *Clang::getBaseInputName(const ArgList &Args,
6116 const InputInfo &Input) {
6117 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6120 const char *Clang::getBaseInputStem(const ArgList &Args,
6121 const InputInfoList &Inputs) {
6122 const char *Str = getBaseInputName(Args, Inputs[0]);
6124 if (const char *End = strrchr(Str, '.'))
6125 return Args.MakeArgString(std::string(Str, End));
6130 const char *Clang::getDependencyFileName(const ArgList &Args,
6131 const InputInfoList &Inputs) {
6132 // FIXME: Think about this more.
6135 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6136 std::string Str(OutputOpt->getValue());
6137 Res = Str.substr(0, Str.rfind('.'));
6139 Res = getBaseInputStem(Args, Inputs);
6141 return Args.MakeArgString(Res + ".d");
6144 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6145 const InputInfo &Output,
6146 const InputInfoList &Inputs,
6147 const ArgList &Args,
6148 const char *LinkingOutput) const {
6149 const ToolChain &ToolChain = getToolChain();
6150 const Driver &D = ToolChain.getDriver();
6151 ArgStringList CmdArgs;
6153 // Silence warning for "clang -g foo.o -o foo"
6154 Args.ClaimAllArgs(options::OPT_g_Group);
6155 // and "clang -emit-llvm foo.o -o foo"
6156 Args.ClaimAllArgs(options::OPT_emit_llvm);
6157 // and for "clang -w foo.o -o foo". Other warning options are already
6158 // handled somewhere else.
6159 Args.ClaimAllArgs(options::OPT_w);
6161 if (!D.SysRoot.empty())
6162 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6164 // CloudABI only supports static linkage.
6165 CmdArgs.push_back("-Bstatic");
6166 CmdArgs.push_back("--eh-frame-hdr");
6167 CmdArgs.push_back("--gc-sections");
6169 if (Output.isFilename()) {
6170 CmdArgs.push_back("-o");
6171 CmdArgs.push_back(Output.getFilename());
6173 assert(Output.isNothing() && "Invalid output.");
6176 if (!Args.hasArg(options::OPT_nostdlib) &&
6177 !Args.hasArg(options::OPT_nostartfiles)) {
6178 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6179 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6182 Args.AddAllArgs(CmdArgs, options::OPT_L);
6183 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
6184 for (const auto &Path : Paths)
6185 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
6186 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6187 Args.AddAllArgs(CmdArgs, options::OPT_e);
6188 Args.AddAllArgs(CmdArgs, options::OPT_s);
6189 Args.AddAllArgs(CmdArgs, options::OPT_t);
6190 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6191 Args.AddAllArgs(CmdArgs, options::OPT_r);
6193 if (D.IsUsingLTO(Args))
6194 AddGoldPlugin(ToolChain, Args, CmdArgs);
6196 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6198 if (!Args.hasArg(options::OPT_nostdlib) &&
6199 !Args.hasArg(options::OPT_nodefaultlibs)) {
6201 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6202 CmdArgs.push_back("-lc");
6203 CmdArgs.push_back("-lcompiler_rt");
6206 if (!Args.hasArg(options::OPT_nostdlib) &&
6207 !Args.hasArg(options::OPT_nostartfiles))
6208 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6210 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6211 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6214 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6215 const InputInfo &Output,
6216 const InputInfoList &Inputs,
6217 const ArgList &Args,
6218 const char *LinkingOutput) const {
6219 ArgStringList CmdArgs;
6221 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6222 const InputInfo &Input = Inputs[0];
6224 // Determine the original source input.
6225 const Action *SourceAction = &JA;
6226 while (SourceAction->getKind() != Action::InputClass) {
6227 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6228 SourceAction = SourceAction->getInputs()[0];
6231 // If -fno_integrated_as is used add -Q to the darwin assember driver to make
6232 // sure it runs its system assembler not clang's integrated assembler.
6233 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6234 // FIXME: at run-time detect assembler capabilities or rely on version
6235 // information forwarded by -target-assembler-version (future)
6236 if (Args.hasArg(options::OPT_fno_integrated_as)) {
6237 const llvm::Triple &T(getToolChain().getTriple());
6238 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6239 CmdArgs.push_back("-Q");
6242 // Forward -g, assuming we are dealing with an actual assembly file.
6243 if (SourceAction->getType() == types::TY_Asm ||
6244 SourceAction->getType() == types::TY_PP_Asm) {
6245 if (Args.hasArg(options::OPT_gstabs))
6246 CmdArgs.push_back("--gstabs");
6247 else if (Args.hasArg(options::OPT_g_Group))
6248 CmdArgs.push_back("-g");
6251 // Derived from asm spec.
6252 AddMachOArch(Args, CmdArgs);
6254 // Use -force_cpusubtype_ALL on x86 by default.
6255 if (getToolChain().getArch() == llvm::Triple::x86 ||
6256 getToolChain().getArch() == llvm::Triple::x86_64 ||
6257 Args.hasArg(options::OPT_force__cpusubtype__ALL))
6258 CmdArgs.push_back("-force_cpusubtype_ALL");
6260 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6261 (((Args.hasArg(options::OPT_mkernel) ||
6262 Args.hasArg(options::OPT_fapple_kext)) &&
6263 getMachOToolChain().isKernelStatic()) ||
6264 Args.hasArg(options::OPT_static)))
6265 CmdArgs.push_back("-static");
6267 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6269 assert(Output.isFilename() && "Unexpected lipo output.");
6270 CmdArgs.push_back("-o");
6271 CmdArgs.push_back(Output.getFilename());
6273 assert(Input.isFilename() && "Invalid input.");
6274 CmdArgs.push_back(Input.getFilename());
6276 // asm_final spec is empty.
6278 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6279 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6282 void darwin::MachOTool::anchor() {}
6284 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6285 ArgStringList &CmdArgs) const {
6286 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6288 // Derived from darwin_arch spec.
6289 CmdArgs.push_back("-arch");
6290 CmdArgs.push_back(Args.MakeArgString(ArchName));
6292 // FIXME: Is this needed anymore?
6293 if (ArchName == "arm")
6294 CmdArgs.push_back("-force_cpusubtype_ALL");
6297 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6298 // We only need to generate a temp path for LTO if we aren't compiling object
6299 // files. When compiling source files, we run 'dsymutil' after linking. We
6300 // don't run 'dsymutil' when compiling object files.
6301 for (const auto &Input : Inputs)
6302 if (Input.getType() != types::TY_Object)
6308 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6309 ArgStringList &CmdArgs,
6310 const InputInfoList &Inputs) const {
6311 const Driver &D = getToolChain().getDriver();
6312 const toolchains::MachO &MachOTC = getMachOToolChain();
6314 unsigned Version[3] = {0, 0, 0};
6315 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6317 if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6318 Version[2], HadExtra) ||
6320 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6323 // Newer linkers support -demangle. Pass it if supported and not disabled by
6325 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6326 CmdArgs.push_back("-demangle");
6328 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6329 CmdArgs.push_back("-export_dynamic");
6331 // If we are using App Extension restrictions, pass a flag to the linker
6332 // telling it that the compiled code has been audited.
6333 if (Args.hasFlag(options::OPT_fapplication_extension,
6334 options::OPT_fno_application_extension, false))
6335 CmdArgs.push_back("-application_extension");
6337 // If we are using LTO, then automatically create a temporary file path for
6338 // the linker to use, so that it's lifetime will extend past a possible
6340 if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
6341 const char *TmpPath = C.getArgs().MakeArgString(
6342 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6343 C.addTempFile(TmpPath);
6344 CmdArgs.push_back("-object_path_lto");
6345 CmdArgs.push_back(TmpPath);
6348 // Derived from the "link" spec.
6349 Args.AddAllArgs(CmdArgs, options::OPT_static);
6350 if (!Args.hasArg(options::OPT_static))
6351 CmdArgs.push_back("-dynamic");
6352 if (Args.hasArg(options::OPT_fgnu_runtime)) {
6353 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6354 // here. How do we wish to handle such things?
6357 if (!Args.hasArg(options::OPT_dynamiclib)) {
6358 AddMachOArch(Args, CmdArgs);
6359 // FIXME: Why do this only on this path?
6360 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
6362 Args.AddLastArg(CmdArgs, options::OPT_bundle);
6363 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
6364 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
6367 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
6368 (A = Args.getLastArg(options::OPT_current__version)) ||
6369 (A = Args.getLastArg(options::OPT_install__name)))
6370 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
6373 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
6374 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
6375 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
6377 CmdArgs.push_back("-dylib");
6380 if ((A = Args.getLastArg(options::OPT_bundle)) ||
6381 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
6382 (A = Args.getLastArg(options::OPT_client__name)) ||
6383 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
6384 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
6385 (A = Args.getLastArg(options::OPT_private__bundle)))
6386 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
6389 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
6390 "-dylib_compatibility_version");
6391 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
6392 "-dylib_current_version");
6394 AddMachOArch(Args, CmdArgs);
6396 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
6397 "-dylib_install_name");
6400 Args.AddLastArg(CmdArgs, options::OPT_all__load);
6401 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
6402 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
6403 if (MachOTC.isTargetIOSBased())
6404 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
6405 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
6406 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
6407 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
6408 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
6409 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
6410 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
6411 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
6412 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
6413 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
6414 Args.AddAllArgs(CmdArgs, options::OPT_init);
6416 // Add the deployment target.
6417 MachOTC.addMinVersionArgs(Args, CmdArgs);
6419 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
6420 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
6421 Args.AddLastArg(CmdArgs, options::OPT_single__module);
6422 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
6423 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
6426 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
6427 options::OPT_fno_pie, options::OPT_fno_PIE)) {
6428 if (A->getOption().matches(options::OPT_fpie) ||
6429 A->getOption().matches(options::OPT_fPIE))
6430 CmdArgs.push_back("-pie");
6432 CmdArgs.push_back("-no_pie");
6435 Args.AddLastArg(CmdArgs, options::OPT_prebind);
6436 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
6437 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
6438 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
6439 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
6440 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
6441 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
6442 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
6443 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
6444 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
6445 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
6446 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
6447 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
6448 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
6449 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
6450 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
6452 // Give --sysroot= preference, over the Apple specific behavior to also use
6453 // --isysroot as the syslibroot.
6454 StringRef sysroot = C.getSysRoot();
6455 if (sysroot != "") {
6456 CmdArgs.push_back("-syslibroot");
6457 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
6458 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
6459 CmdArgs.push_back("-syslibroot");
6460 CmdArgs.push_back(A->getValue());
6463 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
6464 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
6465 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
6466 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
6467 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
6468 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
6469 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
6470 Args.AddAllArgs(CmdArgs, options::OPT_y);
6471 Args.AddLastArg(CmdArgs, options::OPT_w);
6472 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
6473 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
6474 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
6475 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
6476 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
6477 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
6478 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
6479 Args.AddLastArg(CmdArgs, options::OPT_whyload);
6480 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
6481 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
6482 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
6483 Args.AddLastArg(CmdArgs, options::OPT_Mach);
6486 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6487 const InputInfo &Output,
6488 const InputInfoList &Inputs,
6489 const ArgList &Args,
6490 const char *LinkingOutput) const {
6491 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
6493 // If the number of arguments surpasses the system limits, we will encode the
6494 // input files in a separate file, shortening the command line. To this end,
6495 // build a list of input file names that can be passed via a file with the
6496 // -filelist linker option.
6497 llvm::opt::ArgStringList InputFileList;
6499 // The logic here is derived from gcc's behavior; most of which
6500 // comes from specs (starting with link_command). Consult gcc for
6501 // more information.
6502 ArgStringList CmdArgs;
6504 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
6505 if (Args.hasArg(options::OPT_ccc_arcmt_check,
6506 options::OPT_ccc_arcmt_migrate)) {
6507 for (const auto &Arg : Args)
6510 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
6511 CmdArgs.push_back(Output.getFilename());
6512 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6516 // I'm not sure why this particular decomposition exists in gcc, but
6517 // we follow suite for ease of comparison.
6518 AddLinkArgs(C, Args, CmdArgs, Inputs);
6520 Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
6521 Args.AddAllArgs(CmdArgs, options::OPT_s);
6522 Args.AddAllArgs(CmdArgs, options::OPT_t);
6523 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6524 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
6525 Args.AddLastArg(CmdArgs, options::OPT_e);
6526 Args.AddAllArgs(CmdArgs, options::OPT_r);
6528 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
6529 // members of static archive libraries which implement Objective-C classes or
6531 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
6532 CmdArgs.push_back("-ObjC");
6534 CmdArgs.push_back("-o");
6535 CmdArgs.push_back(Output.getFilename());
6537 if (!Args.hasArg(options::OPT_nostdlib) &&
6538 !Args.hasArg(options::OPT_nostartfiles))
6539 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
6541 // SafeStack requires its own runtime libraries
6542 // These libraries should be linked first, to make sure the
6543 // __safestack_init constructor executes before everything else
6544 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
6545 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
6546 "libclang_rt.safestack_osx.a",
6547 /*AlwaysLink=*/true);
6550 Args.AddAllArgs(CmdArgs, options::OPT_L);
6552 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6553 // Build the input file for -filelist (list of linker input files) in case we
6555 for (const auto &II : Inputs) {
6556 if (!II.isFilename()) {
6557 // This is a linker input argument.
6558 // We cannot mix input arguments and file names in a -filelist input, thus
6559 // we prematurely stop our list (remaining files shall be passed as
6561 if (InputFileList.size() > 0)
6567 InputFileList.push_back(II.getFilename());
6570 if (!Args.hasArg(options::OPT_nostdlib) &&
6571 !Args.hasArg(options::OPT_nodefaultlibs))
6572 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
6574 if (isObjCRuntimeLinked(Args) && !Args.hasArg(options::OPT_nostdlib) &&
6575 !Args.hasArg(options::OPT_nodefaultlibs)) {
6576 // We use arclite library for both ARC and subscripting support.
6577 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
6579 CmdArgs.push_back("-framework");
6580 CmdArgs.push_back("Foundation");
6582 CmdArgs.push_back("-lobjc");
6585 if (LinkingOutput) {
6586 CmdArgs.push_back("-arch_multiple");
6587 CmdArgs.push_back("-final_output");
6588 CmdArgs.push_back(LinkingOutput);
6591 if (Args.hasArg(options::OPT_fnested_functions))
6592 CmdArgs.push_back("-allow_stack_execute");
6594 // TODO: It would be nice to use addProfileRT() here, but darwin's compiler-rt
6595 // paths are different enough from other toolchains that this needs a fair
6596 // amount of refactoring done first.
6597 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
6599 if (!Args.hasArg(options::OPT_nostdlib) &&
6600 !Args.hasArg(options::OPT_nodefaultlibs)) {
6601 if (getToolChain().getDriver().CCCIsCXX())
6602 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6604 // link_ssp spec is empty.
6606 // Let the tool chain choose which runtime library to link.
6607 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
6610 if (!Args.hasArg(options::OPT_nostdlib) &&
6611 !Args.hasArg(options::OPT_nostartfiles)) {
6612 // endfile_spec is empty.
6615 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6616 Args.AddAllArgs(CmdArgs, options::OPT_F);
6618 // -iframework should be forwarded as -F.
6619 for (const Arg *A : Args.filtered(options::OPT_iframework))
6620 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
6622 if (!Args.hasArg(options::OPT_nostdlib) &&
6623 !Args.hasArg(options::OPT_nodefaultlibs)) {
6624 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6625 if (A->getValue() == StringRef("Accelerate")) {
6626 CmdArgs.push_back("-framework");
6627 CmdArgs.push_back("Accelerate");
6632 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6633 std::unique_ptr<Command> Cmd =
6634 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
6635 Cmd->setInputFileList(std::move(InputFileList));
6636 C.addCommand(std::move(Cmd));
6639 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
6640 const InputInfo &Output,
6641 const InputInfoList &Inputs,
6642 const ArgList &Args,
6643 const char *LinkingOutput) const {
6644 ArgStringList CmdArgs;
6646 CmdArgs.push_back("-create");
6647 assert(Output.isFilename() && "Unexpected lipo output.");
6649 CmdArgs.push_back("-output");
6650 CmdArgs.push_back(Output.getFilename());
6652 for (const auto &II : Inputs) {
6653 assert(II.isFilename() && "Unexpected lipo input.");
6654 CmdArgs.push_back(II.getFilename());
6657 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
6658 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6661 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
6662 const InputInfo &Output,
6663 const InputInfoList &Inputs,
6664 const ArgList &Args,
6665 const char *LinkingOutput) const {
6666 ArgStringList CmdArgs;
6668 CmdArgs.push_back("-o");
6669 CmdArgs.push_back(Output.getFilename());
6671 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6672 const InputInfo &Input = Inputs[0];
6673 assert(Input.isFilename() && "Unexpected dsymutil input.");
6674 CmdArgs.push_back(Input.getFilename());
6677 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
6678 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6681 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
6682 const InputInfo &Output,
6683 const InputInfoList &Inputs,
6684 const ArgList &Args,
6685 const char *LinkingOutput) const {
6686 ArgStringList CmdArgs;
6687 CmdArgs.push_back("--verify");
6688 CmdArgs.push_back("--debug-info");
6689 CmdArgs.push_back("--eh-frame");
6690 CmdArgs.push_back("--quiet");
6692 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6693 const InputInfo &Input = Inputs[0];
6694 assert(Input.isFilename() && "Unexpected verify input");
6696 // Grabbing the output of the earlier dsymutil run.
6697 CmdArgs.push_back(Input.getFilename());
6700 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
6701 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6704 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6705 const InputInfo &Output,
6706 const InputInfoList &Inputs,
6707 const ArgList &Args,
6708 const char *LinkingOutput) const {
6709 claimNoWarnArgs(Args);
6710 ArgStringList CmdArgs;
6712 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6714 CmdArgs.push_back("-o");
6715 CmdArgs.push_back(Output.getFilename());
6717 for (const auto &II : Inputs)
6718 CmdArgs.push_back(II.getFilename());
6720 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6721 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6724 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6725 const InputInfo &Output,
6726 const InputInfoList &Inputs,
6727 const ArgList &Args,
6728 const char *LinkingOutput) const {
6729 // FIXME: Find a real GCC, don't hard-code versions here
6730 std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
6731 const llvm::Triple &T = getToolChain().getTriple();
6732 std::string LibPath = "/usr/lib/";
6733 const llvm::Triple::ArchType Arch = T.getArch();
6735 case llvm::Triple::x86:
6737 ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
6739 case llvm::Triple::x86_64:
6740 GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
6741 GCCLibPath += "/4.5.2/amd64/";
6742 LibPath += "amd64/";
6745 llvm_unreachable("Unsupported architecture");
6748 ArgStringList CmdArgs;
6750 // Demangle C++ names in errors
6751 CmdArgs.push_back("-C");
6753 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6754 (!Args.hasArg(options::OPT_shared))) {
6755 CmdArgs.push_back("-e");
6756 CmdArgs.push_back("_start");
6759 if (Args.hasArg(options::OPT_static)) {
6760 CmdArgs.push_back("-Bstatic");
6761 CmdArgs.push_back("-dn");
6763 CmdArgs.push_back("-Bdynamic");
6764 if (Args.hasArg(options::OPT_shared)) {
6765 CmdArgs.push_back("-shared");
6767 CmdArgs.push_back("--dynamic-linker");
6768 CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
6772 if (Output.isFilename()) {
6773 CmdArgs.push_back("-o");
6774 CmdArgs.push_back(Output.getFilename());
6776 assert(Output.isNothing() && "Invalid output.");
6779 if (!Args.hasArg(options::OPT_nostdlib) &&
6780 !Args.hasArg(options::OPT_nostartfiles)) {
6781 if (!Args.hasArg(options::OPT_shared)) {
6782 CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
6783 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6784 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6785 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6787 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6788 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6789 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6791 if (getToolChain().getDriver().CCCIsCXX())
6792 CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
6795 CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
6797 Args.AddAllArgs(CmdArgs, options::OPT_L);
6798 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6799 Args.AddAllArgs(CmdArgs, options::OPT_e);
6800 Args.AddAllArgs(CmdArgs, options::OPT_r);
6802 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6804 if (!Args.hasArg(options::OPT_nostdlib) &&
6805 !Args.hasArg(options::OPT_nodefaultlibs)) {
6806 if (getToolChain().getDriver().CCCIsCXX())
6807 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6808 CmdArgs.push_back("-lgcc_s");
6809 if (!Args.hasArg(options::OPT_shared)) {
6810 CmdArgs.push_back("-lgcc");
6811 CmdArgs.push_back("-lc");
6812 CmdArgs.push_back("-lm");
6816 if (!Args.hasArg(options::OPT_nostdlib) &&
6817 !Args.hasArg(options::OPT_nostartfiles)) {
6818 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
6820 CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
6822 addProfileRT(getToolChain(), Args, CmdArgs);
6824 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6825 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6828 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6829 const InputInfo &Output,
6830 const InputInfoList &Inputs,
6831 const ArgList &Args,
6832 const char *LinkingOutput) const {
6833 claimNoWarnArgs(Args);
6834 ArgStringList CmdArgs;
6835 bool NeedsKPIC = false;
6837 switch (getToolChain().getArch()) {
6838 case llvm::Triple::x86:
6839 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
6840 // instruct as in the base system to assemble 32-bit code.
6841 CmdArgs.push_back("--32");
6844 case llvm::Triple::ppc:
6845 CmdArgs.push_back("-mppc");
6846 CmdArgs.push_back("-many");
6849 case llvm::Triple::sparc:
6850 case llvm::Triple::sparcel:
6851 CmdArgs.push_back("-32");
6855 case llvm::Triple::sparcv9:
6856 CmdArgs.push_back("-64");
6857 CmdArgs.push_back("-Av9a");
6861 case llvm::Triple::mips64:
6862 case llvm::Triple::mips64el: {
6865 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6867 CmdArgs.push_back("-mabi");
6868 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6870 if (getToolChain().getArch() == llvm::Triple::mips64)
6871 CmdArgs.push_back("-EB");
6873 CmdArgs.push_back("-EL");
6884 addAssemblerKPIC(Args, CmdArgs);
6886 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6888 CmdArgs.push_back("-o");
6889 CmdArgs.push_back(Output.getFilename());
6891 for (const auto &II : Inputs)
6892 CmdArgs.push_back(II.getFilename());
6894 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6895 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6898 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6899 const InputInfo &Output,
6900 const InputInfoList &Inputs,
6901 const ArgList &Args,
6902 const char *LinkingOutput) const {
6903 const Driver &D = getToolChain().getDriver();
6904 ArgStringList CmdArgs;
6906 // Silence warning for "clang -g foo.o -o foo"
6907 Args.ClaimAllArgs(options::OPT_g_Group);
6908 // and "clang -emit-llvm foo.o -o foo"
6909 Args.ClaimAllArgs(options::OPT_emit_llvm);
6910 // and for "clang -w foo.o -o foo". Other warning options are already
6911 // handled somewhere else.
6912 Args.ClaimAllArgs(options::OPT_w);
6914 if (getToolChain().getArch() == llvm::Triple::mips64)
6915 CmdArgs.push_back("-EB");
6916 else if (getToolChain().getArch() == llvm::Triple::mips64el)
6917 CmdArgs.push_back("-EL");
6919 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6920 (!Args.hasArg(options::OPT_shared))) {
6921 CmdArgs.push_back("-e");
6922 CmdArgs.push_back("__start");
6925 if (Args.hasArg(options::OPT_static)) {
6926 CmdArgs.push_back("-Bstatic");
6928 if (Args.hasArg(options::OPT_rdynamic))
6929 CmdArgs.push_back("-export-dynamic");
6930 CmdArgs.push_back("--eh-frame-hdr");
6931 CmdArgs.push_back("-Bdynamic");
6932 if (Args.hasArg(options::OPT_shared)) {
6933 CmdArgs.push_back("-shared");
6935 CmdArgs.push_back("-dynamic-linker");
6936 CmdArgs.push_back("/usr/libexec/ld.so");
6940 if (Args.hasArg(options::OPT_nopie))
6941 CmdArgs.push_back("-nopie");
6943 if (Output.isFilename()) {
6944 CmdArgs.push_back("-o");
6945 CmdArgs.push_back(Output.getFilename());
6947 assert(Output.isNothing() && "Invalid output.");
6950 if (!Args.hasArg(options::OPT_nostdlib) &&
6951 !Args.hasArg(options::OPT_nostartfiles)) {
6952 if (!Args.hasArg(options::OPT_shared)) {
6953 if (Args.hasArg(options::OPT_pg))
6955 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
6958 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
6960 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6963 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6967 std::string Triple = getToolChain().getTripleString();
6968 if (Triple.substr(0, 6) == "x86_64")
6969 Triple.replace(0, 6, "amd64");
6971 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
6973 Args.AddAllArgs(CmdArgs, options::OPT_L);
6974 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6975 Args.AddAllArgs(CmdArgs, options::OPT_e);
6976 Args.AddAllArgs(CmdArgs, options::OPT_s);
6977 Args.AddAllArgs(CmdArgs, options::OPT_t);
6978 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6979 Args.AddAllArgs(CmdArgs, options::OPT_r);
6981 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6983 if (!Args.hasArg(options::OPT_nostdlib) &&
6984 !Args.hasArg(options::OPT_nodefaultlibs)) {
6986 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6987 if (Args.hasArg(options::OPT_pg))
6988 CmdArgs.push_back("-lm_p");
6990 CmdArgs.push_back("-lm");
6993 // FIXME: For some reason GCC passes -lgcc before adding
6994 // the default system libraries. Just mimic this for now.
6995 CmdArgs.push_back("-lgcc");
6997 if (Args.hasArg(options::OPT_pthread)) {
6998 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
6999 CmdArgs.push_back("-lpthread_p");
7001 CmdArgs.push_back("-lpthread");
7004 if (!Args.hasArg(options::OPT_shared)) {
7005 if (Args.hasArg(options::OPT_pg))
7006 CmdArgs.push_back("-lc_p");
7008 CmdArgs.push_back("-lc");
7011 CmdArgs.push_back("-lgcc");
7014 if (!Args.hasArg(options::OPT_nostdlib) &&
7015 !Args.hasArg(options::OPT_nostartfiles)) {
7016 if (!Args.hasArg(options::OPT_shared))
7018 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7021 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7024 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7025 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7028 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7029 const InputInfo &Output,
7030 const InputInfoList &Inputs,
7031 const ArgList &Args,
7032 const char *LinkingOutput) const {
7033 claimNoWarnArgs(Args);
7034 ArgStringList CmdArgs;
7036 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7038 CmdArgs.push_back("-o");
7039 CmdArgs.push_back(Output.getFilename());
7041 for (const auto &II : Inputs)
7042 CmdArgs.push_back(II.getFilename());
7044 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7045 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7048 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7049 const InputInfo &Output,
7050 const InputInfoList &Inputs,
7051 const ArgList &Args,
7052 const char *LinkingOutput) const {
7053 const Driver &D = getToolChain().getDriver();
7054 ArgStringList CmdArgs;
7056 if ((!Args.hasArg(options::OPT_nostdlib)) &&
7057 (!Args.hasArg(options::OPT_shared))) {
7058 CmdArgs.push_back("-e");
7059 CmdArgs.push_back("__start");
7062 if (Args.hasArg(options::OPT_static)) {
7063 CmdArgs.push_back("-Bstatic");
7065 if (Args.hasArg(options::OPT_rdynamic))
7066 CmdArgs.push_back("-export-dynamic");
7067 CmdArgs.push_back("--eh-frame-hdr");
7068 CmdArgs.push_back("-Bdynamic");
7069 if (Args.hasArg(options::OPT_shared)) {
7070 CmdArgs.push_back("-shared");
7072 CmdArgs.push_back("-dynamic-linker");
7073 CmdArgs.push_back("/usr/libexec/ld.so");
7077 if (Output.isFilename()) {
7078 CmdArgs.push_back("-o");
7079 CmdArgs.push_back(Output.getFilename());
7081 assert(Output.isNothing() && "Invalid output.");
7084 if (!Args.hasArg(options::OPT_nostdlib) &&
7085 !Args.hasArg(options::OPT_nostartfiles)) {
7086 if (!Args.hasArg(options::OPT_shared)) {
7087 if (Args.hasArg(options::OPT_pg))
7089 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7092 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7094 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7097 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7101 Args.AddAllArgs(CmdArgs, options::OPT_L);
7102 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7103 Args.AddAllArgs(CmdArgs, options::OPT_e);
7105 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7107 if (!Args.hasArg(options::OPT_nostdlib) &&
7108 !Args.hasArg(options::OPT_nodefaultlibs)) {
7110 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7111 if (Args.hasArg(options::OPT_pg))
7112 CmdArgs.push_back("-lm_p");
7114 CmdArgs.push_back("-lm");
7117 if (Args.hasArg(options::OPT_pthread)) {
7118 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7119 CmdArgs.push_back("-lpthread_p");
7121 CmdArgs.push_back("-lpthread");
7124 if (!Args.hasArg(options::OPT_shared)) {
7125 if (Args.hasArg(options::OPT_pg))
7126 CmdArgs.push_back("-lc_p");
7128 CmdArgs.push_back("-lc");
7132 switch (getToolChain().getArch()) {
7133 case llvm::Triple::arm:
7136 case llvm::Triple::x86:
7139 case llvm::Triple::x86_64:
7143 llvm_unreachable("Unsupported architecture");
7145 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7148 if (!Args.hasArg(options::OPT_nostdlib) &&
7149 !Args.hasArg(options::OPT_nostartfiles)) {
7150 if (!Args.hasArg(options::OPT_shared))
7152 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7155 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7158 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7159 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7162 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7163 const InputInfo &Output,
7164 const InputInfoList &Inputs,
7165 const ArgList &Args,
7166 const char *LinkingOutput) const {
7167 claimNoWarnArgs(Args);
7168 ArgStringList CmdArgs;
7170 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7171 // instruct as in the base system to assemble 32-bit code.
7172 if (getToolChain().getArch() == llvm::Triple::x86)
7173 CmdArgs.push_back("--32");
7174 else if (getToolChain().getArch() == llvm::Triple::ppc)
7175 CmdArgs.push_back("-a32");
7176 else if (getToolChain().getArch() == llvm::Triple::mips ||
7177 getToolChain().getArch() == llvm::Triple::mipsel ||
7178 getToolChain().getArch() == llvm::Triple::mips64 ||
7179 getToolChain().getArch() == llvm::Triple::mips64el) {
7182 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7184 CmdArgs.push_back("-march");
7185 CmdArgs.push_back(CPUName.data());
7187 CmdArgs.push_back("-mabi");
7188 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7190 if (getToolChain().getArch() == llvm::Triple::mips ||
7191 getToolChain().getArch() == llvm::Triple::mips64)
7192 CmdArgs.push_back("-EB");
7194 CmdArgs.push_back("-EL");
7196 addAssemblerKPIC(Args, CmdArgs);
7197 } else if (getToolChain().getArch() == llvm::Triple::arm ||
7198 getToolChain().getArch() == llvm::Triple::armeb ||
7199 getToolChain().getArch() == llvm::Triple::thumb ||
7200 getToolChain().getArch() == llvm::Triple::thumbeb) {
7201 const Driver &D = getToolChain().getDriver();
7202 const llvm::Triple &Triple = getToolChain().getTriple();
7203 StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
7205 if (FloatABI == "hard") {
7206 CmdArgs.push_back("-mfpu=vfp");
7208 CmdArgs.push_back("-mfpu=softvfp");
7211 switch (getToolChain().getTriple().getEnvironment()) {
7212 case llvm::Triple::GNUEABIHF:
7213 case llvm::Triple::GNUEABI:
7214 case llvm::Triple::EABI:
7215 CmdArgs.push_back("-meabi=5");
7219 CmdArgs.push_back("-matpcs");
7221 } else if (getToolChain().getArch() == llvm::Triple::sparc ||
7222 getToolChain().getArch() == llvm::Triple::sparcel ||
7223 getToolChain().getArch() == llvm::Triple::sparcv9) {
7224 if (getToolChain().getArch() == llvm::Triple::sparc)
7225 CmdArgs.push_back("-Av8plusa");
7227 CmdArgs.push_back("-Av9a");
7229 addAssemblerKPIC(Args, CmdArgs);
7232 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7234 CmdArgs.push_back("-o");
7235 CmdArgs.push_back(Output.getFilename());
7237 for (const auto &II : Inputs)
7238 CmdArgs.push_back(II.getFilename());
7240 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7241 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7244 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7245 const InputInfo &Output,
7246 const InputInfoList &Inputs,
7247 const ArgList &Args,
7248 const char *LinkingOutput) const {
7249 const toolchains::FreeBSD &ToolChain =
7250 static_cast<const toolchains::FreeBSD &>(getToolChain());
7251 const Driver &D = ToolChain.getDriver();
7252 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7254 !Args.hasArg(options::OPT_shared) &&
7255 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7256 ArgStringList CmdArgs;
7258 // Silence warning for "clang -g foo.o -o foo"
7259 Args.ClaimAllArgs(options::OPT_g_Group);
7260 // and "clang -emit-llvm foo.o -o foo"
7261 Args.ClaimAllArgs(options::OPT_emit_llvm);
7262 // and for "clang -w foo.o -o foo". Other warning options are already
7263 // handled somewhere else.
7264 Args.ClaimAllArgs(options::OPT_w);
7266 if (!D.SysRoot.empty())
7267 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7270 CmdArgs.push_back("-pie");
7272 if (Args.hasArg(options::OPT_static)) {
7273 CmdArgs.push_back("-Bstatic");
7275 if (Args.hasArg(options::OPT_rdynamic))
7276 CmdArgs.push_back("-export-dynamic");
7277 CmdArgs.push_back("--eh-frame-hdr");
7278 if (Args.hasArg(options::OPT_shared)) {
7279 CmdArgs.push_back("-Bshareable");
7281 CmdArgs.push_back("-dynamic-linker");
7282 CmdArgs.push_back("/libexec/ld-elf.so.1");
7284 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7285 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7286 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7287 CmdArgs.push_back("--hash-style=both");
7290 CmdArgs.push_back("--enable-new-dtags");
7293 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7294 // instruct ld in the base system to link 32-bit code.
7295 if (Arch == llvm::Triple::x86) {
7296 CmdArgs.push_back("-m");
7297 CmdArgs.push_back("elf_i386_fbsd");
7300 if (Arch == llvm::Triple::ppc) {
7301 CmdArgs.push_back("-m");
7302 CmdArgs.push_back("elf32ppc_fbsd");
7305 if (Arg *A = Args.getLastArg(options::OPT_G)) {
7306 if (ToolChain.getArch() == llvm::Triple::mips ||
7307 ToolChain.getArch() == llvm::Triple::mipsel ||
7308 ToolChain.getArch() == llvm::Triple::mips64 ||
7309 ToolChain.getArch() == llvm::Triple::mips64el) {
7310 StringRef v = A->getValue();
7311 CmdArgs.push_back(Args.MakeArgString("-G" + v));
7316 if (Output.isFilename()) {
7317 CmdArgs.push_back("-o");
7318 CmdArgs.push_back(Output.getFilename());
7320 assert(Output.isNothing() && "Invalid output.");
7323 if (!Args.hasArg(options::OPT_nostdlib) &&
7324 !Args.hasArg(options::OPT_nostartfiles)) {
7325 const char *crt1 = nullptr;
7326 if (!Args.hasArg(options::OPT_shared)) {
7327 if (Args.hasArg(options::OPT_pg))
7335 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7337 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7339 const char *crtbegin = nullptr;
7340 if (Args.hasArg(options::OPT_static))
7341 crtbegin = "crtbeginT.o";
7342 else if (Args.hasArg(options::OPT_shared) || IsPIE)
7343 crtbegin = "crtbeginS.o";
7345 crtbegin = "crtbegin.o";
7347 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7350 Args.AddAllArgs(CmdArgs, options::OPT_L);
7351 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
7352 for (const auto &Path : Paths)
7353 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
7354 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7355 Args.AddAllArgs(CmdArgs, options::OPT_e);
7356 Args.AddAllArgs(CmdArgs, options::OPT_s);
7357 Args.AddAllArgs(CmdArgs, options::OPT_t);
7358 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7359 Args.AddAllArgs(CmdArgs, options::OPT_r);
7361 if (D.IsUsingLTO(Args))
7362 AddGoldPlugin(ToolChain, Args, CmdArgs);
7364 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7365 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7367 if (!Args.hasArg(options::OPT_nostdlib) &&
7368 !Args.hasArg(options::OPT_nodefaultlibs)) {
7369 addOpenMPRuntime(CmdArgs, ToolChain, Args);
7371 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7372 if (Args.hasArg(options::OPT_pg))
7373 CmdArgs.push_back("-lm_p");
7375 CmdArgs.push_back("-lm");
7377 if (NeedsSanitizerDeps)
7378 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7379 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7380 // the default system libraries. Just mimic this for now.
7381 if (Args.hasArg(options::OPT_pg))
7382 CmdArgs.push_back("-lgcc_p");
7384 CmdArgs.push_back("-lgcc");
7385 if (Args.hasArg(options::OPT_static)) {
7386 CmdArgs.push_back("-lgcc_eh");
7387 } else if (Args.hasArg(options::OPT_pg)) {
7388 CmdArgs.push_back("-lgcc_eh_p");
7390 CmdArgs.push_back("--as-needed");
7391 CmdArgs.push_back("-lgcc_s");
7392 CmdArgs.push_back("--no-as-needed");
7395 if (Args.hasArg(options::OPT_pthread)) {
7396 if (Args.hasArg(options::OPT_pg))
7397 CmdArgs.push_back("-lpthread_p");
7399 CmdArgs.push_back("-lpthread");
7402 if (Args.hasArg(options::OPT_pg)) {
7403 if (Args.hasArg(options::OPT_shared))
7404 CmdArgs.push_back("-lc");
7406 CmdArgs.push_back("-lc_p");
7407 CmdArgs.push_back("-lgcc_p");
7409 CmdArgs.push_back("-lc");
7410 CmdArgs.push_back("-lgcc");
7413 if (Args.hasArg(options::OPT_static)) {
7414 CmdArgs.push_back("-lgcc_eh");
7415 } else if (Args.hasArg(options::OPT_pg)) {
7416 CmdArgs.push_back("-lgcc_eh_p");
7418 CmdArgs.push_back("--as-needed");
7419 CmdArgs.push_back("-lgcc_s");
7420 CmdArgs.push_back("--no-as-needed");
7424 if (!Args.hasArg(options::OPT_nostdlib) &&
7425 !Args.hasArg(options::OPT_nostartfiles)) {
7426 if (Args.hasArg(options::OPT_shared) || IsPIE)
7427 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
7429 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7430 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7433 addProfileRT(ToolChain, Args, CmdArgs);
7435 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7436 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7439 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7440 const InputInfo &Output,
7441 const InputInfoList &Inputs,
7442 const ArgList &Args,
7443 const char *LinkingOutput) const {
7444 claimNoWarnArgs(Args);
7445 ArgStringList CmdArgs;
7447 // GNU as needs different flags for creating the correct output format
7448 // on architectures with different ABIs or optional feature sets.
7449 switch (getToolChain().getArch()) {
7450 case llvm::Triple::x86:
7451 CmdArgs.push_back("--32");
7453 case llvm::Triple::arm:
7454 case llvm::Triple::armeb:
7455 case llvm::Triple::thumb:
7456 case llvm::Triple::thumbeb: {
7457 StringRef MArch, MCPU;
7458 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
7460 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
7461 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
7465 case llvm::Triple::mips:
7466 case llvm::Triple::mipsel:
7467 case llvm::Triple::mips64:
7468 case llvm::Triple::mips64el: {
7471 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7473 CmdArgs.push_back("-march");
7474 CmdArgs.push_back(CPUName.data());
7476 CmdArgs.push_back("-mabi");
7477 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7479 if (getToolChain().getArch() == llvm::Triple::mips ||
7480 getToolChain().getArch() == llvm::Triple::mips64)
7481 CmdArgs.push_back("-EB");
7483 CmdArgs.push_back("-EL");
7485 addAssemblerKPIC(Args, CmdArgs);
7489 case llvm::Triple::sparc:
7490 case llvm::Triple::sparcel:
7491 CmdArgs.push_back("-32");
7492 addAssemblerKPIC(Args, CmdArgs);
7495 case llvm::Triple::sparcv9:
7496 CmdArgs.push_back("-64");
7497 CmdArgs.push_back("-Av9");
7498 addAssemblerKPIC(Args, CmdArgs);
7505 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7507 CmdArgs.push_back("-o");
7508 CmdArgs.push_back(Output.getFilename());
7510 for (const auto &II : Inputs)
7511 CmdArgs.push_back(II.getFilename());
7513 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
7514 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7517 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7518 const InputInfo &Output,
7519 const InputInfoList &Inputs,
7520 const ArgList &Args,
7521 const char *LinkingOutput) const {
7522 const Driver &D = getToolChain().getDriver();
7523 ArgStringList CmdArgs;
7525 if (!D.SysRoot.empty())
7526 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7528 CmdArgs.push_back("--eh-frame-hdr");
7529 if (Args.hasArg(options::OPT_static)) {
7530 CmdArgs.push_back("-Bstatic");
7532 if (Args.hasArg(options::OPT_rdynamic))
7533 CmdArgs.push_back("-export-dynamic");
7534 if (Args.hasArg(options::OPT_shared)) {
7535 CmdArgs.push_back("-Bshareable");
7537 CmdArgs.push_back("-dynamic-linker");
7538 CmdArgs.push_back("/libexec/ld.elf_so");
7542 // Many NetBSD architectures support more than one ABI.
7543 // Determine the correct emulation for ld.
7544 switch (getToolChain().getArch()) {
7545 case llvm::Triple::x86:
7546 CmdArgs.push_back("-m");
7547 CmdArgs.push_back("elf_i386");
7549 case llvm::Triple::arm:
7550 case llvm::Triple::thumb:
7551 CmdArgs.push_back("-m");
7552 switch (getToolChain().getTriple().getEnvironment()) {
7553 case llvm::Triple::EABI:
7554 case llvm::Triple::GNUEABI:
7555 CmdArgs.push_back("armelf_nbsd_eabi");
7557 case llvm::Triple::EABIHF:
7558 case llvm::Triple::GNUEABIHF:
7559 CmdArgs.push_back("armelf_nbsd_eabihf");
7562 CmdArgs.push_back("armelf_nbsd");
7566 case llvm::Triple::armeb:
7567 case llvm::Triple::thumbeb:
7568 arm::appendEBLinkFlags(
7570 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7571 CmdArgs.push_back("-m");
7572 switch (getToolChain().getTriple().getEnvironment()) {
7573 case llvm::Triple::EABI:
7574 case llvm::Triple::GNUEABI:
7575 CmdArgs.push_back("armelfb_nbsd_eabi");
7577 case llvm::Triple::EABIHF:
7578 case llvm::Triple::GNUEABIHF:
7579 CmdArgs.push_back("armelfb_nbsd_eabihf");
7582 CmdArgs.push_back("armelfb_nbsd");
7586 case llvm::Triple::mips64:
7587 case llvm::Triple::mips64el:
7588 if (mips::hasMipsAbiArg(Args, "32")) {
7589 CmdArgs.push_back("-m");
7590 if (getToolChain().getArch() == llvm::Triple::mips64)
7591 CmdArgs.push_back("elf32btsmip");
7593 CmdArgs.push_back("elf32ltsmip");
7594 } else if (mips::hasMipsAbiArg(Args, "64")) {
7595 CmdArgs.push_back("-m");
7596 if (getToolChain().getArch() == llvm::Triple::mips64)
7597 CmdArgs.push_back("elf64btsmip");
7599 CmdArgs.push_back("elf64ltsmip");
7602 case llvm::Triple::ppc:
7603 CmdArgs.push_back("-m");
7604 CmdArgs.push_back("elf32ppc_nbsd");
7607 case llvm::Triple::ppc64:
7608 case llvm::Triple::ppc64le:
7609 CmdArgs.push_back("-m");
7610 CmdArgs.push_back("elf64ppc");
7613 case llvm::Triple::sparc:
7614 CmdArgs.push_back("-m");
7615 CmdArgs.push_back("elf32_sparc");
7618 case llvm::Triple::sparcv9:
7619 CmdArgs.push_back("-m");
7620 CmdArgs.push_back("elf64_sparc");
7627 if (Output.isFilename()) {
7628 CmdArgs.push_back("-o");
7629 CmdArgs.push_back(Output.getFilename());
7631 assert(Output.isNothing() && "Invalid output.");
7634 if (!Args.hasArg(options::OPT_nostdlib) &&
7635 !Args.hasArg(options::OPT_nostartfiles)) {
7636 if (!Args.hasArg(options::OPT_shared)) {
7638 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7640 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7642 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7645 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7647 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7651 Args.AddAllArgs(CmdArgs, options::OPT_L);
7652 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7653 Args.AddAllArgs(CmdArgs, options::OPT_e);
7654 Args.AddAllArgs(CmdArgs, options::OPT_s);
7655 Args.AddAllArgs(CmdArgs, options::OPT_t);
7656 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7657 Args.AddAllArgs(CmdArgs, options::OPT_r);
7659 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7661 unsigned Major, Minor, Micro;
7662 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
7663 bool useLibgcc = true;
7664 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
7665 switch (getToolChain().getArch()) {
7666 case llvm::Triple::aarch64:
7667 case llvm::Triple::arm:
7668 case llvm::Triple::armeb:
7669 case llvm::Triple::thumb:
7670 case llvm::Triple::thumbeb:
7671 case llvm::Triple::ppc:
7672 case llvm::Triple::ppc64:
7673 case llvm::Triple::ppc64le:
7674 case llvm::Triple::x86:
7675 case llvm::Triple::x86_64:
7683 if (!Args.hasArg(options::OPT_nostdlib) &&
7684 !Args.hasArg(options::OPT_nodefaultlibs)) {
7685 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7687 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7688 CmdArgs.push_back("-lm");
7690 if (Args.hasArg(options::OPT_pthread))
7691 CmdArgs.push_back("-lpthread");
7692 CmdArgs.push_back("-lc");
7695 if (Args.hasArg(options::OPT_static)) {
7696 // libgcc_eh depends on libc, so resolve as much as possible,
7697 // pull in any new requirements from libc and then get the rest
7699 CmdArgs.push_back("-lgcc_eh");
7700 CmdArgs.push_back("-lc");
7701 CmdArgs.push_back("-lgcc");
7703 CmdArgs.push_back("-lgcc");
7704 CmdArgs.push_back("--as-needed");
7705 CmdArgs.push_back("-lgcc_s");
7706 CmdArgs.push_back("--no-as-needed");
7711 if (!Args.hasArg(options::OPT_nostdlib) &&
7712 !Args.hasArg(options::OPT_nostartfiles)) {
7713 if (!Args.hasArg(options::OPT_shared))
7715 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7718 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7719 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7722 addProfileRT(getToolChain(), Args, CmdArgs);
7724 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7725 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7728 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7729 const InputInfo &Output,
7730 const InputInfoList &Inputs,
7731 const ArgList &Args,
7732 const char *LinkingOutput) const {
7733 claimNoWarnArgs(Args);
7735 ArgStringList CmdArgs;
7736 bool NeedsKPIC = false;
7738 switch (getToolChain().getArch()) {
7741 // Add --32/--64 to make sure we get the format we want.
7742 // This is incomplete
7743 case llvm::Triple::x86:
7744 CmdArgs.push_back("--32");
7746 case llvm::Triple::x86_64:
7747 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
7748 CmdArgs.push_back("--x32");
7750 CmdArgs.push_back("--64");
7752 case llvm::Triple::ppc:
7753 CmdArgs.push_back("-a32");
7754 CmdArgs.push_back("-mppc");
7755 CmdArgs.push_back("-many");
7757 case llvm::Triple::ppc64:
7758 CmdArgs.push_back("-a64");
7759 CmdArgs.push_back("-mppc64");
7760 CmdArgs.push_back("-many");
7762 case llvm::Triple::ppc64le:
7763 CmdArgs.push_back("-a64");
7764 CmdArgs.push_back("-mppc64");
7765 CmdArgs.push_back("-many");
7766 CmdArgs.push_back("-mlittle-endian");
7768 case llvm::Triple::sparc:
7769 case llvm::Triple::sparcel:
7770 CmdArgs.push_back("-32");
7771 CmdArgs.push_back("-Av8plusa");
7774 case llvm::Triple::sparcv9:
7775 CmdArgs.push_back("-64");
7776 CmdArgs.push_back("-Av9a");
7779 case llvm::Triple::arm:
7780 case llvm::Triple::armeb:
7781 case llvm::Triple::thumb:
7782 case llvm::Triple::thumbeb: {
7783 const llvm::Triple &Triple = getToolChain().getTriple();
7784 switch (Triple.getSubArch()) {
7785 case llvm::Triple::ARMSubArch_v7:
7786 CmdArgs.push_back("-mfpu=neon");
7788 case llvm::Triple::ARMSubArch_v8:
7789 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
7795 StringRef ARMFloatABI = tools::arm::getARMFloatABI(
7796 getToolChain().getDriver(), Args,
7797 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7798 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
7800 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
7802 // FIXME: remove krait check when GNU tools support krait cpu
7803 // for now replace it with -march=armv7-a to avoid a lower
7804 // march from being picked in the absence of a cpu flag.
7806 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
7807 StringRef(A->getValue()).lower() == "krait")
7808 CmdArgs.push_back("-march=armv7-a");
7810 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
7811 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
7814 case llvm::Triple::mips:
7815 case llvm::Triple::mipsel:
7816 case llvm::Triple::mips64:
7817 case llvm::Triple::mips64el: {
7820 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7821 ABIName = getGnuCompatibleMipsABIName(ABIName);
7823 CmdArgs.push_back("-march");
7824 CmdArgs.push_back(CPUName.data());
7826 CmdArgs.push_back("-mabi");
7827 CmdArgs.push_back(ABIName.data());
7829 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
7830 // or -mshared (not implemented) is in effect.
7831 bool IsPicOrPie = false;
7832 if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
7833 options::OPT_fpic, options::OPT_fno_pic,
7834 options::OPT_fPIE, options::OPT_fno_PIE,
7835 options::OPT_fpie, options::OPT_fno_pie)) {
7836 if (A->getOption().matches(options::OPT_fPIC) ||
7837 A->getOption().matches(options::OPT_fpic) ||
7838 A->getOption().matches(options::OPT_fPIE) ||
7839 A->getOption().matches(options::OPT_fpie))
7843 CmdArgs.push_back("-mno-shared");
7845 // LLVM doesn't support -mplt yet and acts as if it is always given.
7846 // However, -mplt has no effect with the N64 ABI.
7847 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
7849 if (getToolChain().getArch() == llvm::Triple::mips ||
7850 getToolChain().getArch() == llvm::Triple::mips64)
7851 CmdArgs.push_back("-EB");
7853 CmdArgs.push_back("-EL");
7855 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
7856 if (StringRef(A->getValue()) == "2008")
7857 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
7860 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
7861 StringRef MIPSFloatABI = getMipsFloatABI(getToolChain().getDriver(), Args);
7862 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
7863 options::OPT_mfp64)) {
7865 A->render(Args, CmdArgs);
7866 } else if (mips::shouldUseFPXX(Args, getToolChain().getTriple(), CPUName,
7867 ABIName, MIPSFloatABI))
7868 CmdArgs.push_back("-mfpxx");
7870 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
7871 // -mno-mips16 is actually -no-mips16.
7873 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
7874 if (A->getOption().matches(options::OPT_mips16)) {
7876 A->render(Args, CmdArgs);
7879 CmdArgs.push_back("-no-mips16");
7883 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
7884 options::OPT_mno_micromips);
7885 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
7886 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
7888 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
7889 // Do not use AddLastArg because not all versions of MIPS assembler
7890 // support -mmsa / -mno-msa options.
7891 if (A->getOption().matches(options::OPT_mmsa))
7892 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
7895 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
7896 options::OPT_msoft_float);
7898 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
7899 options::OPT_msingle_float);
7901 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
7902 options::OPT_mno_odd_spreg);
7907 case llvm::Triple::systemz: {
7908 // Always pass an -march option, since our default of z10 is later
7909 // than the GNU assembler's default.
7910 StringRef CPUName = getSystemZTargetCPU(Args);
7911 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
7917 addAssemblerKPIC(Args, CmdArgs);
7919 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7921 CmdArgs.push_back("-o");
7922 CmdArgs.push_back(Output.getFilename());
7924 for (const auto &II : Inputs)
7925 CmdArgs.push_back(II.getFilename());
7927 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7928 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7930 // Handle the debug info splitting at object creation time if we're
7931 // creating an object.
7932 // TODO: Currently only works on linux with newer objcopy.
7933 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7934 getToolChain().getTriple().isOSLinux())
7935 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7936 SplitDebugName(Args, Inputs[0]));
7939 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
7940 ArgStringList &CmdArgs, const ArgList &Args) {
7941 bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
7942 bool isCygMing = Triple.isOSCygMing();
7943 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
7944 Args.hasArg(options::OPT_static);
7946 CmdArgs.push_back("-lgcc");
7948 if (StaticLibgcc || isAndroid) {
7950 CmdArgs.push_back("-lgcc");
7952 if (!D.CCCIsCXX() && !isCygMing)
7953 CmdArgs.push_back("--as-needed");
7954 CmdArgs.push_back("-lgcc_s");
7955 if (!D.CCCIsCXX() && !isCygMing)
7956 CmdArgs.push_back("--no-as-needed");
7959 if (StaticLibgcc && !isAndroid)
7960 CmdArgs.push_back("-lgcc_eh");
7961 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
7962 CmdArgs.push_back("-lgcc");
7964 // According to Android ABI, we have to link with libdl if we are
7965 // linking with non-static libgcc.
7967 // NOTE: This fixes a link error on Android MIPS as well. The non-static
7968 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
7969 if (isAndroid && !StaticLibgcc)
7970 CmdArgs.push_back("-ldl");
7973 static std::string getLinuxDynamicLinker(const ArgList &Args,
7974 const toolchains::Linux &ToolChain) {
7975 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7977 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
7978 if (ToolChain.getTriple().isArch64Bit())
7979 return "/system/bin/linker64";
7981 return "/system/bin/linker";
7982 } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
7983 Arch == llvm::Triple::sparcel)
7984 return "/lib/ld-linux.so.2";
7985 else if (Arch == llvm::Triple::aarch64)
7986 return "/lib/ld-linux-aarch64.so.1";
7987 else if (Arch == llvm::Triple::aarch64_be)
7988 return "/lib/ld-linux-aarch64_be.so.1";
7989 else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
7990 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
7991 tools::arm::getARMFloatABI(ToolChain.getDriver(), Args, ToolChain.getTriple()) == "hard")
7992 return "/lib/ld-linux-armhf.so.3";
7994 return "/lib/ld-linux.so.3";
7995 } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
7996 // TODO: check which dynamic linker name.
7997 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
7998 tools::arm::getARMFloatABI(ToolChain.getDriver(), Args, ToolChain.getTriple()) == "hard")
7999 return "/lib/ld-linux-armhf.so.3";
8001 return "/lib/ld-linux.so.3";
8002 } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8003 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8006 mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
8007 bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8009 StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
8010 .Case("o32", "/lib")
8011 .Case("n32", "/lib32")
8012 .Case("n64", "/lib64")
8015 if (mips::isUCLibc(Args))
8016 LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8018 LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8020 return (LibDir + "/" + LibName).str();
8021 } else if (Arch == llvm::Triple::ppc)
8022 return "/lib/ld.so.1";
8023 else if (Arch == llvm::Triple::ppc64) {
8024 if (ppc::hasPPCAbiArg(Args, "elfv2"))
8025 return "/lib64/ld64.so.2";
8026 return "/lib64/ld64.so.1";
8027 } else if (Arch == llvm::Triple::ppc64le) {
8028 if (ppc::hasPPCAbiArg(Args, "elfv1"))
8029 return "/lib64/ld64.so.1";
8030 return "/lib64/ld64.so.2";
8031 } else if (Arch == llvm::Triple::systemz)
8032 return "/lib64/ld64.so.1";
8033 else if (Arch == llvm::Triple::sparcv9)
8034 return "/lib64/ld-linux.so.2";
8035 else if (Arch == llvm::Triple::x86_64 &&
8036 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8037 return "/libx32/ld-linux-x32.so.2";
8039 return "/lib64/ld-linux-x86-64.so.2";
8042 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8043 ArgStringList &CmdArgs, const ArgList &Args) {
8044 // Make use of compiler-rt if --rtlib option is used
8045 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8048 case ToolChain::RLT_CompilerRT:
8049 switch (TC.getTriple().getOS()) {
8051 llvm_unreachable("unsupported OS");
8052 case llvm::Triple::Win32:
8053 case llvm::Triple::Linux:
8054 addClangRT(TC, Args, CmdArgs);
8058 case ToolChain::RLT_Libgcc:
8059 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8064 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8065 switch (T.getArch()) {
8066 case llvm::Triple::x86:
8068 case llvm::Triple::aarch64:
8069 return "aarch64linux";
8070 case llvm::Triple::aarch64_be:
8071 return "aarch64_be_linux";
8072 case llvm::Triple::arm:
8073 case llvm::Triple::thumb:
8074 return "armelf_linux_eabi";
8075 case llvm::Triple::armeb:
8076 case llvm::Triple::thumbeb:
8077 return "armebelf_linux_eabi"; /* TODO: check which NAME. */
8078 case llvm::Triple::ppc:
8079 return "elf32ppclinux";
8080 case llvm::Triple::ppc64:
8082 case llvm::Triple::ppc64le:
8084 case llvm::Triple::sparc:
8085 case llvm::Triple::sparcel:
8086 return "elf32_sparc";
8087 case llvm::Triple::sparcv9:
8088 return "elf64_sparc";
8089 case llvm::Triple::mips:
8090 return "elf32btsmip";
8091 case llvm::Triple::mipsel:
8092 return "elf32ltsmip";
8093 case llvm::Triple::mips64:
8094 if (mips::hasMipsAbiArg(Args, "n32"))
8095 return "elf32btsmipn32";
8096 return "elf64btsmip";
8097 case llvm::Triple::mips64el:
8098 if (mips::hasMipsAbiArg(Args, "n32"))
8099 return "elf32ltsmipn32";
8100 return "elf64ltsmip";
8101 case llvm::Triple::systemz:
8102 return "elf64_s390";
8103 case llvm::Triple::x86_64:
8104 if (T.getEnvironment() == llvm::Triple::GNUX32)
8105 return "elf32_x86_64";
8106 return "elf_x86_64";
8108 llvm_unreachable("Unexpected arch");
8112 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8113 const InputInfo &Output,
8114 const InputInfoList &Inputs,
8115 const ArgList &Args,
8116 const char *LinkingOutput) const {
8117 const toolchains::Linux &ToolChain =
8118 static_cast<const toolchains::Linux &>(getToolChain());
8119 const Driver &D = ToolChain.getDriver();
8120 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8121 const bool isAndroid =
8122 ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
8124 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8125 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8127 ArgStringList CmdArgs;
8129 // Silence warning for "clang -g foo.o -o foo"
8130 Args.ClaimAllArgs(options::OPT_g_Group);
8131 // and "clang -emit-llvm foo.o -o foo"
8132 Args.ClaimAllArgs(options::OPT_emit_llvm);
8133 // and for "clang -w foo.o -o foo". Other warning options are already
8134 // handled somewhere else.
8135 Args.ClaimAllArgs(options::OPT_w);
8137 if (!D.SysRoot.empty())
8138 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8141 CmdArgs.push_back("-pie");
8143 if (Args.hasArg(options::OPT_rdynamic))
8144 CmdArgs.push_back("-export-dynamic");
8146 if (Args.hasArg(options::OPT_s))
8147 CmdArgs.push_back("-s");
8149 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8150 arm::appendEBLinkFlags(
8152 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8154 for (const auto &Opt : ToolChain.ExtraOpts)
8155 CmdArgs.push_back(Opt.c_str());
8157 if (!Args.hasArg(options::OPT_static)) {
8158 CmdArgs.push_back("--eh-frame-hdr");
8161 CmdArgs.push_back("-m");
8162 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8164 if (Args.hasArg(options::OPT_static)) {
8165 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8166 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8167 CmdArgs.push_back("-Bstatic");
8169 CmdArgs.push_back("-static");
8170 } else if (Args.hasArg(options::OPT_shared)) {
8171 CmdArgs.push_back("-shared");
8174 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8175 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8176 (!Args.hasArg(options::OPT_static) &&
8177 !Args.hasArg(options::OPT_shared))) {
8178 CmdArgs.push_back("-dynamic-linker");
8179 CmdArgs.push_back(Args.MakeArgString(
8180 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8183 CmdArgs.push_back("-o");
8184 CmdArgs.push_back(Output.getFilename());
8186 if (!Args.hasArg(options::OPT_nostdlib) &&
8187 !Args.hasArg(options::OPT_nostartfiles)) {
8189 const char *crt1 = nullptr;
8190 if (!Args.hasArg(options::OPT_shared)) {
8191 if (Args.hasArg(options::OPT_pg))
8199 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8201 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8204 const char *crtbegin;
8205 if (Args.hasArg(options::OPT_static))
8206 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8207 else if (Args.hasArg(options::OPT_shared))
8208 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8210 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8212 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8213 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8215 // Add crtfastmath.o if available and fast math is enabled.
8216 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8219 Args.AddAllArgs(CmdArgs, options::OPT_L);
8220 Args.AddAllArgs(CmdArgs, options::OPT_u);
8222 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8224 for (const auto &Path : Paths)
8225 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8227 if (D.IsUsingLTO(Args))
8228 AddGoldPlugin(ToolChain, Args, CmdArgs);
8230 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8231 CmdArgs.push_back("--no-demangle");
8233 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8234 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8235 // The profile runtime also needs access to system libraries.
8236 addProfileRT(getToolChain(), Args, CmdArgs);
8238 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8239 !Args.hasArg(options::OPT_nodefaultlibs)) {
8240 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8241 !Args.hasArg(options::OPT_static);
8242 if (OnlyLibstdcxxStatic)
8243 CmdArgs.push_back("-Bstatic");
8244 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8245 if (OnlyLibstdcxxStatic)
8246 CmdArgs.push_back("-Bdynamic");
8247 CmdArgs.push_back("-lm");
8249 // Silence warnings when linking C code with a C++ '-stdlib' argument.
8250 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8252 if (!Args.hasArg(options::OPT_nostdlib)) {
8253 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8254 if (Args.hasArg(options::OPT_static))
8255 CmdArgs.push_back("--start-group");
8257 if (NeedsSanitizerDeps)
8258 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8260 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8261 Args.hasArg(options::OPT_pthreads);
8263 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8264 options::OPT_fno_openmp, false)) {
8265 // OpenMP runtimes implies pthreads when using the GNU toolchain.
8266 // FIXME: Does this really make sense for all GNU toolchains?
8269 // Also link the particular OpenMP runtimes.
8270 switch (getOpenMPRuntime(ToolChain, Args)) {
8272 CmdArgs.push_back("-lomp");
8275 CmdArgs.push_back("-lgomp");
8277 // FIXME: Exclude this for platforms with libgomp that don't require
8278 // librt. Most modern Linux platforms require it, but some may not.
8279 CmdArgs.push_back("-lrt");
8282 CmdArgs.push_back("-liomp5");
8285 // Already diagnosed.
8290 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8292 if (WantPthread && !isAndroid)
8293 CmdArgs.push_back("-lpthread");
8295 CmdArgs.push_back("-lc");
8297 if (Args.hasArg(options::OPT_static))
8298 CmdArgs.push_back("--end-group");
8300 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8303 if (!Args.hasArg(options::OPT_nostartfiles)) {
8305 if (Args.hasArg(options::OPT_shared))
8306 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8308 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8310 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8312 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8314 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8319 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8322 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8323 // for the various SFI requirements like register masking. The assembly tool
8324 // inserts the file containing the macros as an input into all the assembly
8326 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8327 const InputInfo &Output,
8328 const InputInfoList &Inputs,
8329 const ArgList &Args,
8330 const char *LinkingOutput) const {
8331 const toolchains::NaCl_TC &ToolChain =
8332 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8333 InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8334 "nacl-arm-macros.s");
8335 InputInfoList NewInputs;
8336 NewInputs.push_back(NaClMacros);
8337 NewInputs.append(Inputs.begin(), Inputs.end());
8338 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8342 // This is quite similar to gnutools::Linker::ConstructJob with changes that
8343 // we use static by default, do not yet support sanitizers or LTO, and a few
8344 // others. Eventually we can support more of that and hopefully migrate back
8345 // to gnutools::Linker.
8346 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8347 const InputInfo &Output,
8348 const InputInfoList &Inputs,
8349 const ArgList &Args,
8350 const char *LinkingOutput) const {
8352 const toolchains::NaCl_TC &ToolChain =
8353 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8354 const Driver &D = ToolChain.getDriver();
8355 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8356 const bool IsStatic =
8357 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8359 ArgStringList CmdArgs;
8361 // Silence warning for "clang -g foo.o -o foo"
8362 Args.ClaimAllArgs(options::OPT_g_Group);
8363 // and "clang -emit-llvm foo.o -o foo"
8364 Args.ClaimAllArgs(options::OPT_emit_llvm);
8365 // and for "clang -w foo.o -o foo". Other warning options are already
8366 // handled somewhere else.
8367 Args.ClaimAllArgs(options::OPT_w);
8369 if (!D.SysRoot.empty())
8370 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8372 if (Args.hasArg(options::OPT_rdynamic))
8373 CmdArgs.push_back("-export-dynamic");
8375 if (Args.hasArg(options::OPT_s))
8376 CmdArgs.push_back("-s");
8378 // NaCl_TC doesn't have ExtraOpts like Linux; the only relevant flag from
8379 // there is --build-id, which we do want.
8380 CmdArgs.push_back("--build-id");
8383 CmdArgs.push_back("--eh-frame-hdr");
8385 CmdArgs.push_back("-m");
8386 if (Arch == llvm::Triple::x86)
8387 CmdArgs.push_back("elf_i386_nacl");
8388 else if (Arch == llvm::Triple::arm)
8389 CmdArgs.push_back("armelf_nacl");
8390 else if (Arch == llvm::Triple::x86_64)
8391 CmdArgs.push_back("elf_x86_64_nacl");
8392 else if (Arch == llvm::Triple::mipsel)
8393 CmdArgs.push_back("mipselelf_nacl");
8395 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
8399 CmdArgs.push_back("-static");
8400 else if (Args.hasArg(options::OPT_shared))
8401 CmdArgs.push_back("-shared");
8403 CmdArgs.push_back("-o");
8404 CmdArgs.push_back(Output.getFilename());
8405 if (!Args.hasArg(options::OPT_nostdlib) &&
8406 !Args.hasArg(options::OPT_nostartfiles)) {
8407 if (!Args.hasArg(options::OPT_shared))
8408 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
8409 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8411 const char *crtbegin;
8413 crtbegin = "crtbeginT.o";
8414 else if (Args.hasArg(options::OPT_shared))
8415 crtbegin = "crtbeginS.o";
8417 crtbegin = "crtbegin.o";
8418 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8421 Args.AddAllArgs(CmdArgs, options::OPT_L);
8422 Args.AddAllArgs(CmdArgs, options::OPT_u);
8424 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8426 for (const auto &Path : Paths)
8427 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8429 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8430 CmdArgs.push_back("--no-demangle");
8432 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8434 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8435 !Args.hasArg(options::OPT_nodefaultlibs)) {
8436 bool OnlyLibstdcxxStatic =
8437 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
8438 if (OnlyLibstdcxxStatic)
8439 CmdArgs.push_back("-Bstatic");
8440 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8441 if (OnlyLibstdcxxStatic)
8442 CmdArgs.push_back("-Bdynamic");
8443 CmdArgs.push_back("-lm");
8446 if (!Args.hasArg(options::OPT_nostdlib)) {
8447 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8448 // Always use groups, since it has no effect on dynamic libraries.
8449 CmdArgs.push_back("--start-group");
8450 CmdArgs.push_back("-lc");
8451 // NaCl's libc++ currently requires libpthread, so just always include it
8452 // in the group for C++.
8453 if (Args.hasArg(options::OPT_pthread) ||
8454 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
8455 // Gold, used by Mips, handles nested groups differently than ld, and
8456 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
8457 // which is not a desired behaviour here.
8458 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
8459 if (getToolChain().getArch() == llvm::Triple::mipsel)
8460 CmdArgs.push_back("-lnacl");
8462 CmdArgs.push_back("-lpthread");
8465 CmdArgs.push_back("-lgcc");
8466 CmdArgs.push_back("--as-needed");
8468 CmdArgs.push_back("-lgcc_eh");
8470 CmdArgs.push_back("-lgcc_s");
8471 CmdArgs.push_back("--no-as-needed");
8473 // Mips needs to create and use pnacl_legacy library that contains
8474 // definitions from bitcode/pnaclmm.c and definitions for
8475 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
8476 if (getToolChain().getArch() == llvm::Triple::mipsel)
8477 CmdArgs.push_back("-lpnacl_legacy");
8479 CmdArgs.push_back("--end-group");
8482 if (!Args.hasArg(options::OPT_nostartfiles)) {
8484 if (Args.hasArg(options::OPT_shared))
8485 crtend = "crtendS.o";
8487 crtend = "crtend.o";
8489 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8490 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8495 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8498 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8499 const InputInfo &Output,
8500 const InputInfoList &Inputs,
8501 const ArgList &Args,
8502 const char *LinkingOutput) const {
8503 claimNoWarnArgs(Args);
8504 ArgStringList CmdArgs;
8506 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8508 CmdArgs.push_back("-o");
8509 CmdArgs.push_back(Output.getFilename());
8511 for (const auto &II : Inputs)
8512 CmdArgs.push_back(II.getFilename());
8514 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8515 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8518 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8519 const InputInfo &Output,
8520 const InputInfoList &Inputs,
8521 const ArgList &Args,
8522 const char *LinkingOutput) const {
8523 const Driver &D = getToolChain().getDriver();
8524 ArgStringList CmdArgs;
8526 if (Output.isFilename()) {
8527 CmdArgs.push_back("-o");
8528 CmdArgs.push_back(Output.getFilename());
8530 assert(Output.isNothing() && "Invalid output.");
8533 if (!Args.hasArg(options::OPT_nostdlib) &&
8534 !Args.hasArg(options::OPT_nostartfiles)) {
8535 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8536 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8538 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8539 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8542 Args.AddAllArgs(CmdArgs, options::OPT_L);
8543 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8544 Args.AddAllArgs(CmdArgs, options::OPT_e);
8546 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8548 addProfileRT(getToolChain(), Args, CmdArgs);
8550 if (!Args.hasArg(options::OPT_nostdlib) &&
8551 !Args.hasArg(options::OPT_nodefaultlibs)) {
8553 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8554 CmdArgs.push_back("-lm");
8558 if (!Args.hasArg(options::OPT_nostdlib) &&
8559 !Args.hasArg(options::OPT_nostartfiles)) {
8560 if (Args.hasArg(options::OPT_pthread))
8561 CmdArgs.push_back("-lpthread");
8562 CmdArgs.push_back("-lc");
8563 CmdArgs.push_back("-lCompilerRT-Generic");
8564 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
8566 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8569 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8570 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8575 // For now, DragonFly Assemble does just about the same as for
8576 // FreeBSD, but this may change soon.
8577 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8578 const InputInfo &Output,
8579 const InputInfoList &Inputs,
8580 const ArgList &Args,
8581 const char *LinkingOutput) const {
8582 claimNoWarnArgs(Args);
8583 ArgStringList CmdArgs;
8585 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8586 // instruct as in the base system to assemble 32-bit code.
8587 if (getToolChain().getArch() == llvm::Triple::x86)
8588 CmdArgs.push_back("--32");
8590 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8592 CmdArgs.push_back("-o");
8593 CmdArgs.push_back(Output.getFilename());
8595 for (const auto &II : Inputs)
8596 CmdArgs.push_back(II.getFilename());
8598 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8599 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8602 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8603 const InputInfo &Output,
8604 const InputInfoList &Inputs,
8605 const ArgList &Args,
8606 const char *LinkingOutput) const {
8607 const Driver &D = getToolChain().getDriver();
8608 ArgStringList CmdArgs;
8609 bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
8611 if (!D.SysRoot.empty())
8612 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8614 CmdArgs.push_back("--eh-frame-hdr");
8615 if (Args.hasArg(options::OPT_static)) {
8616 CmdArgs.push_back("-Bstatic");
8618 if (Args.hasArg(options::OPT_rdynamic))
8619 CmdArgs.push_back("-export-dynamic");
8620 if (Args.hasArg(options::OPT_shared))
8621 CmdArgs.push_back("-Bshareable");
8623 CmdArgs.push_back("-dynamic-linker");
8624 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
8626 CmdArgs.push_back("--hash-style=both");
8629 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8630 // instruct ld in the base system to link 32-bit code.
8631 if (getToolChain().getArch() == llvm::Triple::x86) {
8632 CmdArgs.push_back("-m");
8633 CmdArgs.push_back("elf_i386");
8636 if (Output.isFilename()) {
8637 CmdArgs.push_back("-o");
8638 CmdArgs.push_back(Output.getFilename());
8640 assert(Output.isNothing() && "Invalid output.");
8643 if (!Args.hasArg(options::OPT_nostdlib) &&
8644 !Args.hasArg(options::OPT_nostartfiles)) {
8645 if (!Args.hasArg(options::OPT_shared)) {
8646 if (Args.hasArg(options::OPT_pg))
8648 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
8650 if (Args.hasArg(options::OPT_pie))
8652 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
8655 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8658 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8659 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8661 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8664 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8667 Args.AddAllArgs(CmdArgs, options::OPT_L);
8668 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8669 Args.AddAllArgs(CmdArgs, options::OPT_e);
8671 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8673 if (!Args.hasArg(options::OPT_nostdlib) &&
8674 !Args.hasArg(options::OPT_nodefaultlibs)) {
8675 // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
8678 CmdArgs.push_back("-L/usr/lib/gcc47");
8680 CmdArgs.push_back("-L/usr/lib/gcc44");
8682 if (!Args.hasArg(options::OPT_static)) {
8684 CmdArgs.push_back("-rpath");
8685 CmdArgs.push_back("/usr/lib/gcc47");
8687 CmdArgs.push_back("-rpath");
8688 CmdArgs.push_back("/usr/lib/gcc44");
8693 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8694 CmdArgs.push_back("-lm");
8697 if (Args.hasArg(options::OPT_pthread))
8698 CmdArgs.push_back("-lpthread");
8700 if (!Args.hasArg(options::OPT_nolibc)) {
8701 CmdArgs.push_back("-lc");
8705 if (Args.hasArg(options::OPT_static) ||
8706 Args.hasArg(options::OPT_static_libgcc)) {
8707 CmdArgs.push_back("-lgcc");
8708 CmdArgs.push_back("-lgcc_eh");
8710 if (Args.hasArg(options::OPT_shared_libgcc)) {
8711 CmdArgs.push_back("-lgcc_pic");
8712 if (!Args.hasArg(options::OPT_shared))
8713 CmdArgs.push_back("-lgcc");
8715 CmdArgs.push_back("-lgcc");
8716 CmdArgs.push_back("--as-needed");
8717 CmdArgs.push_back("-lgcc_pic");
8718 CmdArgs.push_back("--no-as-needed");
8722 if (Args.hasArg(options::OPT_shared)) {
8723 CmdArgs.push_back("-lgcc_pic");
8725 CmdArgs.push_back("-lgcc");
8730 if (!Args.hasArg(options::OPT_nostdlib) &&
8731 !Args.hasArg(options::OPT_nostartfiles)) {
8732 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8734 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8737 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8738 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8741 addProfileRT(getToolChain(), Args, CmdArgs);
8743 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8744 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8747 // Try to find Exe from a Visual Studio distribution. This first tries to find
8748 // an installed copy of Visual Studio and, failing that, looks in the PATH,
8749 // making sure that whatever executable that's found is not a same-named exe
8750 // from clang itself to prevent clang from falling back to itself.
8751 static std::string FindVisualStudioExecutable(const ToolChain &TC,
8753 const char *ClangProgramPath) {
8754 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8755 std::string visualStudioBinDir;
8756 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
8757 visualStudioBinDir)) {
8758 SmallString<128> FilePath(visualStudioBinDir);
8759 llvm::sys::path::append(FilePath, Exe);
8760 if (llvm::sys::fs::can_execute(FilePath.c_str()))
8761 return FilePath.str();
8767 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8768 const InputInfo &Output,
8769 const InputInfoList &Inputs,
8770 const ArgList &Args,
8771 const char *LinkingOutput) const {
8772 ArgStringList CmdArgs;
8773 const ToolChain &TC = getToolChain();
8775 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
8776 if (Output.isFilename())
8778 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
8780 if (!Args.hasArg(options::OPT_nostdlib) &&
8781 !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
8782 CmdArgs.push_back("-defaultlib:libcmt");
8784 if (!llvm::sys::Process::GetEnv("LIB")) {
8785 // If the VC environment hasn't been configured (perhaps because the user
8786 // did not run vcvarsall), try to build a consistent link environment. If
8787 // the environment variable is set however, assume the user knows what
8789 std::string VisualStudioDir;
8790 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8791 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
8792 SmallString<128> LibDir(VisualStudioDir);
8793 llvm::sys::path::append(LibDir, "VC", "lib");
8794 switch (MSVC.getArch()) {
8795 case llvm::Triple::x86:
8796 // x86 just puts the libraries directly in lib
8798 case llvm::Triple::x86_64:
8799 llvm::sys::path::append(LibDir, "amd64");
8801 case llvm::Triple::arm:
8802 llvm::sys::path::append(LibDir, "arm");
8808 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
8811 std::string WindowsSdkLibPath;
8812 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
8813 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
8814 WindowsSdkLibPath.c_str()));
8817 CmdArgs.push_back("-nologo");
8819 if (Args.hasArg(options::OPT_g_Group))
8820 CmdArgs.push_back("-debug");
8822 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
8823 options::OPT_shared);
8825 CmdArgs.push_back(Args.MakeArgString("-dll"));
8827 SmallString<128> ImplibName(Output.getFilename());
8828 llvm::sys::path::replace_extension(ImplibName, "lib");
8829 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
8832 if (TC.getSanitizerArgs().needsAsanRt()) {
8833 CmdArgs.push_back(Args.MakeArgString("-debug"));
8834 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
8835 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
8836 static const char *CompilerRTComponents[] = {
8837 "asan_dynamic", "asan_dynamic_runtime_thunk",
8839 for (const auto &Component : CompilerRTComponents)
8840 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8841 // Make sure the dynamic runtime thunk is not optimized out at link time
8842 // to ensure proper SEH handling.
8843 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
8846 Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
8848 static const char *CompilerRTComponents[] = {
8851 for (const auto &Component : CompilerRTComponents)
8852 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8856 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
8858 // Add filenames, libraries, and other linker inputs.
8859 for (const auto &Input : Inputs) {
8860 if (Input.isFilename()) {
8861 CmdArgs.push_back(Input.getFilename());
8865 const Arg &A = Input.getInputArg();
8867 // Render -l options differently for the MSVC linker.
8868 if (A.getOption().matches(options::OPT_l)) {
8869 StringRef Lib = A.getValue();
8870 const char *LinkLibArg;
8871 if (Lib.endswith(".lib"))
8872 LinkLibArg = Args.MakeArgString(Lib);
8874 LinkLibArg = Args.MakeArgString(Lib + ".lib");
8875 CmdArgs.push_back(LinkLibArg);
8879 // Otherwise, this is some other kind of linker input option like -Wl, -z,
8880 // or -L. Render it, even if MSVC doesn't understand it.
8881 A.renderAsInput(Args, CmdArgs);
8884 // We need to special case some linker paths. In the case of lld, we need to
8885 // translate 'lld' into 'lld-link', and in the case of the regular msvc
8886 // linker, we need to use a special search algorithm.
8887 llvm::SmallString<128> linkPath;
8888 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
8889 if (Linker.equals_lower("lld"))
8890 Linker = "lld-link";
8892 if (Linker.equals_lower("link")) {
8893 // If we're using the MSVC linker, it's not sufficient to just use link
8894 // from the program PATH, because other environments like GnuWin32 install
8895 // their own link.exe which may come first.
8896 linkPath = FindVisualStudioExecutable(TC, "link.exe",
8897 C.getDriver().getClangProgramPath());
8900 llvm::sys::path::replace_extension(linkPath, "exe");
8901 linkPath = TC.GetProgramPath(linkPath.c_str());
8904 const char *Exec = Args.MakeArgString(linkPath);
8905 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8908 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
8909 const InputInfo &Output,
8910 const InputInfoList &Inputs,
8911 const ArgList &Args,
8912 const char *LinkingOutput) const {
8913 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
8916 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
8917 Compilation &C, const JobAction &JA, const InputInfo &Output,
8918 const InputInfoList &Inputs, const ArgList &Args,
8919 const char *LinkingOutput) const {
8920 ArgStringList CmdArgs;
8921 CmdArgs.push_back("/nologo");
8922 CmdArgs.push_back("/c"); // Compile only.
8923 CmdArgs.push_back("/W0"); // No warnings.
8925 // The goal is to be able to invoke this tool correctly based on
8926 // any flag accepted by clang-cl.
8928 // These are spelled the same way in clang and cl.exe,.
8929 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
8930 Args.AddAllArgs(CmdArgs, options::OPT_I);
8932 // Optimization level.
8933 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
8934 if (A->getOption().getID() == options::OPT_O0) {
8935 CmdArgs.push_back("/Od");
8937 StringRef OptLevel = A->getValue();
8938 if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
8939 A->render(Args, CmdArgs);
8940 else if (OptLevel == "3")
8941 CmdArgs.push_back("/Ox");
8945 // Flags for which clang-cl has an alias.
8946 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
8948 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8950 CmdArgs.push_back("/GR-");
8951 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
8952 options::OPT_fno_function_sections))
8953 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
8956 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
8957 options::OPT_fno_data_sections))
8959 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
8960 if (Args.hasArg(options::OPT_fsyntax_only))
8961 CmdArgs.push_back("/Zs");
8962 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
8963 CmdArgs.push_back("/Z7");
8965 std::vector<std::string> Includes =
8966 Args.getAllArgValues(options::OPT_include);
8967 for (const auto &Include : Includes)
8968 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
8970 // Flags that can simply be passed through.
8971 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
8972 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
8973 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
8975 // The order of these flags is relevant, so pick the last one.
8976 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
8977 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
8978 A->render(Args, CmdArgs);
8981 assert(Inputs.size() == 1);
8982 const InputInfo &II = Inputs[0];
8983 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
8984 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
8985 if (II.isFilename())
8986 CmdArgs.push_back(II.getFilename());
8988 II.getInputArg().renderAsInput(Args, CmdArgs);
8991 assert(Output.getType() == types::TY_Object);
8993 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
8994 CmdArgs.push_back(Fo);
8996 const Driver &D = getToolChain().getDriver();
8997 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
8998 D.getClangProgramPath());
8999 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9004 void MinGW::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);
9010 ArgStringList CmdArgs;
9012 if (getToolChain().getArch() == llvm::Triple::x86) {
9013 CmdArgs.push_back("--32");
9014 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9015 CmdArgs.push_back("--64");
9018 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9020 CmdArgs.push_back("-o");
9021 CmdArgs.push_back(Output.getFilename());
9023 for (const auto &II : Inputs)
9024 CmdArgs.push_back(II.getFilename());
9026 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9027 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9029 if (Args.hasArg(options::OPT_gsplit_dwarf))
9030 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9031 SplitDebugName(Args, Inputs[0]));
9034 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9035 ArgStringList &CmdArgs) const {
9036 if (Args.hasArg(options::OPT_mthreads))
9037 CmdArgs.push_back("-lmingwthrd");
9038 CmdArgs.push_back("-lmingw32");
9040 // Add libgcc or compiler-rt.
9041 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9043 CmdArgs.push_back("-lmoldname");
9044 CmdArgs.push_back("-lmingwex");
9045 CmdArgs.push_back("-lmsvcrt");
9048 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9049 const InputInfo &Output,
9050 const InputInfoList &Inputs,
9051 const ArgList &Args,
9052 const char *LinkingOutput) const {
9053 const ToolChain &TC = getToolChain();
9054 const Driver &D = TC.getDriver();
9055 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9057 ArgStringList CmdArgs;
9059 // Silence warning for "clang -g foo.o -o foo"
9060 Args.ClaimAllArgs(options::OPT_g_Group);
9061 // and "clang -emit-llvm foo.o -o foo"
9062 Args.ClaimAllArgs(options::OPT_emit_llvm);
9063 // and for "clang -w foo.o -o foo". Other warning options are already
9064 // handled somewhere else.
9065 Args.ClaimAllArgs(options::OPT_w);
9067 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9068 if (LinkerName.equals_lower("lld")) {
9069 CmdArgs.push_back("-flavor");
9070 CmdArgs.push_back("gnu");
9073 if (!D.SysRoot.empty())
9074 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9076 if (Args.hasArg(options::OPT_s))
9077 CmdArgs.push_back("-s");
9079 CmdArgs.push_back("-m");
9080 if (TC.getArch() == llvm::Triple::x86)
9081 CmdArgs.push_back("i386pe");
9082 if (TC.getArch() == llvm::Triple::x86_64)
9083 CmdArgs.push_back("i386pep");
9084 if (TC.getArch() == llvm::Triple::arm)
9085 CmdArgs.push_back("thumb2pe");
9087 if (Args.hasArg(options::OPT_mwindows)) {
9088 CmdArgs.push_back("--subsystem");
9089 CmdArgs.push_back("windows");
9090 } else if (Args.hasArg(options::OPT_mconsole)) {
9091 CmdArgs.push_back("--subsystem");
9092 CmdArgs.push_back("console");
9095 if (Args.hasArg(options::OPT_static))
9096 CmdArgs.push_back("-Bstatic");
9098 if (Args.hasArg(options::OPT_mdll))
9099 CmdArgs.push_back("--dll");
9100 else if (Args.hasArg(options::OPT_shared))
9101 CmdArgs.push_back("--shared");
9102 CmdArgs.push_back("-Bdynamic");
9103 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9104 CmdArgs.push_back("-e");
9105 if (TC.getArch() == llvm::Triple::x86)
9106 CmdArgs.push_back("_DllMainCRTStartup@12");
9108 CmdArgs.push_back("DllMainCRTStartup");
9109 CmdArgs.push_back("--enable-auto-image-base");
9113 CmdArgs.push_back("-o");
9114 CmdArgs.push_back(Output.getFilename());
9116 Args.AddAllArgs(CmdArgs, options::OPT_e);
9117 // FIXME: add -N, -n flags
9118 Args.AddLastArg(CmdArgs, options::OPT_r);
9119 Args.AddLastArg(CmdArgs, options::OPT_s);
9120 Args.AddLastArg(CmdArgs, options::OPT_t);
9121 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9122 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9124 if (!Args.hasArg(options::OPT_nostdlib) &&
9125 !Args.hasArg(options::OPT_nostartfiles)) {
9126 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9127 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9129 if (Args.hasArg(options::OPT_municode))
9130 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9132 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9134 if (Args.hasArg(options::OPT_pg))
9135 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9136 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9139 Args.AddAllArgs(CmdArgs, options::OPT_L);
9140 const ToolChain::path_list Paths = TC.getFilePaths();
9141 for (const auto &Path : Paths)
9142 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9144 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9146 // TODO: Add ASan stuff here
9148 // TODO: Add profile stuff here
9150 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9151 !Args.hasArg(options::OPT_nodefaultlibs)) {
9152 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9153 !Args.hasArg(options::OPT_static);
9154 if (OnlyLibstdcxxStatic)
9155 CmdArgs.push_back("-Bstatic");
9156 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9157 if (OnlyLibstdcxxStatic)
9158 CmdArgs.push_back("-Bdynamic");
9161 if (!Args.hasArg(options::OPT_nostdlib)) {
9162 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9163 if (Args.hasArg(options::OPT_static))
9164 CmdArgs.push_back("--start-group");
9166 if (Args.hasArg(options::OPT_fstack_protector) ||
9167 Args.hasArg(options::OPT_fstack_protector_strong) ||
9168 Args.hasArg(options::OPT_fstack_protector_all)) {
9169 CmdArgs.push_back("-lssp_nonshared");
9170 CmdArgs.push_back("-lssp");
9172 if (Args.hasArg(options::OPT_fopenmp))
9173 CmdArgs.push_back("-lgomp");
9175 AddLibGCC(Args, CmdArgs);
9177 if (Args.hasArg(options::OPT_pg))
9178 CmdArgs.push_back("-lgmon");
9180 if (Args.hasArg(options::OPT_pthread))
9181 CmdArgs.push_back("-lpthread");
9183 // add system libraries
9184 if (Args.hasArg(options::OPT_mwindows)) {
9185 CmdArgs.push_back("-lgdi32");
9186 CmdArgs.push_back("-lcomdlg32");
9188 CmdArgs.push_back("-ladvapi32");
9189 CmdArgs.push_back("-lshell32");
9190 CmdArgs.push_back("-luser32");
9191 CmdArgs.push_back("-lkernel32");
9193 if (Args.hasArg(options::OPT_static))
9194 CmdArgs.push_back("--end-group");
9195 else if (!LinkerName.equals_lower("lld"))
9196 AddLibGCC(Args, CmdArgs);
9199 if (!Args.hasArg(options::OPT_nostartfiles)) {
9200 // Add crtfastmath.o if available and fast math is enabled.
9201 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9203 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9206 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9207 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9211 // We pass assemble and link construction to the xcc tool.
9213 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9214 const InputInfo &Output,
9215 const InputInfoList &Inputs,
9216 const ArgList &Args,
9217 const char *LinkingOutput) const {
9218 claimNoWarnArgs(Args);
9219 ArgStringList CmdArgs;
9221 CmdArgs.push_back("-o");
9222 CmdArgs.push_back(Output.getFilename());
9224 CmdArgs.push_back("-c");
9226 if (Args.hasArg(options::OPT_v))
9227 CmdArgs.push_back("-v");
9229 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9230 if (!A->getOption().matches(options::OPT_g0))
9231 CmdArgs.push_back("-g");
9233 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9235 CmdArgs.push_back("-fverbose-asm");
9237 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9239 for (const auto &II : Inputs)
9240 CmdArgs.push_back(II.getFilename());
9242 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9243 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9246 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9247 const InputInfo &Output,
9248 const InputInfoList &Inputs,
9249 const ArgList &Args,
9250 const char *LinkingOutput) const {
9251 ArgStringList CmdArgs;
9253 if (Output.isFilename()) {
9254 CmdArgs.push_back("-o");
9255 CmdArgs.push_back(Output.getFilename());
9257 assert(Output.isNothing() && "Invalid output.");
9260 if (Args.hasArg(options::OPT_v))
9261 CmdArgs.push_back("-v");
9263 // Pass -fexceptions through to the linker if it was present.
9264 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9266 CmdArgs.push_back("-fexceptions");
9268 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9270 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9271 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9274 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9275 const InputInfo &Output,
9276 const InputInfoList &Inputs,
9277 const ArgList &Args,
9278 const char *LinkingOutput) const {
9279 claimNoWarnArgs(Args);
9281 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9282 ArgStringList CmdArgs;
9285 switch (TC.getArch()) {
9287 llvm_unreachable("unsupported architecture");
9288 case llvm::Triple::arm:
9289 case llvm::Triple::thumb:
9291 case llvm::Triple::x86:
9292 CmdArgs.push_back("--32");
9294 case llvm::Triple::x86_64:
9295 CmdArgs.push_back("--64");
9299 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9301 CmdArgs.push_back("-o");
9302 CmdArgs.push_back(Output.getFilename());
9304 for (const auto &Input : Inputs)
9305 CmdArgs.push_back(Input.getFilename());
9307 const std::string Assembler = TC.GetProgramPath("as");
9308 Exec = Args.MakeArgString(Assembler);
9310 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9313 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9314 const InputInfo &Output,
9315 const InputInfoList &Inputs,
9316 const ArgList &Args,
9317 const char *LinkingOutput) const {
9319 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9320 const llvm::Triple &T = TC.getTriple();
9321 const Driver &D = TC.getDriver();
9322 SmallString<128> EntryPoint;
9323 ArgStringList CmdArgs;
9326 // Silence warning for "clang -g foo.o -o foo"
9327 Args.ClaimAllArgs(options::OPT_g_Group);
9328 // and "clang -emit-llvm foo.o -o foo"
9329 Args.ClaimAllArgs(options::OPT_emit_llvm);
9330 // and for "clang -w foo.o -o foo"
9331 Args.ClaimAllArgs(options::OPT_w);
9332 // Other warning options are already handled somewhere else.
9334 if (!D.SysRoot.empty())
9335 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9337 if (Args.hasArg(options::OPT_pie))
9338 CmdArgs.push_back("-pie");
9339 if (Args.hasArg(options::OPT_rdynamic))
9340 CmdArgs.push_back("-export-dynamic");
9341 if (Args.hasArg(options::OPT_s))
9342 CmdArgs.push_back("--strip-all");
9344 CmdArgs.push_back("-m");
9345 switch (TC.getArch()) {
9347 llvm_unreachable("unsupported architecture");
9348 case llvm::Triple::arm:
9349 case llvm::Triple::thumb:
9350 // FIXME: this is incorrect for WinCE
9351 CmdArgs.push_back("thumb2pe");
9353 case llvm::Triple::x86:
9354 CmdArgs.push_back("i386pe");
9355 EntryPoint.append("_");
9357 case llvm::Triple::x86_64:
9358 CmdArgs.push_back("i386pep");
9362 if (Args.hasArg(options::OPT_shared)) {
9363 switch (T.getArch()) {
9365 llvm_unreachable("unsupported architecture");
9366 case llvm::Triple::arm:
9367 case llvm::Triple::thumb:
9368 case llvm::Triple::x86_64:
9369 EntryPoint.append("_DllMainCRTStartup");
9371 case llvm::Triple::x86:
9372 EntryPoint.append("_DllMainCRTStartup@12");
9376 CmdArgs.push_back("-shared");
9377 CmdArgs.push_back("-Bdynamic");
9379 CmdArgs.push_back("--enable-auto-image-base");
9381 CmdArgs.push_back("--entry");
9382 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9384 EntryPoint.append("mainCRTStartup");
9386 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
9389 if (!Args.hasArg(options::OPT_nostdlib) &&
9390 !Args.hasArg(options::OPT_nostartfiles)) {
9391 CmdArgs.push_back("--entry");
9392 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9395 // FIXME: handle subsystem
9398 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
9399 CmdArgs.push_back("--allow-multiple-definition");
9401 CmdArgs.push_back("-o");
9402 CmdArgs.push_back(Output.getFilename());
9404 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
9405 SmallString<261> ImpLib(Output.getFilename());
9406 llvm::sys::path::replace_extension(ImpLib, ".lib");
9408 CmdArgs.push_back("--out-implib");
9409 CmdArgs.push_back(Args.MakeArgString(ImpLib));
9412 if (!Args.hasArg(options::OPT_nostdlib) &&
9413 !Args.hasArg(options::OPT_nostartfiles)) {
9414 const std::string CRTPath(D.SysRoot + "/usr/lib/");
9415 const char *CRTBegin;
9418 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
9419 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
9422 Args.AddAllArgs(CmdArgs, options::OPT_L);
9424 const auto &Paths = TC.getFilePaths();
9425 for (const auto &Path : Paths)
9426 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9428 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9430 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9431 !Args.hasArg(options::OPT_nodefaultlibs)) {
9432 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
9433 !Args.hasArg(options::OPT_static);
9435 CmdArgs.push_back("-Bstatic");
9436 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9438 CmdArgs.push_back("-Bdynamic");
9441 if (!Args.hasArg(options::OPT_nostdlib)) {
9442 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9443 // TODO handle /MT[d] /MD[d]
9444 CmdArgs.push_back("-lmsvcrt");
9445 AddRunTimeLibs(TC, D, CmdArgs, Args);
9449 const std::string Linker = TC.GetProgramPath("ld");
9450 Exec = Args.MakeArgString(Linker);
9452 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9455 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9456 const InputInfo &Output,
9457 const InputInfoList &Inputs,
9458 const ArgList &Args,
9459 const char *LinkingOutput) const {
9461 ArgStringList CmdArgs;
9463 assert(Inputs.size() == 1);
9464 const InputInfo &II = Inputs[0];
9465 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9466 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
9468 // Append all -I, -iquote, -isystem paths.
9469 Args.AddAllArgs(CmdArgs, options::OPT_clang_i_Group);
9470 // These are spelled the same way in clang and moviCompile.
9471 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
9473 CmdArgs.push_back("-DMYRIAD2");
9474 CmdArgs.push_back("-mcpu=myriad2");
9475 CmdArgs.push_back("-S");
9477 // Any -O option passes through without translation. What about -Ofast ?
9478 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
9479 A->render(Args, CmdArgs);
9481 if (Args.hasFlag(options::OPT_ffunction_sections,
9482 options::OPT_fno_function_sections)) {
9483 CmdArgs.push_back("-ffunction-sections");
9485 if (Args.hasArg(options::OPT_fno_inline_functions))
9486 CmdArgs.push_back("-fno-inline-functions");
9488 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
9490 CmdArgs.push_back(II.getFilename());
9491 CmdArgs.push_back("-o");
9492 CmdArgs.push_back(Output.getFilename());
9495 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
9497 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
9500 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9501 const InputInfo &Output,
9502 const InputInfoList &Inputs,
9503 const ArgList &Args,
9504 const char *LinkingOutput) const {
9505 ArgStringList CmdArgs;
9507 assert(Inputs.size() == 1);
9508 const InputInfo &II = Inputs[0];
9509 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
9510 assert(Output.getType() == types::TY_Object);
9512 CmdArgs.push_back("-no6thSlotCompression");
9513 CmdArgs.push_back("-cv:myriad2"); // Chip Version ?
9514 CmdArgs.push_back("-noSPrefixing");
9515 CmdArgs.push_back("-a"); // Mystery option.
9516 for (auto Arg : Args.filtered(options::OPT_I)) {
9519 Args.MakeArgString(std::string("-i:") + Arg->getValue(0)));
9521 CmdArgs.push_back("-elf"); // Output format.
9522 CmdArgs.push_back(II.getFilename());
9524 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
9527 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
9529 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));