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:
506 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
508 std::vector<const char *> &Features) {
509 StringRef HWDiv = A->getValue();
510 if (HWDiv == "arm") {
511 Features.push_back("+hwdiv-arm");
512 Features.push_back("-hwdiv");
513 } else if (HWDiv == "thumb") {
514 Features.push_back("-hwdiv-arm");
515 Features.push_back("+hwdiv");
516 } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
517 Features.push_back("+hwdiv-arm");
518 Features.push_back("+hwdiv");
519 } else if (HWDiv == "none") {
520 Features.push_back("-hwdiv-arm");
521 Features.push_back("-hwdiv");
523 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
527 static void getARMFPUFeatures(const Driver &D, const Arg *A,
529 std::vector<const char *> &Features) {
530 StringRef FPU = A->getValue();
531 unsigned FPUID = llvm::ARMTargetParser::parseFPU(FPU);
532 if (!llvm::ARMTargetParser::getFPUFeatures(FPUID, Features))
533 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
536 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
537 llvm::StringRef Arch = Triple.getArchName();
538 return llvm::ARMTargetParser::parseArchVersion(Arch);
541 static bool isARMMProfile(const llvm::Triple &Triple) {
542 llvm::StringRef Arch = Triple.getArchName();
543 unsigned Profile = llvm::ARMTargetParser::parseArchProfile(Arch);
544 return Profile == llvm::ARM::PK_M;
547 // Select the float ABI as determined by -msoft-float, -mhard-float, and
549 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
550 const llvm::Triple &Triple) {
553 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
554 options::OPT_mfloat_abi_EQ)) {
555 if (A->getOption().matches(options::OPT_msoft_float))
557 else if (A->getOption().matches(options::OPT_mhard_float))
560 FloatABI = A->getValue();
561 if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
562 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
568 // If unspecified, choose the default based on the platform.
569 if (FloatABI.empty()) {
570 switch (Triple.getOS()) {
571 case llvm::Triple::Darwin:
572 case llvm::Triple::MacOSX:
573 case llvm::Triple::IOS: {
574 // Darwin defaults to "softfp" for v6 and v7.
576 if (getARMSubArchVersionNumber(Triple) == 6 ||
577 getARMSubArchVersionNumber(Triple) == 7)
584 // FIXME: this is invalid for WindowsCE
585 case llvm::Triple::Win32:
589 case llvm::Triple::FreeBSD:
590 switch (Triple.getEnvironment()) {
591 case llvm::Triple::GNUEABIHF:
595 // FreeBSD defaults to soft float
602 switch (Triple.getEnvironment()) {
603 case llvm::Triple::GNUEABIHF:
606 case llvm::Triple::GNUEABI:
609 case llvm::Triple::EABIHF:
612 case llvm::Triple::EABI:
613 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
616 case llvm::Triple::Android: {
617 if (getARMSubArchVersionNumber(Triple) == 7)
624 // Assume "soft", but warn the user we are guessing.
626 if (Triple.getOS() != llvm::Triple::UnknownOS ||
627 !Triple.isOSBinFormatMachO())
628 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
637 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
639 std::vector<const char *> &Features,
642 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
643 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
645 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
646 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
647 // stripped out by the ARM target. We should probably pass this a new
648 // -target-option, which is handled by the -cc1/-cc1as invocation.
650 // FIXME2: For consistency, it would be ideal if we set up the target
651 // machine state the same when using the frontend or the assembler. We don't
652 // currently do that for the assembler, we pass the options directly to the
653 // backend and never even instantiate the frontend TargetInfo. If we did,
654 // and used its handleTargetFeatures hook, then we could ensure the
655 // assembler and the frontend behave the same.
657 // Use software floating point operations?
658 if (FloatABI == "soft")
659 Features.push_back("+soft-float");
661 // Use software floating point argument passing?
662 if (FloatABI != "hard")
663 Features.push_back("+soft-float-abi");
667 if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
668 getARMFPUFeatures(D, A, Args, Features);
669 if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
670 getARMHWDivFeatures(D, A, Args, Features);
672 // Check if -march is valid by checking if it can be canonicalised and parsed.
673 // getARMArch is used here instead of just checking the -march value in order
674 // to handle -march=native correctly.
675 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
676 std::string Arch = arm::getARMArch(Args, Triple);
677 if (llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_INVALID)
678 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
681 // We do a similar thing with -mcpu, but here things are complicated because
682 // the only function we have to check if a cpu is valid is
683 // getLLVMArchSuffixForARM which also needs an architecture.
684 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
685 std::string CPU = arm::getARMTargetCPU(Args, Triple);
686 std::string Arch = arm::getARMArch(Args, Triple);
687 if (strcmp(arm::getLLVMArchSuffixForARM(CPU, Arch), "") == 0)
688 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
691 // Setting -msoft-float effectively disables NEON because of the GCC
692 // implementation, although the same isn't true of VFP or VFP3.
693 if (FloatABI == "soft") {
694 Features.push_back("-neon");
695 // Also need to explicitly disable features which imply NEON.
696 Features.push_back("-crypto");
699 // En/disable crc code generation.
700 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
701 if (A->getOption().matches(options::OPT_mcrc))
702 Features.push_back("+crc");
704 Features.push_back("-crc");
707 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
708 Features.insert(Features.begin(), "+v8.1a");
711 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
712 // neither options are specified, see if we are compiling for kernel/kext and
713 // decide whether to pass "+long-calls" based on the OS and its version.
714 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
715 options::OPT_mno_long_calls)) {
716 if (A->getOption().matches(options::OPT_mlong_calls))
717 Features.push_back("+long-calls");
718 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6))) {
719 Features.push_back("+long-calls");
723 void Clang::AddARMTargetArgs(const ArgList &Args, ArgStringList &CmdArgs,
724 bool KernelOrKext) const {
725 const Driver &D = getToolChain().getDriver();
726 // Get the effective triple, which takes into account the deployment target.
727 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
728 llvm::Triple Triple(TripleStr);
730 // Select the ABI to use.
732 // FIXME: Support -meabi.
733 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
734 const char *ABIName = nullptr;
735 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
736 ABIName = A->getValue();
737 } else if (Triple.isOSBinFormatMachO()) {
738 // The backend is hardwired to assume AAPCS for M-class processors, ensure
739 // the frontend matches that.
740 if (Triple.getEnvironment() == llvm::Triple::EABI ||
741 Triple.getOS() == llvm::Triple::UnknownOS || isARMMProfile(Triple)) {
744 ABIName = "apcs-gnu";
746 } else if (Triple.isOSWindows()) {
747 // FIXME: this is invalid for WindowsCE
750 // Select the default based on the platform.
751 switch (Triple.getEnvironment()) {
752 case llvm::Triple::Android:
753 case llvm::Triple::GNUEABI:
754 case llvm::Triple::GNUEABIHF:
755 ABIName = "aapcs-linux";
757 case llvm::Triple::EABIHF:
758 case llvm::Triple::EABI:
762 if (Triple.getOS() == llvm::Triple::NetBSD)
763 ABIName = "apcs-gnu";
769 CmdArgs.push_back("-target-abi");
770 CmdArgs.push_back(ABIName);
772 // Determine floating point ABI from the options & target defaults.
773 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
774 if (FloatABI == "soft") {
775 // Floating point operations and argument passing are soft.
777 // FIXME: This changes CPP defines, we need -target-soft-float.
778 CmdArgs.push_back("-msoft-float");
779 CmdArgs.push_back("-mfloat-abi");
780 CmdArgs.push_back("soft");
781 } else if (FloatABI == "softfp") {
782 // Floating point operations are hard, but argument passing is soft.
783 CmdArgs.push_back("-mfloat-abi");
784 CmdArgs.push_back("soft");
786 // Floating point operations and argument passing are hard.
787 assert(FloatABI == "hard" && "Invalid float abi!");
788 CmdArgs.push_back("-mfloat-abi");
789 CmdArgs.push_back("hard");
792 // Kernel code has more strict alignment requirements.
794 CmdArgs.push_back("-backend-option");
795 CmdArgs.push_back("-arm-strict-align");
797 // The kext linker doesn't know how to deal with movw/movt.
798 CmdArgs.push_back("-backend-option");
799 CmdArgs.push_back("-arm-use-movt=0");
802 // -mkernel implies -mstrict-align; don't add the redundant option.
804 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
805 options::OPT_munaligned_access)) {
806 CmdArgs.push_back("-backend-option");
807 if (A->getOption().matches(options::OPT_mno_unaligned_access))
808 CmdArgs.push_back("-arm-strict-align");
810 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
811 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
812 CmdArgs.push_back("-arm-no-strict-align");
817 // Forward the -mglobal-merge option for explicit control over the pass.
818 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
819 options::OPT_mno_global_merge)) {
820 CmdArgs.push_back("-backend-option");
821 if (A->getOption().matches(options::OPT_mno_global_merge))
822 CmdArgs.push_back("-arm-global-merge=false");
824 CmdArgs.push_back("-arm-global-merge=true");
827 if (!Args.hasFlag(options::OPT_mimplicit_float,
828 options::OPT_mno_implicit_float, true))
829 CmdArgs.push_back("-no-implicit-float");
831 // llvm does not support reserving registers in general. There is support
832 // for reserving r9 on ARM though (defined as a platform-specific register
834 if (Args.hasArg(options::OPT_ffixed_r9)) {
835 CmdArgs.push_back("-backend-option");
836 CmdArgs.push_back("-arm-reserve-r9");
840 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
842 static std::string getAArch64TargetCPU(const ArgList &Args) {
845 // If we have -mtune or -mcpu, use that.
846 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
848 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
849 StringRef Mcpu = A->getValue();
850 CPU = Mcpu.split("+").first.lower();
853 // Handle CPU name is 'native'.
855 return llvm::sys::getHostCPUName();
859 // Make sure we pick "cyclone" if -arch is used.
860 // FIXME: Should this be picked by checking the target triple instead?
861 if (Args.getLastArg(options::OPT_arch))
867 void Clang::AddAArch64TargetArgs(const ArgList &Args,
868 ArgStringList &CmdArgs) const {
869 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
870 llvm::Triple Triple(TripleStr);
872 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
873 Args.hasArg(options::OPT_mkernel) ||
874 Args.hasArg(options::OPT_fapple_kext))
875 CmdArgs.push_back("-disable-red-zone");
877 if (!Args.hasFlag(options::OPT_mimplicit_float,
878 options::OPT_mno_implicit_float, true))
879 CmdArgs.push_back("-no-implicit-float");
881 const char *ABIName = nullptr;
882 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
883 ABIName = A->getValue();
884 else if (Triple.isOSDarwin())
885 ABIName = "darwinpcs";
889 CmdArgs.push_back("-target-abi");
890 CmdArgs.push_back(ABIName);
892 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
893 options::OPT_munaligned_access)) {
894 CmdArgs.push_back("-backend-option");
895 if (A->getOption().matches(options::OPT_mno_unaligned_access))
896 CmdArgs.push_back("-aarch64-strict-align");
898 CmdArgs.push_back("-aarch64-no-strict-align");
901 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
902 options::OPT_mno_fix_cortex_a53_835769)) {
903 CmdArgs.push_back("-backend-option");
904 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
905 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
907 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
908 } else if (Triple.getEnvironment() == llvm::Triple::Android) {
909 // Enabled A53 errata (835769) workaround by default on android
910 CmdArgs.push_back("-backend-option");
911 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
914 // Forward the -mglobal-merge option for explicit control over the pass.
915 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
916 options::OPT_mno_global_merge)) {
917 CmdArgs.push_back("-backend-option");
918 if (A->getOption().matches(options::OPT_mno_global_merge))
919 CmdArgs.push_back("-aarch64-global-merge=false");
921 CmdArgs.push_back("-aarch64-global-merge=true");
924 if (Args.hasArg(options::OPT_ffixed_x18)) {
925 CmdArgs.push_back("-backend-option");
926 CmdArgs.push_back("-aarch64-reserve-x18");
930 // Get CPU and ABI names. They are not independent
931 // so we have to calculate them together.
932 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
933 StringRef &CPUName, StringRef &ABIName) {
934 const char *DefMips32CPU = "mips32r2";
935 const char *DefMips64CPU = "mips64r2";
937 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
938 // default for mips64(el)?-img-linux-gnu.
939 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
940 Triple.getEnvironment() == llvm::Triple::GNU) {
941 DefMips32CPU = "mips32r6";
942 DefMips64CPU = "mips64r6";
945 // MIPS3 is the default for mips64*-unknown-openbsd.
946 if (Triple.getOS() == llvm::Triple::OpenBSD)
947 DefMips64CPU = "mips3";
949 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
950 CPUName = A->getValue();
952 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
953 ABIName = A->getValue();
954 // Convert a GNU style Mips ABI name to the name
955 // accepted by LLVM Mips backend.
956 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
962 // Setup default CPU and ABI names.
963 if (CPUName.empty() && ABIName.empty()) {
964 switch (Triple.getArch()) {
966 llvm_unreachable("Unexpected triple arch name");
967 case llvm::Triple::mips:
968 case llvm::Triple::mipsel:
969 CPUName = DefMips32CPU;
971 case llvm::Triple::mips64:
972 case llvm::Triple::mips64el:
973 CPUName = DefMips64CPU;
978 if (ABIName.empty()) {
979 // Deduce ABI name from the target triple.
980 if (Triple.getArch() == llvm::Triple::mips ||
981 Triple.getArch() == llvm::Triple::mipsel)
987 if (CPUName.empty()) {
988 // Deduce CPU name from ABI name.
989 CPUName = llvm::StringSwitch<const char *>(ABIName)
990 .Cases("o32", "eabi", DefMips32CPU)
991 .Cases("n32", "n64", DefMips64CPU)
995 // FIXME: Warn on inconsistent use of -march and -mabi.
998 // Convert ABI name to the GNU tools acceptable variant.
999 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1000 return llvm::StringSwitch<llvm::StringRef>(ABI)
1006 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1007 // and -mfloat-abi=.
1008 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
1011 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1012 options::OPT_mfloat_abi_EQ)) {
1013 if (A->getOption().matches(options::OPT_msoft_float))
1015 else if (A->getOption().matches(options::OPT_mhard_float))
1018 FloatABI = A->getValue();
1019 if (FloatABI != "soft" && FloatABI != "hard") {
1020 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1026 // If unspecified, choose the default based on the platform.
1027 if (FloatABI.empty()) {
1028 // Assume "hard", because it's a default value used by gcc.
1029 // When we start to recognize specific target MIPS processors,
1030 // we will be able to select the default more correctly.
1037 static void AddTargetFeature(const ArgList &Args,
1038 std::vector<const char *> &Features,
1039 OptSpecifier OnOpt, OptSpecifier OffOpt,
1040 StringRef FeatureName) {
1041 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1042 if (A->getOption().matches(OnOpt))
1043 Features.push_back(Args.MakeArgString("+" + FeatureName));
1045 Features.push_back(Args.MakeArgString("-" + FeatureName));
1049 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1050 const ArgList &Args,
1051 std::vector<const char *> &Features) {
1054 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1055 ABIName = getGnuCompatibleMipsABIName(ABIName);
1057 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1058 options::OPT_mabicalls, "noabicalls");
1060 StringRef FloatABI = getMipsFloatABI(D, Args);
1061 if (FloatABI == "soft") {
1062 // FIXME: Note, this is a hack. We need to pass the selected float
1063 // mode to the MipsTargetInfoBase to define appropriate macros there.
1064 // Now it is the only method.
1065 Features.push_back("+soft-float");
1068 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1069 StringRef Val = StringRef(A->getValue());
1070 if (Val == "2008") {
1071 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1072 Features.push_back("+nan2008");
1074 Features.push_back("-nan2008");
1075 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1077 } else if (Val == "legacy") {
1078 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1079 Features.push_back("-nan2008");
1081 Features.push_back("+nan2008");
1082 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1085 D.Diag(diag::err_drv_unsupported_option_argument)
1086 << A->getOption().getName() << Val;
1089 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1090 options::OPT_mdouble_float, "single-float");
1091 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1093 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1094 options::OPT_mno_micromips, "micromips");
1095 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1097 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1099 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1102 // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1104 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1105 options::OPT_mfp64)) {
1106 if (A->getOption().matches(options::OPT_mfp32))
1107 Features.push_back(Args.MakeArgString("-fp64"));
1108 else if (A->getOption().matches(options::OPT_mfpxx)) {
1109 Features.push_back(Args.MakeArgString("+fpxx"));
1110 Features.push_back(Args.MakeArgString("+nooddspreg"));
1112 Features.push_back(Args.MakeArgString("+fp64"));
1113 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1114 Features.push_back(Args.MakeArgString("+fpxx"));
1115 Features.push_back(Args.MakeArgString("+nooddspreg"));
1118 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1119 options::OPT_modd_spreg, "nooddspreg");
1122 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1123 ArgStringList &CmdArgs) const {
1124 const Driver &D = getToolChain().getDriver();
1127 const llvm::Triple &Triple = getToolChain().getTriple();
1128 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1130 CmdArgs.push_back("-target-abi");
1131 CmdArgs.push_back(ABIName.data());
1133 StringRef FloatABI = getMipsFloatABI(D, Args);
1135 if (FloatABI == "soft") {
1136 // Floating point operations and argument passing are soft.
1137 CmdArgs.push_back("-msoft-float");
1138 CmdArgs.push_back("-mfloat-abi");
1139 CmdArgs.push_back("soft");
1141 // Floating point operations and argument passing are hard.
1142 assert(FloatABI == "hard" && "Invalid float abi!");
1143 CmdArgs.push_back("-mfloat-abi");
1144 CmdArgs.push_back("hard");
1147 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1148 if (A->getOption().matches(options::OPT_mxgot)) {
1149 CmdArgs.push_back("-mllvm");
1150 CmdArgs.push_back("-mxgot");
1154 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1155 options::OPT_mno_ldc1_sdc1)) {
1156 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1157 CmdArgs.push_back("-mllvm");
1158 CmdArgs.push_back("-mno-ldc1-sdc1");
1162 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1163 options::OPT_mno_check_zero_division)) {
1164 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1165 CmdArgs.push_back("-mllvm");
1166 CmdArgs.push_back("-mno-check-zero-division");
1170 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1171 StringRef v = A->getValue();
1172 CmdArgs.push_back("-mllvm");
1173 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1178 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1179 static std::string getPPCTargetCPU(const ArgList &Args) {
1180 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1181 StringRef CPUName = A->getValue();
1183 if (CPUName == "native") {
1184 std::string CPU = llvm::sys::getHostCPUName();
1185 if (!CPU.empty() && CPU != "generic")
1191 return llvm::StringSwitch<const char *>(CPUName)
1192 .Case("common", "generic")
1194 .Case("440fp", "440")
1199 .Case("603e", "603e")
1200 .Case("603ev", "603ev")
1202 .Case("604e", "604e")
1204 .Case("630", "pwr3")
1206 .Case("7400", "7400")
1208 .Case("7450", "7450")
1215 .Case("e500mc", "e500mc")
1216 .Case("e5500", "e5500")
1217 .Case("power3", "pwr3")
1218 .Case("power4", "pwr4")
1219 .Case("power5", "pwr5")
1220 .Case("power5x", "pwr5x")
1221 .Case("power6", "pwr6")
1222 .Case("power6x", "pwr6x")
1223 .Case("power7", "pwr7")
1224 .Case("power8", "pwr8")
1225 .Case("pwr3", "pwr3")
1226 .Case("pwr4", "pwr4")
1227 .Case("pwr5", "pwr5")
1228 .Case("pwr5x", "pwr5x")
1229 .Case("pwr6", "pwr6")
1230 .Case("pwr6x", "pwr6x")
1231 .Case("pwr7", "pwr7")
1232 .Case("pwr8", "pwr8")
1233 .Case("powerpc", "ppc")
1234 .Case("powerpc64", "ppc64")
1235 .Case("powerpc64le", "ppc64le")
1242 static void getPPCTargetFeatures(const ArgList &Args,
1243 std::vector<const char *> &Features) {
1244 for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
1245 StringRef Name = A->getOption().getName();
1249 assert(Name.startswith("m") && "Invalid feature name.");
1250 Name = Name.substr(1);
1252 bool IsNegative = Name.startswith("no-");
1254 Name = Name.substr(3);
1256 // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1257 // pass the correct option to the backend while calling the frontend
1259 // TODO: Change the LLVM backend option maybe?
1260 if (Name == "mfcrf")
1263 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1266 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1267 AddTargetFeature(Args, Features, options::OPT_faltivec,
1268 options::OPT_fno_altivec, "altivec");
1271 void Clang::AddPPCTargetArgs(const ArgList &Args,
1272 ArgStringList &CmdArgs) const {
1273 // Select the ABI to use.
1274 const char *ABIName = nullptr;
1275 if (getToolChain().getTriple().isOSLinux())
1276 switch (getToolChain().getArch()) {
1277 case llvm::Triple::ppc64: {
1278 // When targeting a processor that supports QPX, or if QPX is
1279 // specifically enabled, default to using the ABI that supports QPX (so
1280 // long as it is not specifically disabled).
1281 bool HasQPX = false;
1282 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1283 HasQPX = A->getValue() == StringRef("a2q");
1284 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1286 ABIName = "elfv1-qpx";
1293 case llvm::Triple::ppc64le:
1300 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1301 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1302 // the option if given as we don't have backend support for any targets
1303 // that don't use the altivec abi.
1304 if (StringRef(A->getValue()) != "altivec")
1305 ABIName = A->getValue();
1308 CmdArgs.push_back("-target-abi");
1309 CmdArgs.push_back(ABIName);
1313 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1314 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1315 return A && (A->getValue() == StringRef(Value));
1318 /// Get the (LLVM) name of the R600 gpu we are targeting.
1319 static std::string getR600TargetGPU(const ArgList &Args) {
1320 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1321 const char *GPUName = A->getValue();
1322 return llvm::StringSwitch<const char *>(GPUName)
1323 .Cases("rv630", "rv635", "r600")
1324 .Cases("rv610", "rv620", "rs780", "rs880")
1325 .Case("rv740", "rv770")
1326 .Case("palm", "cedar")
1327 .Cases("sumo", "sumo2", "sumo")
1328 .Case("hemlock", "cypress")
1329 .Case("aruba", "cayman")
1335 void Clang::AddSparcTargetArgs(const ArgList &Args,
1336 ArgStringList &CmdArgs) const {
1337 const Driver &D = getToolChain().getDriver();
1338 std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1340 bool SoftFloatABI = false;
1342 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1343 if (A->getOption().matches(options::OPT_msoft_float))
1344 SoftFloatABI = true;
1347 // Only the hard-float ABI on Sparc is standardized, and it is the
1348 // default. GCC also supports a nonstandard soft-float ABI mode, and
1349 // perhaps LLVM should implement that, too. However, since llvm
1350 // currently does not support Sparc soft-float, at all, display an
1351 // error if it's requested.
1353 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1358 static const char *getSystemZTargetCPU(const ArgList &Args) {
1359 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1360 return A->getValue();
1364 static void getSystemZTargetFeatures(const ArgList &Args,
1365 std::vector<const char *> &Features) {
1366 // -m(no-)htm overrides use of the transactional-execution facility.
1367 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1368 if (A->getOption().matches(options::OPT_mhtm))
1369 Features.push_back("+transactional-execution");
1371 Features.push_back("-transactional-execution");
1373 // -m(no-)vx overrides use of the vector facility.
1374 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1375 if (A->getOption().matches(options::OPT_mvx))
1376 Features.push_back("+vector");
1378 Features.push_back("-vector");
1382 static const char *getX86TargetCPU(const ArgList &Args,
1383 const llvm::Triple &Triple) {
1384 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1385 if (StringRef(A->getValue()) != "native") {
1386 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1389 return A->getValue();
1392 // FIXME: Reject attempts to use -march=native unless the target matches
1395 // FIXME: We should also incorporate the detected target features for use
1397 std::string CPU = llvm::sys::getHostCPUName();
1398 if (!CPU.empty() && CPU != "generic")
1399 return Args.MakeArgString(CPU);
1402 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1403 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1404 StringRef Arch = A->getValue();
1406 if (Triple.getArch() == llvm::Triple::x86) {
1407 CPU = llvm::StringSwitch<const char *>(Arch)
1408 .Case("IA32", "i386")
1409 .Case("SSE", "pentium3")
1410 .Case("SSE2", "pentium4")
1411 .Case("AVX", "sandybridge")
1412 .Case("AVX2", "haswell")
1415 CPU = llvm::StringSwitch<const char *>(Arch)
1416 .Case("AVX", "sandybridge")
1417 .Case("AVX2", "haswell")
1424 // Select the default CPU if none was given (or detection failed).
1426 if (Triple.getArch() != llvm::Triple::x86_64 &&
1427 Triple.getArch() != llvm::Triple::x86)
1428 return nullptr; // This routine is only handling x86 targets.
1430 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1432 // FIXME: Need target hooks.
1433 if (Triple.isOSDarwin()) {
1434 if (Triple.getArchName() == "x86_64h")
1436 return Is64Bit ? "core2" : "yonah";
1439 // Set up default CPU name for PS4 compilers.
1440 if (Triple.isPS4CPU())
1443 // On Android use targets compatible with gcc
1444 if (Triple.getEnvironment() == llvm::Triple::Android)
1445 return Is64Bit ? "x86-64" : "i686";
1447 // Everything else goes to x86-64 in 64-bit mode.
1451 switch (Triple.getOS()) {
1452 case llvm::Triple::FreeBSD:
1453 case llvm::Triple::NetBSD:
1454 case llvm::Triple::OpenBSD:
1456 case llvm::Triple::Haiku:
1458 case llvm::Triple::Bitrig:
1466 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
1467 switch (T.getArch()) {
1471 case llvm::Triple::aarch64:
1472 case llvm::Triple::aarch64_be:
1473 return getAArch64TargetCPU(Args);
1475 case llvm::Triple::arm:
1476 case llvm::Triple::armeb:
1477 case llvm::Triple::thumb:
1478 case llvm::Triple::thumbeb:
1479 return arm::getARMTargetCPU(Args, T);
1481 case llvm::Triple::mips:
1482 case llvm::Triple::mipsel:
1483 case llvm::Triple::mips64:
1484 case llvm::Triple::mips64el: {
1487 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1491 case llvm::Triple::nvptx:
1492 case llvm::Triple::nvptx64:
1493 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1494 return A->getValue();
1497 case llvm::Triple::ppc:
1498 case llvm::Triple::ppc64:
1499 case llvm::Triple::ppc64le: {
1500 std::string TargetCPUName = getPPCTargetCPU(Args);
1501 // LLVM may default to generating code for the native CPU,
1502 // but, like gcc, we default to a more generic option for
1503 // each architecture. (except on Darwin)
1504 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1505 if (T.getArch() == llvm::Triple::ppc64)
1506 TargetCPUName = "ppc64";
1507 else if (T.getArch() == llvm::Triple::ppc64le)
1508 TargetCPUName = "ppc64le";
1510 TargetCPUName = "ppc";
1512 return TargetCPUName;
1515 case llvm::Triple::sparc:
1516 case llvm::Triple::sparcel:
1517 case llvm::Triple::sparcv9:
1518 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1519 return A->getValue();
1522 case llvm::Triple::x86:
1523 case llvm::Triple::x86_64:
1524 return getX86TargetCPU(Args, T);
1526 case llvm::Triple::hexagon:
1527 return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1529 case llvm::Triple::systemz:
1530 return getSystemZTargetCPU(Args);
1532 case llvm::Triple::r600:
1533 case llvm::Triple::amdgcn:
1534 return getR600TargetGPU(Args);
1538 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1539 ArgStringList &CmdArgs) {
1540 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1541 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1543 CmdArgs.push_back("-plugin");
1544 std::string Plugin =
1545 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1546 CmdArgs.push_back(Args.MakeArgString(Plugin));
1548 // Try to pass driver level flags relevant to LTO code generation down to
1551 // Handle flags for selecting CPU variants.
1552 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1554 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1557 /// This is a helper function for validating the optional refinement step
1558 /// parameter in reciprocal argument strings. Return false if there is an error
1559 /// parsing the refinement step. Otherwise, return true and set the Position
1560 /// of the refinement step in the input string.
1561 static bool getRefinementStep(const StringRef &In, const Driver &D,
1562 const Arg &A, size_t &Position) {
1563 const char RefinementStepToken = ':';
1564 Position = In.find(RefinementStepToken);
1565 if (Position != StringRef::npos) {
1566 StringRef Option = A.getOption().getName();
1567 StringRef RefStep = In.substr(Position + 1);
1568 // Allow exactly one numeric character for the additional refinement
1569 // step parameter. This is reasonable for all currently-supported
1570 // operations and architectures because we would expect that a larger value
1571 // of refinement steps would cause the estimate "optimization" to
1572 // under-perform the native operation. Also, if the estimate does not
1573 // converge quickly, it probably will not ever converge, so further
1574 // refinement steps will not produce a better answer.
1575 if (RefStep.size() != 1) {
1576 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1579 char RefStepChar = RefStep[0];
1580 if (RefStepChar < '0' || RefStepChar > '9') {
1581 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1588 /// The -mrecip flag requires processing of many optional parameters.
1589 static void ParseMRecip(const Driver &D, const ArgList &Args,
1590 ArgStringList &OutStrings) {
1591 StringRef DisabledPrefixIn = "!";
1592 StringRef DisabledPrefixOut = "!";
1593 StringRef EnabledPrefixOut = "";
1594 StringRef Out = "-mrecip=";
1596 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1600 unsigned NumOptions = A->getNumValues();
1601 if (NumOptions == 0) {
1602 // No option is the same as "all".
1603 OutStrings.push_back(Args.MakeArgString(Out + "all"));
1607 // Pass through "all", "none", or "default" with an optional refinement step.
1608 if (NumOptions == 1) {
1609 StringRef Val = A->getValue(0);
1611 if (!getRefinementStep(Val, D, *A, RefStepLoc))
1613 StringRef ValBase = Val.slice(0, RefStepLoc);
1614 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1615 OutStrings.push_back(Args.MakeArgString(Out + Val));
1620 // Each reciprocal type may be enabled or disabled individually.
1621 // Check each input value for validity, concatenate them all back together,
1622 // and pass through.
1624 llvm::StringMap<bool> OptionStrings;
1625 OptionStrings.insert(std::make_pair("divd", false));
1626 OptionStrings.insert(std::make_pair("divf", false));
1627 OptionStrings.insert(std::make_pair("vec-divd", false));
1628 OptionStrings.insert(std::make_pair("vec-divf", false));
1629 OptionStrings.insert(std::make_pair("sqrtd", false));
1630 OptionStrings.insert(std::make_pair("sqrtf", false));
1631 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1632 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1634 for (unsigned i = 0; i != NumOptions; ++i) {
1635 StringRef Val = A->getValue(i);
1637 bool IsDisabled = Val.startswith(DisabledPrefixIn);
1638 // Ignore the disablement token for string matching.
1640 Val = Val.substr(1);
1643 if (!getRefinementStep(Val, D, *A, RefStep))
1646 StringRef ValBase = Val.slice(0, RefStep);
1647 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1648 if (OptionIter == OptionStrings.end()) {
1649 // Try again specifying float suffix.
1650 OptionIter = OptionStrings.find(ValBase.str() + 'f');
1651 if (OptionIter == OptionStrings.end()) {
1652 // The input name did not match any known option string.
1653 D.Diag(diag::err_drv_unknown_argument) << Val;
1656 // The option was specified without a float or double suffix.
1657 // Make sure that the double entry was not already specified.
1658 // The float entry will be checked below.
1659 if (OptionStrings[ValBase.str() + 'd']) {
1660 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1665 if (OptionIter->second == true) {
1666 // Duplicate option specified.
1667 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1671 // Mark the matched option as found. Do not allow duplicate specifiers.
1672 OptionIter->second = true;
1674 // If the precision was not specified, also mark the double entry as found.
1675 if (ValBase.back() != 'f' && ValBase.back() != 'd')
1676 OptionStrings[ValBase.str() + 'd'] = true;
1678 // Build the output string.
1679 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1680 Out = Args.MakeArgString(Out + Prefix + Val);
1681 if (i != NumOptions - 1)
1682 Out = Args.MakeArgString(Out + ",");
1685 OutStrings.push_back(Args.MakeArgString(Out));
1688 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1689 const ArgList &Args,
1690 std::vector<const char *> &Features) {
1691 // If -march=native, autodetect the feature list.
1692 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1693 if (StringRef(A->getValue()) == "native") {
1694 llvm::StringMap<bool> HostFeatures;
1695 if (llvm::sys::getHostCPUFeatures(HostFeatures))
1696 for (auto &F : HostFeatures)
1698 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1702 if (Triple.getArchName() == "x86_64h") {
1703 // x86_64h implies quite a few of the more modern subtarget features
1704 // for Haswell class CPUs, but not all of them. Opt-out of a few.
1705 Features.push_back("-rdrnd");
1706 Features.push_back("-aes");
1707 Features.push_back("-pclmul");
1708 Features.push_back("-rtm");
1709 Features.push_back("-hle");
1710 Features.push_back("-fsgsbase");
1713 const llvm::Triple::ArchType ArchType = Triple.getArch();
1714 // Add features to be compatible with gcc for Android.
1715 if (Triple.getEnvironment() == llvm::Triple::Android) {
1716 if (ArchType == llvm::Triple::x86_64) {
1717 Features.push_back("+sse4.2");
1718 Features.push_back("+popcnt");
1720 Features.push_back("+ssse3");
1723 // Set features according to the -arch flag on MSVC.
1724 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1725 StringRef Arch = A->getValue();
1726 bool ArchUsed = false;
1727 // First, look for flags that are shared in x86 and x86-64.
1728 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1729 if (Arch == "AVX" || Arch == "AVX2") {
1731 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1734 // Then, look for x86-specific flags.
1735 if (ArchType == llvm::Triple::x86) {
1736 if (Arch == "IA32") {
1738 } else if (Arch == "SSE" || Arch == "SSE2") {
1740 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1744 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
1747 // Now add any that the user explicitly requested on the command line,
1748 // which may override the defaults.
1749 for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
1750 StringRef Name = A->getOption().getName();
1754 assert(Name.startswith("m") && "Invalid feature name.");
1755 Name = Name.substr(1);
1757 bool IsNegative = Name.startswith("no-");
1759 Name = Name.substr(3);
1761 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1765 void Clang::AddX86TargetArgs(const ArgList &Args,
1766 ArgStringList &CmdArgs) const {
1767 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1768 Args.hasArg(options::OPT_mkernel) ||
1769 Args.hasArg(options::OPT_fapple_kext))
1770 CmdArgs.push_back("-disable-red-zone");
1772 // Default to avoid implicit floating-point for kernel/kext code, but allow
1773 // that to be overridden with -mno-soft-float.
1774 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1775 Args.hasArg(options::OPT_fapple_kext));
1776 if (Arg *A = Args.getLastArg(
1777 options::OPT_msoft_float, options::OPT_mno_soft_float,
1778 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1779 const Option &O = A->getOption();
1780 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1781 O.matches(options::OPT_msoft_float));
1783 if (NoImplicitFloat)
1784 CmdArgs.push_back("-no-implicit-float");
1786 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1787 StringRef Value = A->getValue();
1788 if (Value == "intel" || Value == "att") {
1789 CmdArgs.push_back("-mllvm");
1790 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1792 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1793 << A->getOption().getName() << Value;
1798 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1799 ArgStringList &CmdArgs) const {
1800 CmdArgs.push_back("-mqdsp6-compat");
1801 CmdArgs.push_back("-Wreturn-type");
1803 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
1804 std::string SmallDataThreshold = "-hexagon-small-data-threshold=";
1805 SmallDataThreshold += v;
1806 CmdArgs.push_back("-mllvm");
1807 CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
1810 if (!Args.hasArg(options::OPT_fno_short_enums))
1811 CmdArgs.push_back("-fshort-enums");
1812 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1813 CmdArgs.push_back("-mllvm");
1814 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1816 CmdArgs.push_back("-mllvm");
1817 CmdArgs.push_back("-machine-sink-split=0");
1820 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
1821 static bool DecodeAArch64Features(const Driver &D, StringRef text,
1822 std::vector<const char *> &Features) {
1823 SmallVector<StringRef, 8> Split;
1824 text.split(Split, StringRef("+"), -1, false);
1826 for (const StringRef Feature : Split) {
1827 const char *result = llvm::StringSwitch<const char *>(Feature)
1828 .Case("fp", "+fp-armv8")
1829 .Case("simd", "+neon")
1830 .Case("crc", "+crc")
1831 .Case("crypto", "+crypto")
1832 .Case("nofp", "-fp-armv8")
1833 .Case("nosimd", "-neon")
1834 .Case("nocrc", "-crc")
1835 .Case("nocrypto", "-crypto")
1838 Features.push_back(result);
1839 else if (Feature == "neon" || Feature == "noneon")
1840 D.Diag(diag::err_drv_no_neon_modifier);
1847 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
1848 // decode CPU and feature.
1849 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
1850 std::vector<const char *> &Features) {
1851 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
1853 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
1854 CPU == "cortex-a72") {
1855 Features.push_back("+neon");
1856 Features.push_back("+crc");
1857 Features.push_back("+crypto");
1858 } else if (CPU == "generic") {
1859 Features.push_back("+neon");
1864 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1871 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
1872 const ArgList &Args,
1873 std::vector<const char *> &Features) {
1874 std::string MarchLowerCase = March.lower();
1875 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
1877 if (Split.first == "armv8-a" || Split.first == "armv8a") {
1878 // ok, no additional features.
1879 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
1880 Features.push_back("+v8.1a");
1885 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1892 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1893 const ArgList &Args,
1894 std::vector<const char *> &Features) {
1896 std::string McpuLowerCase = Mcpu.lower();
1897 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
1904 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
1905 const ArgList &Args,
1906 std::vector<const char *> &Features) {
1907 // Handle CPU name is 'native'.
1908 if (Mtune == "native")
1909 Mtune = llvm::sys::getHostCPUName();
1910 if (Mtune == "cyclone") {
1911 Features.push_back("+zcm");
1912 Features.push_back("+zcz");
1918 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1919 const ArgList &Args,
1920 std::vector<const char *> &Features) {
1922 std::vector<const char *> DecodedFeature;
1923 std::string McpuLowerCase = Mcpu.lower();
1924 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
1927 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
1930 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
1931 std::vector<const char *> &Features) {
1933 bool success = true;
1934 // Enable NEON by default.
1935 Features.push_back("+neon");
1936 if ((A = Args.getLastArg(options::OPT_march_EQ)))
1937 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
1938 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
1939 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1940 else if (Args.hasArg(options::OPT_arch))
1941 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
1944 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
1946 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
1947 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
1949 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1950 else if (Args.hasArg(options::OPT_arch))
1951 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
1955 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
1957 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
1958 Features.push_back("-fp-armv8");
1959 Features.push_back("-crypto");
1960 Features.push_back("-neon");
1964 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
1965 if (A->getOption().matches(options::OPT_mcrc))
1966 Features.push_back("+crc");
1968 Features.push_back("-crc");
1972 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1973 const ArgList &Args, ArgStringList &CmdArgs,
1975 std::vector<const char *> Features;
1976 switch (Triple.getArch()) {
1979 case llvm::Triple::mips:
1980 case llvm::Triple::mipsel:
1981 case llvm::Triple::mips64:
1982 case llvm::Triple::mips64el:
1983 getMIPSTargetFeatures(D, Triple, Args, Features);
1986 case llvm::Triple::arm:
1987 case llvm::Triple::armeb:
1988 case llvm::Triple::thumb:
1989 case llvm::Triple::thumbeb:
1990 getARMTargetFeatures(D, Triple, Args, Features, ForAS);
1993 case llvm::Triple::ppc:
1994 case llvm::Triple::ppc64:
1995 case llvm::Triple::ppc64le:
1996 getPPCTargetFeatures(Args, Features);
1998 case llvm::Triple::systemz:
1999 getSystemZTargetFeatures(Args, Features);
2001 case llvm::Triple::aarch64:
2002 case llvm::Triple::aarch64_be:
2003 getAArch64TargetFeatures(D, Args, Features);
2005 case llvm::Triple::x86:
2006 case llvm::Triple::x86_64:
2007 getX86TargetFeatures(D, Triple, Args, Features);
2011 // Find the last of each feature.
2012 llvm::StringMap<unsigned> LastOpt;
2013 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2014 const char *Name = Features[I];
2015 assert(Name[0] == '-' || Name[0] == '+');
2016 LastOpt[Name + 1] = I;
2019 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2020 // If this feature was overridden, ignore it.
2021 const char *Name = Features[I];
2022 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2023 assert(LastI != LastOpt.end());
2024 unsigned Last = LastI->second;
2028 CmdArgs.push_back("-target-feature");
2029 CmdArgs.push_back(Name);
2034 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2035 const llvm::Triple &Triple) {
2036 // We use the zero-cost exception tables for Objective-C if the non-fragile
2037 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2039 if (runtime.isNonFragile())
2042 if (!Triple.isMacOSX())
2045 return (!Triple.isMacOSXVersionLT(10, 5) &&
2046 (Triple.getArch() == llvm::Triple::x86_64 ||
2047 Triple.getArch() == llvm::Triple::arm));
2050 /// Adds exception related arguments to the driver command arguments. There's a
2051 /// master flag, -fexceptions and also language specific flags to enable/disable
2052 /// C++ and Objective-C exceptions. This makes it possible to for example
2053 /// disable C++ exceptions but enable Objective-C exceptions.
2054 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2055 const ToolChain &TC, bool KernelOrKext,
2056 const ObjCRuntime &objcRuntime,
2057 ArgStringList &CmdArgs) {
2058 const Driver &D = TC.getDriver();
2059 const llvm::Triple &Triple = TC.getTriple();
2062 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2063 // arguments now to avoid warnings about unused arguments.
2064 Args.ClaimAllArgs(options::OPT_fexceptions);
2065 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2066 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2067 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2068 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2069 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2073 // See if the user explicitly enabled exceptions.
2074 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2077 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2078 // is not necessarily sensible, but follows GCC.
2079 if (types::isObjC(InputType) &&
2080 Args.hasFlag(options::OPT_fobjc_exceptions,
2081 options::OPT_fno_objc_exceptions, true)) {
2082 CmdArgs.push_back("-fobjc-exceptions");
2084 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2087 if (types::isCXX(InputType)) {
2088 // Disable C++ EH by default on XCore, PS4, and MSVC.
2089 // FIXME: Remove MSVC from this list once things work.
2090 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2091 !Triple.isPS4CPU() &&
2092 !Triple.isWindowsMSVCEnvironment();
2093 Arg *ExceptionArg = Args.getLastArg(
2094 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2095 options::OPT_fexceptions, options::OPT_fno_exceptions);
2097 CXXExceptionsEnabled =
2098 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2099 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2101 if (CXXExceptionsEnabled) {
2102 if (Triple.isPS4CPU()) {
2103 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2104 assert(ExceptionArg &&
2105 "On the PS4 exceptions should only be enabled if passing "
2107 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2108 const Arg *RTTIArg = TC.getRTTIArg();
2109 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2110 D.Diag(diag::err_drv_argument_not_allowed_with)
2111 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2112 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2113 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2115 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2117 CmdArgs.push_back("-fcxx-exceptions");
2124 CmdArgs.push_back("-fexceptions");
2127 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2128 bool Default = true;
2129 if (TC.getTriple().isOSDarwin()) {
2130 // The native darwin assembler doesn't support the linker_option directives,
2131 // so we disable them if we think the .s file will be passed to it.
2132 Default = TC.useIntegratedAs();
2134 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2138 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2139 const ToolChain &TC) {
2140 bool UseDwarfDirectory =
2141 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2142 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2143 return !UseDwarfDirectory;
2146 /// \brief Check whether the given input tree contains any compilation actions.
2147 static bool ContainsCompileAction(const Action *A) {
2148 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2151 for (const auto &Act : *A)
2152 if (ContainsCompileAction(Act))
2158 /// \brief Check if -relax-all should be passed to the internal assembler.
2159 /// This is done by default when compiling non-assembler source with -O0.
2160 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2161 bool RelaxDefault = true;
2163 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2164 RelaxDefault = A->getOption().matches(options::OPT_O0);
2167 RelaxDefault = false;
2168 for (const auto &Act : C.getActions()) {
2169 if (ContainsCompileAction(Act)) {
2170 RelaxDefault = true;
2176 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2180 static void CollectArgsForIntegratedAssembler(Compilation &C,
2181 const ArgList &Args,
2182 ArgStringList &CmdArgs,
2184 if (UseRelaxAll(C, Args))
2185 CmdArgs.push_back("-mrelax-all");
2187 // When passing -I arguments to the assembler we sometimes need to
2188 // unconditionally take the next argument. For example, when parsing
2189 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2190 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2191 // arg after parsing the '-I' arg.
2192 bool TakeNextArg = false;
2194 // When using an integrated assembler, translate -Wa, and -Xassembler
2196 bool CompressDebugSections = false;
2198 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2201 for (const StringRef Value : A->getValues()) {
2203 CmdArgs.push_back(Value.data());
2204 TakeNextArg = false;
2208 if (Value == "-force_cpusubtype_ALL") {
2209 // Do nothing, this is the default and we don't support anything else.
2210 } else if (Value == "-L") {
2211 CmdArgs.push_back("-msave-temp-labels");
2212 } else if (Value == "--fatal-warnings") {
2213 CmdArgs.push_back("-massembler-fatal-warnings");
2214 } else if (Value == "--noexecstack") {
2215 CmdArgs.push_back("-mnoexecstack");
2216 } else if (Value == "-compress-debug-sections" ||
2217 Value == "--compress-debug-sections") {
2218 CompressDebugSections = true;
2219 } else if (Value == "-nocompress-debug-sections" ||
2220 Value == "--nocompress-debug-sections") {
2221 CompressDebugSections = false;
2222 } else if (Value.startswith("-I")) {
2223 CmdArgs.push_back(Value.data());
2224 // We need to consume the next argument if the current arg is a plain
2225 // -I. The next arg will be the include directory.
2228 } else if (Value.startswith("-gdwarf-")) {
2229 CmdArgs.push_back(Value.data());
2231 D.Diag(diag::err_drv_unsupported_option_argument)
2232 << A->getOption().getName() << Value;
2236 if (CompressDebugSections) {
2237 if (llvm::zlib::isAvailable())
2238 CmdArgs.push_back("-compress-debug-sections");
2240 D.Diag(diag::warn_debug_compression_unavailable);
2244 // Until ARM libraries are build separately, we have them all in one library
2245 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
2246 if (TC.getTriple().isOSWindows() &&
2247 !TC.getTriple().isWindowsItaniumEnvironment() &&
2248 TC.getArch() == llvm::Triple::x86)
2250 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
2252 return TC.getArchName();
2255 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
2256 // The runtimes are located in the OS-specific resource directory.
2257 SmallString<128> Res(TC.getDriver().ResourceDir);
2258 const llvm::Triple &Triple = TC.getTriple();
2259 // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
2260 StringRef OSLibName =
2261 (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
2262 llvm::sys::path::append(Res, "lib", OSLibName);
2266 SmallString<128> tools::getCompilerRT(const ToolChain &TC, StringRef Component,
2268 const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
2272 bool IsOSWindows = TC.getTriple().isOSWindows();
2273 StringRef Arch = getArchNameForCompilerRTLib(TC);
2274 const char *Prefix = IsOSWindows ? "" : "lib";
2275 const char *Suffix =
2276 Shared ? (IsOSWindows ? ".dll" : ".so") : (IsOSWindows ? ".lib" : ".a");
2278 SmallString<128> Path = getCompilerRTLibDir(TC);
2279 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
2280 Arch + Env + Suffix);
2285 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2286 // FIXME: Make sure we can also emit shared objects if they're requested
2287 // and available, check for possible errors, etc.
2288 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2289 ArgStringList &CmdArgs) {
2290 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
2292 if (!TC.getTriple().isOSWindows()) {
2293 // FIXME: why do we link against gcc when we are using compiler-rt?
2294 CmdArgs.push_back("-lgcc_s");
2295 if (TC.getDriver().CCCIsCXX())
2296 CmdArgs.push_back("-lgcc_eh");
2300 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
2301 ArgStringList &CmdArgs) {
2302 if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2304 Args.hasArg(options::OPT_fprofile_generate) ||
2305 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
2306 Args.hasArg(options::OPT_fprofile_instr_generate) ||
2307 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
2308 Args.hasArg(options::OPT_fcreate_profile) ||
2309 Args.hasArg(options::OPT_coverage)))
2312 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
2316 enum OpenMPRuntimeKind {
2317 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2318 /// without knowing what runtime to target.
2321 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2322 /// the default for Clang.
2325 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2326 /// this runtime but can swallow the pragmas, and find and link against the
2327 /// runtime library itself.
2330 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2331 /// OpenMP runtime. We support this mode for users with existing dependencies
2332 /// on this runtime library name.
2337 /// Compute the desired OpenMP runtime from the flag provided.
2338 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2339 const ArgList &Args) {
2340 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2342 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2344 RuntimeName = A->getValue();
2346 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2347 .Case("libomp", OMPRT_OMP)
2348 .Case("libgomp", OMPRT_GOMP)
2349 .Case("libiomp5", OMPRT_IOMP5)
2350 .Default(OMPRT_Unknown);
2352 if (RT == OMPRT_Unknown) {
2354 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2355 << A->getOption().getName() << A->getValue();
2357 // FIXME: We could use a nicer diagnostic here.
2358 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2364 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2365 ArgStringList &CmdArgs, StringRef Sanitizer,
2367 // Static runtimes must be forced into executable, so we wrap them in
2370 CmdArgs.push_back("-whole-archive");
2371 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared)));
2373 CmdArgs.push_back("-no-whole-archive");
2376 // Tries to use a file with the list of dynamic symbols that need to be exported
2377 // from the runtime library. Returns true if the file was found.
2378 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2379 ArgStringList &CmdArgs,
2380 StringRef Sanitizer) {
2381 SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
2382 if (llvm::sys::fs::exists(SanRT + ".syms")) {
2383 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2389 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2390 ArgStringList &CmdArgs) {
2391 // Force linking against the system libraries sanitizers depends on
2392 // (see PR15823 why this is necessary).
2393 CmdArgs.push_back("--no-as-needed");
2394 CmdArgs.push_back("-lpthread");
2395 CmdArgs.push_back("-lrt");
2396 CmdArgs.push_back("-lm");
2397 // There's no libdl on FreeBSD.
2398 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2399 CmdArgs.push_back("-ldl");
2403 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2404 SmallVectorImpl<StringRef> &SharedRuntimes,
2405 SmallVectorImpl<StringRef> &StaticRuntimes,
2406 SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2407 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2408 // Collect shared runtimes.
2409 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2410 SharedRuntimes.push_back("asan");
2413 // Collect static runtimes.
2414 if (Args.hasArg(options::OPT_shared) ||
2415 (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
2416 // Don't link static runtimes into DSOs or if compiling for Android.
2419 if (SanArgs.needsAsanRt()) {
2420 if (SanArgs.needsSharedAsanRt()) {
2421 HelperStaticRuntimes.push_back("asan-preinit");
2423 StaticRuntimes.push_back("asan");
2424 if (SanArgs.linkCXXRuntimes())
2425 StaticRuntimes.push_back("asan_cxx");
2428 if (SanArgs.needsDfsanRt())
2429 StaticRuntimes.push_back("dfsan");
2430 if (SanArgs.needsLsanRt())
2431 StaticRuntimes.push_back("lsan");
2432 if (SanArgs.needsMsanRt()) {
2433 StaticRuntimes.push_back("msan");
2434 if (SanArgs.linkCXXRuntimes())
2435 StaticRuntimes.push_back("msan_cxx");
2437 if (SanArgs.needsTsanRt()) {
2438 StaticRuntimes.push_back("tsan");
2439 if (SanArgs.linkCXXRuntimes())
2440 StaticRuntimes.push_back("tsan_cxx");
2442 if (SanArgs.needsUbsanRt()) {
2443 StaticRuntimes.push_back("ubsan_standalone");
2444 if (SanArgs.linkCXXRuntimes())
2445 StaticRuntimes.push_back("ubsan_standalone_cxx");
2447 if (SanArgs.needsSafeStackRt())
2448 StaticRuntimes.push_back("safestack");
2451 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2452 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2453 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2454 ArgStringList &CmdArgs) {
2455 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2456 HelperStaticRuntimes;
2457 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2458 HelperStaticRuntimes);
2459 for (auto RT : SharedRuntimes)
2460 addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2461 for (auto RT : HelperStaticRuntimes)
2462 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2463 bool AddExportDynamic = false;
2464 for (auto RT : StaticRuntimes) {
2465 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2466 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2468 // If there is a static runtime with no dynamic list, force all the symbols
2469 // to be dynamic to be sure we export sanitizer interface functions.
2470 if (AddExportDynamic)
2471 CmdArgs.push_back("-export-dynamic");
2472 return !StaticRuntimes.empty();
2475 static bool areOptimizationsEnabled(const ArgList &Args) {
2476 // Find the last -O arg and see if it is non-zero.
2477 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2478 return !A->getOption().matches(options::OPT_O0);
2483 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2484 const llvm::Triple &Triple) {
2485 // XCore never wants frame pointers, regardless of OS.
2486 if (Triple.getArch() == llvm::Triple::xcore) {
2490 if (Triple.isOSLinux()) {
2491 switch (Triple.getArch()) {
2492 // Don't use a frame pointer on linux if optimizing for certain targets.
2493 case llvm::Triple::mips64:
2494 case llvm::Triple::mips64el:
2495 case llvm::Triple::mips:
2496 case llvm::Triple::mipsel:
2497 case llvm::Triple::systemz:
2498 case llvm::Triple::x86:
2499 case llvm::Triple::x86_64:
2500 return !areOptimizationsEnabled(Args);
2506 if (Triple.isOSWindows()) {
2507 switch (Triple.getArch()) {
2508 case llvm::Triple::x86:
2509 return !areOptimizationsEnabled(Args);
2511 // All other supported Windows ISAs use xdata unwind information, so frame
2512 // pointers are not generally useful.
2520 static bool shouldUseFramePointer(const ArgList &Args,
2521 const llvm::Triple &Triple) {
2522 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2523 options::OPT_fomit_frame_pointer))
2524 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2526 return shouldUseFramePointerForTarget(Args, Triple);
2529 static bool shouldUseLeafFramePointer(const ArgList &Args,
2530 const llvm::Triple &Triple) {
2531 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2532 options::OPT_momit_leaf_frame_pointer))
2533 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2535 if (Triple.isPS4CPU())
2538 return shouldUseFramePointerForTarget(Args, Triple);
2541 /// Add a CC1 option to specify the debug compilation directory.
2542 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2543 SmallString<128> cwd;
2544 if (!llvm::sys::fs::current_path(cwd)) {
2545 CmdArgs.push_back("-fdebug-compilation-dir");
2546 CmdArgs.push_back(Args.MakeArgString(cwd));
2550 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2551 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2552 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2553 SmallString<128> T(FinalOutput->getValue());
2554 llvm::sys::path::replace_extension(T, "dwo");
2555 return Args.MakeArgString(T);
2557 // Use the compilation dir.
2559 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2560 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2561 llvm::sys::path::replace_extension(F, "dwo");
2563 return Args.MakeArgString(F);
2567 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2568 const JobAction &JA, const ArgList &Args,
2569 const InputInfo &Output, const char *OutFile) {
2570 ArgStringList ExtractArgs;
2571 ExtractArgs.push_back("--extract-dwo");
2573 ArgStringList StripArgs;
2574 StripArgs.push_back("--strip-dwo");
2576 // Grabbing the output of the earlier compile step.
2577 StripArgs.push_back(Output.getFilename());
2578 ExtractArgs.push_back(Output.getFilename());
2579 ExtractArgs.push_back(OutFile);
2581 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2583 // First extract the dwo sections.
2584 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
2586 // Then remove them from the original .o file.
2587 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
2590 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2591 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2592 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2593 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2594 if (A->getOption().matches(options::OPT_O4) ||
2595 A->getOption().matches(options::OPT_Ofast))
2598 if (A->getOption().matches(options::OPT_O0))
2601 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2604 StringRef S(A->getValue());
2608 // Don't vectorize -Oz, unless it's the slp vectorizer.
2612 unsigned OptLevel = 0;
2613 if (S.getAsInteger(10, OptLevel))
2616 return OptLevel > 1;
2622 /// Add -x lang to \p CmdArgs for \p Input.
2623 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
2624 ArgStringList &CmdArgs) {
2625 // When using -verify-pch, we don't want to provide the type
2626 // 'precompiled-header' if it was inferred from the file extension
2627 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
2630 CmdArgs.push_back("-x");
2631 if (Args.hasArg(options::OPT_rewrite_objc))
2632 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
2634 CmdArgs.push_back(types::getTypeName(Input.getType()));
2637 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
2639 return VersionTuple(Version);
2641 if (Version < 10000)
2642 return VersionTuple(Version / 100, Version % 100);
2644 unsigned Build = 0, Factor = 1;
2645 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
2646 Build = Build + (Version % 10) * Factor;
2647 return VersionTuple(Version / 100, Version % 100, Build);
2650 // Claim options we don't want to warn if they are unused. We do this for
2651 // options that build systems might add but are unused when assembling or only
2652 // running the preprocessor for example.
2653 static void claimNoWarnArgs(const ArgList &Args) {
2654 // Don't warn about unused -f(no-)?lto. This can happen when we're
2655 // preprocessing, precompiling or assembling.
2656 Args.ClaimAllArgs(options::OPT_flto);
2657 Args.ClaimAllArgs(options::OPT_fno_lto);
2660 static void appendUserToPath(SmallVectorImpl<char> &Result) {
2662 const char *Username = getenv("LOGNAME");
2664 const char *Username = getenv("USERNAME");
2667 // Validate that LoginName can be used in a path, and get its length.
2669 for (const char *P = Username; *P; ++P, ++Len) {
2670 if (!isAlphanumeric(*P) && *P != '_') {
2676 if (Username && Len > 0) {
2677 Result.append(Username, Username + Len);
2682 // Fallback to user id.
2684 std::string UID = llvm::utostr(getuid());
2686 // FIXME: Windows seems to have an 'SID' that might work.
2687 std::string UID = "9999";
2689 Result.append(UID.begin(), UID.end());
2692 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
2693 const llvm::Triple &Triple,
2694 const llvm::opt::ArgList &Args,
2695 bool IsWindowsMSVC) {
2696 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2698 Args.hasArg(options::OPT_fmsc_version) ||
2699 Args.hasArg(options::OPT_fms_compatibility_version)) {
2700 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
2701 const Arg *MSCompatibilityVersion =
2702 Args.getLastArg(options::OPT_fms_compatibility_version);
2704 if (MSCVersion && MSCompatibilityVersion) {
2706 D->Diag(diag::err_drv_argument_not_allowed_with)
2707 << MSCVersion->getAsString(Args)
2708 << MSCompatibilityVersion->getAsString(Args);
2709 return VersionTuple();
2712 if (MSCompatibilityVersion) {
2714 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
2715 D->Diag(diag::err_drv_invalid_value)
2716 << MSCompatibilityVersion->getAsString(Args)
2717 << MSCompatibilityVersion->getValue();
2722 unsigned Version = 0;
2723 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
2724 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
2725 << MSCVersion->getValue();
2726 return getMSCompatibilityVersion(Version);
2729 unsigned Major, Minor, Micro;
2730 Triple.getEnvironmentVersion(Major, Minor, Micro);
2731 if (Major || Minor || Micro)
2732 return VersionTuple(Major, Minor, Micro);
2734 return VersionTuple(18);
2736 return VersionTuple();
2739 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
2740 const InputInfo &Output, const ArgList &Args,
2741 ArgStringList &CmdArgs) {
2742 auto *ProfileGenerateArg = Args.getLastArg(
2743 options::OPT_fprofile_instr_generate,
2744 options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
2745 options::OPT_fprofile_generate_EQ);
2747 auto *ProfileUseArg = Args.getLastArg(
2748 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
2749 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
2751 if (ProfileGenerateArg && ProfileUseArg)
2752 D.Diag(diag::err_drv_argument_not_allowed_with)
2753 << ProfileGenerateArg->getSpelling()
2754 << ProfileUseArg->getSpelling();
2756 if (ProfileGenerateArg &&
2757 ProfileGenerateArg->getOption().matches(
2758 options::OPT_fprofile_instr_generate_EQ))
2759 ProfileGenerateArg->render(Args, CmdArgs);
2760 else if (ProfileGenerateArg &&
2761 ProfileGenerateArg->getOption().matches(
2762 options::OPT_fprofile_generate_EQ)) {
2763 SmallString<128> Path(ProfileGenerateArg->getValue());
2764 llvm::sys::path::append(Path, "default.profraw");
2766 Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
2768 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
2770 if (ProfileUseArg &&
2771 ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
2772 ProfileUseArg->render(Args, CmdArgs);
2773 else if (ProfileUseArg &&
2774 (ProfileUseArg->getOption().matches(options::OPT_fprofile_use_EQ) ||
2775 ProfileUseArg->getOption().matches(
2776 options::OPT_fprofile_instr_use))) {
2777 SmallString<128> Path(
2778 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
2779 if (Path.empty() || llvm::sys::fs::is_directory(Path))
2780 llvm::sys::path::append(Path, "default.profdata");
2781 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
2784 if (Args.hasArg(options::OPT_ftest_coverage) ||
2785 Args.hasArg(options::OPT_coverage))
2786 CmdArgs.push_back("-femit-coverage-notes");
2787 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2789 Args.hasArg(options::OPT_coverage))
2790 CmdArgs.push_back("-femit-coverage-data");
2792 if (Args.hasArg(options::OPT_fcoverage_mapping) && !ProfileGenerateArg)
2793 D.Diag(diag::err_drv_argument_only_allowed_with)
2794 << "-fcoverage-mapping"
2795 << "-fprofile-instr-generate";
2797 if (Args.hasArg(options::OPT_fcoverage_mapping))
2798 CmdArgs.push_back("-fcoverage-mapping");
2800 if (C.getArgs().hasArg(options::OPT_c) ||
2801 C.getArgs().hasArg(options::OPT_S)) {
2802 if (Output.isFilename()) {
2803 CmdArgs.push_back("-coverage-file");
2804 SmallString<128> CoverageFilename;
2805 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
2806 CoverageFilename = FinalOutput->getValue();
2808 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
2810 if (llvm::sys::path::is_relative(CoverageFilename)) {
2811 SmallString<128> Pwd;
2812 if (!llvm::sys::fs::current_path(Pwd)) {
2813 llvm::sys::path::append(Pwd, CoverageFilename);
2814 CoverageFilename.swap(Pwd);
2817 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
2822 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2823 const InputInfo &Output, const InputInfoList &Inputs,
2824 const ArgList &Args, const char *LinkingOutput) const {
2826 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
2827 const Driver &D = getToolChain().getDriver();
2828 ArgStringList CmdArgs;
2830 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
2831 bool IsWindowsCygnus =
2832 getToolChain().getTriple().isWindowsCygwinEnvironment();
2833 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
2835 // Check number of inputs for sanity. We need at least one input.
2836 assert(Inputs.size() >= 1 && "Must have at least one input.");
2837 const InputInfo &Input = Inputs[0];
2838 // CUDA compilation may have multiple inputs (source file + results of
2839 // device-side compilations). All other jobs are expected to have exactly one
2841 bool IsCuda = types::isCuda(Input.getType());
2842 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
2844 // Invoke ourselves in -cc1 mode.
2846 // FIXME: Implement custom jobs for internal actions.
2847 CmdArgs.push_back("-cc1");
2849 // Add the "effective" target triple.
2850 CmdArgs.push_back("-triple");
2851 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2852 CmdArgs.push_back(Args.MakeArgString(TripleStr));
2854 const llvm::Triple TT(TripleStr);
2855 if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
2856 TT.getArch() == llvm::Triple::thumb)) {
2857 unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
2859 TT.getArchName().substr(Offset).getAsInteger(10, Version);
2861 D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
2865 // Push all default warning arguments that are specific to
2866 // the given target. These come before user provided warning options
2868 getToolChain().addClangWarningOptions(CmdArgs);
2870 // Select the appropriate action.
2871 RewriteKind rewriteKind = RK_None;
2873 if (isa<AnalyzeJobAction>(JA)) {
2874 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2875 CmdArgs.push_back("-analyze");
2876 } else if (isa<MigrateJobAction>(JA)) {
2877 CmdArgs.push_back("-migrate");
2878 } else if (isa<PreprocessJobAction>(JA)) {
2879 if (Output.getType() == types::TY_Dependencies)
2880 CmdArgs.push_back("-Eonly");
2882 CmdArgs.push_back("-E");
2883 if (Args.hasArg(options::OPT_rewrite_objc) &&
2884 !Args.hasArg(options::OPT_g_Group))
2885 CmdArgs.push_back("-P");
2887 } else if (isa<AssembleJobAction>(JA)) {
2888 CmdArgs.push_back("-emit-obj");
2890 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2892 // Also ignore explicit -force_cpusubtype_ALL option.
2893 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
2894 } else if (isa<PrecompileJobAction>(JA)) {
2895 // Use PCH if the user requested it.
2896 bool UsePCH = D.CCCUsePCH;
2898 if (JA.getType() == types::TY_Nothing)
2899 CmdArgs.push_back("-fsyntax-only");
2901 CmdArgs.push_back("-emit-pch");
2903 CmdArgs.push_back("-emit-pth");
2904 } else if (isa<VerifyPCHJobAction>(JA)) {
2905 CmdArgs.push_back("-verify-pch");
2907 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
2908 "Invalid action for clang tool.");
2910 if (JA.getType() == types::TY_LTO_IR ||
2911 JA.getType() == types::TY_LTO_BC) {
2912 CmdArgs.push_back("-flto");
2914 if (JA.getType() == types::TY_Nothing) {
2915 CmdArgs.push_back("-fsyntax-only");
2916 } else if (JA.getType() == types::TY_LLVM_IR ||
2917 JA.getType() == types::TY_LTO_IR) {
2918 CmdArgs.push_back("-emit-llvm");
2919 } else if (JA.getType() == types::TY_LLVM_BC ||
2920 JA.getType() == types::TY_LTO_BC) {
2921 CmdArgs.push_back("-emit-llvm-bc");
2922 } else if (JA.getType() == types::TY_PP_Asm) {
2923 CmdArgs.push_back("-S");
2924 } else if (JA.getType() == types::TY_AST) {
2925 CmdArgs.push_back("-emit-pch");
2926 } else if (JA.getType() == types::TY_ModuleFile) {
2927 CmdArgs.push_back("-module-file-info");
2928 } else if (JA.getType() == types::TY_RewrittenObjC) {
2929 CmdArgs.push_back("-rewrite-objc");
2930 rewriteKind = RK_NonFragile;
2931 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2932 CmdArgs.push_back("-rewrite-objc");
2933 rewriteKind = RK_Fragile;
2935 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
2938 // Preserve use-list order by default when emitting bitcode, so that
2939 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
2940 // same result as running passes here. For LTO, we don't need to preserve
2941 // the use-list order, since serialization to bitcode is part of the flow.
2942 if (JA.getType() == types::TY_LLVM_BC)
2943 CmdArgs.push_back("-emit-llvm-uselists");
2946 // We normally speed up the clang process a bit by skipping destructors at
2947 // exit, but when we're generating diagnostics we can rely on some of the
2949 if (!C.isForDiagnostics())
2950 CmdArgs.push_back("-disable-free");
2952 // Disable the verification pass in -asserts builds.
2954 CmdArgs.push_back("-disable-llvm-verifier");
2957 // Set the main file name, so that debug info works even with
2959 CmdArgs.push_back("-main-file-name");
2960 CmdArgs.push_back(getBaseInputName(Args, Input));
2962 // Some flags which affect the language (via preprocessor
2964 if (Args.hasArg(options::OPT_static))
2965 CmdArgs.push_back("-static-define");
2967 if (isa<AnalyzeJobAction>(JA)) {
2968 // Enable region store model by default.
2969 CmdArgs.push_back("-analyzer-store=region");
2971 // Treat blocks as analysis entry points.
2972 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2974 CmdArgs.push_back("-analyzer-eagerly-assume");
2976 // Add default argument set.
2977 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2978 CmdArgs.push_back("-analyzer-checker=core");
2981 CmdArgs.push_back("-analyzer-checker=unix");
2983 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2984 CmdArgs.push_back("-analyzer-checker=osx");
2986 CmdArgs.push_back("-analyzer-checker=deadcode");
2988 if (types::isCXX(Input.getType()))
2989 CmdArgs.push_back("-analyzer-checker=cplusplus");
2991 // Enable the following experimental checkers for testing.
2993 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
2994 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2995 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2996 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2997 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2998 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3001 // Set the output format. The default is plist, for (lame) historical
3003 CmdArgs.push_back("-analyzer-output");
3004 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3005 CmdArgs.push_back(A->getValue());
3007 CmdArgs.push_back("plist");
3009 // Disable the presentation of standard compiler warnings when
3010 // using --analyze. We only want to show static analyzer diagnostics
3011 // or frontend errors.
3012 CmdArgs.push_back("-w");
3014 // Add -Xanalyzer arguments when running as analyzer.
3015 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3018 CheckCodeGenerationOptions(D, Args);
3020 bool PIE = getToolChain().isPIEDefault();
3021 bool PIC = PIE || getToolChain().isPICDefault();
3022 bool IsPICLevelTwo = PIC;
3024 // Android-specific defaults for PIC/PIE
3025 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
3026 switch (getToolChain().getArch()) {
3027 case llvm::Triple::arm:
3028 case llvm::Triple::armeb:
3029 case llvm::Triple::thumb:
3030 case llvm::Triple::thumbeb:
3031 case llvm::Triple::aarch64:
3032 case llvm::Triple::mips:
3033 case llvm::Triple::mipsel:
3034 case llvm::Triple::mips64:
3035 case llvm::Triple::mips64el:
3036 PIC = true; // "-fpic"
3039 case llvm::Triple::x86:
3040 case llvm::Triple::x86_64:
3041 PIC = true; // "-fPIC"
3042 IsPICLevelTwo = true;
3050 // OpenBSD-specific defaults for PIE
3051 if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
3052 switch (getToolChain().getArch()) {
3053 case llvm::Triple::mips64:
3054 case llvm::Triple::mips64el:
3055 case llvm::Triple::sparcel:
3056 case llvm::Triple::x86:
3057 case llvm::Triple::x86_64:
3058 IsPICLevelTwo = false; // "-fpie"
3061 case llvm::Triple::ppc:
3062 case llvm::Triple::sparc:
3063 case llvm::Triple::sparcv9:
3064 IsPICLevelTwo = true; // "-fPIE"
3072 // For the PIC and PIE flag options, this logic is different from the
3073 // legacy logic in very old versions of GCC, as that logic was just
3074 // a bug no one had ever fixed. This logic is both more rational and
3075 // consistent with GCC's new logic now that the bugs are fixed. The last
3076 // argument relating to either PIC or PIE wins, and no other argument is
3077 // used. If the last argument is any flavor of the '-fno-...' arguments,
3078 // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
3079 // at the same level.
3080 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3081 options::OPT_fpic, options::OPT_fno_pic,
3082 options::OPT_fPIE, options::OPT_fno_PIE,
3083 options::OPT_fpie, options::OPT_fno_pie);
3084 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3085 // is forced, then neither PIC nor PIE flags will have no effect.
3086 if (!getToolChain().isPICDefaultForced()) {
3088 Option O = LastPICArg->getOption();
3089 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3090 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3091 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3093 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3095 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3102 // Introduce a Darwin-specific hack. If the default is PIC but the flags
3103 // specified while enabling PIC enabled level 1 PIC, just force it back to
3104 // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
3105 // informal testing).
3106 if (PIC && getToolChain().getTriple().isOSDarwin())
3107 IsPICLevelTwo |= getToolChain().isPICDefault();
3109 // Note that these flags are trump-cards. Regardless of the order w.r.t. the
3110 // PIC or PIE options above, if these show up, PIC is disabled.
3111 llvm::Triple Triple(TripleStr);
3112 if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
3114 if (Args.hasArg(options::OPT_static))
3117 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3118 // This is a very special mode. It trumps the other modes, almost no one
3119 // uses it, and it isn't even valid on any OS but Darwin.
3120 if (!getToolChain().getTriple().isOSDarwin())
3121 D.Diag(diag::err_drv_unsupported_opt_for_target)
3122 << A->getSpelling() << getToolChain().getTriple().str();
3124 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3126 CmdArgs.push_back("-mrelocation-model");
3127 CmdArgs.push_back("dynamic-no-pic");
3129 // Only a forced PIC mode can cause the actual compile to have PIC defines
3130 // etc., no flags are sufficient. This behavior was selected to closely
3131 // match that of llvm-gcc and Apple GCC before that.
3132 if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
3133 CmdArgs.push_back("-pic-level");
3134 CmdArgs.push_back("2");
3137 // Currently, LLVM only knows about PIC vs. static; the PIE differences are
3138 // handled in Clang's IRGen by the -pie-level flag.
3139 CmdArgs.push_back("-mrelocation-model");
3140 CmdArgs.push_back(PIC ? "pic" : "static");
3143 CmdArgs.push_back("-pic-level");
3144 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3146 CmdArgs.push_back("-pie-level");
3147 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3152 CmdArgs.push_back("-mthread-model");
3153 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3154 CmdArgs.push_back(A->getValue());
3156 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3158 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3160 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3161 options::OPT_fno_merge_all_constants))
3162 CmdArgs.push_back("-fno-merge-all-constants");
3164 // LLVM Code Generator Options.
3166 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3167 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3168 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3169 options::OPT_frewrite_map_file_EQ)) {
3170 CmdArgs.push_back("-frewrite-map-file");
3171 CmdArgs.push_back(A->getValue());
3176 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3177 StringRef v = A->getValue();
3178 CmdArgs.push_back("-mllvm");
3179 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3183 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3184 CmdArgs.push_back("-mregparm");
3185 CmdArgs.push_back(A->getValue());
3188 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3189 options::OPT_freg_struct_return)) {
3190 if (getToolChain().getArch() != llvm::Triple::x86) {
3191 D.Diag(diag::err_drv_unsupported_opt_for_target)
3192 << A->getSpelling() << getToolChain().getTriple().str();
3193 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3194 CmdArgs.push_back("-fpcc-struct-return");
3196 assert(A->getOption().matches(options::OPT_freg_struct_return));
3197 CmdArgs.push_back("-freg-struct-return");
3201 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3202 CmdArgs.push_back("-mrtd");
3204 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3205 CmdArgs.push_back("-mdisable-fp-elim");
3206 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3207 options::OPT_fno_zero_initialized_in_bss))
3208 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3210 bool OFastEnabled = isOptimizationLevelFast(Args);
3211 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3212 // enabled. This alias option is being used to simplify the hasFlag logic.
3213 OptSpecifier StrictAliasingAliasOption =
3214 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3215 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3216 // doesn't do any TBAA.
3217 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3218 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3219 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3220 CmdArgs.push_back("-relaxed-aliasing");
3221 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3222 options::OPT_fno_struct_path_tbaa))
3223 CmdArgs.push_back("-no-struct-path-tbaa");
3224 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3226 CmdArgs.push_back("-fstrict-enums");
3227 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3228 options::OPT_fno_optimize_sibling_calls))
3229 CmdArgs.push_back("-mdisable-tail-calls");
3231 // Handle segmented stacks.
3232 if (Args.hasArg(options::OPT_fsplit_stack))
3233 CmdArgs.push_back("-split-stacks");
3235 // If -Ofast is the optimization level, then -ffast-math should be enabled.
3236 // This alias option is being used to simplify the getLastArg logic.
3237 OptSpecifier FastMathAliasOption =
3238 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3240 // Handle various floating point optimization flags, mapping them to the
3241 // appropriate LLVM code generation flags. The pattern for all of these is to
3242 // default off the codegen optimizations, and if any flag enables them and no
3243 // flag disables them after the flag enabling them, enable the codegen
3244 // optimization. This is complicated by several "umbrella" flags.
3245 if (Arg *A = Args.getLastArg(
3246 options::OPT_ffast_math, FastMathAliasOption,
3247 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3248 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3249 options::OPT_fno_honor_infinities))
3250 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3251 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3252 A->getOption().getID() != options::OPT_fhonor_infinities)
3253 CmdArgs.push_back("-menable-no-infs");
3254 if (Arg *A = Args.getLastArg(
3255 options::OPT_ffast_math, FastMathAliasOption,
3256 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3257 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3258 options::OPT_fno_honor_nans))
3259 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3260 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3261 A->getOption().getID() != options::OPT_fhonor_nans)
3262 CmdArgs.push_back("-menable-no-nans");
3264 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3265 bool MathErrno = getToolChain().IsMathErrnoDefault();
3267 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3268 options::OPT_fno_fast_math, options::OPT_fmath_errno,
3269 options::OPT_fno_math_errno)) {
3270 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3271 // However, turning *off* -ffast_math merely restores the toolchain default
3272 // (which may be false).
3273 if (A->getOption().getID() == options::OPT_fno_math_errno ||
3274 A->getOption().getID() == options::OPT_ffast_math ||
3275 A->getOption().getID() == options::OPT_Ofast)
3277 else if (A->getOption().getID() == options::OPT_fmath_errno)
3281 CmdArgs.push_back("-fmath-errno");
3283 // There are several flags which require disabling very specific
3284 // optimizations. Any of these being disabled forces us to turn off the
3285 // entire set of LLVM optimizations, so collect them through all the flag
3287 bool AssociativeMath = false;
3288 if (Arg *A = Args.getLastArg(
3289 options::OPT_ffast_math, FastMathAliasOption,
3290 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3291 options::OPT_fno_unsafe_math_optimizations,
3292 options::OPT_fassociative_math, options::OPT_fno_associative_math))
3293 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3294 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3295 A->getOption().getID() != options::OPT_fno_associative_math)
3296 AssociativeMath = true;
3297 bool ReciprocalMath = false;
3298 if (Arg *A = Args.getLastArg(
3299 options::OPT_ffast_math, FastMathAliasOption,
3300 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3301 options::OPT_fno_unsafe_math_optimizations,
3302 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3303 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3304 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3305 A->getOption().getID() != options::OPT_fno_reciprocal_math)
3306 ReciprocalMath = true;
3307 bool SignedZeros = true;
3308 if (Arg *A = Args.getLastArg(
3309 options::OPT_ffast_math, FastMathAliasOption,
3310 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3311 options::OPT_fno_unsafe_math_optimizations,
3312 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3313 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3314 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3315 A->getOption().getID() != options::OPT_fsigned_zeros)
3316 SignedZeros = false;
3317 bool TrappingMath = true;
3318 if (Arg *A = Args.getLastArg(
3319 options::OPT_ffast_math, FastMathAliasOption,
3320 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3321 options::OPT_fno_unsafe_math_optimizations,
3322 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3323 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3324 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3325 A->getOption().getID() != options::OPT_ftrapping_math)
3326 TrappingMath = false;
3327 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3329 CmdArgs.push_back("-menable-unsafe-fp-math");
3332 CmdArgs.push_back("-fno-signed-zeros");
3335 CmdArgs.push_back("-freciprocal-math");
3337 // Validate and pass through -fp-contract option.
3338 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3339 options::OPT_fno_fast_math,
3340 options::OPT_ffp_contract)) {
3341 if (A->getOption().getID() == options::OPT_ffp_contract) {
3342 StringRef Val = A->getValue();
3343 if (Val == "fast" || Val == "on" || Val == "off") {
3344 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3346 D.Diag(diag::err_drv_unsupported_option_argument)
3347 << A->getOption().getName() << Val;
3349 } else if (A->getOption().matches(options::OPT_ffast_math) ||
3350 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3351 // If fast-math is set then set the fp-contract mode to fast.
3352 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3356 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3358 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3359 // and if we find them, tell the frontend to provide the appropriate
3360 // preprocessor macros. This is distinct from enabling any optimizations as
3361 // these options induce language changes which must survive serialization
3362 // and deserialization, etc.
3363 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3364 options::OPT_fno_fast_math))
3365 if (!A->getOption().matches(options::OPT_fno_fast_math))
3366 CmdArgs.push_back("-ffast-math");
3367 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3368 options::OPT_fno_fast_math))
3369 if (A->getOption().matches(options::OPT_ffinite_math_only))
3370 CmdArgs.push_back("-ffinite-math-only");
3372 // Decide whether to use verbose asm. Verbose assembly is the default on
3373 // toolchains which have the integrated assembler on by default.
3374 bool IsIntegratedAssemblerDefault =
3375 getToolChain().IsIntegratedAssemblerDefault();
3376 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3377 IsIntegratedAssemblerDefault) ||
3378 Args.hasArg(options::OPT_dA))
3379 CmdArgs.push_back("-masm-verbose");
3381 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3382 IsIntegratedAssemblerDefault))
3383 CmdArgs.push_back("-no-integrated-as");
3385 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3386 CmdArgs.push_back("-mdebug-pass");
3387 CmdArgs.push_back("Structure");
3389 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3390 CmdArgs.push_back("-mdebug-pass");
3391 CmdArgs.push_back("Arguments");
3394 // Enable -mconstructor-aliases except on darwin, where we have to
3395 // work around a linker bug; see <rdar://problem/7651567>.
3396 if (!getToolChain().getTriple().isOSDarwin())
3397 CmdArgs.push_back("-mconstructor-aliases");
3399 // Darwin's kernel doesn't support guard variables; just die if we
3401 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3402 CmdArgs.push_back("-fforbid-guard-variables");
3404 if (Args.hasArg(options::OPT_mms_bitfields)) {
3405 CmdArgs.push_back("-mms-bitfields");
3408 // This is a coarse approximation of what llvm-gcc actually does, both
3409 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3410 // complicated ways.
3411 bool AsynchronousUnwindTables =
3412 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3413 options::OPT_fno_asynchronous_unwind_tables,
3414 (getToolChain().IsUnwindTablesDefault() ||
3415 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3417 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3418 AsynchronousUnwindTables))
3419 CmdArgs.push_back("-munwind-tables");
3421 getToolChain().addClangTargetOptions(Args, CmdArgs);
3423 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3424 CmdArgs.push_back("-mlimit-float-precision");
3425 CmdArgs.push_back(A->getValue());
3428 // FIXME: Handle -mtune=.
3429 (void)Args.hasArg(options::OPT_mtune_EQ);
3431 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3432 CmdArgs.push_back("-mcode-model");
3433 CmdArgs.push_back(A->getValue());
3436 // Add the target cpu
3437 std::string CPU = getCPUName(Args, Triple);
3439 CmdArgs.push_back("-target-cpu");
3440 CmdArgs.push_back(Args.MakeArgString(CPU));
3443 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3444 CmdArgs.push_back("-mfpmath");
3445 CmdArgs.push_back(A->getValue());
3448 // Add the target features
3449 getTargetFeatures(D, Triple, Args, CmdArgs, false);
3451 // Add target specific flags.
3452 switch (getToolChain().getArch()) {
3456 case llvm::Triple::arm:
3457 case llvm::Triple::armeb:
3458 case llvm::Triple::thumb:
3459 case llvm::Triple::thumbeb:
3460 AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
3463 case llvm::Triple::aarch64:
3464 case llvm::Triple::aarch64_be:
3465 AddAArch64TargetArgs(Args, CmdArgs);
3468 case llvm::Triple::mips:
3469 case llvm::Triple::mipsel:
3470 case llvm::Triple::mips64:
3471 case llvm::Triple::mips64el:
3472 AddMIPSTargetArgs(Args, CmdArgs);
3475 case llvm::Triple::ppc:
3476 case llvm::Triple::ppc64:
3477 case llvm::Triple::ppc64le:
3478 AddPPCTargetArgs(Args, CmdArgs);
3481 case llvm::Triple::sparc:
3482 case llvm::Triple::sparcel:
3483 case llvm::Triple::sparcv9:
3484 AddSparcTargetArgs(Args, CmdArgs);
3487 case llvm::Triple::x86:
3488 case llvm::Triple::x86_64:
3489 AddX86TargetArgs(Args, CmdArgs);
3492 case llvm::Triple::hexagon:
3493 AddHexagonTargetArgs(Args, CmdArgs);
3497 // Add clang-cl arguments.
3498 if (getToolChain().getDriver().IsCLMode())
3499 AddClangCLArgs(Args, CmdArgs);
3501 // Pass the linker version in use.
3502 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3503 CmdArgs.push_back("-target-linker-version");
3504 CmdArgs.push_back(A->getValue());
3507 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
3508 CmdArgs.push_back("-momit-leaf-frame-pointer");
3510 // Explicitly error on some things we know we don't support and can't just
3512 types::ID InputType = Input.getType();
3513 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3515 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
3516 getToolChain().getArch() == llvm::Triple::x86) {
3517 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3518 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3519 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3520 << Unsupported->getOption().getName();
3524 Args.AddAllArgs(CmdArgs, options::OPT_v);
3525 Args.AddLastArg(CmdArgs, options::OPT_H);
3526 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3527 CmdArgs.push_back("-header-include-file");
3528 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3531 Args.AddLastArg(CmdArgs, options::OPT_P);
3532 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3534 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3535 CmdArgs.push_back("-diagnostic-log-file");
3536 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3540 // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
3541 // are preserved, all other debug options are substituted with "-g".
3542 Args.ClaimAllArgs(options::OPT_g_Group);
3543 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3544 if (A->getOption().matches(options::OPT_gline_tables_only) ||
3545 A->getOption().matches(options::OPT_g1)) {
3546 // FIXME: we should support specifying dwarf version with
3547 // -gline-tables-only.
3548 CmdArgs.push_back("-gline-tables-only");
3549 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3550 const llvm::Triple &Triple = getToolChain().getTriple();
3551 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3552 Triple.getOS() == llvm::Triple::FreeBSD ||
3553 Triple.getOS() == llvm::Triple::Solaris)
3554 CmdArgs.push_back("-gdwarf-2");
3555 } else if (A->getOption().matches(options::OPT_gdwarf_2))
3556 CmdArgs.push_back("-gdwarf-2");
3557 else if (A->getOption().matches(options::OPT_gdwarf_3))
3558 CmdArgs.push_back("-gdwarf-3");
3559 else if (A->getOption().matches(options::OPT_gdwarf_4))
3560 CmdArgs.push_back("-gdwarf-4");
3561 else if (!A->getOption().matches(options::OPT_g0) &&
3562 !A->getOption().matches(options::OPT_ggdb0)) {
3563 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3564 const llvm::Triple &Triple = getToolChain().getTriple();
3565 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3566 Triple.getOS() == llvm::Triple::FreeBSD ||
3567 Triple.getOS() == llvm::Triple::Solaris)
3568 CmdArgs.push_back("-gdwarf-2");
3570 CmdArgs.push_back("-g");
3574 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
3575 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3576 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3578 CmdArgs.push_back("-dwarf-column-info");
3580 // FIXME: Move backend command line options to the module.
3581 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3582 // splitting and extraction.
3583 // FIXME: Currently only works on Linux.
3584 if (getToolChain().getTriple().isOSLinux() &&
3585 Args.hasArg(options::OPT_gsplit_dwarf)) {
3586 CmdArgs.push_back("-g");
3587 CmdArgs.push_back("-backend-option");
3588 CmdArgs.push_back("-split-dwarf=Enable");
3591 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3592 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
3593 CmdArgs.push_back("-backend-option");
3594 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
3597 // -gdwarf-aranges turns on the emission of the aranges section in the
3599 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
3600 CmdArgs.push_back("-backend-option");
3601 CmdArgs.push_back("-generate-arange-section");
3604 if (Args.hasFlag(options::OPT_fdebug_types_section,
3605 options::OPT_fno_debug_types_section, false)) {
3606 CmdArgs.push_back("-backend-option");
3607 CmdArgs.push_back("-generate-type-units");
3610 // CloudABI uses -ffunction-sections and -fdata-sections by default.
3611 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
3613 if (Args.hasFlag(options::OPT_ffunction_sections,
3614 options::OPT_fno_function_sections, UseSeparateSections)) {
3615 CmdArgs.push_back("-ffunction-sections");
3618 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3619 UseSeparateSections)) {
3620 CmdArgs.push_back("-fdata-sections");
3623 if (!Args.hasFlag(options::OPT_funique_section_names,
3624 options::OPT_fno_unique_section_names, true))
3625 CmdArgs.push_back("-fno-unique-section-names");
3627 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
3629 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
3631 // Pass options for controlling the default header search paths.
3632 if (Args.hasArg(options::OPT_nostdinc)) {
3633 CmdArgs.push_back("-nostdsysteminc");
3634 CmdArgs.push_back("-nobuiltininc");
3636 if (Args.hasArg(options::OPT_nostdlibinc))
3637 CmdArgs.push_back("-nostdsysteminc");
3638 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3639 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3642 // Pass the path to compiler resource files.
3643 CmdArgs.push_back("-resource-dir");
3644 CmdArgs.push_back(D.ResourceDir.c_str());
3646 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3648 bool ARCMTEnabled = false;
3649 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3650 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3651 options::OPT_ccc_arcmt_modify,
3652 options::OPT_ccc_arcmt_migrate)) {
3653 ARCMTEnabled = true;
3654 switch (A->getOption().getID()) {
3656 llvm_unreachable("missed a case");
3657 case options::OPT_ccc_arcmt_check:
3658 CmdArgs.push_back("-arcmt-check");
3660 case options::OPT_ccc_arcmt_modify:
3661 CmdArgs.push_back("-arcmt-modify");
3663 case options::OPT_ccc_arcmt_migrate:
3664 CmdArgs.push_back("-arcmt-migrate");
3665 CmdArgs.push_back("-mt-migrate-directory");
3666 CmdArgs.push_back(A->getValue());
3668 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3669 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3674 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3675 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3676 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3679 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3681 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
3682 << "-ccc-arcmt-migrate";
3684 CmdArgs.push_back("-mt-migrate-directory");
3685 CmdArgs.push_back(A->getValue());
3687 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3688 options::OPT_objcmt_migrate_subscripting,
3689 options::OPT_objcmt_migrate_property)) {
3690 // None specified, means enable them all.
3691 CmdArgs.push_back("-objcmt-migrate-literals");
3692 CmdArgs.push_back("-objcmt-migrate-subscripting");
3693 CmdArgs.push_back("-objcmt-migrate-property");
3695 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3696 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3697 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3700 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3701 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3702 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3703 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3704 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3705 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3706 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3707 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3708 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3709 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3710 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3711 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3712 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3713 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3714 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3715 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3718 // Add preprocessing options like -I, -D, etc. if we are using the
3721 // FIXME: Support -fpreprocessed
3722 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3723 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3725 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3726 // that "The compiler can only warn and ignore the option if not recognized".
3727 // When building with ccache, it will pass -D options to clang even on
3728 // preprocessed inputs and configure concludes that -fPIC is not supported.
3729 Args.ClaimAllArgs(options::OPT_D);
3731 // Manually translate -O4 to -O3; let clang reject others.
3732 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3733 if (A->getOption().matches(options::OPT_O4)) {
3734 CmdArgs.push_back("-O3");
3735 D.Diag(diag::warn_O4_is_O3);
3737 A->render(Args, CmdArgs);
3741 // Warn about ignored options to clang.
3743 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3744 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3747 claimNoWarnArgs(Args);
3749 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3750 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3751 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3752 CmdArgs.push_back("-pedantic");
3753 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3754 Args.AddLastArg(CmdArgs, options::OPT_w);
3756 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3757 // (-ansi is equivalent to -std=c89 or -std=c++98).
3759 // If a std is supplied, only add -trigraphs if it follows the
3761 bool ImplyVCPPCXXVer = false;
3762 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3763 if (Std->getOption().matches(options::OPT_ansi))
3764 if (types::isCXX(InputType))
3765 CmdArgs.push_back("-std=c++98");
3767 CmdArgs.push_back("-std=c89");
3769 Std->render(Args, CmdArgs);
3771 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3772 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3773 options::OPT_ftrigraphs,
3774 options::OPT_fno_trigraphs))
3776 A->render(Args, CmdArgs);
3778 // Honor -std-default.
3780 // FIXME: Clang doesn't correctly handle -std= when the input language
3781 // doesn't match. For the time being just ignore this for C++ inputs;
3782 // eventually we want to do all the standard defaulting here instead of
3783 // splitting it between the driver and clang -cc1.
3784 if (!types::isCXX(InputType))
3785 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3787 else if (IsWindowsMSVC)
3788 ImplyVCPPCXXVer = true;
3790 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3791 options::OPT_fno_trigraphs);
3794 // GCC's behavior for -Wwrite-strings is a bit strange:
3795 // * In C, this "warning flag" changes the types of string literals from
3796 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3797 // for the discarded qualifier.
3798 // * In C++, this is just a normal warning flag.
3800 // Implementing this warning correctly in C is hard, so we follow GCC's
3801 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3802 // a non-const char* in C, rather than using this crude hack.
3803 if (!types::isCXX(InputType)) {
3804 // FIXME: This should behave just like a warning flag, and thus should also
3805 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3807 Args.getLastArg(options::OPT_Wwrite_strings,
3808 options::OPT_Wno_write_strings, options::OPT_w);
3810 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3811 CmdArgs.push_back("-fconst-strings");
3814 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3815 // during C++ compilation, which it is by default. GCC keeps this define even
3816 // in the presence of '-w', match this behavior bug-for-bug.
3817 if (types::isCXX(InputType) &&
3818 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3820 CmdArgs.push_back("-fdeprecated-macro");
3823 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3824 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3825 if (Asm->getOption().matches(options::OPT_fasm))
3826 CmdArgs.push_back("-fgnu-keywords");
3828 CmdArgs.push_back("-fno-gnu-keywords");
3831 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3832 CmdArgs.push_back("-fno-dwarf-directory-asm");
3834 if (ShouldDisableAutolink(Args, getToolChain()))
3835 CmdArgs.push_back("-fno-autolink");
3837 // Add in -fdebug-compilation-dir if necessary.
3838 addDebugCompDirArg(Args, CmdArgs);
3840 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3841 options::OPT_ftemplate_depth_EQ)) {
3842 CmdArgs.push_back("-ftemplate-depth");
3843 CmdArgs.push_back(A->getValue());
3846 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3847 CmdArgs.push_back("-foperator-arrow-depth");
3848 CmdArgs.push_back(A->getValue());
3851 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3852 CmdArgs.push_back("-fconstexpr-depth");
3853 CmdArgs.push_back(A->getValue());
3856 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3857 CmdArgs.push_back("-fconstexpr-steps");
3858 CmdArgs.push_back(A->getValue());
3861 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3862 CmdArgs.push_back("-fbracket-depth");
3863 CmdArgs.push_back(A->getValue());
3866 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3867 options::OPT_Wlarge_by_value_copy_def)) {
3868 if (A->getNumValues()) {
3869 StringRef bytes = A->getValue();
3870 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3872 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3875 if (Args.hasArg(options::OPT_relocatable_pch))
3876 CmdArgs.push_back("-relocatable-pch");
3878 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3879 CmdArgs.push_back("-fconstant-string-class");
3880 CmdArgs.push_back(A->getValue());
3883 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3884 CmdArgs.push_back("-ftabstop");
3885 CmdArgs.push_back(A->getValue());
3888 CmdArgs.push_back("-ferror-limit");
3889 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3890 CmdArgs.push_back(A->getValue());
3892 CmdArgs.push_back("19");
3894 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3895 CmdArgs.push_back("-fmacro-backtrace-limit");
3896 CmdArgs.push_back(A->getValue());
3899 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3900 CmdArgs.push_back("-ftemplate-backtrace-limit");
3901 CmdArgs.push_back(A->getValue());
3904 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3905 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3906 CmdArgs.push_back(A->getValue());
3909 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3910 CmdArgs.push_back("-fspell-checking-limit");
3911 CmdArgs.push_back(A->getValue());
3914 // Pass -fmessage-length=.
3915 CmdArgs.push_back("-fmessage-length");
3916 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3917 CmdArgs.push_back(A->getValue());
3919 // If -fmessage-length=N was not specified, determine whether this is a
3920 // terminal and, if so, implicitly define -fmessage-length appropriately.
3921 unsigned N = llvm::sys::Process::StandardErrColumns();
3922 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3925 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3926 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3927 options::OPT_fvisibility_ms_compat)) {
3928 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3929 CmdArgs.push_back("-fvisibility");
3930 CmdArgs.push_back(A->getValue());
3932 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3933 CmdArgs.push_back("-fvisibility");
3934 CmdArgs.push_back("hidden");
3935 CmdArgs.push_back("-ftype-visibility");
3936 CmdArgs.push_back("default");
3940 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3942 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3944 // -fhosted is default.
3945 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3947 CmdArgs.push_back("-ffreestanding");
3949 // Forward -f (flag) options which we can pass directly.
3950 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3951 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3952 Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
3953 Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
3954 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3955 // AltiVec language extensions aren't relevant for assembling.
3956 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
3957 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
3958 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3959 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3961 // Forward flags for OpenMP
3962 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3963 options::OPT_fno_openmp, false))
3964 switch (getOpenMPRuntime(getToolChain(), Args)) {
3967 // Clang can generate useful OpenMP code for these two runtime libraries.
3968 CmdArgs.push_back("-fopenmp");
3970 // If no option regarding the use of TLS in OpenMP codegeneration is
3971 // given, decide a default based on the target. Otherwise rely on the
3972 // options and pass the right information to the frontend.
3973 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3974 options::OPT_fnoopenmp_use_tls,
3975 getToolChain().getArch() == llvm::Triple::ppc ||
3976 getToolChain().getArch() == llvm::Triple::ppc64 ||
3977 getToolChain().getArch() == llvm::Triple::ppc64le))
3978 CmdArgs.push_back("-fnoopenmp-use-tls");
3981 // By default, if Clang doesn't know how to generate useful OpenMP code
3982 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3983 // down to the actual compilation.
3984 // FIXME: It would be better to have a mode which *only* omits IR
3985 // generation based on the OpenMP support so that we get consistent
3986 // semantic analysis, etc.
3990 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3991 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3993 // Report an error for -faltivec on anything other than PowerPC.
3994 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
3995 const llvm::Triple::ArchType Arch = getToolChain().getArch();
3996 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
3997 Arch == llvm::Triple::ppc64le))
3998 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3999 << "ppc/ppc64/ppc64le";
4002 if (getToolChain().SupportsProfiling())
4003 Args.AddLastArg(CmdArgs, options::OPT_pg);
4005 // -flax-vector-conversions is default.
4006 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4007 options::OPT_fno_lax_vector_conversions))
4008 CmdArgs.push_back("-fno-lax-vector-conversions");
4010 if (Args.getLastArg(options::OPT_fapple_kext))
4011 CmdArgs.push_back("-fapple-kext");
4013 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4014 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4015 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4016 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4017 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4019 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4020 CmdArgs.push_back("-ftrapv-handler");
4021 CmdArgs.push_back(A->getValue());
4024 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4026 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4027 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4028 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4029 if (A->getOption().matches(options::OPT_fwrapv))
4030 CmdArgs.push_back("-fwrapv");
4031 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4032 options::OPT_fno_strict_overflow)) {
4033 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4034 CmdArgs.push_back("-fwrapv");
4037 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4038 options::OPT_fno_reroll_loops))
4039 if (A->getOption().matches(options::OPT_freroll_loops))
4040 CmdArgs.push_back("-freroll-loops");
4042 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4043 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4044 options::OPT_fno_unroll_loops);
4046 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4048 // -stack-protector=0 is default.
4049 unsigned StackProtectorLevel = 0;
4050 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4051 Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4052 Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4053 Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4054 Args.ClaimAllArgs(options::OPT_fstack_protector);
4055 } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4056 options::OPT_fstack_protector_all,
4057 options::OPT_fstack_protector_strong,
4058 options::OPT_fstack_protector)) {
4059 if (A->getOption().matches(options::OPT_fstack_protector)) {
4060 StackProtectorLevel = std::max<unsigned>(
4062 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4063 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4064 StackProtectorLevel = LangOptions::SSPStrong;
4065 else if (A->getOption().matches(options::OPT_fstack_protector_all))
4066 StackProtectorLevel = LangOptions::SSPReq;
4068 StackProtectorLevel =
4069 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4071 if (StackProtectorLevel) {
4072 CmdArgs.push_back("-stack-protector");
4073 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4076 // --param ssp-buffer-size=
4077 for (const Arg *A : Args.filtered(options::OPT__param)) {
4078 StringRef Str(A->getValue());
4079 if (Str.startswith("ssp-buffer-size=")) {
4080 if (StackProtectorLevel) {
4081 CmdArgs.push_back("-stack-protector-buffer-size");
4082 // FIXME: Verify the argument is a valid integer.
4083 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4089 // Translate -mstackrealign
4090 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4092 CmdArgs.push_back("-backend-option");
4093 CmdArgs.push_back("-force-align-stack");
4095 if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
4097 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4100 if (Args.hasArg(options::OPT_mstack_alignment)) {
4101 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4102 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4105 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4106 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4109 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4111 CmdArgs.push_back("-mstack-probe-size=0");
4114 if (getToolChain().getArch() == llvm::Triple::aarch64 ||
4115 getToolChain().getArch() == llvm::Triple::aarch64_be)
4116 CmdArgs.push_back("-fallow-half-arguments-and-returns");
4118 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4119 options::OPT_mno_restrict_it)) {
4120 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4121 CmdArgs.push_back("-backend-option");
4122 CmdArgs.push_back("-arm-restrict-it");
4124 CmdArgs.push_back("-backend-option");
4125 CmdArgs.push_back("-arm-no-restrict-it");
4127 } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
4128 TT.getArch() == llvm::Triple::thumb)) {
4129 // Windows on ARM expects restricted IT blocks
4130 CmdArgs.push_back("-backend-option");
4131 CmdArgs.push_back("-arm-restrict-it");
4134 // Forward -f options with positive and negative forms; we translate
4136 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4137 StringRef fname = A->getValue();
4138 if (!llvm::sys::fs::exists(fname))
4139 D.Diag(diag::err_drv_no_such_file) << fname;
4141 A->render(Args, CmdArgs);
4144 if (Args.hasArg(options::OPT_mkernel)) {
4145 if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
4146 CmdArgs.push_back("-fapple-kext");
4147 if (!Args.hasArg(options::OPT_fbuiltin))
4148 CmdArgs.push_back("-fno-builtin");
4149 Args.ClaimAllArgs(options::OPT_fno_builtin);
4151 // -fbuiltin is default.
4152 else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
4153 CmdArgs.push_back("-fno-builtin");
4155 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4156 options::OPT_fno_assume_sane_operator_new))
4157 CmdArgs.push_back("-fno-assume-sane-operator-new");
4159 // -fblocks=0 is default.
4160 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4161 getToolChain().IsBlocksDefault()) ||
4162 (Args.hasArg(options::OPT_fgnu_runtime) &&
4163 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4164 !Args.hasArg(options::OPT_fno_blocks))) {
4165 CmdArgs.push_back("-fblocks");
4167 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4168 !getToolChain().hasBlocksRuntime())
4169 CmdArgs.push_back("-fblocks-runtime-optional");
4172 // -fmodules enables the use of precompiled modules (off by default).
4173 // Users can pass -fno-cxx-modules to turn off modules support for
4174 // C++/Objective-C++ programs.
4175 bool HaveModules = false;
4176 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4177 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4178 options::OPT_fno_cxx_modules, true);
4179 if (AllowedInCXX || !types::isCXX(InputType)) {
4180 CmdArgs.push_back("-fmodules");
4185 // -fmodule-maps enables implicit reading of module map files. By default,
4186 // this is enabled if we are using precompiled modules.
4187 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4188 options::OPT_fno_implicit_module_maps, HaveModules)) {
4189 CmdArgs.push_back("-fimplicit-module-maps");
4192 // -fmodules-decluse checks that modules used are declared so (off by
4194 if (Args.hasFlag(options::OPT_fmodules_decluse,
4195 options::OPT_fno_modules_decluse, false)) {
4196 CmdArgs.push_back("-fmodules-decluse");
4199 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4200 // all #included headers are part of modules.
4201 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4202 options::OPT_fno_modules_strict_decluse, false)) {
4203 CmdArgs.push_back("-fmodules-strict-decluse");
4206 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4207 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4208 options::OPT_fno_implicit_modules)) {
4209 CmdArgs.push_back("-fno-implicit-modules");
4212 // -fmodule-name specifies the module that is currently being built (or
4213 // used for header checking by -fmodule-maps).
4214 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4216 // -fmodule-map-file can be used to specify files containing module
4218 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4220 // -fmodule-file can be used to specify files containing precompiled modules.
4221 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4223 // -fmodule-cache-path specifies where our implicitly-built module files
4224 // should be written.
4225 SmallString<128> Path;
4226 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4227 Path = A->getValue();
4229 if (C.isForDiagnostics()) {
4230 // When generating crash reports, we want to emit the modules along with
4231 // the reproduction sources, so we ignore any provided module path.
4232 Path = Output.getFilename();
4233 llvm::sys::path::replace_extension(Path, ".cache");
4234 llvm::sys::path::append(Path, "modules");
4235 } else if (Path.empty()) {
4236 // No module path was provided: use the default.
4237 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
4239 llvm::sys::path::append(Path, "org.llvm.clang.");
4240 appendUserToPath(Path);
4241 llvm::sys::path::append(Path, "ModuleCache");
4243 const char Arg[] = "-fmodules-cache-path=";
4244 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4245 CmdArgs.push_back(Args.MakeArgString(Path));
4248 // When building modules and generating crashdumps, we need to dump a module
4249 // dependency VFS alongside the output.
4250 if (HaveModules && C.isForDiagnostics()) {
4251 SmallString<128> VFSDir(Output.getFilename());
4252 llvm::sys::path::replace_extension(VFSDir, ".cache");
4253 // Add the cache directory as a temp so the crash diagnostics pick it up.
4254 C.addTempFile(Args.MakeArgString(VFSDir));
4256 llvm::sys::path::append(VFSDir, "vfs");
4257 CmdArgs.push_back("-module-dependency-dir");
4258 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4262 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4264 // Pass through all -fmodules-ignore-macro arguments.
4265 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4266 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4267 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4269 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4271 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4272 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4273 D.Diag(diag::err_drv_argument_not_allowed_with)
4274 << A->getAsString(Args) << "-fbuild-session-timestamp";
4276 llvm::sys::fs::file_status Status;
4277 if (llvm::sys::fs::status(A->getValue(), Status))
4278 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4279 CmdArgs.push_back(Args.MakeArgString(
4280 "-fbuild-session-timestamp=" +
4281 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4284 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4285 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4286 options::OPT_fbuild_session_file))
4287 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4289 Args.AddLastArg(CmdArgs,
4290 options::OPT_fmodules_validate_once_per_build_session);
4293 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4295 // -faccess-control is default.
4296 if (Args.hasFlag(options::OPT_fno_access_control,
4297 options::OPT_faccess_control, false))
4298 CmdArgs.push_back("-fno-access-control");
4300 // -felide-constructors is the default.
4301 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4302 options::OPT_felide_constructors, false))
4303 CmdArgs.push_back("-fno-elide-constructors");
4305 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4307 if (KernelOrKext || (types::isCXX(InputType) &&
4308 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4309 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4310 CmdArgs.push_back("-fno-rtti");
4312 // -fshort-enums=0 is default for all architectures except Hexagon.
4313 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4314 getToolChain().getArch() == llvm::Triple::hexagon))
4315 CmdArgs.push_back("-fshort-enums");
4317 // -fsigned-char is default.
4318 if (Arg *A = Args.getLastArg(
4319 options::OPT_fsigned_char, options::OPT_fno_signed_char,
4320 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4321 if (A->getOption().matches(options::OPT_funsigned_char) ||
4322 A->getOption().matches(options::OPT_fno_signed_char)) {
4323 CmdArgs.push_back("-fno-signed-char");
4325 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4326 CmdArgs.push_back("-fno-signed-char");
4329 // -fuse-cxa-atexit is default.
4330 if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
4331 options::OPT_fno_use_cxa_atexit,
4332 !IsWindowsCygnus && !IsWindowsGNU &&
4333 getToolChain().getArch() != llvm::Triple::hexagon &&
4334 getToolChain().getArch() != llvm::Triple::xcore) ||
4336 CmdArgs.push_back("-fno-use-cxa-atexit");
4338 // -fms-extensions=0 is default.
4339 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4341 CmdArgs.push_back("-fms-extensions");
4343 // -fno-use-line-directives is default.
4344 if (Args.hasFlag(options::OPT_fuse_line_directives,
4345 options::OPT_fno_use_line_directives, false))
4346 CmdArgs.push_back("-fuse-line-directives");
4348 // -fms-compatibility=0 is default.
4349 if (Args.hasFlag(options::OPT_fms_compatibility,
4350 options::OPT_fno_ms_compatibility,
4352 Args.hasFlag(options::OPT_fms_extensions,
4353 options::OPT_fno_ms_extensions, true))))
4354 CmdArgs.push_back("-fms-compatibility");
4356 // -fms-compatibility-version=18.00 is default.
4357 VersionTuple MSVT = visualstudio::getMSVCVersion(
4358 &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4361 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4363 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4364 if (ImplyVCPPCXXVer) {
4365 if (IsMSVC2015Compatible)
4366 CmdArgs.push_back("-std=c++14");
4368 CmdArgs.push_back("-std=c++11");
4371 // -fno-borland-extensions is default.
4372 if (Args.hasFlag(options::OPT_fborland_extensions,
4373 options::OPT_fno_borland_extensions, false))
4374 CmdArgs.push_back("-fborland-extensions");
4376 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4378 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4379 options::OPT_fno_threadsafe_statics,
4380 !IsWindowsMSVC || IsMSVC2015Compatible))
4381 CmdArgs.push_back("-fno-threadsafe-statics");
4383 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4385 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4386 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4387 CmdArgs.push_back("-fdelayed-template-parsing");
4389 // -fgnu-keywords default varies depending on language; only pass if
4391 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4392 options::OPT_fno_gnu_keywords))
4393 A->render(Args, CmdArgs);
4395 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4397 CmdArgs.push_back("-fgnu89-inline");
4399 if (Args.hasArg(options::OPT_fno_inline))
4400 CmdArgs.push_back("-fno-inline");
4402 if (Args.hasArg(options::OPT_fno_inline_functions))
4403 CmdArgs.push_back("-fno-inline-functions");
4405 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4407 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
4408 // legacy is the default. Except for deployment taget of 10.5,
4409 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
4410 // gets ignored silently.
4411 if (objcRuntime.isNonFragile()) {
4412 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4413 options::OPT_fno_objc_legacy_dispatch,
4414 objcRuntime.isLegacyDispatchDefaultForArch(
4415 getToolChain().getArch()))) {
4416 if (getToolChain().UseObjCMixedDispatch())
4417 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4419 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4423 // When ObjectiveC legacy runtime is in effect on MacOSX,
4424 // turn on the option to do Array/Dictionary subscripting
4426 if (getToolChain().getArch() == llvm::Triple::x86 &&
4427 getToolChain().getTriple().isMacOSX() &&
4428 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
4429 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
4430 objcRuntime.isNeXTFamily())
4431 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4433 // -fencode-extended-block-signature=1 is default.
4434 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
4435 CmdArgs.push_back("-fencode-extended-block-signature");
4438 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4439 // NOTE: This logic is duplicated in ToolChains.cpp.
4440 bool ARC = isObjCAutoRefCount(Args);
4442 getToolChain().CheckObjCARC();
4444 CmdArgs.push_back("-fobjc-arc");
4446 // FIXME: It seems like this entire block, and several around it should be
4447 // wrapped in isObjC, but for now we just use it here as this is where it
4448 // was being used previously.
4449 if (types::isCXX(InputType) && types::isObjC(InputType)) {
4450 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4451 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4453 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4456 // Allow the user to enable full exceptions code emission.
4457 // We define off for Objective-CC, on for Objective-C++.
4458 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4459 options::OPT_fno_objc_arc_exceptions,
4460 /*default*/ types::isCXX(InputType)))
4461 CmdArgs.push_back("-fobjc-arc-exceptions");
4464 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4466 if (rewriteKind != RK_None)
4467 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4469 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
4470 // takes precedence.
4471 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
4473 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
4476 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
4477 } else if (getToolChain().SupportsObjCGC()) {
4478 GCArg->render(Args, CmdArgs);
4480 // FIXME: We should move this to a hard error.
4481 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
4485 if (Args.hasFlag(options::OPT_fapplication_extension,
4486 options::OPT_fno_application_extension, false))
4487 CmdArgs.push_back("-fapplication-extension");
4489 // Handle GCC-style exception args.
4490 if (!C.getDriver().IsCLMode())
4491 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
4494 if (getToolChain().UseSjLjExceptions())
4495 CmdArgs.push_back("-fsjlj-exceptions");
4497 // C++ "sane" operator new.
4498 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4499 options::OPT_fno_assume_sane_operator_new))
4500 CmdArgs.push_back("-fno-assume-sane-operator-new");
4502 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4504 if (Args.hasFlag(options::OPT_fsized_deallocation,
4505 options::OPT_fno_sized_deallocation, false))
4506 CmdArgs.push_back("-fsized-deallocation");
4508 // -fconstant-cfstrings is default, and may be subject to argument translation
4510 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4511 options::OPT_fno_constant_cfstrings) ||
4512 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4513 options::OPT_mno_constant_cfstrings))
4514 CmdArgs.push_back("-fno-constant-cfstrings");
4516 // -fshort-wchar default varies depending on platform; only
4517 // pass if specified.
4518 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4519 options::OPT_fno_short_wchar))
4520 A->render(Args, CmdArgs);
4522 // -fno-pascal-strings is default, only pass non-default.
4523 if (Args.hasFlag(options::OPT_fpascal_strings,
4524 options::OPT_fno_pascal_strings, false))
4525 CmdArgs.push_back("-fpascal-strings");
4527 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4528 // -fno-pack-struct doesn't apply to -fpack-struct=.
4529 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4530 std::string PackStructStr = "-fpack-struct=";
4531 PackStructStr += A->getValue();
4532 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4533 } else if (Args.hasFlag(options::OPT_fpack_struct,
4534 options::OPT_fno_pack_struct, false)) {
4535 CmdArgs.push_back("-fpack-struct=1");
4538 // Handle -fmax-type-align=N and -fno-type-align
4539 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4540 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4541 if (!SkipMaxTypeAlign) {
4542 std::string MaxTypeAlignStr = "-fmax-type-align=";
4543 MaxTypeAlignStr += A->getValue();
4544 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4546 } else if (getToolChain().getTriple().isOSDarwin()) {
4547 if (!SkipMaxTypeAlign) {
4548 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4549 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4553 if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
4554 if (!Args.hasArg(options::OPT_fcommon))
4555 CmdArgs.push_back("-fno-common");
4556 Args.ClaimAllArgs(options::OPT_fno_common);
4559 // -fcommon is default, only pass non-default.
4560 else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
4561 CmdArgs.push_back("-fno-common");
4563 // -fsigned-bitfields is default, and clang doesn't yet support
4564 // -funsigned-bitfields.
4565 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4566 options::OPT_funsigned_bitfields))
4567 D.Diag(diag::warn_drv_clang_unsupported)
4568 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4570 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4571 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4572 D.Diag(diag::err_drv_clang_unsupported)
4573 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4575 // -finput_charset=UTF-8 is default. Reject others
4576 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4577 StringRef value = inputCharset->getValue();
4578 if (value != "UTF-8")
4579 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4583 // -fexec_charset=UTF-8 is default. Reject others
4584 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4585 StringRef value = execCharset->getValue();
4586 if (value != "UTF-8")
4587 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4591 // -fcaret-diagnostics is default.
4592 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4593 options::OPT_fno_caret_diagnostics, true))
4594 CmdArgs.push_back("-fno-caret-diagnostics");
4596 // -fdiagnostics-fixit-info is default, only pass non-default.
4597 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4598 options::OPT_fno_diagnostics_fixit_info))
4599 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4601 // Enable -fdiagnostics-show-option by default.
4602 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4603 options::OPT_fno_diagnostics_show_option))
4604 CmdArgs.push_back("-fdiagnostics-show-option");
4607 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4608 CmdArgs.push_back("-fdiagnostics-show-category");
4609 CmdArgs.push_back(A->getValue());
4612 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4613 CmdArgs.push_back("-fdiagnostics-format");
4614 CmdArgs.push_back(A->getValue());
4617 if (Arg *A = Args.getLastArg(
4618 options::OPT_fdiagnostics_show_note_include_stack,
4619 options::OPT_fno_diagnostics_show_note_include_stack)) {
4620 if (A->getOption().matches(
4621 options::OPT_fdiagnostics_show_note_include_stack))
4622 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4624 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4627 // Color diagnostics are the default, unless the terminal doesn't support
4629 // Support both clang's -f[no-]color-diagnostics and gcc's
4630 // -f[no-]diagnostics-colors[=never|always|auto].
4631 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
4632 for (const auto &Arg : Args) {
4633 const Option &O = Arg->getOption();
4634 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4635 !O.matches(options::OPT_fdiagnostics_color) &&
4636 !O.matches(options::OPT_fno_color_diagnostics) &&
4637 !O.matches(options::OPT_fno_diagnostics_color) &&
4638 !O.matches(options::OPT_fdiagnostics_color_EQ))
4642 if (O.matches(options::OPT_fcolor_diagnostics) ||
4643 O.matches(options::OPT_fdiagnostics_color)) {
4644 ShowColors = Colors_On;
4645 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
4646 O.matches(options::OPT_fno_diagnostics_color)) {
4647 ShowColors = Colors_Off;
4649 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
4650 StringRef value(Arg->getValue());
4651 if (value == "always")
4652 ShowColors = Colors_On;
4653 else if (value == "never")
4654 ShowColors = Colors_Off;
4655 else if (value == "auto")
4656 ShowColors = Colors_Auto;
4658 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4659 << ("-fdiagnostics-color=" + value).str();
4662 if (ShowColors == Colors_On ||
4663 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
4664 CmdArgs.push_back("-fcolor-diagnostics");
4666 if (Args.hasArg(options::OPT_fansi_escape_codes))
4667 CmdArgs.push_back("-fansi-escape-codes");
4669 if (!Args.hasFlag(options::OPT_fshow_source_location,
4670 options::OPT_fno_show_source_location))
4671 CmdArgs.push_back("-fno-show-source-location");
4673 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4675 CmdArgs.push_back("-fno-show-column");
4677 if (!Args.hasFlag(options::OPT_fspell_checking,
4678 options::OPT_fno_spell_checking))
4679 CmdArgs.push_back("-fno-spell-checking");
4681 // -fno-asm-blocks is default.
4682 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4684 CmdArgs.push_back("-fasm-blocks");
4686 // -fgnu-inline-asm is default.
4687 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4688 options::OPT_fno_gnu_inline_asm, true))
4689 CmdArgs.push_back("-fno-gnu-inline-asm");
4691 // Enable vectorization per default according to the optimization level
4692 // selected. For optimization levels that want vectorization we use the alias
4693 // option to simplify the hasFlag logic.
4694 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4695 OptSpecifier VectorizeAliasOption =
4696 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4697 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4698 options::OPT_fno_vectorize, EnableVec))
4699 CmdArgs.push_back("-vectorize-loops");
4701 // -fslp-vectorize is enabled based on the optimization level selected.
4702 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4703 OptSpecifier SLPVectAliasOption =
4704 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4705 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4706 options::OPT_fno_slp_vectorize, EnableSLPVec))
4707 CmdArgs.push_back("-vectorize-slp");
4709 // -fno-slp-vectorize-aggressive is default.
4710 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4711 options::OPT_fno_slp_vectorize_aggressive, false))
4712 CmdArgs.push_back("-vectorize-slp-aggressive");
4714 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4715 A->render(Args, CmdArgs);
4717 // -fdollars-in-identifiers default varies depending on platform and
4718 // language; only pass if specified.
4719 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4720 options::OPT_fno_dollars_in_identifiers)) {
4721 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4722 CmdArgs.push_back("-fdollars-in-identifiers");
4724 CmdArgs.push_back("-fno-dollars-in-identifiers");
4727 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4728 // practical purposes.
4729 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4730 options::OPT_fno_unit_at_a_time)) {
4731 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4732 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4735 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4736 options::OPT_fno_apple_pragma_pack, false))
4737 CmdArgs.push_back("-fapple-pragma-pack");
4739 // le32-specific flags:
4740 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4742 if (getToolChain().getArch() == llvm::Triple::le32) {
4743 CmdArgs.push_back("-fno-math-builtin");
4746 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4748 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
4750 if (getToolChain().getTriple().isOSDarwin() &&
4751 (getToolChain().getArch() == llvm::Triple::arm ||
4752 getToolChain().getArch() == llvm::Triple::thumb)) {
4753 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4754 CmdArgs.push_back("-fno-builtin-strcat");
4755 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4756 CmdArgs.push_back("-fno-builtin-strcpy");
4760 // Enable rewrite includes if the user's asked for it or if we're generating
4762 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4763 // nice to enable this when doing a crashdump for modules as well.
4764 if (Args.hasFlag(options::OPT_frewrite_includes,
4765 options::OPT_fno_rewrite_includes, false) ||
4766 (C.isForDiagnostics() && !HaveModules))
4767 CmdArgs.push_back("-frewrite-includes");
4769 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4770 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4771 options::OPT_traditional_cpp)) {
4772 if (isa<PreprocessJobAction>(JA))
4773 CmdArgs.push_back("-traditional-cpp");
4775 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4778 Args.AddLastArg(CmdArgs, options::OPT_dM);
4779 Args.AddLastArg(CmdArgs, options::OPT_dD);
4781 // Handle serialized diagnostics.
4782 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4783 CmdArgs.push_back("-serialize-diagnostic-file");
4784 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4787 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4788 CmdArgs.push_back("-fretain-comments-from-system-headers");
4790 // Forward -fcomment-block-commands to -cc1.
4791 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4792 // Forward -fparse-all-comments to -cc1.
4793 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4795 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4797 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4798 bool OptDisabled = false;
4799 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4802 // We translate this by hand to the -cc1 argument, since nightly test uses
4803 // it and developers have been trained to spell it with -mllvm.
4804 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4805 CmdArgs.push_back("-disable-llvm-optzns");
4808 A->render(Args, CmdArgs);
4811 // With -save-temps, we want to save the unoptimized bitcode output from the
4812 // CompileJobAction, so disable optimizations if they are not already
4814 if (C.getDriver().isSaveTempsEnabled() && !OptDisabled &&
4815 isa<CompileJobAction>(JA))
4816 CmdArgs.push_back("-disable-llvm-optzns");
4818 if (Output.getType() == types::TY_Dependencies) {
4819 // Handled with other dependency code.
4820 } else if (Output.isFilename()) {
4821 CmdArgs.push_back("-o");
4822 CmdArgs.push_back(Output.getFilename());
4824 assert(Output.isNothing() && "Invalid output.");
4827 addDashXForInput(Args, Input, CmdArgs);
4829 if (Input.isFilename())
4830 CmdArgs.push_back(Input.getFilename());
4832 Input.getInputArg().renderAsInput(Args, CmdArgs);
4834 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4836 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4838 // Optionally embed the -cc1 level arguments into the debug info, for build
4840 if (getToolChain().UseDwarfDebugFlags()) {
4841 ArgStringList OriginalArgs;
4842 for (const auto &Arg : Args)
4843 Arg->render(Args, OriginalArgs);
4845 SmallString<256> Flags;
4847 for (const char *OriginalArg : OriginalArgs) {
4848 SmallString<128> EscapedArg;
4849 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4851 Flags += EscapedArg;
4853 CmdArgs.push_back("-dwarf-debug-flags");
4854 CmdArgs.push_back(Args.MakeArgString(Flags));
4857 // Add the split debug info name to the command lines here so we
4858 // can propagate it to the backend.
4859 bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
4860 getToolChain().getTriple().isOSLinux() &&
4861 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4862 isa<BackendJobAction>(JA));
4863 const char *SplitDwarfOut;
4865 CmdArgs.push_back("-split-dwarf-file");
4866 SplitDwarfOut = SplitDebugName(Args, Input);
4867 CmdArgs.push_back(SplitDwarfOut);
4870 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4871 // Include them with -fcuda-include-gpubinary.
4872 if (IsCuda && Inputs.size() > 1)
4873 for (InputInfoList::const_iterator it = std::next(Inputs.begin()),
4876 CmdArgs.push_back("-fcuda-include-gpubinary");
4877 CmdArgs.push_back(it->getFilename());
4880 // Finally add the compile command to the compilation.
4881 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4882 Output.getType() == types::TY_Object &&
4883 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4885 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4886 C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
4887 std::move(CLCommand)));
4889 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
4892 // Handle the debug info splitting at object creation time if we're
4893 // creating an object.
4894 // TODO: Currently only works on linux with newer objcopy.
4895 if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4896 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4898 if (Arg *A = Args.getLastArg(options::OPT_pg))
4899 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4900 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4901 << A->getAsString(Args);
4903 // Claim some arguments which clang supports automatically.
4905 // -fpch-preprocess is used with gcc to add a special marker in the output to
4906 // include the PCH file. Clang's PTH solution is completely transparent, so we
4907 // do not need to deal with it at all.
4908 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4910 // Claim some arguments which clang doesn't support, but we don't
4911 // care to warn the user about.
4912 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4913 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4915 // Disable warnings for clang -E -emit-llvm foo.c
4916 Args.ClaimAllArgs(options::OPT_emit_llvm);
4919 /// Add options related to the Objective-C runtime/ABI.
4921 /// Returns true if the runtime is non-fragile.
4922 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4923 ArgStringList &cmdArgs,
4924 RewriteKind rewriteKind) const {
4925 // Look for the controlling runtime option.
4927 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4928 options::OPT_fobjc_runtime_EQ);
4930 // Just forward -fobjc-runtime= to the frontend. This supercedes
4931 // options about fragility.
4933 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4934 ObjCRuntime runtime;
4935 StringRef value = runtimeArg->getValue();
4936 if (runtime.tryParse(value)) {
4937 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4941 runtimeArg->render(args, cmdArgs);
4945 // Otherwise, we'll need the ABI "version". Version numbers are
4946 // slightly confusing for historical reasons:
4947 // 1 - Traditional "fragile" ABI
4948 // 2 - Non-fragile ABI, version 1
4949 // 3 - Non-fragile ABI, version 2
4950 unsigned objcABIVersion = 1;
4951 // If -fobjc-abi-version= is present, use that to set the version.
4952 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4953 StringRef value = abiArg->getValue();
4956 else if (value == "2")
4958 else if (value == "3")
4961 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4963 // Otherwise, determine if we are using the non-fragile ABI.
4964 bool nonFragileABIIsDefault =
4965 (rewriteKind == RK_NonFragile ||
4966 (rewriteKind == RK_None &&
4967 getToolChain().IsObjCNonFragileABIDefault()));
4968 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4969 options::OPT_fno_objc_nonfragile_abi,
4970 nonFragileABIIsDefault)) {
4971 // Determine the non-fragile ABI version to use.
4972 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4973 unsigned nonFragileABIVersion = 1;
4975 unsigned nonFragileABIVersion = 2;
4979 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4980 StringRef value = abiArg->getValue();
4982 nonFragileABIVersion = 1;
4983 else if (value == "2")
4984 nonFragileABIVersion = 2;
4986 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4990 objcABIVersion = 1 + nonFragileABIVersion;
4996 // We don't actually care about the ABI version other than whether
4997 // it's non-fragile.
4998 bool isNonFragile = objcABIVersion != 1;
5000 // If we have no runtime argument, ask the toolchain for its default runtime.
5001 // However, the rewriter only really supports the Mac runtime, so assume that.
5002 ObjCRuntime runtime;
5004 switch (rewriteKind) {
5006 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5009 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5012 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5017 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5018 // On Darwin, make this use the default behavior for the toolchain.
5019 if (getToolChain().getTriple().isOSDarwin()) {
5020 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5022 // Otherwise, build for a generic macosx port.
5024 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5029 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5030 // Legacy behaviour is to target the gnustep runtime if we are i
5031 // non-fragile mode or the GCC runtime in fragile mode.
5033 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5035 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5039 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5043 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5044 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5050 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5056 /// /EH controls whether to run destructor cleanups when exceptions are
5057 /// thrown. There are three modifiers:
5058 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5059 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5060 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5061 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5062 /// modifier is an optimization, so we ignore it for now.
5063 /// The default is /EHs-c-, meaning cleanups are disabled.
5064 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5067 std::vector<std::string> EHArgs =
5068 Args.getAllArgValues(options::OPT__SLASH_EH);
5069 for (auto EHVal : EHArgs) {
5070 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5073 EH.Asynch = maybeConsumeDash(EHVal, I);
5076 EH.NoExceptC = maybeConsumeDash(EHVal, I);
5079 EH.Synch = maybeConsumeDash(EHVal, I);
5084 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5089 // FIXME: Disable C++ EH completely, until it becomes more reliable. Users
5090 // can use -Xclang to manually enable C++ EH until then.
5096 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
5097 unsigned RTOptionID = options::OPT__SLASH_MT;
5099 if (Args.hasArg(options::OPT__SLASH_LDd))
5100 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5101 // but defining _DEBUG is sticky.
5102 RTOptionID = options::OPT__SLASH_MTd;
5104 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5105 RTOptionID = A->getOption().getID();
5107 switch (RTOptionID) {
5108 case options::OPT__SLASH_MD:
5109 if (Args.hasArg(options::OPT__SLASH_LDd))
5110 CmdArgs.push_back("-D_DEBUG");
5111 CmdArgs.push_back("-D_MT");
5112 CmdArgs.push_back("-D_DLL");
5113 CmdArgs.push_back("--dependent-lib=msvcrt");
5115 case options::OPT__SLASH_MDd:
5116 CmdArgs.push_back("-D_DEBUG");
5117 CmdArgs.push_back("-D_MT");
5118 CmdArgs.push_back("-D_DLL");
5119 CmdArgs.push_back("--dependent-lib=msvcrtd");
5121 case options::OPT__SLASH_MT:
5122 if (Args.hasArg(options::OPT__SLASH_LDd))
5123 CmdArgs.push_back("-D_DEBUG");
5124 CmdArgs.push_back("-D_MT");
5125 CmdArgs.push_back("--dependent-lib=libcmt");
5127 case options::OPT__SLASH_MTd:
5128 CmdArgs.push_back("-D_DEBUG");
5129 CmdArgs.push_back("-D_MT");
5130 CmdArgs.push_back("--dependent-lib=libcmtd");
5133 llvm_unreachable("Unexpected option ID.");
5136 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5137 // users want. The /Za flag to cl.exe turns this off, but it's not
5138 // implemented in clang.
5139 CmdArgs.push_back("--dependent-lib=oldnames");
5141 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5142 // would produce interleaved output, so ignore /showIncludes in such cases.
5143 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5144 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5145 A->render(Args, CmdArgs);
5147 // This controls whether or not we emit RTTI data for polymorphic types.
5148 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5150 CmdArgs.push_back("-fno-rtti-data");
5152 const Driver &D = getToolChain().getDriver();
5153 EHFlags EH = parseClangCLEHFlags(D, Args);
5154 // FIXME: Do something with NoExceptC.
5155 if (EH.Synch || EH.Asynch) {
5156 CmdArgs.push_back("-fcxx-exceptions");
5157 CmdArgs.push_back("-fexceptions");
5160 // /EP should expand to -E -P.
5161 if (Args.hasArg(options::OPT__SLASH_EP)) {
5162 CmdArgs.push_back("-E");
5163 CmdArgs.push_back("-P");
5166 unsigned VolatileOptionID;
5167 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5168 getToolChain().getArch() == llvm::Triple::x86)
5169 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5171 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5173 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5174 VolatileOptionID = A->getOption().getID();
5176 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5177 CmdArgs.push_back("-fms-volatile");
5179 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5180 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5181 if (MostGeneralArg && BestCaseArg)
5182 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5183 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5185 if (MostGeneralArg) {
5186 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5187 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5188 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5190 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5191 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5192 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5193 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5194 << FirstConflict->getAsString(Args)
5195 << SecondConflict->getAsString(Args);
5198 CmdArgs.push_back("-fms-memptr-rep=single");
5199 else if (MultipleArg)
5200 CmdArgs.push_back("-fms-memptr-rep=multiple");
5202 CmdArgs.push_back("-fms-memptr-rep=virtual");
5205 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5206 A->render(Args, CmdArgs);
5208 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5209 CmdArgs.push_back("-fdiagnostics-format");
5210 if (Args.hasArg(options::OPT__SLASH_fallback))
5211 CmdArgs.push_back("msvc-fallback");
5213 CmdArgs.push_back("msvc");
5217 visualstudio::Compiler *Clang::getCLFallback() const {
5219 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5220 return CLFallback.get();
5223 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5224 ArgStringList &CmdArgs) const {
5227 const llvm::Triple &Triple = getToolChain().getTriple();
5228 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5230 CmdArgs.push_back("-target-abi");
5231 CmdArgs.push_back(ABIName.data());
5234 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5235 const InputInfo &Output, const InputInfoList &Inputs,
5236 const ArgList &Args,
5237 const char *LinkingOutput) const {
5238 ArgStringList CmdArgs;
5240 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5241 const InputInfo &Input = Inputs[0];
5243 // Don't warn about "clang -w -c foo.s"
5244 Args.ClaimAllArgs(options::OPT_w);
5245 // and "clang -emit-llvm -c foo.s"
5246 Args.ClaimAllArgs(options::OPT_emit_llvm);
5248 claimNoWarnArgs(Args);
5250 // Invoke ourselves in -cc1as mode.
5252 // FIXME: Implement custom jobs for internal actions.
5253 CmdArgs.push_back("-cc1as");
5255 // Add the "effective" target triple.
5256 CmdArgs.push_back("-triple");
5257 std::string TripleStr =
5258 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5259 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5261 // Set the output mode, we currently only expect to be used as a real
5263 CmdArgs.push_back("-filetype");
5264 CmdArgs.push_back("obj");
5266 // Set the main file name, so that debug info works even with
5267 // -save-temps or preprocessed assembly.
5268 CmdArgs.push_back("-main-file-name");
5269 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5271 // Add the target cpu
5272 const llvm::Triple Triple(TripleStr);
5273 std::string CPU = getCPUName(Args, Triple);
5275 CmdArgs.push_back("-target-cpu");
5276 CmdArgs.push_back(Args.MakeArgString(CPU));
5279 // Add the target features
5280 const Driver &D = getToolChain().getDriver();
5281 getTargetFeatures(D, Triple, Args, CmdArgs, true);
5283 // Ignore explicit -force_cpusubtype_ALL option.
5284 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5286 // Pass along any -I options so we get proper .include search paths.
5287 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5289 // Determine the original source input.
5290 const Action *SourceAction = &JA;
5291 while (SourceAction->getKind() != Action::InputClass) {
5292 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5293 SourceAction = SourceAction->getInputs()[0];
5296 // Forward -g and handle debug info related flags, assuming we are dealing
5297 // with an actual assembly file.
5298 if (SourceAction->getType() == types::TY_Asm ||
5299 SourceAction->getType() == types::TY_PP_Asm) {
5300 Args.ClaimAllArgs(options::OPT_g_Group);
5301 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
5302 if (!A->getOption().matches(options::OPT_g0))
5303 CmdArgs.push_back("-g");
5305 if (Args.hasArg(options::OPT_gdwarf_2))
5306 CmdArgs.push_back("-gdwarf-2");
5307 if (Args.hasArg(options::OPT_gdwarf_3))
5308 CmdArgs.push_back("-gdwarf-3");
5309 if (Args.hasArg(options::OPT_gdwarf_4))
5310 CmdArgs.push_back("-gdwarf-4");
5312 // Add the -fdebug-compilation-dir flag if needed.
5313 addDebugCompDirArg(Args, CmdArgs);
5315 // Set the AT_producer to the clang version when using the integrated
5316 // assembler on assembly source files.
5317 CmdArgs.push_back("-dwarf-debug-producer");
5318 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5321 // Optionally embed the -cc1as level arguments into the debug info, for build
5323 if (getToolChain().UseDwarfDebugFlags()) {
5324 ArgStringList OriginalArgs;
5325 for (const auto &Arg : Args)
5326 Arg->render(Args, OriginalArgs);
5328 SmallString<256> Flags;
5329 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5331 for (const char *OriginalArg : OriginalArgs) {
5332 SmallString<128> EscapedArg;
5333 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5335 Flags += EscapedArg;
5337 CmdArgs.push_back("-dwarf-debug-flags");
5338 CmdArgs.push_back(Args.MakeArgString(Flags));
5341 // FIXME: Add -static support, once we have it.
5343 // Add target specific flags.
5344 switch (getToolChain().getArch()) {
5348 case llvm::Triple::mips:
5349 case llvm::Triple::mipsel:
5350 case llvm::Triple::mips64:
5351 case llvm::Triple::mips64el:
5352 AddMIPSTargetArgs(Args, CmdArgs);
5356 // Consume all the warning flags. Usually this would be handled more
5357 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5358 // doesn't handle that so rather than warning about unused flags that are
5359 // actually used, we'll lie by omission instead.
5360 // FIXME: Stop lying and consume only the appropriate driver flags
5361 for (const Arg *A : Args.filtered(options::OPT_W_Group))
5364 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5365 getToolChain().getDriver());
5367 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5369 assert(Output.isFilename() && "Unexpected lipo output.");
5370 CmdArgs.push_back("-o");
5371 CmdArgs.push_back(Output.getFilename());
5373 assert(Input.isFilename() && "Invalid input.");
5374 CmdArgs.push_back(Input.getFilename());
5376 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5377 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5379 // Handle the debug info splitting at object creation time if we're
5380 // creating an object.
5381 // TODO: Currently only works on linux with newer objcopy.
5382 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5383 getToolChain().getTriple().isOSLinux())
5384 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5385 SplitDebugName(Args, Input));
5388 void GnuTool::anchor() {}
5390 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
5391 const InputInfo &Output,
5392 const InputInfoList &Inputs, const ArgList &Args,
5393 const char *LinkingOutput) const {
5394 const Driver &D = getToolChain().getDriver();
5395 ArgStringList CmdArgs;
5397 for (const auto &A : Args) {
5398 if (forwardToGCC(A->getOption())) {
5399 // Don't forward any -g arguments to assembly steps.
5400 if (isa<AssembleJobAction>(JA) &&
5401 A->getOption().matches(options::OPT_g_Group))
5404 // Don't forward any -W arguments to assembly and link steps.
5405 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
5406 A->getOption().matches(options::OPT_W_Group))
5409 // It is unfortunate that we have to claim here, as this means
5410 // we will basically never report anything interesting for
5411 // platforms using a generic gcc, even if we are just using gcc
5412 // to get to the assembler.
5414 A->render(Args, CmdArgs);
5418 RenderExtraToolArgs(JA, CmdArgs);
5420 // If using a driver driver, force the arch.
5421 if (getToolChain().getTriple().isOSDarwin()) {
5422 CmdArgs.push_back("-arch");
5424 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
5427 // Try to force gcc to match the tool chain we want, if we recognize
5430 // FIXME: The triple class should directly provide the information we want
5432 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5433 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
5434 CmdArgs.push_back("-m32");
5435 else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
5436 Arch == llvm::Triple::ppc64le)
5437 CmdArgs.push_back("-m64");
5439 if (Output.isFilename()) {
5440 CmdArgs.push_back("-o");
5441 CmdArgs.push_back(Output.getFilename());
5443 assert(Output.isNothing() && "Unexpected output");
5444 CmdArgs.push_back("-fsyntax-only");
5447 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5449 // Only pass -x if gcc will understand it; otherwise hope gcc
5450 // understands the suffix correctly. The main use case this would go
5451 // wrong in is for linker inputs if they happened to have an odd
5452 // suffix; really the only way to get this to happen is a command
5453 // like '-x foobar a.c' which will treat a.c like a linker input.
5455 // FIXME: For the linker case specifically, can we safely convert
5456 // inputs into '-Wl,' options?
5457 for (const auto &II : Inputs) {
5458 // Don't try to pass LLVM or AST inputs to a generic gcc.
5459 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5460 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5461 D.Diag(diag::err_drv_no_linker_llvm_support)
5462 << getToolChain().getTripleString();
5463 else if (II.getType() == types::TY_AST)
5464 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
5465 else if (II.getType() == types::TY_ModuleFile)
5466 D.Diag(diag::err_drv_no_module_support)
5467 << getToolChain().getTripleString();
5469 if (types::canTypeBeUserSpecified(II.getType())) {
5470 CmdArgs.push_back("-x");
5471 CmdArgs.push_back(types::getTypeName(II.getType()));
5474 if (II.isFilename())
5475 CmdArgs.push_back(II.getFilename());
5477 const Arg &A = II.getInputArg();
5479 // Reverse translate some rewritten options.
5480 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
5481 CmdArgs.push_back("-lstdc++");
5485 // Don't render as input, we need gcc to do the translations.
5486 A.render(Args, CmdArgs);
5490 const std::string customGCCName = D.getCCCGenericGCCName();
5491 const char *GCCName;
5492 if (!customGCCName.empty())
5493 GCCName = customGCCName.c_str();
5494 else if (D.CCCIsCXX()) {
5499 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5500 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5503 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
5504 ArgStringList &CmdArgs) const {
5505 CmdArgs.push_back("-E");
5508 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
5509 ArgStringList &CmdArgs) const {
5510 const Driver &D = getToolChain().getDriver();
5512 switch (JA.getType()) {
5513 // If -flto, etc. are present then make sure not to force assembly output.
5514 case types::TY_LLVM_IR:
5515 case types::TY_LTO_IR:
5516 case types::TY_LLVM_BC:
5517 case types::TY_LTO_BC:
5518 CmdArgs.push_back("-c");
5520 case types::TY_PP_Asm:
5521 CmdArgs.push_back("-S");
5523 case types::TY_Nothing:
5524 CmdArgs.push_back("-fsyntax-only");
5527 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
5531 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
5532 ArgStringList &CmdArgs) const {
5533 // The types are (hopefully) good enough.
5536 // Hexagon tools start.
5537 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
5538 ArgStringList &CmdArgs) const {}
5539 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
5540 const InputInfo &Output,
5541 const InputInfoList &Inputs,
5542 const ArgList &Args,
5543 const char *LinkingOutput) const {
5544 claimNoWarnArgs(Args);
5546 const Driver &D = getToolChain().getDriver();
5547 ArgStringList CmdArgs;
5549 std::string MarchString = "-march=";
5550 MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
5551 CmdArgs.push_back(Args.MakeArgString(MarchString));
5553 RenderExtraToolArgs(JA, CmdArgs);
5555 if (Output.isFilename()) {
5556 CmdArgs.push_back("-o");
5557 CmdArgs.push_back(Output.getFilename());
5559 assert(Output.isNothing() && "Unexpected output");
5560 CmdArgs.push_back("-fsyntax-only");
5563 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args))
5564 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5566 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5568 // Only pass -x if gcc will understand it; otherwise hope gcc
5569 // understands the suffix correctly. The main use case this would go
5570 // wrong in is for linker inputs if they happened to have an odd
5571 // suffix; really the only way to get this to happen is a command
5572 // like '-x foobar a.c' which will treat a.c like a linker input.
5574 // FIXME: For the linker case specifically, can we safely convert
5575 // inputs into '-Wl,' options?
5576 for (const auto &II : Inputs) {
5577 // Don't try to pass LLVM or AST inputs to a generic gcc.
5578 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5579 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5580 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
5581 << getToolChain().getTripleString();
5582 else if (II.getType() == types::TY_AST)
5583 D.Diag(clang::diag::err_drv_no_ast_support)
5584 << getToolChain().getTripleString();
5585 else if (II.getType() == types::TY_ModuleFile)
5586 D.Diag(diag::err_drv_no_module_support)
5587 << getToolChain().getTripleString();
5589 if (II.isFilename())
5590 CmdArgs.push_back(II.getFilename());
5592 // Don't render as input, we need gcc to do the translations.
5593 // FIXME: Pranav: What is this ?
5594 II.getInputArg().render(Args, CmdArgs);
5597 const char *GCCName = "hexagon-as";
5598 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5599 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5602 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
5603 ArgStringList &CmdArgs) const {
5604 // The types are (hopefully) good enough.
5607 static void constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
5608 const toolchains::Hexagon_TC &ToolChain,
5609 const InputInfo &Output,
5610 const InputInfoList &Inputs,
5611 const ArgList &Args,
5612 ArgStringList &CmdArgs,
5613 const char *LinkingOutput) {
5615 const Driver &D = ToolChain.getDriver();
5617 //----------------------------------------------------------------------------
5619 //----------------------------------------------------------------------------
5620 bool hasStaticArg = Args.hasArg(options::OPT_static);
5621 bool buildingLib = Args.hasArg(options::OPT_shared);
5622 bool buildPIE = Args.hasArg(options::OPT_pie);
5623 bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
5624 bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
5625 bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
5627 bool useShared = buildingLib && !hasStaticArg;
5629 //----------------------------------------------------------------------------
5630 // Silence warnings for various options
5631 //----------------------------------------------------------------------------
5633 Args.ClaimAllArgs(options::OPT_g_Group);
5634 Args.ClaimAllArgs(options::OPT_emit_llvm);
5635 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
5636 // handled somewhere else.
5637 Args.ClaimAllArgs(options::OPT_static_libgcc);
5639 //----------------------------------------------------------------------------
5641 //----------------------------------------------------------------------------
5642 for (const auto &Opt : ToolChain.ExtraOpts)
5643 CmdArgs.push_back(Opt.c_str());
5645 std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
5646 CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
5649 CmdArgs.push_back("-shared");
5650 CmdArgs.push_back("-call_shared"); // should be the default, but doing as
5655 CmdArgs.push_back("-static");
5657 if (buildPIE && !buildingLib)
5658 CmdArgs.push_back("-pie");
5660 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
5661 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5662 useG0 = toolchains::Hexagon_TC::UsesG0(v);
5665 //----------------------------------------------------------------------------
5667 //----------------------------------------------------------------------------
5668 CmdArgs.push_back("-o");
5669 CmdArgs.push_back(Output.getFilename());
5671 const std::string MarchSuffix = "/" + MarchString;
5672 const std::string G0Suffix = "/G0";
5673 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
5674 const std::string RootDir =
5675 toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
5676 const std::string StartFilesDir =
5677 RootDir + "hexagon/lib" + (useG0 ? MarchG0Suffix : MarchSuffix);
5679 //----------------------------------------------------------------------------
5681 //----------------------------------------------------------------------------
5682 std::vector<std::string> oslibs;
5683 bool hasStandalone = false;
5685 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
5687 oslibs.emplace_back(A->getValue());
5688 hasStandalone = hasStandalone || (oslibs.back() == "standalone");
5690 if (oslibs.empty()) {
5691 oslibs.push_back("standalone");
5692 hasStandalone = true;
5695 //----------------------------------------------------------------------------
5697 //----------------------------------------------------------------------------
5698 if (incStdLib && incStartFiles) {
5701 if (hasStandalone) {
5703 Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
5705 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
5707 std::string initObj = useShared ? "/initS.o" : "/init.o";
5708 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
5711 //----------------------------------------------------------------------------
5712 // Library Search Paths
5713 //----------------------------------------------------------------------------
5714 const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
5715 for (const auto &LibPath : LibPaths)
5716 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
5718 //----------------------------------------------------------------------------
5720 //----------------------------------------------------------------------------
5721 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5722 Args.AddAllArgs(CmdArgs, options::OPT_e);
5723 Args.AddAllArgs(CmdArgs, options::OPT_s);
5724 Args.AddAllArgs(CmdArgs, options::OPT_t);
5725 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5727 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5729 //----------------------------------------------------------------------------
5731 //----------------------------------------------------------------------------
5732 if (incStdLib && incDefLibs) {
5734 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5735 CmdArgs.push_back("-lm");
5738 CmdArgs.push_back("--start-group");
5741 for (const std::string &Lib : oslibs)
5742 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
5743 CmdArgs.push_back("-lc");
5745 CmdArgs.push_back("-lgcc");
5747 CmdArgs.push_back("--end-group");
5750 //----------------------------------------------------------------------------
5752 //----------------------------------------------------------------------------
5753 if (incStdLib && incStartFiles) {
5754 std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
5755 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
5759 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
5760 const InputInfo &Output,
5761 const InputInfoList &Inputs,
5762 const ArgList &Args,
5763 const char *LinkingOutput) const {
5765 const toolchains::Hexagon_TC &ToolChain =
5766 static_cast<const toolchains::Hexagon_TC &>(getToolChain());
5768 ArgStringList CmdArgs;
5769 constructHexagonLinkArgs(C, JA, ToolChain, Output, Inputs, Args, CmdArgs,
5772 std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
5773 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
5776 // Hexagon tools end.
5778 const std::string arm::getARMArch(const ArgList &Args,
5779 const llvm::Triple &Triple) {
5781 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
5782 // Otherwise, if we have -march= choose the base CPU for that arch.
5783 MArch = A->getValue();
5785 // Otherwise, use the Arch from the triple.
5786 MArch = Triple.getArchName();
5788 MArch = StringRef(MArch).lower();
5790 // Handle -march=native.
5791 if (MArch == "native") {
5792 std::string CPU = llvm::sys::getHostCPUName();
5793 if (CPU != "generic") {
5794 // Translate the native cpu into the architecture suffix for that CPU.
5795 const char *Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch);
5796 // If there is no valid architecture suffix for this CPU we don't know how
5797 // to handle it, so return no architecture.
5798 if (strcmp(Suffix, "") == 0)
5801 MArch = std::string("arm") + Suffix;
5807 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
5808 const char *arm::getARMCPUForMArch(const ArgList &Args,
5809 const llvm::Triple &Triple) {
5810 std::string MArch = getARMArch(Args, Triple);
5811 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
5812 // here means an -march=native that we can't handle, so instead return no CPU.
5816 // We need to return an empty string here on invalid MArch values as the
5817 // various places that call this function can't cope with a null result.
5818 const char *result = Triple.getARMCPUForArch(MArch);
5825 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
5826 std::string arm::getARMTargetCPU(const ArgList &Args,
5827 const llvm::Triple &Triple) {
5828 // FIXME: Warn on inconsistent use of -mcpu and -march.
5829 // If we have -mcpu=, use that.
5830 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
5831 std::string MCPU = StringRef(A->getValue()).lower();
5832 // Handle -mcpu=native.
5833 if (MCPU == "native")
5834 return llvm::sys::getHostCPUName();
5839 return getARMCPUForMArch(Args, Triple);
5842 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
5843 /// CPU (or Arch, if CPU is generic).
5844 // FIXME: This is redundant with -mcpu, why does LLVM use this.
5845 const char *arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch) {
5846 if (CPU == "generic" &&
5847 llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_ARMV8_1A)
5850 unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(CPU);
5851 if (ArchKind == llvm::ARM::AK_INVALID)
5853 return llvm::ARMTargetParser::getSubArch(ArchKind);
5856 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
5857 const llvm::Triple &Triple) {
5858 if (Args.hasArg(options::OPT_r))
5861 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
5862 // to generate BE-8 executables.
5863 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
5864 CmdArgs.push_back("--be8");
5867 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
5868 return (NanEncoding)llvm::StringSwitch<int>(CPU)
5869 .Case("mips1", NanLegacy)
5870 .Case("mips2", NanLegacy)
5871 .Case("mips3", NanLegacy)
5872 .Case("mips4", NanLegacy)
5873 .Case("mips5", NanLegacy)
5874 .Case("mips32", NanLegacy)
5875 .Case("mips32r2", NanLegacy)
5876 .Case("mips32r3", NanLegacy | Nan2008)
5877 .Case("mips32r5", NanLegacy | Nan2008)
5878 .Case("mips32r6", Nan2008)
5879 .Case("mips64", NanLegacy)
5880 .Case("mips64r2", NanLegacy)
5881 .Case("mips64r3", NanLegacy | Nan2008)
5882 .Case("mips64r5", NanLegacy | Nan2008)
5883 .Case("mips64r6", Nan2008)
5884 .Default(NanLegacy);
5887 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
5888 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
5889 return A && (A->getValue() == StringRef(Value));
5892 bool mips::isUCLibc(const ArgList &Args) {
5893 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
5894 return A && A->getOption().matches(options::OPT_muclibc);
5897 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
5898 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
5899 return llvm::StringSwitch<bool>(NaNArg->getValue())
5901 .Case("legacy", false)
5904 // NaN2008 is the default for MIPS32r6/MIPS64r6.
5905 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
5906 .Cases("mips32r6", "mips64r6", true)
5912 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
5913 StringRef ABIName, StringRef FloatABI) {
5914 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
5915 Triple.getVendor() != llvm::Triple::MipsTechnologies)
5918 if (ABIName != "32")
5921 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
5923 if (FloatABI == "soft")
5926 return llvm::StringSwitch<bool>(CPUName)
5927 .Cases("mips2", "mips3", "mips4", "mips5", true)
5928 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
5929 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
5933 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
5934 StringRef CPUName, StringRef ABIName,
5935 StringRef FloatABI) {
5936 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
5938 // FPXX shouldn't be used if -msingle-float is present.
5939 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
5940 options::OPT_mdouble_float))
5941 if (A->getOption().matches(options::OPT_msingle_float))
5947 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
5948 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
5949 // archs which Darwin doesn't use.
5951 // The matching this routine does is fairly pointless, since it is neither the
5952 // complete architecture list, nor a reasonable subset. The problem is that
5953 // historically the driver driver accepts this and also ties its -march=
5954 // handling to the architecture name, so we need to be careful before removing
5957 // This code must be kept in sync with Clang's Darwin specific argument
5960 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
5961 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
5962 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
5963 .Case("ppc64", llvm::Triple::ppc64)
5964 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
5965 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
5967 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
5968 // This is derived from the driver driver.
5969 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
5970 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
5971 .Cases("armv7s", "xscale", llvm::Triple::arm)
5972 .Case("arm64", llvm::Triple::aarch64)
5973 .Case("r600", llvm::Triple::r600)
5974 .Case("amdgcn", llvm::Triple::amdgcn)
5975 .Case("nvptx", llvm::Triple::nvptx)
5976 .Case("nvptx64", llvm::Triple::nvptx64)
5977 .Case("amdil", llvm::Triple::amdil)
5978 .Case("spir", llvm::Triple::spir)
5979 .Default(llvm::Triple::UnknownArch);
5982 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
5983 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
5986 if (Str == "x86_64h")
5988 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
5989 T.setOS(llvm::Triple::UnknownOS);
5990 T.setObjectFormat(llvm::Triple::MachO);
5994 const char *Clang::getBaseInputName(const ArgList &Args,
5995 const InputInfo &Input) {
5996 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5999 const char *Clang::getBaseInputStem(const ArgList &Args,
6000 const InputInfoList &Inputs) {
6001 const char *Str = getBaseInputName(Args, Inputs[0]);
6003 if (const char *End = strrchr(Str, '.'))
6004 return Args.MakeArgString(std::string(Str, End));
6009 const char *Clang::getDependencyFileName(const ArgList &Args,
6010 const InputInfoList &Inputs) {
6011 // FIXME: Think about this more.
6014 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6015 std::string Str(OutputOpt->getValue());
6016 Res = Str.substr(0, Str.rfind('.'));
6018 Res = getBaseInputStem(Args, Inputs);
6020 return Args.MakeArgString(Res + ".d");
6023 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6024 const InputInfo &Output,
6025 const InputInfoList &Inputs,
6026 const ArgList &Args,
6027 const char *LinkingOutput) const {
6028 const ToolChain &ToolChain = getToolChain();
6029 const Driver &D = ToolChain.getDriver();
6030 ArgStringList CmdArgs;
6032 // Silence warning for "clang -g foo.o -o foo"
6033 Args.ClaimAllArgs(options::OPT_g_Group);
6034 // and "clang -emit-llvm foo.o -o foo"
6035 Args.ClaimAllArgs(options::OPT_emit_llvm);
6036 // and for "clang -w foo.o -o foo". Other warning options are already
6037 // handled somewhere else.
6038 Args.ClaimAllArgs(options::OPT_w);
6040 if (!D.SysRoot.empty())
6041 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6043 // CloudABI only supports static linkage.
6044 CmdArgs.push_back("-Bstatic");
6045 CmdArgs.push_back("--eh-frame-hdr");
6046 CmdArgs.push_back("--gc-sections");
6048 if (Output.isFilename()) {
6049 CmdArgs.push_back("-o");
6050 CmdArgs.push_back(Output.getFilename());
6052 assert(Output.isNothing() && "Invalid output.");
6055 if (!Args.hasArg(options::OPT_nostdlib) &&
6056 !Args.hasArg(options::OPT_nostartfiles)) {
6057 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6058 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6061 Args.AddAllArgs(CmdArgs, options::OPT_L);
6062 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
6063 for (const auto &Path : Paths)
6064 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
6065 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6066 Args.AddAllArgs(CmdArgs, options::OPT_e);
6067 Args.AddAllArgs(CmdArgs, options::OPT_s);
6068 Args.AddAllArgs(CmdArgs, options::OPT_t);
6069 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6070 Args.AddAllArgs(CmdArgs, options::OPT_r);
6072 if (D.IsUsingLTO(Args))
6073 AddGoldPlugin(ToolChain, Args, CmdArgs);
6075 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6077 if (!Args.hasArg(options::OPT_nostdlib) &&
6078 !Args.hasArg(options::OPT_nodefaultlibs)) {
6080 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6081 CmdArgs.push_back("-lc");
6082 CmdArgs.push_back("-lcompiler_rt");
6085 if (!Args.hasArg(options::OPT_nostdlib) &&
6086 !Args.hasArg(options::OPT_nostartfiles))
6087 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6089 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6090 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6093 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6094 const InputInfo &Output,
6095 const InputInfoList &Inputs,
6096 const ArgList &Args,
6097 const char *LinkingOutput) const {
6098 ArgStringList CmdArgs;
6100 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6101 const InputInfo &Input = Inputs[0];
6103 // Determine the original source input.
6104 const Action *SourceAction = &JA;
6105 while (SourceAction->getKind() != Action::InputClass) {
6106 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6107 SourceAction = SourceAction->getInputs()[0];
6110 // If -fno_integrated_as is used add -Q to the darwin assember driver to make
6111 // sure it runs its system assembler not clang's integrated assembler.
6112 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6113 // FIXME: at run-time detect assembler capabilities or rely on version
6114 // information forwarded by -target-assembler-version (future)
6115 if (Args.hasArg(options::OPT_fno_integrated_as)) {
6116 const llvm::Triple &T(getToolChain().getTriple());
6117 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6118 CmdArgs.push_back("-Q");
6121 // Forward -g, assuming we are dealing with an actual assembly file.
6122 if (SourceAction->getType() == types::TY_Asm ||
6123 SourceAction->getType() == types::TY_PP_Asm) {
6124 if (Args.hasArg(options::OPT_gstabs))
6125 CmdArgs.push_back("--gstabs");
6126 else if (Args.hasArg(options::OPT_g_Group))
6127 CmdArgs.push_back("-g");
6130 // Derived from asm spec.
6131 AddMachOArch(Args, CmdArgs);
6133 // Use -force_cpusubtype_ALL on x86 by default.
6134 if (getToolChain().getArch() == llvm::Triple::x86 ||
6135 getToolChain().getArch() == llvm::Triple::x86_64 ||
6136 Args.hasArg(options::OPT_force__cpusubtype__ALL))
6137 CmdArgs.push_back("-force_cpusubtype_ALL");
6139 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6140 (((Args.hasArg(options::OPT_mkernel) ||
6141 Args.hasArg(options::OPT_fapple_kext)) &&
6142 getMachOToolChain().isKernelStatic()) ||
6143 Args.hasArg(options::OPT_static)))
6144 CmdArgs.push_back("-static");
6146 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6148 assert(Output.isFilename() && "Unexpected lipo output.");
6149 CmdArgs.push_back("-o");
6150 CmdArgs.push_back(Output.getFilename());
6152 assert(Input.isFilename() && "Invalid input.");
6153 CmdArgs.push_back(Input.getFilename());
6155 // asm_final spec is empty.
6157 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6158 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6161 void darwin::MachOTool::anchor() {}
6163 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6164 ArgStringList &CmdArgs) const {
6165 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6167 // Derived from darwin_arch spec.
6168 CmdArgs.push_back("-arch");
6169 CmdArgs.push_back(Args.MakeArgString(ArchName));
6171 // FIXME: Is this needed anymore?
6172 if (ArchName == "arm")
6173 CmdArgs.push_back("-force_cpusubtype_ALL");
6176 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6177 // We only need to generate a temp path for LTO if we aren't compiling object
6178 // files. When compiling source files, we run 'dsymutil' after linking. We
6179 // don't run 'dsymutil' when compiling object files.
6180 for (const auto &Input : Inputs)
6181 if (Input.getType() != types::TY_Object)
6187 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6188 ArgStringList &CmdArgs,
6189 const InputInfoList &Inputs) const {
6190 const Driver &D = getToolChain().getDriver();
6191 const toolchains::MachO &MachOTC = getMachOToolChain();
6193 unsigned Version[3] = {0, 0, 0};
6194 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6196 if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6197 Version[2], HadExtra) ||
6199 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6202 // Newer linkers support -demangle. Pass it if supported and not disabled by
6204 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6205 CmdArgs.push_back("-demangle");
6207 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6208 CmdArgs.push_back("-export_dynamic");
6210 // If we are using App Extension restrictions, pass a flag to the linker
6211 // telling it that the compiled code has been audited.
6212 if (Args.hasFlag(options::OPT_fapplication_extension,
6213 options::OPT_fno_application_extension, false))
6214 CmdArgs.push_back("-application_extension");
6216 // If we are using LTO, then automatically create a temporary file path for
6217 // the linker to use, so that it's lifetime will extend past a possible
6219 if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
6220 const char *TmpPath = C.getArgs().MakeArgString(
6221 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6222 C.addTempFile(TmpPath);
6223 CmdArgs.push_back("-object_path_lto");
6224 CmdArgs.push_back(TmpPath);
6227 // Derived from the "link" spec.
6228 Args.AddAllArgs(CmdArgs, options::OPT_static);
6229 if (!Args.hasArg(options::OPT_static))
6230 CmdArgs.push_back("-dynamic");
6231 if (Args.hasArg(options::OPT_fgnu_runtime)) {
6232 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6233 // here. How do we wish to handle such things?
6236 if (!Args.hasArg(options::OPT_dynamiclib)) {
6237 AddMachOArch(Args, CmdArgs);
6238 // FIXME: Why do this only on this path?
6239 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
6241 Args.AddLastArg(CmdArgs, options::OPT_bundle);
6242 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
6243 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
6246 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
6247 (A = Args.getLastArg(options::OPT_current__version)) ||
6248 (A = Args.getLastArg(options::OPT_install__name)))
6249 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
6252 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
6253 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
6254 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
6256 CmdArgs.push_back("-dylib");
6259 if ((A = Args.getLastArg(options::OPT_bundle)) ||
6260 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
6261 (A = Args.getLastArg(options::OPT_client__name)) ||
6262 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
6263 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
6264 (A = Args.getLastArg(options::OPT_private__bundle)))
6265 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
6268 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
6269 "-dylib_compatibility_version");
6270 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
6271 "-dylib_current_version");
6273 AddMachOArch(Args, CmdArgs);
6275 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
6276 "-dylib_install_name");
6279 Args.AddLastArg(CmdArgs, options::OPT_all__load);
6280 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
6281 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
6282 if (MachOTC.isTargetIOSBased())
6283 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
6284 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
6285 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
6286 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
6287 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
6288 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
6289 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
6290 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
6291 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
6292 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
6293 Args.AddAllArgs(CmdArgs, options::OPT_init);
6295 // Add the deployment target.
6296 MachOTC.addMinVersionArgs(Args, CmdArgs);
6298 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
6299 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
6300 Args.AddLastArg(CmdArgs, options::OPT_single__module);
6301 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
6302 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
6305 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
6306 options::OPT_fno_pie, options::OPT_fno_PIE)) {
6307 if (A->getOption().matches(options::OPT_fpie) ||
6308 A->getOption().matches(options::OPT_fPIE))
6309 CmdArgs.push_back("-pie");
6311 CmdArgs.push_back("-no_pie");
6314 Args.AddLastArg(CmdArgs, options::OPT_prebind);
6315 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
6316 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
6317 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
6318 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
6319 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
6320 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
6321 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
6322 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
6323 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
6324 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
6325 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
6326 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
6327 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
6328 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
6329 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
6331 // Give --sysroot= preference, over the Apple specific behavior to also use
6332 // --isysroot as the syslibroot.
6333 StringRef sysroot = C.getSysRoot();
6334 if (sysroot != "") {
6335 CmdArgs.push_back("-syslibroot");
6336 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
6337 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
6338 CmdArgs.push_back("-syslibroot");
6339 CmdArgs.push_back(A->getValue());
6342 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
6343 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
6344 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
6345 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
6346 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
6347 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
6348 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
6349 Args.AddAllArgs(CmdArgs, options::OPT_y);
6350 Args.AddLastArg(CmdArgs, options::OPT_w);
6351 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
6352 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
6353 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
6354 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
6355 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
6356 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
6357 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
6358 Args.AddLastArg(CmdArgs, options::OPT_whyload);
6359 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
6360 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
6361 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
6362 Args.AddLastArg(CmdArgs, options::OPT_Mach);
6365 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6366 const InputInfo &Output,
6367 const InputInfoList &Inputs,
6368 const ArgList &Args,
6369 const char *LinkingOutput) const {
6370 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
6372 // If the number of arguments surpasses the system limits, we will encode the
6373 // input files in a separate file, shortening the command line. To this end,
6374 // build a list of input file names that can be passed via a file with the
6375 // -filelist linker option.
6376 llvm::opt::ArgStringList InputFileList;
6378 // The logic here is derived from gcc's behavior; most of which
6379 // comes from specs (starting with link_command). Consult gcc for
6380 // more information.
6381 ArgStringList CmdArgs;
6383 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
6384 if (Args.hasArg(options::OPT_ccc_arcmt_check,
6385 options::OPT_ccc_arcmt_migrate)) {
6386 for (const auto &Arg : Args)
6389 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
6390 CmdArgs.push_back(Output.getFilename());
6391 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6395 // I'm not sure why this particular decomposition exists in gcc, but
6396 // we follow suite for ease of comparison.
6397 AddLinkArgs(C, Args, CmdArgs, Inputs);
6399 Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
6400 Args.AddAllArgs(CmdArgs, options::OPT_s);
6401 Args.AddAllArgs(CmdArgs, options::OPT_t);
6402 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6403 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
6404 Args.AddLastArg(CmdArgs, options::OPT_e);
6405 Args.AddAllArgs(CmdArgs, options::OPT_r);
6407 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
6408 // members of static archive libraries which implement Objective-C classes or
6410 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
6411 CmdArgs.push_back("-ObjC");
6413 CmdArgs.push_back("-o");
6414 CmdArgs.push_back(Output.getFilename());
6416 if (!Args.hasArg(options::OPT_nostdlib) &&
6417 !Args.hasArg(options::OPT_nostartfiles))
6418 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
6420 // SafeStack requires its own runtime libraries
6421 // These libraries should be linked first, to make sure the
6422 // __safestack_init constructor executes before everything else
6423 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
6424 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
6425 "libclang_rt.safestack_osx.a",
6426 /*AlwaysLink=*/true);
6429 Args.AddAllArgs(CmdArgs, options::OPT_L);
6431 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6432 options::OPT_fno_openmp, false)) {
6433 switch (getOpenMPRuntime(getToolChain(), Args)) {
6435 CmdArgs.push_back("-lomp");
6438 CmdArgs.push_back("-lgomp");
6441 CmdArgs.push_back("-liomp5");
6444 // Already diagnosed.
6449 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6450 // Build the input file for -filelist (list of linker input files) in case we
6452 for (const auto &II : Inputs) {
6453 if (!II.isFilename()) {
6454 // This is a linker input argument.
6455 // We cannot mix input arguments and file names in a -filelist input, thus
6456 // we prematurely stop our list (remaining files shall be passed as
6458 if (InputFileList.size() > 0)
6464 InputFileList.push_back(II.getFilename());
6467 if (isObjCRuntimeLinked(Args) && !Args.hasArg(options::OPT_nostdlib) &&
6468 !Args.hasArg(options::OPT_nodefaultlibs)) {
6469 // We use arclite library for both ARC and subscripting support.
6470 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
6472 CmdArgs.push_back("-framework");
6473 CmdArgs.push_back("Foundation");
6475 CmdArgs.push_back("-lobjc");
6478 if (LinkingOutput) {
6479 CmdArgs.push_back("-arch_multiple");
6480 CmdArgs.push_back("-final_output");
6481 CmdArgs.push_back(LinkingOutput);
6484 if (Args.hasArg(options::OPT_fnested_functions))
6485 CmdArgs.push_back("-allow_stack_execute");
6487 // TODO: It would be nice to use addProfileRT() here, but darwin's compiler-rt
6488 // paths are different enough from other toolchains that this needs a fair
6489 // amount of refactoring done first.
6490 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
6492 if (!Args.hasArg(options::OPT_nostdlib) &&
6493 !Args.hasArg(options::OPT_nodefaultlibs)) {
6494 if (getToolChain().getDriver().CCCIsCXX())
6495 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6497 // link_ssp spec is empty.
6499 // Let the tool chain choose which runtime library to link.
6500 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
6503 if (!Args.hasArg(options::OPT_nostdlib) &&
6504 !Args.hasArg(options::OPT_nostartfiles)) {
6505 // endfile_spec is empty.
6508 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6509 Args.AddAllArgs(CmdArgs, options::OPT_F);
6511 // -iframework should be forwarded as -F.
6512 for (const Arg *A : Args.filtered(options::OPT_iframework))
6513 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
6515 if (!Args.hasArg(options::OPT_nostdlib) &&
6516 !Args.hasArg(options::OPT_nodefaultlibs)) {
6517 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6518 if (A->getValue() == StringRef("Accelerate")) {
6519 CmdArgs.push_back("-framework");
6520 CmdArgs.push_back("Accelerate");
6525 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6526 std::unique_ptr<Command> Cmd =
6527 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
6528 Cmd->setInputFileList(std::move(InputFileList));
6529 C.addCommand(std::move(Cmd));
6532 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
6533 const InputInfo &Output,
6534 const InputInfoList &Inputs,
6535 const ArgList &Args,
6536 const char *LinkingOutput) const {
6537 ArgStringList CmdArgs;
6539 CmdArgs.push_back("-create");
6540 assert(Output.isFilename() && "Unexpected lipo output.");
6542 CmdArgs.push_back("-output");
6543 CmdArgs.push_back(Output.getFilename());
6545 for (const auto &II : Inputs) {
6546 assert(II.isFilename() && "Unexpected lipo input.");
6547 CmdArgs.push_back(II.getFilename());
6550 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
6551 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6554 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
6555 const InputInfo &Output,
6556 const InputInfoList &Inputs,
6557 const ArgList &Args,
6558 const char *LinkingOutput) const {
6559 ArgStringList CmdArgs;
6561 CmdArgs.push_back("-o");
6562 CmdArgs.push_back(Output.getFilename());
6564 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6565 const InputInfo &Input = Inputs[0];
6566 assert(Input.isFilename() && "Unexpected dsymutil input.");
6567 CmdArgs.push_back(Input.getFilename());
6570 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
6571 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6574 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
6575 const InputInfo &Output,
6576 const InputInfoList &Inputs,
6577 const ArgList &Args,
6578 const char *LinkingOutput) const {
6579 ArgStringList CmdArgs;
6580 CmdArgs.push_back("--verify");
6581 CmdArgs.push_back("--debug-info");
6582 CmdArgs.push_back("--eh-frame");
6583 CmdArgs.push_back("--quiet");
6585 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6586 const InputInfo &Input = Inputs[0];
6587 assert(Input.isFilename() && "Unexpected verify input");
6589 // Grabbing the output of the earlier dsymutil run.
6590 CmdArgs.push_back(Input.getFilename());
6593 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
6594 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6597 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6598 const InputInfo &Output,
6599 const InputInfoList &Inputs,
6600 const ArgList &Args,
6601 const char *LinkingOutput) const {
6602 claimNoWarnArgs(Args);
6603 ArgStringList CmdArgs;
6605 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6607 CmdArgs.push_back("-o");
6608 CmdArgs.push_back(Output.getFilename());
6610 for (const auto &II : Inputs)
6611 CmdArgs.push_back(II.getFilename());
6613 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6614 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6617 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6618 const InputInfo &Output,
6619 const InputInfoList &Inputs,
6620 const ArgList &Args,
6621 const char *LinkingOutput) const {
6622 // FIXME: Find a real GCC, don't hard-code versions here
6623 std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
6624 const llvm::Triple &T = getToolChain().getTriple();
6625 std::string LibPath = "/usr/lib/";
6626 const llvm::Triple::ArchType Arch = T.getArch();
6628 case llvm::Triple::x86:
6630 ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
6632 case llvm::Triple::x86_64:
6633 GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
6634 GCCLibPath += "/4.5.2/amd64/";
6635 LibPath += "amd64/";
6638 llvm_unreachable("Unsupported architecture");
6641 ArgStringList CmdArgs;
6643 // Demangle C++ names in errors
6644 CmdArgs.push_back("-C");
6646 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6647 (!Args.hasArg(options::OPT_shared))) {
6648 CmdArgs.push_back("-e");
6649 CmdArgs.push_back("_start");
6652 if (Args.hasArg(options::OPT_static)) {
6653 CmdArgs.push_back("-Bstatic");
6654 CmdArgs.push_back("-dn");
6656 CmdArgs.push_back("-Bdynamic");
6657 if (Args.hasArg(options::OPT_shared)) {
6658 CmdArgs.push_back("-shared");
6660 CmdArgs.push_back("--dynamic-linker");
6661 CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
6665 if (Output.isFilename()) {
6666 CmdArgs.push_back("-o");
6667 CmdArgs.push_back(Output.getFilename());
6669 assert(Output.isNothing() && "Invalid output.");
6672 if (!Args.hasArg(options::OPT_nostdlib) &&
6673 !Args.hasArg(options::OPT_nostartfiles)) {
6674 if (!Args.hasArg(options::OPT_shared)) {
6675 CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
6676 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6677 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6678 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6680 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6681 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6682 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6684 if (getToolChain().getDriver().CCCIsCXX())
6685 CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
6688 CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
6690 Args.AddAllArgs(CmdArgs, options::OPT_L);
6691 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6692 Args.AddAllArgs(CmdArgs, options::OPT_e);
6693 Args.AddAllArgs(CmdArgs, options::OPT_r);
6695 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6697 if (!Args.hasArg(options::OPT_nostdlib) &&
6698 !Args.hasArg(options::OPT_nodefaultlibs)) {
6699 if (getToolChain().getDriver().CCCIsCXX())
6700 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6701 CmdArgs.push_back("-lgcc_s");
6702 if (!Args.hasArg(options::OPT_shared)) {
6703 CmdArgs.push_back("-lgcc");
6704 CmdArgs.push_back("-lc");
6705 CmdArgs.push_back("-lm");
6709 if (!Args.hasArg(options::OPT_nostdlib) &&
6710 !Args.hasArg(options::OPT_nostartfiles)) {
6711 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
6713 CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
6715 addProfileRT(getToolChain(), Args, CmdArgs);
6717 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6718 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6721 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6722 const InputInfo &Output,
6723 const InputInfoList &Inputs,
6724 const ArgList &Args,
6725 const char *LinkingOutput) const {
6726 claimNoWarnArgs(Args);
6727 ArgStringList CmdArgs;
6728 bool NeedsKPIC = false;
6730 switch (getToolChain().getArch()) {
6731 case llvm::Triple::x86:
6732 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
6733 // instruct as in the base system to assemble 32-bit code.
6734 CmdArgs.push_back("--32");
6737 case llvm::Triple::ppc:
6738 CmdArgs.push_back("-mppc");
6739 CmdArgs.push_back("-many");
6742 case llvm::Triple::sparc:
6743 case llvm::Triple::sparcel:
6744 CmdArgs.push_back("-32");
6748 case llvm::Triple::sparcv9:
6749 CmdArgs.push_back("-64");
6750 CmdArgs.push_back("-Av9a");
6754 case llvm::Triple::mips64:
6755 case llvm::Triple::mips64el: {
6758 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6760 CmdArgs.push_back("-mabi");
6761 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6763 if (getToolChain().getArch() == llvm::Triple::mips64)
6764 CmdArgs.push_back("-EB");
6766 CmdArgs.push_back("-EL");
6777 addAssemblerKPIC(Args, CmdArgs);
6779 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6781 CmdArgs.push_back("-o");
6782 CmdArgs.push_back(Output.getFilename());
6784 for (const auto &II : Inputs)
6785 CmdArgs.push_back(II.getFilename());
6787 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6788 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6791 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6792 const InputInfo &Output,
6793 const InputInfoList &Inputs,
6794 const ArgList &Args,
6795 const char *LinkingOutput) const {
6796 const Driver &D = getToolChain().getDriver();
6797 ArgStringList CmdArgs;
6799 // Silence warning for "clang -g foo.o -o foo"
6800 Args.ClaimAllArgs(options::OPT_g_Group);
6801 // and "clang -emit-llvm foo.o -o foo"
6802 Args.ClaimAllArgs(options::OPT_emit_llvm);
6803 // and for "clang -w foo.o -o foo". Other warning options are already
6804 // handled somewhere else.
6805 Args.ClaimAllArgs(options::OPT_w);
6807 if (getToolChain().getArch() == llvm::Triple::mips64)
6808 CmdArgs.push_back("-EB");
6809 else if (getToolChain().getArch() == llvm::Triple::mips64el)
6810 CmdArgs.push_back("-EL");
6812 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6813 (!Args.hasArg(options::OPT_shared))) {
6814 CmdArgs.push_back("-e");
6815 CmdArgs.push_back("__start");
6818 if (Args.hasArg(options::OPT_static)) {
6819 CmdArgs.push_back("-Bstatic");
6821 if (Args.hasArg(options::OPT_rdynamic))
6822 CmdArgs.push_back("-export-dynamic");
6823 CmdArgs.push_back("--eh-frame-hdr");
6824 CmdArgs.push_back("-Bdynamic");
6825 if (Args.hasArg(options::OPT_shared)) {
6826 CmdArgs.push_back("-shared");
6828 CmdArgs.push_back("-dynamic-linker");
6829 CmdArgs.push_back("/usr/libexec/ld.so");
6833 if (Args.hasArg(options::OPT_nopie))
6834 CmdArgs.push_back("-nopie");
6836 if (Output.isFilename()) {
6837 CmdArgs.push_back("-o");
6838 CmdArgs.push_back(Output.getFilename());
6840 assert(Output.isNothing() && "Invalid output.");
6843 if (!Args.hasArg(options::OPT_nostdlib) &&
6844 !Args.hasArg(options::OPT_nostartfiles)) {
6845 if (!Args.hasArg(options::OPT_shared)) {
6846 if (Args.hasArg(options::OPT_pg))
6848 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
6851 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
6853 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6856 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6860 std::string Triple = getToolChain().getTripleString();
6861 if (Triple.substr(0, 6) == "x86_64")
6862 Triple.replace(0, 6, "amd64");
6864 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
6866 Args.AddAllArgs(CmdArgs, options::OPT_L);
6867 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6868 Args.AddAllArgs(CmdArgs, options::OPT_e);
6869 Args.AddAllArgs(CmdArgs, options::OPT_s);
6870 Args.AddAllArgs(CmdArgs, options::OPT_t);
6871 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6872 Args.AddAllArgs(CmdArgs, options::OPT_r);
6874 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6876 if (!Args.hasArg(options::OPT_nostdlib) &&
6877 !Args.hasArg(options::OPT_nodefaultlibs)) {
6879 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6880 if (Args.hasArg(options::OPT_pg))
6881 CmdArgs.push_back("-lm_p");
6883 CmdArgs.push_back("-lm");
6886 // FIXME: For some reason GCC passes -lgcc before adding
6887 // the default system libraries. Just mimic this for now.
6888 CmdArgs.push_back("-lgcc");
6890 if (Args.hasArg(options::OPT_pthread)) {
6891 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
6892 CmdArgs.push_back("-lpthread_p");
6894 CmdArgs.push_back("-lpthread");
6897 if (!Args.hasArg(options::OPT_shared)) {
6898 if (Args.hasArg(options::OPT_pg))
6899 CmdArgs.push_back("-lc_p");
6901 CmdArgs.push_back("-lc");
6904 CmdArgs.push_back("-lgcc");
6907 if (!Args.hasArg(options::OPT_nostdlib) &&
6908 !Args.hasArg(options::OPT_nostartfiles)) {
6909 if (!Args.hasArg(options::OPT_shared))
6911 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
6914 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
6917 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6918 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6921 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6922 const InputInfo &Output,
6923 const InputInfoList &Inputs,
6924 const ArgList &Args,
6925 const char *LinkingOutput) const {
6926 claimNoWarnArgs(Args);
6927 ArgStringList CmdArgs;
6929 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6931 CmdArgs.push_back("-o");
6932 CmdArgs.push_back(Output.getFilename());
6934 for (const auto &II : Inputs)
6935 CmdArgs.push_back(II.getFilename());
6937 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6938 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6941 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6942 const InputInfo &Output,
6943 const InputInfoList &Inputs,
6944 const ArgList &Args,
6945 const char *LinkingOutput) const {
6946 const Driver &D = getToolChain().getDriver();
6947 ArgStringList CmdArgs;
6949 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6950 (!Args.hasArg(options::OPT_shared))) {
6951 CmdArgs.push_back("-e");
6952 CmdArgs.push_back("__start");
6955 if (Args.hasArg(options::OPT_static)) {
6956 CmdArgs.push_back("-Bstatic");
6958 if (Args.hasArg(options::OPT_rdynamic))
6959 CmdArgs.push_back("-export-dynamic");
6960 CmdArgs.push_back("--eh-frame-hdr");
6961 CmdArgs.push_back("-Bdynamic");
6962 if (Args.hasArg(options::OPT_shared)) {
6963 CmdArgs.push_back("-shared");
6965 CmdArgs.push_back("-dynamic-linker");
6966 CmdArgs.push_back("/usr/libexec/ld.so");
6970 if (Output.isFilename()) {
6971 CmdArgs.push_back("-o");
6972 CmdArgs.push_back(Output.getFilename());
6974 assert(Output.isNothing() && "Invalid output.");
6977 if (!Args.hasArg(options::OPT_nostdlib) &&
6978 !Args.hasArg(options::OPT_nostartfiles)) {
6979 if (!Args.hasArg(options::OPT_shared)) {
6980 if (Args.hasArg(options::OPT_pg))
6982 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
6985 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
6987 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6990 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6994 Args.AddAllArgs(CmdArgs, options::OPT_L);
6995 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6996 Args.AddAllArgs(CmdArgs, options::OPT_e);
6998 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7000 if (!Args.hasArg(options::OPT_nostdlib) &&
7001 !Args.hasArg(options::OPT_nodefaultlibs)) {
7003 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7004 if (Args.hasArg(options::OPT_pg))
7005 CmdArgs.push_back("-lm_p");
7007 CmdArgs.push_back("-lm");
7010 if (Args.hasArg(options::OPT_pthread)) {
7011 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7012 CmdArgs.push_back("-lpthread_p");
7014 CmdArgs.push_back("-lpthread");
7017 if (!Args.hasArg(options::OPT_shared)) {
7018 if (Args.hasArg(options::OPT_pg))
7019 CmdArgs.push_back("-lc_p");
7021 CmdArgs.push_back("-lc");
7025 switch (getToolChain().getArch()) {
7026 case llvm::Triple::arm:
7029 case llvm::Triple::x86:
7032 case llvm::Triple::x86_64:
7036 llvm_unreachable("Unsupported architecture");
7038 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7041 if (!Args.hasArg(options::OPT_nostdlib) &&
7042 !Args.hasArg(options::OPT_nostartfiles)) {
7043 if (!Args.hasArg(options::OPT_shared))
7045 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7048 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7051 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7052 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7055 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7056 const InputInfo &Output,
7057 const InputInfoList &Inputs,
7058 const ArgList &Args,
7059 const char *LinkingOutput) const {
7060 claimNoWarnArgs(Args);
7061 ArgStringList CmdArgs;
7063 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7064 // instruct as in the base system to assemble 32-bit code.
7065 if (getToolChain().getArch() == llvm::Triple::x86)
7066 CmdArgs.push_back("--32");
7067 else if (getToolChain().getArch() == llvm::Triple::ppc)
7068 CmdArgs.push_back("-a32");
7069 else if (getToolChain().getArch() == llvm::Triple::mips ||
7070 getToolChain().getArch() == llvm::Triple::mipsel ||
7071 getToolChain().getArch() == llvm::Triple::mips64 ||
7072 getToolChain().getArch() == llvm::Triple::mips64el) {
7075 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7077 CmdArgs.push_back("-march");
7078 CmdArgs.push_back(CPUName.data());
7080 CmdArgs.push_back("-mabi");
7081 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7083 if (getToolChain().getArch() == llvm::Triple::mips ||
7084 getToolChain().getArch() == llvm::Triple::mips64)
7085 CmdArgs.push_back("-EB");
7087 CmdArgs.push_back("-EL");
7089 addAssemblerKPIC(Args, CmdArgs);
7090 } else if (getToolChain().getArch() == llvm::Triple::arm ||
7091 getToolChain().getArch() == llvm::Triple::armeb ||
7092 getToolChain().getArch() == llvm::Triple::thumb ||
7093 getToolChain().getArch() == llvm::Triple::thumbeb) {
7094 const Driver &D = getToolChain().getDriver();
7095 const llvm::Triple &Triple = getToolChain().getTriple();
7096 StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
7098 if (FloatABI == "hard") {
7099 CmdArgs.push_back("-mfpu=vfp");
7101 CmdArgs.push_back("-mfpu=softvfp");
7104 switch (getToolChain().getTriple().getEnvironment()) {
7105 case llvm::Triple::GNUEABIHF:
7106 case llvm::Triple::GNUEABI:
7107 case llvm::Triple::EABI:
7108 CmdArgs.push_back("-meabi=5");
7112 CmdArgs.push_back("-matpcs");
7114 } else if (getToolChain().getArch() == llvm::Triple::sparc ||
7115 getToolChain().getArch() == llvm::Triple::sparcel ||
7116 getToolChain().getArch() == llvm::Triple::sparcv9) {
7117 if (getToolChain().getArch() == llvm::Triple::sparc)
7118 CmdArgs.push_back("-Av8plusa");
7120 CmdArgs.push_back("-Av9a");
7122 addAssemblerKPIC(Args, CmdArgs);
7125 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7127 CmdArgs.push_back("-o");
7128 CmdArgs.push_back(Output.getFilename());
7130 for (const auto &II : Inputs)
7131 CmdArgs.push_back(II.getFilename());
7133 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7134 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7137 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7138 const InputInfo &Output,
7139 const InputInfoList &Inputs,
7140 const ArgList &Args,
7141 const char *LinkingOutput) const {
7142 const toolchains::FreeBSD &ToolChain =
7143 static_cast<const toolchains::FreeBSD &>(getToolChain());
7144 const Driver &D = ToolChain.getDriver();
7145 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7147 !Args.hasArg(options::OPT_shared) &&
7148 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7149 ArgStringList CmdArgs;
7151 // Silence warning for "clang -g foo.o -o foo"
7152 Args.ClaimAllArgs(options::OPT_g_Group);
7153 // and "clang -emit-llvm foo.o -o foo"
7154 Args.ClaimAllArgs(options::OPT_emit_llvm);
7155 // and for "clang -w foo.o -o foo". Other warning options are already
7156 // handled somewhere else.
7157 Args.ClaimAllArgs(options::OPT_w);
7159 if (!D.SysRoot.empty())
7160 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7163 CmdArgs.push_back("-pie");
7165 if (Args.hasArg(options::OPT_static)) {
7166 CmdArgs.push_back("-Bstatic");
7168 if (Args.hasArg(options::OPT_rdynamic))
7169 CmdArgs.push_back("-export-dynamic");
7170 CmdArgs.push_back("--eh-frame-hdr");
7171 if (Args.hasArg(options::OPT_shared)) {
7172 CmdArgs.push_back("-Bshareable");
7174 CmdArgs.push_back("-dynamic-linker");
7175 CmdArgs.push_back("/libexec/ld-elf.so.1");
7177 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7178 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7179 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7180 CmdArgs.push_back("--hash-style=both");
7183 CmdArgs.push_back("--enable-new-dtags");
7186 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7187 // instruct ld in the base system to link 32-bit code.
7188 if (Arch == llvm::Triple::x86) {
7189 CmdArgs.push_back("-m");
7190 CmdArgs.push_back("elf_i386_fbsd");
7193 if (Arch == llvm::Triple::ppc) {
7194 CmdArgs.push_back("-m");
7195 CmdArgs.push_back("elf32ppc_fbsd");
7198 if (Output.isFilename()) {
7199 CmdArgs.push_back("-o");
7200 CmdArgs.push_back(Output.getFilename());
7202 assert(Output.isNothing() && "Invalid output.");
7205 if (!Args.hasArg(options::OPT_nostdlib) &&
7206 !Args.hasArg(options::OPT_nostartfiles)) {
7207 const char *crt1 = nullptr;
7208 if (!Args.hasArg(options::OPT_shared)) {
7209 if (Args.hasArg(options::OPT_pg))
7217 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7219 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7221 const char *crtbegin = nullptr;
7222 if (Args.hasArg(options::OPT_static))
7223 crtbegin = "crtbeginT.o";
7224 else if (Args.hasArg(options::OPT_shared) || IsPIE)
7225 crtbegin = "crtbeginS.o";
7227 crtbegin = "crtbegin.o";
7229 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7232 Args.AddAllArgs(CmdArgs, options::OPT_L);
7233 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
7234 for (const auto &Path : Paths)
7235 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
7236 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7237 Args.AddAllArgs(CmdArgs, options::OPT_e);
7238 Args.AddAllArgs(CmdArgs, options::OPT_s);
7239 Args.AddAllArgs(CmdArgs, options::OPT_t);
7240 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7241 Args.AddAllArgs(CmdArgs, options::OPT_r);
7243 if (D.IsUsingLTO(Args))
7244 AddGoldPlugin(ToolChain, Args, CmdArgs);
7246 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7247 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7249 if (!Args.hasArg(options::OPT_nostdlib) &&
7250 !Args.hasArg(options::OPT_nodefaultlibs)) {
7252 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7253 if (Args.hasArg(options::OPT_pg))
7254 CmdArgs.push_back("-lm_p");
7256 CmdArgs.push_back("-lm");
7258 if (NeedsSanitizerDeps)
7259 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7260 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7261 // the default system libraries. Just mimic this for now.
7262 if (Args.hasArg(options::OPT_pg))
7263 CmdArgs.push_back("-lgcc_p");
7265 CmdArgs.push_back("-lgcc");
7266 if (Args.hasArg(options::OPT_static)) {
7267 CmdArgs.push_back("-lgcc_eh");
7268 } else if (Args.hasArg(options::OPT_pg)) {
7269 CmdArgs.push_back("-lgcc_eh_p");
7271 CmdArgs.push_back("--as-needed");
7272 CmdArgs.push_back("-lgcc_s");
7273 CmdArgs.push_back("--no-as-needed");
7276 if (Args.hasArg(options::OPT_pthread)) {
7277 if (Args.hasArg(options::OPT_pg))
7278 CmdArgs.push_back("-lpthread_p");
7280 CmdArgs.push_back("-lpthread");
7283 if (Args.hasArg(options::OPT_pg)) {
7284 if (Args.hasArg(options::OPT_shared))
7285 CmdArgs.push_back("-lc");
7287 CmdArgs.push_back("-lc_p");
7288 CmdArgs.push_back("-lgcc_p");
7290 CmdArgs.push_back("-lc");
7291 CmdArgs.push_back("-lgcc");
7294 if (Args.hasArg(options::OPT_static)) {
7295 CmdArgs.push_back("-lgcc_eh");
7296 } else if (Args.hasArg(options::OPT_pg)) {
7297 CmdArgs.push_back("-lgcc_eh_p");
7299 CmdArgs.push_back("--as-needed");
7300 CmdArgs.push_back("-lgcc_s");
7301 CmdArgs.push_back("--no-as-needed");
7305 if (!Args.hasArg(options::OPT_nostdlib) &&
7306 !Args.hasArg(options::OPT_nostartfiles)) {
7307 if (Args.hasArg(options::OPT_shared) || IsPIE)
7308 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
7310 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7311 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7314 addProfileRT(ToolChain, Args, CmdArgs);
7316 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7317 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7320 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7321 const InputInfo &Output,
7322 const InputInfoList &Inputs,
7323 const ArgList &Args,
7324 const char *LinkingOutput) const {
7325 claimNoWarnArgs(Args);
7326 ArgStringList CmdArgs;
7328 // GNU as needs different flags for creating the correct output format
7329 // on architectures with different ABIs or optional feature sets.
7330 switch (getToolChain().getArch()) {
7331 case llvm::Triple::x86:
7332 CmdArgs.push_back("--32");
7334 case llvm::Triple::arm:
7335 case llvm::Triple::armeb:
7336 case llvm::Triple::thumb:
7337 case llvm::Triple::thumbeb: {
7338 std::string MArch = arm::getARMTargetCPU(Args, getToolChain().getTriple());
7339 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
7343 case llvm::Triple::mips:
7344 case llvm::Triple::mipsel:
7345 case llvm::Triple::mips64:
7346 case llvm::Triple::mips64el: {
7349 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7351 CmdArgs.push_back("-march");
7352 CmdArgs.push_back(CPUName.data());
7354 CmdArgs.push_back("-mabi");
7355 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7357 if (getToolChain().getArch() == llvm::Triple::mips ||
7358 getToolChain().getArch() == llvm::Triple::mips64)
7359 CmdArgs.push_back("-EB");
7361 CmdArgs.push_back("-EL");
7363 addAssemblerKPIC(Args, CmdArgs);
7367 case llvm::Triple::sparc:
7368 case llvm::Triple::sparcel:
7369 CmdArgs.push_back("-32");
7370 addAssemblerKPIC(Args, CmdArgs);
7373 case llvm::Triple::sparcv9:
7374 CmdArgs.push_back("-64");
7375 CmdArgs.push_back("-Av9");
7376 addAssemblerKPIC(Args, CmdArgs);
7383 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7385 CmdArgs.push_back("-o");
7386 CmdArgs.push_back(Output.getFilename());
7388 for (const auto &II : Inputs)
7389 CmdArgs.push_back(II.getFilename());
7391 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
7392 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7395 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7396 const InputInfo &Output,
7397 const InputInfoList &Inputs,
7398 const ArgList &Args,
7399 const char *LinkingOutput) const {
7400 const Driver &D = getToolChain().getDriver();
7401 ArgStringList CmdArgs;
7403 if (!D.SysRoot.empty())
7404 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7406 CmdArgs.push_back("--eh-frame-hdr");
7407 if (Args.hasArg(options::OPT_static)) {
7408 CmdArgs.push_back("-Bstatic");
7410 if (Args.hasArg(options::OPT_rdynamic))
7411 CmdArgs.push_back("-export-dynamic");
7412 if (Args.hasArg(options::OPT_shared)) {
7413 CmdArgs.push_back("-Bshareable");
7415 CmdArgs.push_back("-dynamic-linker");
7416 CmdArgs.push_back("/libexec/ld.elf_so");
7420 // Many NetBSD architectures support more than one ABI.
7421 // Determine the correct emulation for ld.
7422 switch (getToolChain().getArch()) {
7423 case llvm::Triple::x86:
7424 CmdArgs.push_back("-m");
7425 CmdArgs.push_back("elf_i386");
7427 case llvm::Triple::arm:
7428 case llvm::Triple::thumb:
7429 CmdArgs.push_back("-m");
7430 switch (getToolChain().getTriple().getEnvironment()) {
7431 case llvm::Triple::EABI:
7432 case llvm::Triple::GNUEABI:
7433 CmdArgs.push_back("armelf_nbsd_eabi");
7435 case llvm::Triple::EABIHF:
7436 case llvm::Triple::GNUEABIHF:
7437 CmdArgs.push_back("armelf_nbsd_eabihf");
7440 CmdArgs.push_back("armelf_nbsd");
7444 case llvm::Triple::armeb:
7445 case llvm::Triple::thumbeb:
7446 arm::appendEBLinkFlags(
7448 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7449 CmdArgs.push_back("-m");
7450 switch (getToolChain().getTriple().getEnvironment()) {
7451 case llvm::Triple::EABI:
7452 case llvm::Triple::GNUEABI:
7453 CmdArgs.push_back("armelfb_nbsd_eabi");
7455 case llvm::Triple::EABIHF:
7456 case llvm::Triple::GNUEABIHF:
7457 CmdArgs.push_back("armelfb_nbsd_eabihf");
7460 CmdArgs.push_back("armelfb_nbsd");
7464 case llvm::Triple::mips64:
7465 case llvm::Triple::mips64el:
7466 if (mips::hasMipsAbiArg(Args, "32")) {
7467 CmdArgs.push_back("-m");
7468 if (getToolChain().getArch() == llvm::Triple::mips64)
7469 CmdArgs.push_back("elf32btsmip");
7471 CmdArgs.push_back("elf32ltsmip");
7472 } else if (mips::hasMipsAbiArg(Args, "64")) {
7473 CmdArgs.push_back("-m");
7474 if (getToolChain().getArch() == llvm::Triple::mips64)
7475 CmdArgs.push_back("elf64btsmip");
7477 CmdArgs.push_back("elf64ltsmip");
7480 case llvm::Triple::ppc:
7481 CmdArgs.push_back("-m");
7482 CmdArgs.push_back("elf32ppc_nbsd");
7485 case llvm::Triple::ppc64:
7486 case llvm::Triple::ppc64le:
7487 CmdArgs.push_back("-m");
7488 CmdArgs.push_back("elf64ppc");
7491 case llvm::Triple::sparc:
7492 CmdArgs.push_back("-m");
7493 CmdArgs.push_back("elf32_sparc");
7496 case llvm::Triple::sparcv9:
7497 CmdArgs.push_back("-m");
7498 CmdArgs.push_back("elf64_sparc");
7505 if (Output.isFilename()) {
7506 CmdArgs.push_back("-o");
7507 CmdArgs.push_back(Output.getFilename());
7509 assert(Output.isNothing() && "Invalid output.");
7512 if (!Args.hasArg(options::OPT_nostdlib) &&
7513 !Args.hasArg(options::OPT_nostartfiles)) {
7514 if (!Args.hasArg(options::OPT_shared)) {
7516 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7518 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7520 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7523 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7525 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7529 Args.AddAllArgs(CmdArgs, options::OPT_L);
7530 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7531 Args.AddAllArgs(CmdArgs, options::OPT_e);
7532 Args.AddAllArgs(CmdArgs, options::OPT_s);
7533 Args.AddAllArgs(CmdArgs, options::OPT_t);
7534 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7535 Args.AddAllArgs(CmdArgs, options::OPT_r);
7537 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7539 unsigned Major, Minor, Micro;
7540 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
7541 bool useLibgcc = true;
7542 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
7543 switch (getToolChain().getArch()) {
7544 case llvm::Triple::aarch64:
7545 case llvm::Triple::arm:
7546 case llvm::Triple::armeb:
7547 case llvm::Triple::thumb:
7548 case llvm::Triple::thumbeb:
7549 case llvm::Triple::ppc:
7550 case llvm::Triple::ppc64:
7551 case llvm::Triple::ppc64le:
7552 case llvm::Triple::x86:
7553 case llvm::Triple::x86_64:
7561 if (!Args.hasArg(options::OPT_nostdlib) &&
7562 !Args.hasArg(options::OPT_nodefaultlibs)) {
7564 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7565 CmdArgs.push_back("-lm");
7567 if (Args.hasArg(options::OPT_pthread))
7568 CmdArgs.push_back("-lpthread");
7569 CmdArgs.push_back("-lc");
7572 if (Args.hasArg(options::OPT_static)) {
7573 // libgcc_eh depends on libc, so resolve as much as possible,
7574 // pull in any new requirements from libc and then get the rest
7576 CmdArgs.push_back("-lgcc_eh");
7577 CmdArgs.push_back("-lc");
7578 CmdArgs.push_back("-lgcc");
7580 CmdArgs.push_back("-lgcc");
7581 CmdArgs.push_back("--as-needed");
7582 CmdArgs.push_back("-lgcc_s");
7583 CmdArgs.push_back("--no-as-needed");
7588 if (!Args.hasArg(options::OPT_nostdlib) &&
7589 !Args.hasArg(options::OPT_nostartfiles)) {
7590 if (!Args.hasArg(options::OPT_shared))
7592 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7595 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7596 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7599 addProfileRT(getToolChain(), Args, CmdArgs);
7601 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7602 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7605 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7606 const InputInfo &Output,
7607 const InputInfoList &Inputs,
7608 const ArgList &Args,
7609 const char *LinkingOutput) const {
7610 claimNoWarnArgs(Args);
7612 ArgStringList CmdArgs;
7613 bool NeedsKPIC = false;
7615 switch (getToolChain().getArch()) {
7618 // Add --32/--64 to make sure we get the format we want.
7619 // This is incomplete
7620 case llvm::Triple::x86:
7621 CmdArgs.push_back("--32");
7623 case llvm::Triple::x86_64:
7624 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
7625 CmdArgs.push_back("--x32");
7627 CmdArgs.push_back("--64");
7629 case llvm::Triple::ppc:
7630 CmdArgs.push_back("-a32");
7631 CmdArgs.push_back("-mppc");
7632 CmdArgs.push_back("-many");
7634 case llvm::Triple::ppc64:
7635 CmdArgs.push_back("-a64");
7636 CmdArgs.push_back("-mppc64");
7637 CmdArgs.push_back("-many");
7639 case llvm::Triple::ppc64le:
7640 CmdArgs.push_back("-a64");
7641 CmdArgs.push_back("-mppc64");
7642 CmdArgs.push_back("-many");
7643 CmdArgs.push_back("-mlittle-endian");
7645 case llvm::Triple::sparc:
7646 case llvm::Triple::sparcel:
7647 CmdArgs.push_back("-32");
7648 CmdArgs.push_back("-Av8plusa");
7651 case llvm::Triple::sparcv9:
7652 CmdArgs.push_back("-64");
7653 CmdArgs.push_back("-Av9a");
7656 case llvm::Triple::arm:
7657 case llvm::Triple::armeb:
7658 case llvm::Triple::thumb:
7659 case llvm::Triple::thumbeb: {
7660 const llvm::Triple &Triple = getToolChain().getTriple();
7661 switch (Triple.getSubArch()) {
7662 case llvm::Triple::ARMSubArch_v7:
7663 CmdArgs.push_back("-mfpu=neon");
7665 case llvm::Triple::ARMSubArch_v8:
7666 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
7672 StringRef ARMFloatABI = tools::arm::getARMFloatABI(
7673 getToolChain().getDriver(), Args,
7674 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7675 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
7677 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
7679 // FIXME: remove krait check when GNU tools support krait cpu
7680 // for now replace it with -march=armv7-a to avoid a lower
7681 // march from being picked in the absence of a cpu flag.
7683 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
7684 StringRef(A->getValue()).lower() == "krait")
7685 CmdArgs.push_back("-march=armv7-a");
7687 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
7688 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
7691 case llvm::Triple::mips:
7692 case llvm::Triple::mipsel:
7693 case llvm::Triple::mips64:
7694 case llvm::Triple::mips64el: {
7697 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7698 ABIName = getGnuCompatibleMipsABIName(ABIName);
7700 CmdArgs.push_back("-march");
7701 CmdArgs.push_back(CPUName.data());
7703 CmdArgs.push_back("-mabi");
7704 CmdArgs.push_back(ABIName.data());
7706 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
7707 // or -mshared (not implemented) is in effect.
7708 bool IsPicOrPie = false;
7709 if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
7710 options::OPT_fpic, options::OPT_fno_pic,
7711 options::OPT_fPIE, options::OPT_fno_PIE,
7712 options::OPT_fpie, options::OPT_fno_pie)) {
7713 if (A->getOption().matches(options::OPT_fPIC) ||
7714 A->getOption().matches(options::OPT_fpic) ||
7715 A->getOption().matches(options::OPT_fPIE) ||
7716 A->getOption().matches(options::OPT_fpie))
7720 CmdArgs.push_back("-mno-shared");
7722 // LLVM doesn't support -mplt yet and acts as if it is always given.
7723 // However, -mplt has no effect with the N64 ABI.
7724 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
7726 if (getToolChain().getArch() == llvm::Triple::mips ||
7727 getToolChain().getArch() == llvm::Triple::mips64)
7728 CmdArgs.push_back("-EB");
7730 CmdArgs.push_back("-EL");
7732 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
7733 if (StringRef(A->getValue()) == "2008")
7734 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
7737 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
7738 StringRef MIPSFloatABI = getMipsFloatABI(getToolChain().getDriver(), Args);
7739 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
7740 options::OPT_mfp64)) {
7742 A->render(Args, CmdArgs);
7743 } else if (mips::shouldUseFPXX(Args, getToolChain().getTriple(), CPUName,
7744 ABIName, MIPSFloatABI))
7745 CmdArgs.push_back("-mfpxx");
7747 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
7748 // -mno-mips16 is actually -no-mips16.
7750 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
7751 if (A->getOption().matches(options::OPT_mips16)) {
7753 A->render(Args, CmdArgs);
7756 CmdArgs.push_back("-no-mips16");
7760 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
7761 options::OPT_mno_micromips);
7762 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
7763 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
7765 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
7766 // Do not use AddLastArg because not all versions of MIPS assembler
7767 // support -mmsa / -mno-msa options.
7768 if (A->getOption().matches(options::OPT_mmsa))
7769 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
7772 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
7773 options::OPT_msoft_float);
7775 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
7776 options::OPT_msingle_float);
7778 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
7779 options::OPT_mno_odd_spreg);
7784 case llvm::Triple::systemz: {
7785 // Always pass an -march option, since our default of z10 is later
7786 // than the GNU assembler's default.
7787 StringRef CPUName = getSystemZTargetCPU(Args);
7788 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
7794 addAssemblerKPIC(Args, CmdArgs);
7796 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7798 CmdArgs.push_back("-o");
7799 CmdArgs.push_back(Output.getFilename());
7801 for (const auto &II : Inputs)
7802 CmdArgs.push_back(II.getFilename());
7804 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7805 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7807 // Handle the debug info splitting at object creation time if we're
7808 // creating an object.
7809 // TODO: Currently only works on linux with newer objcopy.
7810 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7811 getToolChain().getTriple().isOSLinux())
7812 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7813 SplitDebugName(Args, Inputs[0]));
7816 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
7817 ArgStringList &CmdArgs, const ArgList &Args) {
7818 bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
7819 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
7820 Args.hasArg(options::OPT_static);
7822 CmdArgs.push_back("-lgcc");
7824 if (StaticLibgcc || isAndroid) {
7826 CmdArgs.push_back("-lgcc");
7829 CmdArgs.push_back("--as-needed");
7830 CmdArgs.push_back("-lgcc_s");
7832 CmdArgs.push_back("--no-as-needed");
7835 if (StaticLibgcc && !isAndroid)
7836 CmdArgs.push_back("-lgcc_eh");
7837 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
7838 CmdArgs.push_back("-lgcc");
7840 // According to Android ABI, we have to link with libdl if we are
7841 // linking with non-static libgcc.
7843 // NOTE: This fixes a link error on Android MIPS as well. The non-static
7844 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
7845 if (isAndroid && !StaticLibgcc)
7846 CmdArgs.push_back("-ldl");
7849 static std::string getLinuxDynamicLinker(const ArgList &Args,
7850 const toolchains::Linux &ToolChain) {
7851 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7853 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
7854 if (ToolChain.getTriple().isArch64Bit())
7855 return "/system/bin/linker64";
7857 return "/system/bin/linker";
7858 } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
7859 Arch == llvm::Triple::sparcel)
7860 return "/lib/ld-linux.so.2";
7861 else if (Arch == llvm::Triple::aarch64)
7862 return "/lib/ld-linux-aarch64.so.1";
7863 else if (Arch == llvm::Triple::aarch64_be)
7864 return "/lib/ld-linux-aarch64_be.so.1";
7865 else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
7866 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7867 return "/lib/ld-linux-armhf.so.3";
7869 return "/lib/ld-linux.so.3";
7870 } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
7871 // TODO: check which dynamic linker name.
7872 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7873 return "/lib/ld-linux-armhf.so.3";
7875 return "/lib/ld-linux.so.3";
7876 } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
7877 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
7880 mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
7881 bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
7883 StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
7884 .Case("o32", "/lib")
7885 .Case("n32", "/lib32")
7886 .Case("n64", "/lib64")
7889 if (mips::isUCLibc(Args))
7890 LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
7892 LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
7894 return (LibDir + "/" + LibName).str();
7895 } else if (Arch == llvm::Triple::ppc)
7896 return "/lib/ld.so.1";
7897 else if (Arch == llvm::Triple::ppc64) {
7898 if (ppc::hasPPCAbiArg(Args, "elfv2"))
7899 return "/lib64/ld64.so.2";
7900 return "/lib64/ld64.so.1";
7901 } else if (Arch == llvm::Triple::ppc64le) {
7902 if (ppc::hasPPCAbiArg(Args, "elfv1"))
7903 return "/lib64/ld64.so.1";
7904 return "/lib64/ld64.so.2";
7905 } else if (Arch == llvm::Triple::systemz)
7906 return "/lib64/ld64.so.1";
7907 else if (Arch == llvm::Triple::sparcv9)
7908 return "/lib64/ld-linux.so.2";
7909 else if (Arch == llvm::Triple::x86_64 &&
7910 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
7911 return "/libx32/ld-linux-x32.so.2";
7913 return "/lib64/ld-linux-x86-64.so.2";
7916 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
7917 ArgStringList &CmdArgs, const ArgList &Args) {
7918 // Make use of compiler-rt if --rtlib option is used
7919 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
7922 case ToolChain::RLT_CompilerRT:
7923 switch (TC.getTriple().getOS()) {
7925 llvm_unreachable("unsupported OS");
7926 case llvm::Triple::Win32:
7927 case llvm::Triple::Linux:
7928 addClangRT(TC, Args, CmdArgs);
7932 case ToolChain::RLT_Libgcc:
7933 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
7938 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
7939 switch (T.getArch()) {
7940 case llvm::Triple::x86:
7942 case llvm::Triple::aarch64:
7943 return "aarch64linux";
7944 case llvm::Triple::aarch64_be:
7945 return "aarch64_be_linux";
7946 case llvm::Triple::arm:
7947 case llvm::Triple::thumb:
7948 return "armelf_linux_eabi";
7949 case llvm::Triple::armeb:
7950 case llvm::Triple::thumbeb:
7951 return "armebelf_linux_eabi"; /* TODO: check which NAME. */
7952 case llvm::Triple::ppc:
7953 return "elf32ppclinux";
7954 case llvm::Triple::ppc64:
7956 case llvm::Triple::ppc64le:
7958 case llvm::Triple::sparc:
7959 case llvm::Triple::sparcel:
7960 return "elf32_sparc";
7961 case llvm::Triple::sparcv9:
7962 return "elf64_sparc";
7963 case llvm::Triple::mips:
7964 return "elf32btsmip";
7965 case llvm::Triple::mipsel:
7966 return "elf32ltsmip";
7967 case llvm::Triple::mips64:
7968 if (mips::hasMipsAbiArg(Args, "n32"))
7969 return "elf32btsmipn32";
7970 return "elf64btsmip";
7971 case llvm::Triple::mips64el:
7972 if (mips::hasMipsAbiArg(Args, "n32"))
7973 return "elf32ltsmipn32";
7974 return "elf64ltsmip";
7975 case llvm::Triple::systemz:
7976 return "elf64_s390";
7977 case llvm::Triple::x86_64:
7978 if (T.getEnvironment() == llvm::Triple::GNUX32)
7979 return "elf32_x86_64";
7980 return "elf_x86_64";
7982 llvm_unreachable("Unexpected arch");
7986 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7987 const InputInfo &Output,
7988 const InputInfoList &Inputs,
7989 const ArgList &Args,
7990 const char *LinkingOutput) const {
7991 const toolchains::Linux &ToolChain =
7992 static_cast<const toolchains::Linux &>(getToolChain());
7993 const Driver &D = ToolChain.getDriver();
7994 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7995 const bool isAndroid =
7996 ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
7998 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
7999 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8001 ArgStringList CmdArgs;
8003 // Silence warning for "clang -g foo.o -o foo"
8004 Args.ClaimAllArgs(options::OPT_g_Group);
8005 // and "clang -emit-llvm foo.o -o foo"
8006 Args.ClaimAllArgs(options::OPT_emit_llvm);
8007 // and for "clang -w foo.o -o foo". Other warning options are already
8008 // handled somewhere else.
8009 Args.ClaimAllArgs(options::OPT_w);
8011 if (!D.SysRoot.empty())
8012 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8015 CmdArgs.push_back("-pie");
8017 if (Args.hasArg(options::OPT_rdynamic))
8018 CmdArgs.push_back("-export-dynamic");
8020 if (Args.hasArg(options::OPT_s))
8021 CmdArgs.push_back("-s");
8023 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8024 arm::appendEBLinkFlags(
8026 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8028 for (const auto &Opt : ToolChain.ExtraOpts)
8029 CmdArgs.push_back(Opt.c_str());
8031 if (!Args.hasArg(options::OPT_static)) {
8032 CmdArgs.push_back("--eh-frame-hdr");
8035 CmdArgs.push_back("-m");
8036 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8038 if (Args.hasArg(options::OPT_static)) {
8039 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8040 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8041 CmdArgs.push_back("-Bstatic");
8043 CmdArgs.push_back("-static");
8044 } else if (Args.hasArg(options::OPT_shared)) {
8045 CmdArgs.push_back("-shared");
8048 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8049 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8050 (!Args.hasArg(options::OPT_static) &&
8051 !Args.hasArg(options::OPT_shared))) {
8052 CmdArgs.push_back("-dynamic-linker");
8053 CmdArgs.push_back(Args.MakeArgString(
8054 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8057 CmdArgs.push_back("-o");
8058 CmdArgs.push_back(Output.getFilename());
8060 if (!Args.hasArg(options::OPT_nostdlib) &&
8061 !Args.hasArg(options::OPT_nostartfiles)) {
8063 const char *crt1 = nullptr;
8064 if (!Args.hasArg(options::OPT_shared)) {
8065 if (Args.hasArg(options::OPT_pg))
8073 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8075 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8078 const char *crtbegin;
8079 if (Args.hasArg(options::OPT_static))
8080 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8081 else if (Args.hasArg(options::OPT_shared))
8082 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8084 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8086 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8087 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8089 // Add crtfastmath.o if available and fast math is enabled.
8090 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8093 Args.AddAllArgs(CmdArgs, options::OPT_L);
8094 Args.AddAllArgs(CmdArgs, options::OPT_u);
8096 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8098 for (const auto &Path : Paths)
8099 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8101 if (D.IsUsingLTO(Args))
8102 AddGoldPlugin(ToolChain, Args, CmdArgs);
8104 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8105 CmdArgs.push_back("--no-demangle");
8107 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8108 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8109 // The profile runtime also needs access to system libraries.
8110 addProfileRT(getToolChain(), Args, CmdArgs);
8112 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8113 !Args.hasArg(options::OPT_nodefaultlibs)) {
8114 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8115 !Args.hasArg(options::OPT_static);
8116 if (OnlyLibstdcxxStatic)
8117 CmdArgs.push_back("-Bstatic");
8118 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8119 if (OnlyLibstdcxxStatic)
8120 CmdArgs.push_back("-Bdynamic");
8121 CmdArgs.push_back("-lm");
8123 // Silence warnings when linking C code with a C++ '-stdlib' argument.
8124 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8126 if (!Args.hasArg(options::OPT_nostdlib)) {
8127 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8128 if (Args.hasArg(options::OPT_static))
8129 CmdArgs.push_back("--start-group");
8131 if (NeedsSanitizerDeps)
8132 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8134 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8135 Args.hasArg(options::OPT_pthreads);
8137 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8138 options::OPT_fno_openmp, false)) {
8139 // OpenMP runtimes implies pthreads when using the GNU toolchain.
8140 // FIXME: Does this really make sense for all GNU toolchains?
8143 // Also link the particular OpenMP runtimes.
8144 switch (getOpenMPRuntime(ToolChain, Args)) {
8146 CmdArgs.push_back("-lomp");
8149 CmdArgs.push_back("-lgomp");
8151 // FIXME: Exclude this for platforms with libgomp that don't require
8152 // librt. Most modern Linux platforms require it, but some may not.
8153 CmdArgs.push_back("-lrt");
8156 CmdArgs.push_back("-liomp5");
8159 // Already diagnosed.
8164 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8166 if (WantPthread && !isAndroid)
8167 CmdArgs.push_back("-lpthread");
8169 CmdArgs.push_back("-lc");
8171 if (Args.hasArg(options::OPT_static))
8172 CmdArgs.push_back("--end-group");
8174 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8177 if (!Args.hasArg(options::OPT_nostartfiles)) {
8179 if (Args.hasArg(options::OPT_shared))
8180 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8182 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8184 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8186 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8188 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8193 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8196 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8197 // for the various SFI requirements like register masking. The assembly tool
8198 // inserts the file containing the macros as an input into all the assembly
8200 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8201 const InputInfo &Output,
8202 const InputInfoList &Inputs,
8203 const ArgList &Args,
8204 const char *LinkingOutput) const {
8205 const toolchains::NaCl_TC &ToolChain =
8206 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8207 InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8208 "nacl-arm-macros.s");
8209 InputInfoList NewInputs;
8210 NewInputs.push_back(NaClMacros);
8211 NewInputs.append(Inputs.begin(), Inputs.end());
8212 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8216 // This is quite similar to gnutools::Linker::ConstructJob with changes that
8217 // we use static by default, do not yet support sanitizers or LTO, and a few
8218 // others. Eventually we can support more of that and hopefully migrate back
8219 // to gnutools::Linker.
8220 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8221 const InputInfo &Output,
8222 const InputInfoList &Inputs,
8223 const ArgList &Args,
8224 const char *LinkingOutput) const {
8226 const toolchains::NaCl_TC &ToolChain =
8227 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8228 const Driver &D = ToolChain.getDriver();
8229 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8230 const bool IsStatic =
8231 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8233 ArgStringList CmdArgs;
8235 // Silence warning for "clang -g foo.o -o foo"
8236 Args.ClaimAllArgs(options::OPT_g_Group);
8237 // and "clang -emit-llvm foo.o -o foo"
8238 Args.ClaimAllArgs(options::OPT_emit_llvm);
8239 // and for "clang -w foo.o -o foo". Other warning options are already
8240 // handled somewhere else.
8241 Args.ClaimAllArgs(options::OPT_w);
8243 if (!D.SysRoot.empty())
8244 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8246 if (Args.hasArg(options::OPT_rdynamic))
8247 CmdArgs.push_back("-export-dynamic");
8249 if (Args.hasArg(options::OPT_s))
8250 CmdArgs.push_back("-s");
8252 // NaCl_TC doesn't have ExtraOpts like Linux; the only relevant flag from
8253 // there is --build-id, which we do want.
8254 CmdArgs.push_back("--build-id");
8257 CmdArgs.push_back("--eh-frame-hdr");
8259 CmdArgs.push_back("-m");
8260 if (Arch == llvm::Triple::x86)
8261 CmdArgs.push_back("elf_i386_nacl");
8262 else if (Arch == llvm::Triple::arm)
8263 CmdArgs.push_back("armelf_nacl");
8264 else if (Arch == llvm::Triple::x86_64)
8265 CmdArgs.push_back("elf_x86_64_nacl");
8266 else if (Arch == llvm::Triple::mipsel)
8267 CmdArgs.push_back("mipselelf_nacl");
8269 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
8273 CmdArgs.push_back("-static");
8274 else if (Args.hasArg(options::OPT_shared))
8275 CmdArgs.push_back("-shared");
8277 CmdArgs.push_back("-o");
8278 CmdArgs.push_back(Output.getFilename());
8279 if (!Args.hasArg(options::OPT_nostdlib) &&
8280 !Args.hasArg(options::OPT_nostartfiles)) {
8281 if (!Args.hasArg(options::OPT_shared))
8282 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
8283 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8285 const char *crtbegin;
8287 crtbegin = "crtbeginT.o";
8288 else if (Args.hasArg(options::OPT_shared))
8289 crtbegin = "crtbeginS.o";
8291 crtbegin = "crtbegin.o";
8292 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8295 Args.AddAllArgs(CmdArgs, options::OPT_L);
8296 Args.AddAllArgs(CmdArgs, options::OPT_u);
8298 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8300 for (const auto &Path : Paths)
8301 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8303 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8304 CmdArgs.push_back("--no-demangle");
8306 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8308 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8309 !Args.hasArg(options::OPT_nodefaultlibs)) {
8310 bool OnlyLibstdcxxStatic =
8311 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
8312 if (OnlyLibstdcxxStatic)
8313 CmdArgs.push_back("-Bstatic");
8314 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8315 if (OnlyLibstdcxxStatic)
8316 CmdArgs.push_back("-Bdynamic");
8317 CmdArgs.push_back("-lm");
8320 if (!Args.hasArg(options::OPT_nostdlib)) {
8321 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8322 // Always use groups, since it has no effect on dynamic libraries.
8323 CmdArgs.push_back("--start-group");
8324 CmdArgs.push_back("-lc");
8325 // NaCl's libc++ currently requires libpthread, so just always include it
8326 // in the group for C++.
8327 if (Args.hasArg(options::OPT_pthread) ||
8328 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
8329 // Gold, used by Mips, handles nested groups differently than ld, and
8330 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
8331 // which is not a desired behaviour here.
8332 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
8333 if (getToolChain().getArch() == llvm::Triple::mipsel)
8334 CmdArgs.push_back("-lnacl");
8336 CmdArgs.push_back("-lpthread");
8339 CmdArgs.push_back("-lgcc");
8340 CmdArgs.push_back("--as-needed");
8342 CmdArgs.push_back("-lgcc_eh");
8344 CmdArgs.push_back("-lgcc_s");
8345 CmdArgs.push_back("--no-as-needed");
8347 // Mips needs to create and use pnacl_legacy library that contains
8348 // definitions from bitcode/pnaclmm.c and definitions for
8349 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
8350 if (getToolChain().getArch() == llvm::Triple::mipsel)
8351 CmdArgs.push_back("-lpnacl_legacy");
8353 CmdArgs.push_back("--end-group");
8356 if (!Args.hasArg(options::OPT_nostartfiles)) {
8358 if (Args.hasArg(options::OPT_shared))
8359 crtend = "crtendS.o";
8361 crtend = "crtend.o";
8363 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8364 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8369 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8372 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8373 const InputInfo &Output,
8374 const InputInfoList &Inputs,
8375 const ArgList &Args,
8376 const char *LinkingOutput) const {
8377 claimNoWarnArgs(Args);
8378 ArgStringList CmdArgs;
8380 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8382 CmdArgs.push_back("-o");
8383 CmdArgs.push_back(Output.getFilename());
8385 for (const auto &II : Inputs)
8386 CmdArgs.push_back(II.getFilename());
8388 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8389 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8392 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8393 const InputInfo &Output,
8394 const InputInfoList &Inputs,
8395 const ArgList &Args,
8396 const char *LinkingOutput) const {
8397 const Driver &D = getToolChain().getDriver();
8398 ArgStringList CmdArgs;
8400 if (Output.isFilename()) {
8401 CmdArgs.push_back("-o");
8402 CmdArgs.push_back(Output.getFilename());
8404 assert(Output.isNothing() && "Invalid output.");
8407 if (!Args.hasArg(options::OPT_nostdlib) &&
8408 !Args.hasArg(options::OPT_nostartfiles)) {
8409 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8410 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8412 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8413 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8416 Args.AddAllArgs(CmdArgs, options::OPT_L);
8417 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8418 Args.AddAllArgs(CmdArgs, options::OPT_e);
8420 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8422 addProfileRT(getToolChain(), Args, CmdArgs);
8424 if (!Args.hasArg(options::OPT_nostdlib) &&
8425 !Args.hasArg(options::OPT_nodefaultlibs)) {
8427 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8428 CmdArgs.push_back("-lm");
8432 if (!Args.hasArg(options::OPT_nostdlib) &&
8433 !Args.hasArg(options::OPT_nostartfiles)) {
8434 if (Args.hasArg(options::OPT_pthread))
8435 CmdArgs.push_back("-lpthread");
8436 CmdArgs.push_back("-lc");
8437 CmdArgs.push_back("-lCompilerRT-Generic");
8438 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
8440 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8443 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8444 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8449 // For now, DragonFly Assemble does just about the same as for
8450 // FreeBSD, but this may change soon.
8451 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8452 const InputInfo &Output,
8453 const InputInfoList &Inputs,
8454 const ArgList &Args,
8455 const char *LinkingOutput) const {
8456 claimNoWarnArgs(Args);
8457 ArgStringList CmdArgs;
8459 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8460 // instruct as in the base system to assemble 32-bit code.
8461 if (getToolChain().getArch() == llvm::Triple::x86)
8462 CmdArgs.push_back("--32");
8464 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8466 CmdArgs.push_back("-o");
8467 CmdArgs.push_back(Output.getFilename());
8469 for (const auto &II : Inputs)
8470 CmdArgs.push_back(II.getFilename());
8472 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8473 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8476 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8477 const InputInfo &Output,
8478 const InputInfoList &Inputs,
8479 const ArgList &Args,
8480 const char *LinkingOutput) const {
8481 const Driver &D = getToolChain().getDriver();
8482 ArgStringList CmdArgs;
8483 bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
8485 if (!D.SysRoot.empty())
8486 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8488 CmdArgs.push_back("--eh-frame-hdr");
8489 if (Args.hasArg(options::OPT_static)) {
8490 CmdArgs.push_back("-Bstatic");
8492 if (Args.hasArg(options::OPT_rdynamic))
8493 CmdArgs.push_back("-export-dynamic");
8494 if (Args.hasArg(options::OPT_shared))
8495 CmdArgs.push_back("-Bshareable");
8497 CmdArgs.push_back("-dynamic-linker");
8498 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
8500 CmdArgs.push_back("--hash-style=both");
8503 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8504 // instruct ld in the base system to link 32-bit code.
8505 if (getToolChain().getArch() == llvm::Triple::x86) {
8506 CmdArgs.push_back("-m");
8507 CmdArgs.push_back("elf_i386");
8510 if (Output.isFilename()) {
8511 CmdArgs.push_back("-o");
8512 CmdArgs.push_back(Output.getFilename());
8514 assert(Output.isNothing() && "Invalid output.");
8517 if (!Args.hasArg(options::OPT_nostdlib) &&
8518 !Args.hasArg(options::OPT_nostartfiles)) {
8519 if (!Args.hasArg(options::OPT_shared)) {
8520 if (Args.hasArg(options::OPT_pg))
8522 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
8524 if (Args.hasArg(options::OPT_pie))
8526 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
8529 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8532 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8533 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8535 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8538 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8541 Args.AddAllArgs(CmdArgs, options::OPT_L);
8542 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8543 Args.AddAllArgs(CmdArgs, options::OPT_e);
8545 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8547 if (!Args.hasArg(options::OPT_nostdlib) &&
8548 !Args.hasArg(options::OPT_nodefaultlibs)) {
8549 // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
8552 CmdArgs.push_back("-L/usr/lib/gcc47");
8554 CmdArgs.push_back("-L/usr/lib/gcc44");
8556 if (!Args.hasArg(options::OPT_static)) {
8558 CmdArgs.push_back("-rpath");
8559 CmdArgs.push_back("/usr/lib/gcc47");
8561 CmdArgs.push_back("-rpath");
8562 CmdArgs.push_back("/usr/lib/gcc44");
8567 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8568 CmdArgs.push_back("-lm");
8571 if (Args.hasArg(options::OPT_pthread))
8572 CmdArgs.push_back("-lpthread");
8574 if (!Args.hasArg(options::OPT_nolibc)) {
8575 CmdArgs.push_back("-lc");
8579 if (Args.hasArg(options::OPT_static) ||
8580 Args.hasArg(options::OPT_static_libgcc)) {
8581 CmdArgs.push_back("-lgcc");
8582 CmdArgs.push_back("-lgcc_eh");
8584 if (Args.hasArg(options::OPT_shared_libgcc)) {
8585 CmdArgs.push_back("-lgcc_pic");
8586 if (!Args.hasArg(options::OPT_shared))
8587 CmdArgs.push_back("-lgcc");
8589 CmdArgs.push_back("-lgcc");
8590 CmdArgs.push_back("--as-needed");
8591 CmdArgs.push_back("-lgcc_pic");
8592 CmdArgs.push_back("--no-as-needed");
8596 if (Args.hasArg(options::OPT_shared)) {
8597 CmdArgs.push_back("-lgcc_pic");
8599 CmdArgs.push_back("-lgcc");
8604 if (!Args.hasArg(options::OPT_nostdlib) &&
8605 !Args.hasArg(options::OPT_nostartfiles)) {
8606 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8608 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8611 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8612 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8615 addProfileRT(getToolChain(), Args, CmdArgs);
8617 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8618 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8621 // Try to find Exe from a Visual Studio distribution. This first tries to find
8622 // an installed copy of Visual Studio and, failing that, looks in the PATH,
8623 // making sure that whatever executable that's found is not a same-named exe
8624 // from clang itself to prevent clang from falling back to itself.
8625 static std::string FindVisualStudioExecutable(const ToolChain &TC,
8627 const char *ClangProgramPath) {
8628 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8629 std::string visualStudioBinDir;
8630 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
8631 visualStudioBinDir)) {
8632 SmallString<128> FilePath(visualStudioBinDir);
8633 llvm::sys::path::append(FilePath, Exe);
8634 if (llvm::sys::fs::can_execute(FilePath.c_str()))
8635 return FilePath.str();
8641 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8642 const InputInfo &Output,
8643 const InputInfoList &Inputs,
8644 const ArgList &Args,
8645 const char *LinkingOutput) const {
8646 ArgStringList CmdArgs;
8647 const ToolChain &TC = getToolChain();
8649 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
8650 if (Output.isFilename())
8652 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
8654 if (!Args.hasArg(options::OPT_nostdlib) &&
8655 !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
8656 CmdArgs.push_back("-defaultlib:libcmt");
8658 if (!llvm::sys::Process::GetEnv("LIB")) {
8659 // If the VC environment hasn't been configured (perhaps because the user
8660 // did not run vcvarsall), try to build a consistent link environment. If
8661 // the environment variable is set however, assume the user knows what
8663 std::string VisualStudioDir;
8664 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8665 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
8666 SmallString<128> LibDir(VisualStudioDir);
8667 llvm::sys::path::append(LibDir, "VC", "lib");
8668 switch (MSVC.getArch()) {
8669 case llvm::Triple::x86:
8670 // x86 just puts the libraries directly in lib
8672 case llvm::Triple::x86_64:
8673 llvm::sys::path::append(LibDir, "amd64");
8675 case llvm::Triple::arm:
8676 llvm::sys::path::append(LibDir, "arm");
8682 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
8685 std::string WindowsSdkLibPath;
8686 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
8687 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
8688 WindowsSdkLibPath.c_str()));
8691 CmdArgs.push_back("-nologo");
8693 if (Args.hasArg(options::OPT_g_Group))
8694 CmdArgs.push_back("-debug");
8696 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
8697 options::OPT_shared);
8699 CmdArgs.push_back(Args.MakeArgString("-dll"));
8701 SmallString<128> ImplibName(Output.getFilename());
8702 llvm::sys::path::replace_extension(ImplibName, "lib");
8703 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
8706 if (TC.getSanitizerArgs().needsAsanRt()) {
8707 CmdArgs.push_back(Args.MakeArgString("-debug"));
8708 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
8709 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
8710 static const char *CompilerRTComponents[] = {
8711 "asan_dynamic", "asan_dynamic_runtime_thunk",
8713 for (const auto &Component : CompilerRTComponents)
8714 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8715 // Make sure the dynamic runtime thunk is not optimized out at link time
8716 // to ensure proper SEH handling.
8717 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
8720 Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
8722 static const char *CompilerRTComponents[] = {
8725 for (const auto &Component : CompilerRTComponents)
8726 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8730 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
8732 // Add filenames, libraries, and other linker inputs.
8733 for (const auto &Input : Inputs) {
8734 if (Input.isFilename()) {
8735 CmdArgs.push_back(Input.getFilename());
8739 const Arg &A = Input.getInputArg();
8741 // Render -l options differently for the MSVC linker.
8742 if (A.getOption().matches(options::OPT_l)) {
8743 StringRef Lib = A.getValue();
8744 const char *LinkLibArg;
8745 if (Lib.endswith(".lib"))
8746 LinkLibArg = Args.MakeArgString(Lib);
8748 LinkLibArg = Args.MakeArgString(Lib + ".lib");
8749 CmdArgs.push_back(LinkLibArg);
8753 // Otherwise, this is some other kind of linker input option like -Wl, -z,
8754 // or -L. Render it, even if MSVC doesn't understand it.
8755 A.renderAsInput(Args, CmdArgs);
8758 // We need to special case some linker paths. In the case of lld, we need to
8759 // translate 'lld' into 'lld-link', and in the case of the regular msvc
8760 // linker, we need to use a special search algorithm.
8761 llvm::SmallString<128> linkPath;
8762 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
8763 if (Linker.equals_lower("lld"))
8764 Linker = "lld-link";
8766 if (Linker.equals_lower("link")) {
8767 // If we're using the MSVC linker, it's not sufficient to just use link
8768 // from the program PATH, because other environments like GnuWin32 install
8769 // their own link.exe which may come first.
8770 linkPath = FindVisualStudioExecutable(TC, "link.exe",
8771 C.getDriver().getClangProgramPath());
8774 llvm::sys::path::replace_extension(linkPath, "exe");
8775 linkPath = TC.GetProgramPath(linkPath.c_str());
8778 const char *Exec = Args.MakeArgString(linkPath);
8779 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8782 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
8783 const InputInfo &Output,
8784 const InputInfoList &Inputs,
8785 const ArgList &Args,
8786 const char *LinkingOutput) const {
8787 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
8790 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
8791 Compilation &C, const JobAction &JA, const InputInfo &Output,
8792 const InputInfoList &Inputs, const ArgList &Args,
8793 const char *LinkingOutput) const {
8794 ArgStringList CmdArgs;
8795 CmdArgs.push_back("/nologo");
8796 CmdArgs.push_back("/c"); // Compile only.
8797 CmdArgs.push_back("/W0"); // No warnings.
8799 // The goal is to be able to invoke this tool correctly based on
8800 // any flag accepted by clang-cl.
8802 // These are spelled the same way in clang and cl.exe,.
8803 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
8804 Args.AddAllArgs(CmdArgs, options::OPT_I);
8806 // Optimization level.
8807 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
8808 if (A->getOption().getID() == options::OPT_O0) {
8809 CmdArgs.push_back("/Od");
8811 StringRef OptLevel = A->getValue();
8812 if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
8813 A->render(Args, CmdArgs);
8814 else if (OptLevel == "3")
8815 CmdArgs.push_back("/Ox");
8819 // Flags for which clang-cl has an alias.
8820 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
8822 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8824 CmdArgs.push_back("/GR-");
8825 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
8826 options::OPT_fno_function_sections))
8827 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
8830 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
8831 options::OPT_fno_data_sections))
8833 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
8834 if (Args.hasArg(options::OPT_fsyntax_only))
8835 CmdArgs.push_back("/Zs");
8836 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
8837 CmdArgs.push_back("/Z7");
8839 std::vector<std::string> Includes =
8840 Args.getAllArgValues(options::OPT_include);
8841 for (const auto &Include : Includes)
8842 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
8844 // Flags that can simply be passed through.
8845 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
8846 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
8847 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
8849 // The order of these flags is relevant, so pick the last one.
8850 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
8851 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
8852 A->render(Args, CmdArgs);
8855 assert(Inputs.size() == 1);
8856 const InputInfo &II = Inputs[0];
8857 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
8858 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
8859 if (II.isFilename())
8860 CmdArgs.push_back(II.getFilename());
8862 II.getInputArg().renderAsInput(Args, CmdArgs);
8865 assert(Output.getType() == types::TY_Object);
8867 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
8868 CmdArgs.push_back(Fo);
8870 const Driver &D = getToolChain().getDriver();
8871 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
8872 D.getClangProgramPath());
8873 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
8878 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8879 const InputInfo &Output,
8880 const InputInfoList &Inputs,
8881 const ArgList &Args,
8882 const char *LinkingOutput) const {
8883 claimNoWarnArgs(Args);
8884 ArgStringList CmdArgs;
8886 if (getToolChain().getArch() == llvm::Triple::x86) {
8887 CmdArgs.push_back("--32");
8888 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
8889 CmdArgs.push_back("--64");
8892 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8894 CmdArgs.push_back("-o");
8895 CmdArgs.push_back(Output.getFilename());
8897 for (const auto &II : Inputs)
8898 CmdArgs.push_back(II.getFilename());
8900 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8901 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8903 if (Args.hasArg(options::OPT_gsplit_dwarf))
8904 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8905 SplitDebugName(Args, Inputs[0]));
8908 void MinGW::Linker::AddLibGCC(const ArgList &Args,
8909 ArgStringList &CmdArgs) const {
8910 if (Args.hasArg(options::OPT_mthreads))
8911 CmdArgs.push_back("-lmingwthrd");
8912 CmdArgs.push_back("-lmingw32");
8913 if (Args.hasArg(options::OPT_shared) ||
8914 Args.hasArg(options::OPT_shared_libgcc) ||
8915 !Args.hasArg(options::OPT_static_libgcc)) {
8916 CmdArgs.push_back("-lgcc_s");
8917 CmdArgs.push_back("-lgcc");
8919 CmdArgs.push_back("-lgcc");
8920 CmdArgs.push_back("-lgcc_eh");
8922 CmdArgs.push_back("-lmoldname");
8923 CmdArgs.push_back("-lmingwex");
8924 CmdArgs.push_back("-lmsvcrt");
8927 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8928 const InputInfo &Output,
8929 const InputInfoList &Inputs,
8930 const ArgList &Args,
8931 const char *LinkingOutput) const {
8932 const ToolChain &TC = getToolChain();
8933 const Driver &D = TC.getDriver();
8934 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
8936 ArgStringList CmdArgs;
8938 // Silence warning for "clang -g foo.o -o foo"
8939 Args.ClaimAllArgs(options::OPT_g_Group);
8940 // and "clang -emit-llvm foo.o -o foo"
8941 Args.ClaimAllArgs(options::OPT_emit_llvm);
8942 // and for "clang -w foo.o -o foo". Other warning options are already
8943 // handled somewhere else.
8944 Args.ClaimAllArgs(options::OPT_w);
8946 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
8947 if (LinkerName.equals_lower("lld")) {
8948 CmdArgs.push_back("-flavor");
8949 CmdArgs.push_back("gnu");
8952 if (!D.SysRoot.empty())
8953 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8955 if (Args.hasArg(options::OPT_s))
8956 CmdArgs.push_back("-s");
8958 CmdArgs.push_back("-m");
8959 if (TC.getArch() == llvm::Triple::x86)
8960 CmdArgs.push_back("i386pe");
8961 if (TC.getArch() == llvm::Triple::x86_64)
8962 CmdArgs.push_back("i386pep");
8963 if (TC.getArch() == llvm::Triple::arm)
8964 CmdArgs.push_back("thumb2pe");
8966 if (Args.hasArg(options::OPT_mwindows)) {
8967 CmdArgs.push_back("--subsystem");
8968 CmdArgs.push_back("windows");
8969 } else if (Args.hasArg(options::OPT_mconsole)) {
8970 CmdArgs.push_back("--subsystem");
8971 CmdArgs.push_back("console");
8974 if (Args.hasArg(options::OPT_static))
8975 CmdArgs.push_back("-Bstatic");
8977 if (Args.hasArg(options::OPT_mdll))
8978 CmdArgs.push_back("--dll");
8979 else if (Args.hasArg(options::OPT_shared))
8980 CmdArgs.push_back("--shared");
8981 CmdArgs.push_back("-Bdynamic");
8982 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
8983 CmdArgs.push_back("-e");
8984 if (TC.getArch() == llvm::Triple::x86)
8985 CmdArgs.push_back("_DllMainCRTStartup@12");
8987 CmdArgs.push_back("DllMainCRTStartup");
8988 CmdArgs.push_back("--enable-auto-image-base");
8992 CmdArgs.push_back("-o");
8993 CmdArgs.push_back(Output.getFilename());
8995 Args.AddAllArgs(CmdArgs, options::OPT_e);
8996 // FIXME: add -N, -n flags
8997 Args.AddLastArg(CmdArgs, options::OPT_r);
8998 Args.AddLastArg(CmdArgs, options::OPT_s);
8999 Args.AddLastArg(CmdArgs, options::OPT_t);
9000 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9001 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9003 if (!Args.hasArg(options::OPT_nostdlib) &&
9004 !Args.hasArg(options::OPT_nostartfiles)) {
9005 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9006 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9008 if (Args.hasArg(options::OPT_municode))
9009 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9011 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9013 if (Args.hasArg(options::OPT_pg))
9014 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9015 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9018 Args.AddAllArgs(CmdArgs, options::OPT_L);
9019 const ToolChain::path_list Paths = TC.getFilePaths();
9020 for (const auto &Path : Paths)
9021 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9023 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9025 // TODO: Add ASan stuff here
9027 // TODO: Add profile stuff here
9029 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9030 !Args.hasArg(options::OPT_nodefaultlibs)) {
9031 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9032 !Args.hasArg(options::OPT_static);
9033 if (OnlyLibstdcxxStatic)
9034 CmdArgs.push_back("-Bstatic");
9035 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9036 if (OnlyLibstdcxxStatic)
9037 CmdArgs.push_back("-Bdynamic");
9040 if (!Args.hasArg(options::OPT_nostdlib)) {
9041 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9042 if (Args.hasArg(options::OPT_static))
9043 CmdArgs.push_back("--start-group");
9045 if (Args.hasArg(options::OPT_fstack_protector) ||
9046 Args.hasArg(options::OPT_fstack_protector_strong) ||
9047 Args.hasArg(options::OPT_fstack_protector_all)) {
9048 CmdArgs.push_back("-lssp_nonshared");
9049 CmdArgs.push_back("-lssp");
9051 if (Args.hasArg(options::OPT_fopenmp))
9052 CmdArgs.push_back("-lgomp");
9054 AddLibGCC(Args, CmdArgs);
9056 if (Args.hasArg(options::OPT_pg))
9057 CmdArgs.push_back("-lgmon");
9059 if (Args.hasArg(options::OPT_pthread))
9060 CmdArgs.push_back("-lpthread");
9062 // add system libraries
9063 if (Args.hasArg(options::OPT_mwindows)) {
9064 CmdArgs.push_back("-lgdi32");
9065 CmdArgs.push_back("-lcomdlg32");
9067 CmdArgs.push_back("-ladvapi32");
9068 CmdArgs.push_back("-lshell32");
9069 CmdArgs.push_back("-luser32");
9070 CmdArgs.push_back("-lkernel32");
9072 if (Args.hasArg(options::OPT_static))
9073 CmdArgs.push_back("--end-group");
9074 else if (!LinkerName.equals_lower("lld"))
9075 AddLibGCC(Args, CmdArgs);
9078 if (!Args.hasArg(options::OPT_nostartfiles)) {
9079 // Add crtfastmath.o if available and fast math is enabled.
9080 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9082 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9085 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9086 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9090 // We pass assemble and link construction to the xcc tool.
9092 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9093 const InputInfo &Output,
9094 const InputInfoList &Inputs,
9095 const ArgList &Args,
9096 const char *LinkingOutput) const {
9097 claimNoWarnArgs(Args);
9098 ArgStringList CmdArgs;
9100 CmdArgs.push_back("-o");
9101 CmdArgs.push_back(Output.getFilename());
9103 CmdArgs.push_back("-c");
9105 if (Args.hasArg(options::OPT_v))
9106 CmdArgs.push_back("-v");
9108 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9109 if (!A->getOption().matches(options::OPT_g0))
9110 CmdArgs.push_back("-g");
9112 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9114 CmdArgs.push_back("-fverbose-asm");
9116 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9118 for (const auto &II : Inputs)
9119 CmdArgs.push_back(II.getFilename());
9121 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9122 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9125 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9126 const InputInfo &Output,
9127 const InputInfoList &Inputs,
9128 const ArgList &Args,
9129 const char *LinkingOutput) const {
9130 ArgStringList CmdArgs;
9132 if (Output.isFilename()) {
9133 CmdArgs.push_back("-o");
9134 CmdArgs.push_back(Output.getFilename());
9136 assert(Output.isNothing() && "Invalid output.");
9139 if (Args.hasArg(options::OPT_v))
9140 CmdArgs.push_back("-v");
9142 // Pass -fexceptions through to the linker if it was present.
9143 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9145 CmdArgs.push_back("-fexceptions");
9147 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9149 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9150 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9153 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9154 const InputInfo &Output,
9155 const InputInfoList &Inputs,
9156 const ArgList &Args,
9157 const char *LinkingOutput) const {
9158 claimNoWarnArgs(Args);
9160 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9161 ArgStringList CmdArgs;
9164 switch (TC.getArch()) {
9166 llvm_unreachable("unsupported architecture");
9167 case llvm::Triple::arm:
9168 case llvm::Triple::thumb:
9170 case llvm::Triple::x86:
9171 CmdArgs.push_back("--32");
9173 case llvm::Triple::x86_64:
9174 CmdArgs.push_back("--64");
9178 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9180 CmdArgs.push_back("-o");
9181 CmdArgs.push_back(Output.getFilename());
9183 for (const auto &Input : Inputs)
9184 CmdArgs.push_back(Input.getFilename());
9186 const std::string Assembler = TC.GetProgramPath("as");
9187 Exec = Args.MakeArgString(Assembler);
9189 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9192 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9193 const InputInfo &Output,
9194 const InputInfoList &Inputs,
9195 const ArgList &Args,
9196 const char *LinkingOutput) const {
9198 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9199 const llvm::Triple &T = TC.getTriple();
9200 const Driver &D = TC.getDriver();
9201 SmallString<128> EntryPoint;
9202 ArgStringList CmdArgs;
9205 // Silence warning for "clang -g foo.o -o foo"
9206 Args.ClaimAllArgs(options::OPT_g_Group);
9207 // and "clang -emit-llvm foo.o -o foo"
9208 Args.ClaimAllArgs(options::OPT_emit_llvm);
9209 // and for "clang -w foo.o -o foo"
9210 Args.ClaimAllArgs(options::OPT_w);
9211 // Other warning options are already handled somewhere else.
9213 if (!D.SysRoot.empty())
9214 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9216 if (Args.hasArg(options::OPT_pie))
9217 CmdArgs.push_back("-pie");
9218 if (Args.hasArg(options::OPT_rdynamic))
9219 CmdArgs.push_back("-export-dynamic");
9220 if (Args.hasArg(options::OPT_s))
9221 CmdArgs.push_back("--strip-all");
9223 CmdArgs.push_back("-m");
9224 switch (TC.getArch()) {
9226 llvm_unreachable("unsupported architecture");
9227 case llvm::Triple::arm:
9228 case llvm::Triple::thumb:
9229 // FIXME: this is incorrect for WinCE
9230 CmdArgs.push_back("thumb2pe");
9232 case llvm::Triple::x86:
9233 CmdArgs.push_back("i386pe");
9234 EntryPoint.append("_");
9236 case llvm::Triple::x86_64:
9237 CmdArgs.push_back("i386pep");
9241 if (Args.hasArg(options::OPT_shared)) {
9242 switch (T.getArch()) {
9244 llvm_unreachable("unsupported architecture");
9245 case llvm::Triple::arm:
9246 case llvm::Triple::thumb:
9247 case llvm::Triple::x86_64:
9248 EntryPoint.append("_DllMainCRTStartup");
9250 case llvm::Triple::x86:
9251 EntryPoint.append("_DllMainCRTStartup@12");
9255 CmdArgs.push_back("-shared");
9256 CmdArgs.push_back("-Bdynamic");
9258 CmdArgs.push_back("--enable-auto-image-base");
9260 CmdArgs.push_back("--entry");
9261 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9263 EntryPoint.append("mainCRTStartup");
9265 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
9268 if (!Args.hasArg(options::OPT_nostdlib) &&
9269 !Args.hasArg(options::OPT_nostartfiles)) {
9270 CmdArgs.push_back("--entry");
9271 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9274 // FIXME: handle subsystem
9277 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
9278 CmdArgs.push_back("--allow-multiple-definition");
9280 CmdArgs.push_back("-o");
9281 CmdArgs.push_back(Output.getFilename());
9283 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
9284 SmallString<261> ImpLib(Output.getFilename());
9285 llvm::sys::path::replace_extension(ImpLib, ".lib");
9287 CmdArgs.push_back("--out-implib");
9288 CmdArgs.push_back(Args.MakeArgString(ImpLib));
9291 if (!Args.hasArg(options::OPT_nostdlib) &&
9292 !Args.hasArg(options::OPT_nostartfiles)) {
9293 const std::string CRTPath(D.SysRoot + "/usr/lib/");
9294 const char *CRTBegin;
9297 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
9298 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
9301 Args.AddAllArgs(CmdArgs, options::OPT_L);
9303 const auto &Paths = TC.getFilePaths();
9304 for (const auto &Path : Paths)
9305 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9307 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9309 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9310 !Args.hasArg(options::OPT_nodefaultlibs)) {
9311 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
9312 !Args.hasArg(options::OPT_static);
9314 CmdArgs.push_back("-Bstatic");
9315 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9317 CmdArgs.push_back("-Bdynamic");
9320 if (!Args.hasArg(options::OPT_nostdlib)) {
9321 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9322 // TODO handle /MT[d] /MD[d]
9323 CmdArgs.push_back("-lmsvcrt");
9324 AddRunTimeLibs(TC, D, CmdArgs, Args);
9328 const std::string Linker = TC.GetProgramPath("ld");
9329 Exec = Args.MakeArgString(Linker);
9331 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9334 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9335 const InputInfo &Output,
9336 const InputInfoList &Inputs,
9337 const ArgList &Args,
9338 const char *LinkingOutput) const {
9340 ArgStringList CmdArgs;
9342 assert(Inputs.size() == 1);
9343 const InputInfo &II = Inputs[0];
9344 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9345 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
9347 // Append all -I, -iquote, -isystem paths.
9348 Args.AddAllArgs(CmdArgs, options::OPT_clang_i_Group);
9349 // These are spelled the same way in clang and moviCompile.
9350 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
9352 CmdArgs.push_back("-DMYRIAD2");
9353 CmdArgs.push_back("-mcpu=myriad2");
9354 CmdArgs.push_back("-S");
9356 // Any -O option passes through without translation. What about -Ofast ?
9357 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
9358 A->render(Args, CmdArgs);
9360 if (Args.hasFlag(options::OPT_ffunction_sections,
9361 options::OPT_fno_function_sections)) {
9362 CmdArgs.push_back("-ffunction-sections");
9364 if (Args.hasArg(options::OPT_fno_inline_functions))
9365 CmdArgs.push_back("-fno-inline-functions");
9367 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
9369 CmdArgs.push_back(II.getFilename());
9370 CmdArgs.push_back("-o");
9371 CmdArgs.push_back(Output.getFilename());
9374 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
9376 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
9379 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9380 const InputInfo &Output,
9381 const InputInfoList &Inputs,
9382 const ArgList &Args,
9383 const char *LinkingOutput) const {
9384 ArgStringList CmdArgs;
9386 assert(Inputs.size() == 1);
9387 const InputInfo &II = Inputs[0];
9388 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
9389 assert(Output.getType() == types::TY_Object);
9391 CmdArgs.push_back("-no6thSlotCompression");
9392 CmdArgs.push_back("-cv:myriad2"); // Chip Version ?
9393 CmdArgs.push_back("-noSPrefixing");
9394 CmdArgs.push_back("-a"); // Mystery option.
9395 for (auto Arg : Args.filtered(options::OPT_I)) {
9398 Args.MakeArgString(std::string("-i:") + Arg->getValue(0)));
9400 CmdArgs.push_back("-elf"); // Output format.
9401 CmdArgs.push_back(II.getFilename());
9403 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
9406 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
9408 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));