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/LangOptions.h"
14 #include "clang/Basic/ObjCRuntime.h"
15 #include "clang/Basic/Version.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/DriverDiagnostic.h"
20 #include "clang/Driver/Job.h"
21 #include "clang/Driver/Options.h"
22 #include "clang/Driver/SanitizerArgs.h"
23 #include "clang/Driver/ToolChain.h"
24 #include "clang/Driver/Util.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Option/Arg.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/Option.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/Program.h"
40 #include "llvm/Support/raw_ostream.h"
42 using namespace clang::driver;
43 using namespace clang::driver::tools;
44 using namespace clang;
45 using namespace llvm::opt;
47 static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
48 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
49 options::OPT_fpic, options::OPT_fno_pic,
50 options::OPT_fPIE, options::OPT_fno_PIE,
51 options::OPT_fpie, options::OPT_fno_pie);
54 if (LastPICArg->getOption().matches(options::OPT_fPIC) ||
55 LastPICArg->getOption().matches(options::OPT_fpic) ||
56 LastPICArg->getOption().matches(options::OPT_fPIE) ||
57 LastPICArg->getOption().matches(options::OPT_fpie)) {
58 CmdArgs.push_back("-KPIC");
62 /// CheckPreprocessingOptions - Perform some validation of preprocessing
63 /// arguments that is shared with gcc.
64 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
65 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
66 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
67 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
68 D.Diag(diag::err_drv_argument_only_allowed_with)
69 << A->getBaseArg().getAsString(Args)
70 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
75 /// CheckCodeGenerationOptions - Perform some validation of code generation
76 /// arguments that is shared with gcc.
77 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
78 // In gcc, only ARM checks this, but it seems reasonable to check universally.
79 if (Args.hasArg(options::OPT_static))
80 if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
81 options::OPT_mdynamic_no_pic))
82 D.Diag(diag::err_drv_argument_not_allowed_with)
83 << A->getAsString(Args) << "-static";
86 // Quote target names for inclusion in GNU Make dependency files.
87 // Only the characters '$', '#', ' ', '\t' are quoted.
88 static void QuoteTarget(StringRef Target,
89 SmallVectorImpl<char> &Res) {
90 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
94 // Escape the preceding backslashes
95 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
98 // Escape the space/tab
111 Res.push_back(Target[i]);
115 static void addDirectoryList(const ArgList &Args,
116 ArgStringList &CmdArgs,
118 const char *EnvVar) {
119 const char *DirList = ::getenv(EnvVar);
120 bool CombinedArg = false;
123 return; // Nothing to do.
125 StringRef Name(ArgName);
126 if (Name.equals("-I") || Name.equals("-L"))
129 StringRef Dirs(DirList);
130 if (Dirs.empty()) // Empty string should not add '.'.
133 StringRef::size_type Delim;
134 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
135 if (Delim == 0) { // Leading colon.
137 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
139 CmdArgs.push_back(ArgName);
140 CmdArgs.push_back(".");
144 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
146 CmdArgs.push_back(ArgName);
147 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
150 Dirs = Dirs.substr(Delim + 1);
153 if (Dirs.empty()) { // Trailing colon.
155 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
157 CmdArgs.push_back(ArgName);
158 CmdArgs.push_back(".");
160 } else { // Add the last path.
162 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
164 CmdArgs.push_back(ArgName);
165 CmdArgs.push_back(Args.MakeArgString(Dirs));
170 static void AddLinkerInputs(const ToolChain &TC,
171 const InputInfoList &Inputs, const ArgList &Args,
172 ArgStringList &CmdArgs) {
173 const Driver &D = TC.getDriver();
175 // Add extra linker input arguments which are not treated as inputs
176 // (constructed via -Xarch_).
177 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
179 for (const auto &II : Inputs) {
180 if (!TC.HasNativeLLVMSupport()) {
181 // Don't try to pass LLVM inputs unless we have native support.
182 if (II.getType() == types::TY_LLVM_IR ||
183 II.getType() == types::TY_LTO_IR ||
184 II.getType() == types::TY_LLVM_BC ||
185 II.getType() == types::TY_LTO_BC)
186 D.Diag(diag::err_drv_no_linker_llvm_support)
187 << TC.getTripleString();
190 // Add filenames immediately.
191 if (II.isFilename()) {
192 CmdArgs.push_back(II.getFilename());
196 // Otherwise, this is a linker input argument.
197 const Arg &A = II.getInputArg();
199 // Handle reserved library options.
200 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
201 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
202 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
203 TC.AddCCKextLibArgs(Args, CmdArgs);
204 else if (A.getOption().matches(options::OPT_z)) {
205 // Pass -z prefix for gcc linker compatibility.
207 A.render(Args, CmdArgs);
209 A.renderAsInput(Args, CmdArgs);
213 // LIBRARY_PATH - included following the user specified library paths.
214 // and only supported on native toolchains.
215 if (!TC.isCrossCompiling())
216 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
219 /// \brief Determine whether Objective-C automated reference counting is
221 static bool isObjCAutoRefCount(const ArgList &Args) {
222 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
225 /// \brief Determine whether we are linking the ObjC runtime.
226 static bool isObjCRuntimeLinked(const ArgList &Args) {
227 if (isObjCAutoRefCount(Args)) {
228 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
231 return Args.hasArg(options::OPT_fobjc_link_runtime);
234 static bool forwardToGCC(const Option &O) {
235 // Don't forward inputs from the original command line. They are added from
237 return O.getKind() != Option::InputClass &&
238 !O.hasFlag(options::DriverOption) &&
239 !O.hasFlag(options::LinkerInput);
242 void Clang::AddPreprocessingOptions(Compilation &C,
246 ArgStringList &CmdArgs,
247 const InputInfo &Output,
248 const InputInfoList &Inputs) const {
251 CheckPreprocessingOptions(D, Args);
253 Args.AddLastArg(CmdArgs, options::OPT_C);
254 Args.AddLastArg(CmdArgs, options::OPT_CC);
256 // Handle dependency file generation.
257 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
258 (A = Args.getLastArg(options::OPT_MD)) ||
259 (A = Args.getLastArg(options::OPT_MMD))) {
260 // Determine the output location.
262 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
263 DepFile = MF->getValue();
264 C.addFailureResultFile(DepFile, &JA);
265 } else if (Output.getType() == types::TY_Dependencies) {
266 DepFile = Output.getFilename();
267 } else if (A->getOption().matches(options::OPT_M) ||
268 A->getOption().matches(options::OPT_MM)) {
271 DepFile = getDependencyFileName(Args, Inputs);
272 C.addFailureResultFile(DepFile, &JA);
274 CmdArgs.push_back("-dependency-file");
275 CmdArgs.push_back(DepFile);
277 // Add a default target if one wasn't specified.
278 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
279 const char *DepTarget;
281 // If user provided -o, that is the dependency target, except
282 // when we are only generating a dependency file.
283 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
284 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
285 DepTarget = OutputOpt->getValue();
287 // Otherwise derive from the base input.
289 // FIXME: This should use the computed output file location.
290 SmallString<128> P(Inputs[0].getBaseInput());
291 llvm::sys::path::replace_extension(P, "o");
292 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
295 CmdArgs.push_back("-MT");
296 SmallString<128> Quoted;
297 QuoteTarget(DepTarget, Quoted);
298 CmdArgs.push_back(Args.MakeArgString(Quoted));
301 if (A->getOption().matches(options::OPT_M) ||
302 A->getOption().matches(options::OPT_MD))
303 CmdArgs.push_back("-sys-header-deps");
305 if (isa<PrecompileJobAction>(JA))
306 CmdArgs.push_back("-module-file-deps");
309 if (Args.hasArg(options::OPT_MG)) {
310 if (!A || A->getOption().matches(options::OPT_MD) ||
311 A->getOption().matches(options::OPT_MMD))
312 D.Diag(diag::err_drv_mg_requires_m_or_mm);
313 CmdArgs.push_back("-MG");
316 Args.AddLastArg(CmdArgs, options::OPT_MP);
318 // Convert all -MQ <target> args to -MT <quoted target>
319 for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
321 ie = Args.filtered_end(); it != ie; ++it) {
325 if (A->getOption().matches(options::OPT_MQ)) {
326 CmdArgs.push_back("-MT");
327 SmallString<128> Quoted;
328 QuoteTarget(A->getValue(), Quoted);
329 CmdArgs.push_back(Args.MakeArgString(Quoted));
331 // -MT flag - no change
333 A->render(Args, CmdArgs);
337 // Add -i* options, and automatically translate to
338 // -include-pch/-include-pth for transparent PCH support. It's
339 // wonky, but we include looking for .gch so we can support seamless
340 // replacement into a build system already set up to be generating
342 bool RenderedImplicitInclude = false;
343 for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
344 ie = Args.filtered_end(); it != ie; ++it) {
347 if (A->getOption().matches(options::OPT_include)) {
348 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
349 RenderedImplicitInclude = true;
351 // Use PCH if the user requested it.
352 bool UsePCH = D.CCCUsePCH;
354 bool FoundPTH = false;
355 bool FoundPCH = false;
356 SmallString<128> P(A->getValue());
357 // We want the files to have a name like foo.h.pch. Add a dummy extension
358 // so that replace_extension does the right thing.
361 llvm::sys::path::replace_extension(P, "pch");
362 if (llvm::sys::fs::exists(P.str()))
367 llvm::sys::path::replace_extension(P, "pth");
368 if (llvm::sys::fs::exists(P.str()))
372 if (!FoundPCH && !FoundPTH) {
373 llvm::sys::path::replace_extension(P, "gch");
374 if (llvm::sys::fs::exists(P.str())) {
380 if (FoundPCH || FoundPTH) {
381 if (IsFirstImplicitInclude) {
384 CmdArgs.push_back("-include-pch");
386 CmdArgs.push_back("-include-pth");
387 CmdArgs.push_back(Args.MakeArgString(P.str()));
390 // Ignore the PCH if not first on command line and emit warning.
391 D.Diag(diag::warn_drv_pch_not_first_include)
392 << P.str() << A->getAsString(Args);
397 // Not translated, render as usual.
399 A->render(Args, CmdArgs);
402 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
403 Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
404 options::OPT_index_header_map);
406 // Add -Wp, and -Xassembler if using the preprocessor.
408 // FIXME: There is a very unfortunate problem here, some troubled
409 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
410 // really support that we would have to parse and then translate
412 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
413 options::OPT_Xpreprocessor);
415 // -I- is a deprecated GCC feature, reject it.
416 if (Arg *A = Args.getLastArg(options::OPT_I_))
417 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
419 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
420 // -isysroot to the CC1 invocation.
421 StringRef sysroot = C.getSysRoot();
423 if (!Args.hasArg(options::OPT_isysroot)) {
424 CmdArgs.push_back("-isysroot");
425 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
429 // Parse additional include paths from environment variables.
430 // FIXME: We should probably sink the logic for handling these from the
431 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
432 // CPATH - included following the user specified includes (but prior to
433 // builtin and standard includes).
434 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
435 // C_INCLUDE_PATH - system includes enabled when compiling C.
436 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
437 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
438 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
439 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
440 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
441 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
442 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
444 // Add C++ include arguments, if needed.
445 if (types::isCXX(Inputs[0].getType()))
446 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
448 // Add system include arguments.
449 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
452 // FIXME: Move to target hook.
453 static bool isSignedCharDefault(const llvm::Triple &Triple) {
454 switch (Triple.getArch()) {
458 case llvm::Triple::aarch64:
459 case llvm::Triple::aarch64_be:
460 case llvm::Triple::arm64:
461 case llvm::Triple::arm64_be:
462 case llvm::Triple::arm:
463 case llvm::Triple::armeb:
464 if (Triple.isOSDarwin() || Triple.isOSWindows())
468 case llvm::Triple::ppc:
469 case llvm::Triple::ppc64:
470 if (Triple.isOSDarwin())
474 case llvm::Triple::ppc64le:
475 case llvm::Triple::systemz:
476 case llvm::Triple::xcore:
481 static bool isNoCommonDefault(const llvm::Triple &Triple) {
482 switch (Triple.getArch()) {
486 case llvm::Triple::xcore:
492 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
494 std::vector<const char *> &Features) {
495 StringRef HWDiv = A->getValue();
496 if (HWDiv == "arm") {
497 Features.push_back("+hwdiv-arm");
498 Features.push_back("-hwdiv");
499 } else if (HWDiv == "thumb") {
500 Features.push_back("-hwdiv-arm");
501 Features.push_back("+hwdiv");
502 } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
503 Features.push_back("+hwdiv-arm");
504 Features.push_back("+hwdiv");
505 } else if (HWDiv == "none") {
506 Features.push_back("-hwdiv-arm");
507 Features.push_back("-hwdiv");
509 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
514 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
516 static void getARMFPUFeatures(const Driver &D, const Arg *A,
518 std::vector<const char *> &Features) {
519 StringRef FPU = A->getValue();
521 // Set the target features based on the FPU.
522 if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
523 // Disable any default FPU support.
524 Features.push_back("-vfp2");
525 Features.push_back("-vfp3");
526 Features.push_back("-neon");
527 } else if (FPU == "vfp") {
528 Features.push_back("+vfp2");
529 Features.push_back("-neon");
530 } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
531 Features.push_back("+vfp3");
532 Features.push_back("+d16");
533 Features.push_back("-neon");
534 } else if (FPU == "vfp3" || FPU == "vfpv3") {
535 Features.push_back("+vfp3");
536 Features.push_back("-neon");
537 } else if (FPU == "vfp4-d16" || FPU == "vfpv4-d16") {
538 Features.push_back("+vfp4");
539 Features.push_back("+d16");
540 Features.push_back("-neon");
541 } else if (FPU == "vfp4" || FPU == "vfpv4") {
542 Features.push_back("+vfp4");
543 Features.push_back("-neon");
544 } else if (FPU == "fp4-sp-d16" || FPU == "fpv4-sp-d16") {
545 Features.push_back("+vfp4");
546 Features.push_back("+d16");
547 Features.push_back("+fp-only-sp");
548 Features.push_back("-neon");
549 } else if (FPU == "fp-armv8") {
550 Features.push_back("+fp-armv8");
551 Features.push_back("-neon");
552 Features.push_back("-crypto");
553 } else if (FPU == "neon-fp-armv8") {
554 Features.push_back("+fp-armv8");
555 Features.push_back("+neon");
556 Features.push_back("-crypto");
557 } else if (FPU == "crypto-neon-fp-armv8") {
558 Features.push_back("+fp-armv8");
559 Features.push_back("+neon");
560 Features.push_back("+crypto");
561 } else if (FPU == "neon") {
562 Features.push_back("+neon");
563 } else if (FPU == "none") {
564 Features.push_back("-vfp2");
565 Features.push_back("-vfp3");
566 Features.push_back("-vfp4");
567 Features.push_back("-fp-armv8");
568 Features.push_back("-crypto");
569 Features.push_back("-neon");
571 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
574 // Select the float ABI as determined by -msoft-float, -mhard-float, and
576 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
577 const llvm::Triple &Triple) {
579 if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
580 options::OPT_mhard_float,
581 options::OPT_mfloat_abi_EQ)) {
582 if (A->getOption().matches(options::OPT_msoft_float))
584 else if (A->getOption().matches(options::OPT_mhard_float))
587 FloatABI = A->getValue();
588 if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
589 D.Diag(diag::err_drv_invalid_mfloat_abi)
590 << A->getAsString(Args);
596 // If unspecified, choose the default based on the platform.
597 if (FloatABI.empty()) {
598 switch (Triple.getOS()) {
599 case llvm::Triple::Darwin:
600 case llvm::Triple::MacOSX:
601 case llvm::Triple::IOS: {
602 // Darwin defaults to "softfp" for v6 and v7.
604 // FIXME: Factor out an ARM class so we can cache the arch somewhere.
605 std::string ArchName =
606 arm::getLLVMArchSuffixForARM(arm::getARMTargetCPU(Args, Triple));
607 if (StringRef(ArchName).startswith("v6") ||
608 StringRef(ArchName).startswith("v7"))
615 // FIXME: this is invalid for WindowsCE
616 case llvm::Triple::Win32:
620 case llvm::Triple::FreeBSD:
621 switch(Triple.getEnvironment()) {
622 case llvm::Triple::GNUEABIHF:
626 // FreeBSD defaults to soft float
633 switch(Triple.getEnvironment()) {
634 case llvm::Triple::GNUEABIHF:
637 case llvm::Triple::GNUEABI:
640 case llvm::Triple::EABIHF:
643 case llvm::Triple::EABI:
644 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
647 case llvm::Triple::Android: {
648 std::string ArchName =
649 arm::getLLVMArchSuffixForARM(arm::getARMTargetCPU(Args, Triple));
650 if (StringRef(ArchName).startswith("v7"))
657 // Assume "soft", but warn the user we are guessing.
659 if (Triple.getOS() != llvm::Triple::UnknownOS ||
660 !Triple.isOSBinFormatMachO())
661 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
670 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
672 std::vector<const char *> &Features,
674 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
676 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
677 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
678 // stripped out by the ARM target. We should probably pass this a new
679 // -target-option, which is handled by the -cc1/-cc1as invocation.
681 // FIXME2: For consistency, it would be ideal if we set up the target
682 // machine state the same when using the frontend or the assembler. We don't
683 // currently do that for the assembler, we pass the options directly to the
684 // backend and never even instantiate the frontend TargetInfo. If we did,
685 // and used its handleTargetFeatures hook, then we could ensure the
686 // assembler and the frontend behave the same.
688 // Use software floating point operations?
689 if (FloatABI == "soft")
690 Features.push_back("+soft-float");
692 // Use software floating point argument passing?
693 if (FloatABI != "hard")
694 Features.push_back("+soft-float-abi");
698 if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
699 getARMFPUFeatures(D, A, Args, Features);
700 if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
701 getARMHWDivFeatures(D, A, Args, Features);
703 // Setting -msoft-float effectively disables NEON because of the GCC
704 // implementation, although the same isn't true of VFP or VFP3.
705 if (FloatABI == "soft") {
706 Features.push_back("-neon");
707 // Also need to explicitly disable features which imply NEON.
708 Features.push_back("-crypto");
712 if (Arg *A = Args.getLastArg(options::OPT_mcrc,
713 options::OPT_mnocrc)) {
714 if (A->getOption().matches(options::OPT_mcrc))
715 Features.push_back("+crc");
717 Features.push_back("-crc");
721 void Clang::AddARMTargetArgs(const ArgList &Args,
722 ArgStringList &CmdArgs,
723 bool KernelOrKext) const {
724 const Driver &D = getToolChain().getDriver();
725 // Get the effective triple, which takes into account the deployment target.
726 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
727 llvm::Triple Triple(TripleStr);
728 std::string CPUName = arm::getARMTargetCPU(Args, Triple);
730 // Select the ABI to use.
732 // FIXME: Support -meabi.
733 const char *ABIName = nullptr;
734 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
735 ABIName = A->getValue();
736 } else if (Triple.isOSBinFormatMachO()) {
737 // The backend is hardwired to assume AAPCS for M-class processors, ensure
738 // the frontend matches that.
739 if (Triple.getEnvironment() == llvm::Triple::EABI ||
740 (Triple.getOS() == llvm::Triple::UnknownOS &&
741 Triple.getObjectFormat() == llvm::Triple::MachO) ||
742 StringRef(CPUName).startswith("cortex-m")) {
745 ABIName = "apcs-gnu";
747 } else if (Triple.isOSWindows()) {
748 // FIXME: this is invalid for WindowsCE
751 // Select the default based on the platform.
752 switch(Triple.getEnvironment()) {
753 case llvm::Triple::Android:
754 case llvm::Triple::GNUEABI:
755 case llvm::Triple::GNUEABIHF:
756 ABIName = "aapcs-linux";
758 case llvm::Triple::EABIHF:
759 case llvm::Triple::EABI:
763 ABIName = "apcs-gnu";
766 CmdArgs.push_back("-target-abi");
767 CmdArgs.push_back(ABIName);
769 // Determine floating point ABI from the options & target defaults.
770 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
771 if (FloatABI == "soft") {
772 // Floating point operations and argument passing are soft.
774 // FIXME: This changes CPP defines, we need -target-soft-float.
775 CmdArgs.push_back("-msoft-float");
776 CmdArgs.push_back("-mfloat-abi");
777 CmdArgs.push_back("soft");
778 } else if (FloatABI == "softfp") {
779 // Floating point operations are hard, but argument passing is soft.
780 CmdArgs.push_back("-mfloat-abi");
781 CmdArgs.push_back("soft");
783 // Floating point operations and argument passing are hard.
784 assert(FloatABI == "hard" && "Invalid float abi!");
785 CmdArgs.push_back("-mfloat-abi");
786 CmdArgs.push_back("hard");
789 // Kernel code has more strict alignment requirements.
791 if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
792 CmdArgs.push_back("-backend-option");
793 CmdArgs.push_back("-arm-long-calls");
796 CmdArgs.push_back("-backend-option");
797 CmdArgs.push_back("-arm-strict-align");
799 // The kext linker doesn't know how to deal with movw/movt.
800 CmdArgs.push_back("-backend-option");
801 CmdArgs.push_back("-arm-use-movt=0");
804 // Setting -mno-global-merge disables the codegen global merge pass. Setting
805 // -mglobal-merge has no effect as the pass is enabled by default.
806 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
807 options::OPT_mno_global_merge)) {
808 if (A->getOption().matches(options::OPT_mno_global_merge))
809 CmdArgs.push_back("-mno-global-merge");
812 if (!Args.hasFlag(options::OPT_mimplicit_float,
813 options::OPT_mno_implicit_float,
815 CmdArgs.push_back("-no-implicit-float");
817 // llvm does not support reserving registers in general. There is support
818 // for reserving r9 on ARM though (defined as a platform-specific register
820 if (Args.hasArg(options::OPT_ffixed_r9)) {
821 CmdArgs.push_back("-backend-option");
822 CmdArgs.push_back("-arm-reserve-r9");
826 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
828 static std::string getAArch64TargetCPU(const ArgList &Args) {
831 // If we have -mtune or -mcpu, use that.
832 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
834 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
835 StringRef Mcpu = A->getValue();
836 CPU = Mcpu.split("+").first;
839 // Handle CPU name is 'native'.
841 return llvm::sys::getHostCPUName();
845 // Make sure we pick "cyclone" if -arch is used.
846 // FIXME: Should this be picked by checking the target triple instead?
847 if (Args.getLastArg(options::OPT_arch))
853 void Clang::AddAArch64TargetArgs(const ArgList &Args,
854 ArgStringList &CmdArgs) const {
855 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
856 llvm::Triple Triple(TripleStr);
858 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
859 Args.hasArg(options::OPT_mkernel) ||
860 Args.hasArg(options::OPT_fapple_kext))
861 CmdArgs.push_back("-disable-red-zone");
863 if (!Args.hasFlag(options::OPT_mimplicit_float,
864 options::OPT_mno_implicit_float, true))
865 CmdArgs.push_back("-no-implicit-float");
867 const char *ABIName = nullptr;
868 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
869 ABIName = A->getValue();
870 else if (Triple.isOSDarwin())
871 ABIName = "darwinpcs";
875 CmdArgs.push_back("-target-abi");
876 CmdArgs.push_back(ABIName);
878 if (Args.hasArg(options::OPT_mstrict_align)) {
879 CmdArgs.push_back("-backend-option");
880 CmdArgs.push_back("-aarch64-strict-align");
883 // Setting -mno-global-merge disables the codegen global merge pass. Setting
884 // -mglobal-merge has no effect as the pass is enabled by default.
885 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
886 options::OPT_mno_global_merge)) {
887 if (A->getOption().matches(options::OPT_mno_global_merge))
888 CmdArgs.push_back("-mno-global-merge");
892 // Get CPU and ABI names. They are not independent
893 // so we have to calculate them together.
894 void mips::getMipsCPUAndABI(const ArgList &Args,
895 const llvm::Triple &Triple,
897 StringRef &ABIName) {
898 const char *DefMips32CPU = "mips32r2";
899 const char *DefMips64CPU = "mips64r2";
901 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
902 // default for mips64(el)?-img-linux-gnu.
903 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
904 Triple.getEnvironment() == llvm::Triple::GNU) {
905 DefMips32CPU = "mips32r6";
906 DefMips64CPU = "mips64r6";
909 if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
910 options::OPT_mcpu_EQ))
911 CPUName = A->getValue();
913 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
914 ABIName = A->getValue();
915 // Convert a GNU style Mips ABI name to the name
916 // accepted by LLVM Mips backend.
917 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
923 // Setup default CPU and ABI names.
924 if (CPUName.empty() && ABIName.empty()) {
925 switch (Triple.getArch()) {
927 llvm_unreachable("Unexpected triple arch name");
928 case llvm::Triple::mips:
929 case llvm::Triple::mipsel:
930 CPUName = DefMips32CPU;
932 case llvm::Triple::mips64:
933 case llvm::Triple::mips64el:
934 CPUName = DefMips64CPU;
939 if (ABIName.empty()) {
940 // Deduce ABI name from the target triple.
941 if (Triple.getArch() == llvm::Triple::mips ||
942 Triple.getArch() == llvm::Triple::mipsel)
948 if (CPUName.empty()) {
949 // Deduce CPU name from ABI name.
950 CPUName = llvm::StringSwitch<const char *>(ABIName)
951 .Cases("o32", "eabi", DefMips32CPU)
952 .Cases("n32", "n64", DefMips64CPU)
957 // Convert ABI name to the GNU tools acceptable variant.
958 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
959 return llvm::StringSwitch<llvm::StringRef>(ABI)
965 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
967 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
969 if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
970 options::OPT_mhard_float,
971 options::OPT_mfloat_abi_EQ)) {
972 if (A->getOption().matches(options::OPT_msoft_float))
974 else if (A->getOption().matches(options::OPT_mhard_float))
977 FloatABI = A->getValue();
978 if (FloatABI != "soft" && FloatABI != "hard") {
979 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
985 // If unspecified, choose the default based on the platform.
986 if (FloatABI.empty()) {
987 // Assume "hard", because it's a default value used by gcc.
988 // When we start to recognize specific target MIPS processors,
989 // we will be able to select the default more correctly.
996 static void AddTargetFeature(const ArgList &Args,
997 std::vector<const char *> &Features,
998 OptSpecifier OnOpt, OptSpecifier OffOpt,
999 StringRef FeatureName) {
1000 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1001 if (A->getOption().matches(OnOpt))
1002 Features.push_back(Args.MakeArgString("+" + FeatureName));
1004 Features.push_back(Args.MakeArgString("-" + FeatureName));
1008 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1009 const ArgList &Args,
1010 std::vector<const char *> &Features) {
1013 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1014 ABIName = getGnuCompatibleMipsABIName(ABIName);
1016 // Always override the backend's default ABI.
1017 std::string ABIFeature = llvm::StringSwitch<StringRef>(ABIName)
1019 .Case("n32", "+n32")
1021 .Case("eabi", "+eabi")
1022 .Default(("+" + ABIName).str());
1023 Features.push_back("-o32");
1024 Features.push_back("-n64");
1025 Features.push_back(Args.MakeArgString(ABIFeature));
1027 StringRef FloatABI = getMipsFloatABI(D, Args);
1028 if (FloatABI == "soft") {
1029 // FIXME: Note, this is a hack. We need to pass the selected float
1030 // mode to the MipsTargetInfoBase to define appropriate macros there.
1031 // Now it is the only method.
1032 Features.push_back("+soft-float");
1035 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1036 StringRef Val = StringRef(A->getValue());
1038 Features.push_back("+nan2008");
1039 else if (Val == "legacy")
1040 Features.push_back("-nan2008");
1042 D.Diag(diag::err_drv_unsupported_option_argument)
1043 << A->getOption().getName() << Val;
1046 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1047 options::OPT_mdouble_float, "single-float");
1048 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1050 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1051 options::OPT_mno_micromips, "micromips");
1052 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1054 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1056 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1059 // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1061 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1062 options::OPT_mfp64)) {
1063 if (A->getOption().matches(options::OPT_mfp32))
1064 Features.push_back(Args.MakeArgString("-fp64"));
1065 else if (A->getOption().matches(options::OPT_mfpxx)) {
1066 Features.push_back(Args.MakeArgString("+fpxx"));
1067 Features.push_back(Args.MakeArgString("+nooddspreg"));
1069 Features.push_back(Args.MakeArgString("+fp64"));
1070 } else if (mips::isFPXXDefault(Triple, CPUName, ABIName)) {
1071 Features.push_back(Args.MakeArgString("+fpxx"));
1072 Features.push_back(Args.MakeArgString("+nooddspreg"));
1075 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1076 options::OPT_modd_spreg, "nooddspreg");
1079 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1080 ArgStringList &CmdArgs) const {
1081 const Driver &D = getToolChain().getDriver();
1084 const llvm::Triple &Triple = getToolChain().getTriple();
1085 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1087 CmdArgs.push_back("-target-abi");
1088 CmdArgs.push_back(ABIName.data());
1090 StringRef FloatABI = getMipsFloatABI(D, Args);
1092 if (FloatABI == "soft") {
1093 // Floating point operations and argument passing are soft.
1094 CmdArgs.push_back("-msoft-float");
1095 CmdArgs.push_back("-mfloat-abi");
1096 CmdArgs.push_back("soft");
1099 // Floating point operations and argument passing are hard.
1100 assert(FloatABI == "hard" && "Invalid float abi!");
1101 CmdArgs.push_back("-mfloat-abi");
1102 CmdArgs.push_back("hard");
1105 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1106 if (A->getOption().matches(options::OPT_mxgot)) {
1107 CmdArgs.push_back("-mllvm");
1108 CmdArgs.push_back("-mxgot");
1112 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1113 options::OPT_mno_ldc1_sdc1)) {
1114 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1115 CmdArgs.push_back("-mllvm");
1116 CmdArgs.push_back("-mno-ldc1-sdc1");
1120 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1121 options::OPT_mno_check_zero_division)) {
1122 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1123 CmdArgs.push_back("-mllvm");
1124 CmdArgs.push_back("-mno-check-zero-division");
1128 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1129 StringRef v = A->getValue();
1130 CmdArgs.push_back("-mllvm");
1131 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1136 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1137 static std::string getPPCTargetCPU(const ArgList &Args) {
1138 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1139 StringRef CPUName = A->getValue();
1141 if (CPUName == "native") {
1142 std::string CPU = llvm::sys::getHostCPUName();
1143 if (!CPU.empty() && CPU != "generic")
1149 return llvm::StringSwitch<const char *>(CPUName)
1150 .Case("common", "generic")
1152 .Case("440fp", "440")
1157 .Case("603e", "603e")
1158 .Case("603ev", "603ev")
1160 .Case("604e", "604e")
1162 .Case("630", "pwr3")
1164 .Case("7400", "7400")
1166 .Case("7450", "7450")
1173 .Case("e500mc", "e500mc")
1174 .Case("e5500", "e5500")
1175 .Case("power3", "pwr3")
1176 .Case("power4", "pwr4")
1177 .Case("power5", "pwr5")
1178 .Case("power5x", "pwr5x")
1179 .Case("power6", "pwr6")
1180 .Case("power6x", "pwr6x")
1181 .Case("power7", "pwr7")
1182 .Case("power8", "pwr8")
1183 .Case("pwr3", "pwr3")
1184 .Case("pwr4", "pwr4")
1185 .Case("pwr5", "pwr5")
1186 .Case("pwr5x", "pwr5x")
1187 .Case("pwr6", "pwr6")
1188 .Case("pwr6x", "pwr6x")
1189 .Case("pwr7", "pwr7")
1190 .Case("pwr8", "pwr8")
1191 .Case("powerpc", "ppc")
1192 .Case("powerpc64", "ppc64")
1193 .Case("powerpc64le", "ppc64le")
1200 static void getPPCTargetFeatures(const ArgList &Args,
1201 std::vector<const char *> &Features) {
1202 for (arg_iterator it = Args.filtered_begin(options::OPT_m_ppc_Features_Group),
1203 ie = Args.filtered_end();
1205 StringRef Name = (*it)->getOption().getName();
1209 assert(Name.startswith("m") && "Invalid feature name.");
1210 Name = Name.substr(1);
1212 bool IsNegative = Name.startswith("no-");
1214 Name = Name.substr(3);
1216 // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1217 // pass the correct option to the backend while calling the frontend
1219 // TODO: Change the LLVM backend option maybe?
1220 if (Name == "mfcrf")
1223 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1226 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1227 AddTargetFeature(Args, Features, options::OPT_faltivec,
1228 options::OPT_fno_altivec, "altivec");
1231 /// Get the (LLVM) name of the R600 gpu we are targeting.
1232 static std::string getR600TargetGPU(const ArgList &Args) {
1233 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1234 const char *GPUName = A->getValue();
1235 return llvm::StringSwitch<const char *>(GPUName)
1236 .Cases("rv630", "rv635", "r600")
1237 .Cases("rv610", "rv620", "rs780", "rs880")
1238 .Case("rv740", "rv770")
1239 .Case("palm", "cedar")
1240 .Cases("sumo", "sumo2", "sumo")
1241 .Case("hemlock", "cypress")
1242 .Case("aruba", "cayman")
1248 static void getSparcTargetFeatures(const ArgList &Args,
1249 std::vector<const char *> Features) {
1250 bool SoftFloatABI = true;
1252 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1253 if (A->getOption().matches(options::OPT_mhard_float))
1254 SoftFloatABI = false;
1257 Features.push_back("+soft-float");
1260 void Clang::AddSparcTargetArgs(const ArgList &Args,
1261 ArgStringList &CmdArgs) const {
1262 const Driver &D = getToolChain().getDriver();
1264 // Select the float ABI as determined by -msoft-float and -mhard-float.
1266 if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1267 options::OPT_mhard_float)) {
1268 if (A->getOption().matches(options::OPT_msoft_float))
1270 else if (A->getOption().matches(options::OPT_mhard_float))
1274 // If unspecified, choose the default based on the platform.
1275 if (FloatABI.empty()) {
1276 // Assume "soft", but warn the user we are guessing.
1278 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
1281 if (FloatABI == "soft") {
1282 // Floating point operations and argument passing are soft.
1284 // FIXME: This changes CPP defines, we need -target-soft-float.
1285 CmdArgs.push_back("-msoft-float");
1287 assert(FloatABI == "hard" && "Invalid float abi!");
1288 CmdArgs.push_back("-mhard-float");
1292 static const char *getSystemZTargetCPU(const ArgList &Args) {
1293 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1294 return A->getValue();
1298 static const char *getX86TargetCPU(const ArgList &Args,
1299 const llvm::Triple &Triple) {
1300 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1301 if (StringRef(A->getValue()) != "native") {
1302 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1305 return A->getValue();
1308 // FIXME: Reject attempts to use -march=native unless the target matches
1311 // FIXME: We should also incorporate the detected target features for use
1313 std::string CPU = llvm::sys::getHostCPUName();
1314 if (!CPU.empty() && CPU != "generic")
1315 return Args.MakeArgString(CPU);
1318 // Select the default CPU if none was given (or detection failed).
1320 if (Triple.getArch() != llvm::Triple::x86_64 &&
1321 Triple.getArch() != llvm::Triple::x86)
1322 return nullptr; // This routine is only handling x86 targets.
1324 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1326 // FIXME: Need target hooks.
1327 if (Triple.isOSDarwin()) {
1328 if (Triple.getArchName() == "x86_64h")
1330 return Is64Bit ? "core2" : "yonah";
1333 // On Android use targets compatible with gcc
1334 if (Triple.getEnvironment() == llvm::Triple::Android)
1335 return Is64Bit ? "x86-64" : "i686";
1337 // Everything else goes to x86-64 in 64-bit mode.
1341 switch (Triple.getOS()) {
1342 case llvm::Triple::FreeBSD:
1343 case llvm::Triple::NetBSD:
1344 case llvm::Triple::OpenBSD:
1346 case llvm::Triple::Haiku:
1348 case llvm::Triple::Bitrig:
1356 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
1357 switch(T.getArch()) {
1361 case llvm::Triple::aarch64:
1362 case llvm::Triple::aarch64_be:
1363 case llvm::Triple::arm64:
1364 case llvm::Triple::arm64_be:
1365 return getAArch64TargetCPU(Args);
1367 case llvm::Triple::arm:
1368 case llvm::Triple::armeb:
1369 case llvm::Triple::thumb:
1370 case llvm::Triple::thumbeb:
1371 return arm::getARMTargetCPU(Args, T);
1373 case llvm::Triple::mips:
1374 case llvm::Triple::mipsel:
1375 case llvm::Triple::mips64:
1376 case llvm::Triple::mips64el: {
1379 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1383 case llvm::Triple::ppc:
1384 case llvm::Triple::ppc64:
1385 case llvm::Triple::ppc64le: {
1386 std::string TargetCPUName = getPPCTargetCPU(Args);
1387 // LLVM may default to generating code for the native CPU,
1388 // but, like gcc, we default to a more generic option for
1389 // each architecture. (except on Darwin)
1390 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1391 if (T.getArch() == llvm::Triple::ppc64)
1392 TargetCPUName = "ppc64";
1393 else if (T.getArch() == llvm::Triple::ppc64le)
1394 TargetCPUName = "ppc64le";
1396 TargetCPUName = "ppc";
1398 return TargetCPUName;
1401 case llvm::Triple::sparc:
1402 case llvm::Triple::sparcv9:
1403 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1404 return A->getValue();
1407 case llvm::Triple::x86:
1408 case llvm::Triple::x86_64:
1409 return getX86TargetCPU(Args, T);
1411 case llvm::Triple::hexagon:
1412 return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1414 case llvm::Triple::systemz:
1415 return getSystemZTargetCPU(Args);
1417 case llvm::Triple::r600:
1418 return getR600TargetGPU(Args);
1422 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1423 ArgStringList &CmdArgs) {
1424 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1425 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1427 CmdArgs.push_back("-plugin");
1428 std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
1429 CmdArgs.push_back(Args.MakeArgString(Plugin));
1431 // Try to pass driver level flags relevant to LTO code generation down to
1434 // Handle flags for selecting CPU variants.
1435 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1437 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1440 static void getX86TargetFeatures(const Driver & D,
1441 const llvm::Triple &Triple,
1442 const ArgList &Args,
1443 std::vector<const char *> &Features) {
1444 if (Triple.getArchName() == "x86_64h") {
1445 // x86_64h implies quite a few of the more modern subtarget features
1446 // for Haswell class CPUs, but not all of them. Opt-out of a few.
1447 Features.push_back("-rdrnd");
1448 Features.push_back("-aes");
1449 Features.push_back("-pclmul");
1450 Features.push_back("-rtm");
1451 Features.push_back("-hle");
1452 Features.push_back("-fsgsbase");
1455 // Add features to comply with gcc on Android
1456 if (Triple.getEnvironment() == llvm::Triple::Android) {
1457 if (Triple.getArch() == llvm::Triple::x86_64) {
1458 Features.push_back("+sse4.2");
1459 Features.push_back("+popcnt");
1461 Features.push_back("+ssse3");
1464 // Set features according to the -arch flag on MSVC
1465 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1466 StringRef Arch = A->getValue();
1467 bool ArchUsed = false;
1468 // First, look for flags that are shared in x86 and x86-64.
1469 if (Triple.getArch() == llvm::Triple::x86_64 ||
1470 Triple.getArch() == llvm::Triple::x86) {
1471 if (Arch == "AVX" || Arch == "AVX2") {
1473 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1476 // Then, look for x86-specific flags.
1477 if (Triple.getArch() == llvm::Triple::x86) {
1478 if (Arch == "IA32") {
1480 } else if (Arch == "SSE" || Arch == "SSE2") {
1482 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1486 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
1489 // Now add any that the user explicitly requested on the command line,
1490 // which may override the defaults.
1491 for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
1492 ie = Args.filtered_end();
1494 StringRef Name = (*it)->getOption().getName();
1498 assert(Name.startswith("m") && "Invalid feature name.");
1499 Name = Name.substr(1);
1501 bool IsNegative = Name.startswith("no-");
1503 Name = Name.substr(3);
1505 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1509 void Clang::AddX86TargetArgs(const ArgList &Args,
1510 ArgStringList &CmdArgs) const {
1511 if (!Args.hasFlag(options::OPT_mred_zone,
1512 options::OPT_mno_red_zone,
1514 Args.hasArg(options::OPT_mkernel) ||
1515 Args.hasArg(options::OPT_fapple_kext))
1516 CmdArgs.push_back("-disable-red-zone");
1518 // Default to avoid implicit floating-point for kernel/kext code, but allow
1519 // that to be overridden with -mno-soft-float.
1520 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1521 Args.hasArg(options::OPT_fapple_kext));
1522 if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1523 options::OPT_mno_soft_float,
1524 options::OPT_mimplicit_float,
1525 options::OPT_mno_implicit_float)) {
1526 const Option &O = A->getOption();
1527 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1528 O.matches(options::OPT_msoft_float));
1530 if (NoImplicitFloat)
1531 CmdArgs.push_back("-no-implicit-float");
1533 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1534 StringRef Value = A->getValue();
1535 if (Value == "intel" || Value == "att") {
1536 CmdArgs.push_back("-mllvm");
1537 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1539 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1540 << A->getOption().getName() << Value;
1545 static inline bool HasPICArg(const ArgList &Args) {
1546 return Args.hasArg(options::OPT_fPIC)
1547 || Args.hasArg(options::OPT_fpic);
1550 static Arg *GetLastSmallDataThresholdArg(const ArgList &Args) {
1551 return Args.getLastArg(options::OPT_G,
1553 options::OPT_msmall_data_threshold_EQ);
1556 static std::string GetHexagonSmallDataThresholdValue(const ArgList &Args) {
1558 if (HasPICArg(Args))
1560 else if (Arg *A = GetLastSmallDataThresholdArg(Args)) {
1561 value = A->getValue();
1567 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1568 ArgStringList &CmdArgs) const {
1569 CmdArgs.push_back("-fno-signed-char");
1570 CmdArgs.push_back("-mqdsp6-compat");
1571 CmdArgs.push_back("-Wreturn-type");
1573 std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
1574 if (!SmallDataThreshold.empty()) {
1575 CmdArgs.push_back ("-mllvm");
1576 CmdArgs.push_back(Args.MakeArgString(
1577 "-hexagon-small-data-threshold=" + SmallDataThreshold));
1580 if (!Args.hasArg(options::OPT_fno_short_enums))
1581 CmdArgs.push_back("-fshort-enums");
1582 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1583 CmdArgs.push_back ("-mllvm");
1584 CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
1586 CmdArgs.push_back ("-mllvm");
1587 CmdArgs.push_back ("-machine-sink-split=0");
1590 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
1591 static bool DecodeAArch64Features(const Driver &D, const StringRef &text,
1592 std::vector<const char *> &Features) {
1593 SmallVector<StringRef, 8> Split;
1594 text.split(Split, StringRef("+"), -1, false);
1596 for (unsigned I = 0, E = Split.size(); I != E; ++I) {
1597 const char *result = llvm::StringSwitch<const char *>(Split[I])
1598 .Case("fp", "+fp-armv8")
1599 .Case("simd", "+neon")
1600 .Case("crc", "+crc")
1601 .Case("crypto", "+crypto")
1602 .Case("nofp", "-fp-armv8")
1603 .Case("nosimd", "-neon")
1604 .Case("nocrc", "-crc")
1605 .Case("nocrypto", "-crypto")
1608 Features.push_back(result);
1609 else if (Split[I] == "neon" || Split[I] == "noneon")
1610 D.Diag(diag::err_drv_no_neon_modifier);
1617 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
1618 // decode CPU and feature.
1619 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
1620 std::vector<const char *> &Features) {
1621 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
1623 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57") {
1624 Features.push_back("+neon");
1625 Features.push_back("+crc");
1626 Features.push_back("+crypto");
1627 } else if (CPU == "generic") {
1628 Features.push_back("+neon");
1633 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1640 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
1641 const ArgList &Args,
1642 std::vector<const char *> &Features) {
1643 std::pair<StringRef, StringRef> Split = March.split("+");
1644 if (Split.first != "armv8-a")
1647 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1654 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1655 const ArgList &Args,
1656 std::vector<const char *> &Features) {
1658 if (!DecodeAArch64Mcpu(D, Mcpu, CPU, Features))
1665 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
1666 const ArgList &Args,
1667 std::vector<const char *> &Features) {
1668 // Handle CPU name is 'native'.
1669 if (Mtune == "native")
1670 Mtune = llvm::sys::getHostCPUName();
1671 if (Mtune == "cyclone") {
1672 Features.push_back("+zcm");
1673 Features.push_back("+zcz");
1679 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1680 const ArgList &Args,
1681 std::vector<const char *> &Features) {
1683 std::vector<const char *> DecodedFeature;
1684 if (!DecodeAArch64Mcpu(D, Mcpu, CPU, DecodedFeature))
1687 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
1690 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
1691 std::vector<const char *> &Features) {
1693 bool success = true;
1694 // Enable NEON by default.
1695 Features.push_back("+neon");
1696 if ((A = Args.getLastArg(options::OPT_march_EQ)))
1697 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
1698 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
1699 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1701 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
1703 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
1704 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
1706 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1709 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
1711 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
1712 Features.push_back("-fp-armv8");
1713 Features.push_back("-crypto");
1714 Features.push_back("-neon");
1718 if (Arg *A = Args.getLastArg(options::OPT_mcrc,
1719 options::OPT_mnocrc)) {
1720 if (A->getOption().matches(options::OPT_mcrc))
1721 Features.push_back("+crc");
1723 Features.push_back("-crc");
1727 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1728 const ArgList &Args, ArgStringList &CmdArgs,
1730 std::vector<const char *> Features;
1731 switch (Triple.getArch()) {
1734 case llvm::Triple::mips:
1735 case llvm::Triple::mipsel:
1736 case llvm::Triple::mips64:
1737 case llvm::Triple::mips64el:
1738 getMIPSTargetFeatures(D, Triple, Args, Features);
1741 case llvm::Triple::arm:
1742 case llvm::Triple::armeb:
1743 case llvm::Triple::thumb:
1744 case llvm::Triple::thumbeb:
1745 getARMTargetFeatures(D, Triple, Args, Features, ForAS);
1748 case llvm::Triple::ppc:
1749 case llvm::Triple::ppc64:
1750 case llvm::Triple::ppc64le:
1751 getPPCTargetFeatures(Args, Features);
1753 case llvm::Triple::sparc:
1754 getSparcTargetFeatures(Args, Features);
1756 case llvm::Triple::aarch64:
1757 case llvm::Triple::aarch64_be:
1758 case llvm::Triple::arm64:
1759 case llvm::Triple::arm64_be:
1760 getAArch64TargetFeatures(D, Args, Features);
1762 case llvm::Triple::x86:
1763 case llvm::Triple::x86_64:
1764 getX86TargetFeatures(D, Triple, Args, Features);
1768 // Find the last of each feature.
1769 llvm::StringMap<unsigned> LastOpt;
1770 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1771 const char *Name = Features[I];
1772 assert(Name[0] == '-' || Name[0] == '+');
1773 LastOpt[Name + 1] = I;
1776 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1777 // If this feature was overridden, ignore it.
1778 const char *Name = Features[I];
1779 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
1780 assert(LastI != LastOpt.end());
1781 unsigned Last = LastI->second;
1785 CmdArgs.push_back("-target-feature");
1786 CmdArgs.push_back(Name);
1791 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
1792 const llvm::Triple &Triple) {
1793 // We use the zero-cost exception tables for Objective-C if the non-fragile
1794 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
1796 if (runtime.isNonFragile())
1799 if (!Triple.isMacOSX())
1802 return (!Triple.isMacOSXVersionLT(10,5) &&
1803 (Triple.getArch() == llvm::Triple::x86_64 ||
1804 Triple.getArch() == llvm::Triple::arm));
1808 struct ExceptionSettings {
1809 bool ExceptionsEnabled;
1810 bool ShouldUseExceptionTables;
1811 ExceptionSettings() : ExceptionsEnabled(false),
1812 ShouldUseExceptionTables(false) {}
1814 } // end anonymous namespace.
1816 // exceptionSettings() exists to share the logic between -cc1 and linker
1818 static ExceptionSettings exceptionSettings(const ArgList &Args,
1819 const llvm::Triple &Triple) {
1820 ExceptionSettings ES;
1822 // Are exceptions enabled by default?
1823 ES.ExceptionsEnabled = (Triple.getArch() != llvm::Triple::xcore);
1825 // This keeps track of whether exceptions were explicitly turned on or off.
1826 bool DidHaveExplicitExceptionFlag = false;
1828 if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
1829 options::OPT_fno_exceptions)) {
1830 if (A->getOption().matches(options::OPT_fexceptions))
1831 ES.ExceptionsEnabled = true;
1833 ES.ExceptionsEnabled = false;
1835 DidHaveExplicitExceptionFlag = true;
1838 // Exception tables and cleanups can be enabled with -fexceptions even if the
1839 // language itself doesn't support exceptions.
1840 if (ES.ExceptionsEnabled && DidHaveExplicitExceptionFlag)
1841 ES.ShouldUseExceptionTables = true;
1846 /// addExceptionArgs - Adds exception related arguments to the driver command
1847 /// arguments. There's a master flag, -fexceptions and also language specific
1848 /// flags to enable/disable C++ and Objective-C exceptions.
1849 /// This makes it possible to for example disable C++ exceptions but enable
1850 /// Objective-C exceptions.
1851 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
1852 const llvm::Triple &Triple,
1854 const ObjCRuntime &objcRuntime,
1855 ArgStringList &CmdArgs) {
1857 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
1858 // arguments now to avoid warnings about unused arguments.
1859 Args.ClaimAllArgs(options::OPT_fexceptions);
1860 Args.ClaimAllArgs(options::OPT_fno_exceptions);
1861 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
1862 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
1863 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
1864 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
1868 // Gather the exception settings from the command line arguments.
1869 ExceptionSettings ES = exceptionSettings(Args, Triple);
1871 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
1872 // is not necessarily sensible, but follows GCC.
1873 if (types::isObjC(InputType) &&
1874 Args.hasFlag(options::OPT_fobjc_exceptions,
1875 options::OPT_fno_objc_exceptions,
1877 CmdArgs.push_back("-fobjc-exceptions");
1879 ES.ShouldUseExceptionTables |=
1880 shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
1883 if (types::isCXX(InputType)) {
1884 bool CXXExceptionsEnabled = ES.ExceptionsEnabled;
1886 if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
1887 options::OPT_fno_cxx_exceptions,
1888 options::OPT_fexceptions,
1889 options::OPT_fno_exceptions)) {
1890 if (A->getOption().matches(options::OPT_fcxx_exceptions))
1891 CXXExceptionsEnabled = true;
1892 else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
1893 CXXExceptionsEnabled = false;
1896 if (CXXExceptionsEnabled) {
1897 CmdArgs.push_back("-fcxx-exceptions");
1899 ES.ShouldUseExceptionTables = true;
1903 if (ES.ShouldUseExceptionTables)
1904 CmdArgs.push_back("-fexceptions");
1907 static bool ShouldDisableAutolink(const ArgList &Args,
1908 const ToolChain &TC) {
1909 bool Default = true;
1910 if (TC.getTriple().isOSDarwin()) {
1911 // The native darwin assembler doesn't support the linker_option directives,
1912 // so we disable them if we think the .s file will be passed to it.
1913 Default = TC.useIntegratedAs();
1915 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
1919 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
1920 const ToolChain &TC) {
1921 bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
1922 options::OPT_fno_dwarf_directory_asm,
1923 TC.useIntegratedAs());
1924 return !UseDwarfDirectory;
1927 /// \brief Check whether the given input tree contains any compilation actions.
1928 static bool ContainsCompileAction(const Action *A) {
1929 if (isa<CompileJobAction>(A))
1932 for (const auto &Act : *A)
1933 if (ContainsCompileAction(Act))
1939 /// \brief Check if -relax-all should be passed to the internal assembler.
1940 /// This is done by default when compiling non-assembler source with -O0.
1941 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
1942 bool RelaxDefault = true;
1944 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1945 RelaxDefault = A->getOption().matches(options::OPT_O0);
1948 RelaxDefault = false;
1949 for (const auto &Act : C.getActions()) {
1950 if (ContainsCompileAction(Act)) {
1951 RelaxDefault = true;
1957 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1961 static void CollectArgsForIntegratedAssembler(Compilation &C,
1962 const ArgList &Args,
1963 ArgStringList &CmdArgs,
1965 if (UseRelaxAll(C, Args))
1966 CmdArgs.push_back("-mrelax-all");
1968 // When passing -I arguments to the assembler we sometimes need to
1969 // unconditionally take the next argument. For example, when parsing
1970 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1971 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1972 // arg after parsing the '-I' arg.
1973 bool TakeNextArg = false;
1975 // When using an integrated assembler, translate -Wa, and -Xassembler
1977 bool CompressDebugSections = false;
1978 for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
1979 options::OPT_Xassembler),
1980 ie = Args.filtered_end(); it != ie; ++it) {
1984 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
1985 StringRef Value = A->getValue(i);
1987 CmdArgs.push_back(Value.data());
1988 TakeNextArg = false;
1992 if (Value == "-force_cpusubtype_ALL") {
1993 // Do nothing, this is the default and we don't support anything else.
1994 } else if (Value == "-L") {
1995 CmdArgs.push_back("-msave-temp-labels");
1996 } else if (Value == "--fatal-warnings") {
1997 CmdArgs.push_back("-mllvm");
1998 CmdArgs.push_back("-fatal-assembler-warnings");
1999 } else if (Value == "--noexecstack") {
2000 CmdArgs.push_back("-mnoexecstack");
2001 } else if (Value == "-compress-debug-sections" ||
2002 Value == "--compress-debug-sections") {
2003 CompressDebugSections = true;
2004 } else if (Value == "-nocompress-debug-sections" ||
2005 Value == "--nocompress-debug-sections") {
2006 CompressDebugSections = false;
2007 } else if (Value.startswith("-I")) {
2008 CmdArgs.push_back(Value.data());
2009 // We need to consume the next argument if the current arg is a plain
2010 // -I. The next arg will be the include directory.
2013 } else if (Value.startswith("-gdwarf-")) {
2014 CmdArgs.push_back(Value.data());
2016 D.Diag(diag::err_drv_unsupported_option_argument)
2017 << A->getOption().getName() << Value;
2021 if (CompressDebugSections) {
2022 if (llvm::zlib::isAvailable())
2023 CmdArgs.push_back("-compress-debug-sections");
2025 D.Diag(diag::warn_debug_compression_unavailable);
2029 // Until ARM libraries are build separately, we have them all in one library
2030 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
2031 if (TC.getArch() == llvm::Triple::arm ||
2032 TC.getArch() == llvm::Triple::armeb)
2035 return TC.getArchName();
2038 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
2039 // The runtimes are located in the OS-specific resource directory.
2040 SmallString<128> Res(TC.getDriver().ResourceDir);
2041 const llvm::Triple &Triple = TC.getTriple();
2042 // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
2043 StringRef OSLibName = (Triple.getOS() == llvm::Triple::FreeBSD) ?
2044 "freebsd" : TC.getOS();
2045 llvm::sys::path::append(Res, "lib", OSLibName);
2049 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2050 // FIXME: Make sure we can also emit shared objects if they're requested
2051 // and available, check for possible errors, etc.
2052 static void addClangRTLinux(
2053 const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
2054 SmallString<128> LibClangRT = getCompilerRTLibDir(TC);
2055 llvm::sys::path::append(LibClangRT, Twine("libclang_rt.builtins-") +
2056 getArchNameForCompilerRTLib(TC) +
2059 CmdArgs.push_back(Args.MakeArgString(LibClangRT));
2060 CmdArgs.push_back("-lgcc_s");
2061 if (TC.getDriver().CCCIsCXX())
2062 CmdArgs.push_back("-lgcc_eh");
2065 static void addProfileRT(
2066 const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
2067 if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
2068 Args.hasArg(options::OPT_fprofile_generate) ||
2069 Args.hasArg(options::OPT_fprofile_instr_generate) ||
2070 Args.hasArg(options::OPT_fcreate_profile) ||
2071 Args.hasArg(options::OPT_coverage)))
2074 // -fprofile-instr-generate requires position-independent code to build with
2075 // shared objects. Link against the right archive.
2076 const char *Lib = "libclang_rt.profile-";
2077 if (Args.hasArg(options::OPT_fprofile_instr_generate) &&
2078 Args.hasArg(options::OPT_shared))
2079 Lib = "libclang_rt.profile-pic-";
2081 SmallString<128> LibProfile = getCompilerRTLibDir(TC);
2082 llvm::sys::path::append(LibProfile,
2083 Twine(Lib) + getArchNameForCompilerRTLib(TC) + ".a");
2085 CmdArgs.push_back(Args.MakeArgString(LibProfile));
2088 static SmallString<128> getSanitizerRTLibName(const ToolChain &TC,
2089 const StringRef Sanitizer,
2091 // Sanitizer runtime has name "libclang_rt.<Sanitizer>-<ArchName>.{a,so}"
2092 // (or "libclang_rt.<Sanitizer>-<ArchName>-android.so for Android)
2093 const char *EnvSuffix =
2094 TC.getTriple().getEnvironment() == llvm::Triple::Android ? "-android" : "";
2095 SmallString<128> LibSanitizer = getCompilerRTLibDir(TC);
2096 llvm::sys::path::append(LibSanitizer,
2097 Twine("libclang_rt.") + Sanitizer + "-" +
2098 getArchNameForCompilerRTLib(TC) + EnvSuffix +
2099 (Shared ? ".so" : ".a"));
2100 return LibSanitizer;
2103 static void addSanitizerRTLinkFlags(const ToolChain &TC, const ArgList &Args,
2104 ArgStringList &CmdArgs,
2105 const StringRef Sanitizer,
2106 bool BeforeLibStdCXX,
2107 bool ExportSymbols = true,
2108 bool LinkDeps = true) {
2109 SmallString<128> LibSanitizer =
2110 getSanitizerRTLibName(TC, Sanitizer, /*Shared*/ false);
2112 // Sanitizer runtime may need to come before -lstdc++ (or -lc++, libstdc++.a,
2113 // etc.) so that the linker picks custom versions of the global 'operator
2114 // new' and 'operator delete' symbols. We take the extreme (but simple)
2115 // strategy of inserting it at the front of the link command. It also
2116 // needs to be forced to end up in the executable, so wrap it in
2118 SmallVector<const char *, 3> LibSanitizerArgs;
2119 LibSanitizerArgs.push_back("-whole-archive");
2120 LibSanitizerArgs.push_back(Args.MakeArgString(LibSanitizer));
2121 LibSanitizerArgs.push_back("-no-whole-archive");
2123 CmdArgs.insert(BeforeLibStdCXX ? CmdArgs.begin() : CmdArgs.end(),
2124 LibSanitizerArgs.begin(), LibSanitizerArgs.end());
2127 // Link sanitizer dependencies explicitly
2128 CmdArgs.push_back("-lpthread");
2129 CmdArgs.push_back("-lrt");
2130 CmdArgs.push_back("-lm");
2131 // There's no libdl on FreeBSD.
2132 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2133 CmdArgs.push_back("-ldl");
2136 // If possible, use a dynamic symbols file to export the symbols from the
2137 // runtime library. If we can't do so, use -export-dynamic instead to export
2138 // all symbols from the binary.
2139 if (ExportSymbols) {
2140 if (llvm::sys::fs::exists(LibSanitizer + ".syms"))
2142 Args.MakeArgString("--dynamic-list=" + LibSanitizer + ".syms"));
2144 CmdArgs.push_back("-export-dynamic");
2148 /// If AddressSanitizer is enabled, add appropriate linker flags (Linux).
2149 /// This needs to be called before we add the C run-time (malloc, etc).
2150 static void addAsanRT(const ToolChain &TC, const ArgList &Args,
2151 ArgStringList &CmdArgs, bool Shared, bool IsCXX) {
2153 // Link dynamic runtime if necessary.
2154 SmallString<128> LibSanitizer =
2155 getSanitizerRTLibName(TC, "asan", Shared);
2156 CmdArgs.insert(CmdArgs.begin(), Args.MakeArgString(LibSanitizer));
2159 // Do not link static runtime to DSOs or if compiling for Android.
2160 if (Args.hasArg(options::OPT_shared) ||
2161 (TC.getTriple().getEnvironment() == llvm::Triple::Android))
2165 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "asan-preinit",
2166 /*BeforeLibStdCXX*/ true, /*ExportSymbols*/ false,
2167 /*LinkDeps*/ false);
2169 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "asan", true);
2171 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "asan_cxx", true);
2175 /// If ThreadSanitizer is enabled, add appropriate linker flags (Linux).
2176 /// This needs to be called before we add the C run-time (malloc, etc).
2177 static void addTsanRT(const ToolChain &TC, const ArgList &Args,
2178 ArgStringList &CmdArgs) {
2179 if (!Args.hasArg(options::OPT_shared))
2180 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "tsan", true);
2183 /// If MemorySanitizer is enabled, add appropriate linker flags (Linux).
2184 /// This needs to be called before we add the C run-time (malloc, etc).
2185 static void addMsanRT(const ToolChain &TC, const ArgList &Args,
2186 ArgStringList &CmdArgs) {
2187 if (!Args.hasArg(options::OPT_shared))
2188 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "msan", true);
2191 /// If LeakSanitizer is enabled, add appropriate linker flags (Linux).
2192 /// This needs to be called before we add the C run-time (malloc, etc).
2193 static void addLsanRT(const ToolChain &TC, const ArgList &Args,
2194 ArgStringList &CmdArgs) {
2195 if (!Args.hasArg(options::OPT_shared))
2196 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "lsan", true);
2199 /// If UndefinedBehaviorSanitizer is enabled, add appropriate linker flags
2201 static void addUbsanRT(const ToolChain &TC, const ArgList &Args,
2202 ArgStringList &CmdArgs, bool IsCXX,
2203 bool HasOtherSanitizerRt) {
2204 // Do not link runtime into shared libraries.
2205 if (Args.hasArg(options::OPT_shared))
2208 // Need a copy of sanitizer_common. This could come from another sanitizer
2209 // runtime; if we're not including one, include our own copy.
2210 if (!HasOtherSanitizerRt)
2211 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "san", true, false);
2213 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "ubsan", false, true);
2215 // Only include the bits of the runtime which need a C++ ABI library if
2216 // we're linking in C++ mode.
2218 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "ubsan_cxx", false, true);
2221 static void addDfsanRT(const ToolChain &TC, const ArgList &Args,
2222 ArgStringList &CmdArgs) {
2223 if (!Args.hasArg(options::OPT_shared))
2224 addSanitizerRTLinkFlags(TC, Args, CmdArgs, "dfsan", true);
2227 // Should be called before we add C++ ABI library.
2228 static void addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2229 ArgStringList &CmdArgs) {
2230 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
2231 const Driver &D = TC.getDriver();
2232 if (Sanitize.needsUbsanRt())
2233 addUbsanRT(TC, Args, CmdArgs, D.CCCIsCXX(),
2234 Sanitize.needsAsanRt() || Sanitize.needsTsanRt() ||
2235 Sanitize.needsMsanRt() || Sanitize.needsLsanRt());
2236 if (Sanitize.needsAsanRt())
2237 addAsanRT(TC, Args, CmdArgs, Sanitize.needsSharedAsanRt(), D.CCCIsCXX());
2238 if (Sanitize.needsTsanRt())
2239 addTsanRT(TC, Args, CmdArgs);
2240 if (Sanitize.needsMsanRt())
2241 addMsanRT(TC, Args, CmdArgs);
2242 if (Sanitize.needsLsanRt())
2243 addLsanRT(TC, Args, CmdArgs);
2244 if (Sanitize.needsDfsanRt())
2245 addDfsanRT(TC, Args, CmdArgs);
2248 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2249 const llvm::Triple &Triple) {
2250 switch (Triple.getArch()) {
2251 // Don't use a frame pointer on linux if optimizing for certain targets.
2252 case llvm::Triple::mips64:
2253 case llvm::Triple::mips64el:
2254 case llvm::Triple::mips:
2255 case llvm::Triple::mipsel:
2256 case llvm::Triple::systemz:
2257 case llvm::Triple::x86:
2258 case llvm::Triple::x86_64:
2259 if (Triple.isOSLinux())
2260 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2261 if (!A->getOption().matches(options::OPT_O0))
2264 case llvm::Triple::xcore:
2271 static bool shouldUseFramePointer(const ArgList &Args,
2272 const llvm::Triple &Triple) {
2273 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2274 options::OPT_fomit_frame_pointer))
2275 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2277 return shouldUseFramePointerForTarget(Args, Triple);
2280 static bool shouldUseLeafFramePointer(const ArgList &Args,
2281 const llvm::Triple &Triple) {
2282 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2283 options::OPT_momit_leaf_frame_pointer))
2284 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2286 return shouldUseFramePointerForTarget(Args, Triple);
2289 /// Add a CC1 option to specify the debug compilation directory.
2290 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2291 SmallString<128> cwd;
2292 if (!llvm::sys::fs::current_path(cwd)) {
2293 CmdArgs.push_back("-fdebug-compilation-dir");
2294 CmdArgs.push_back(Args.MakeArgString(cwd));
2298 static const char *SplitDebugName(const ArgList &Args,
2299 const InputInfoList &Inputs) {
2300 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2301 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2302 SmallString<128> T(FinalOutput->getValue());
2303 llvm::sys::path::replace_extension(T, "dwo");
2304 return Args.MakeArgString(T);
2306 // Use the compilation dir.
2308 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2309 SmallString<128> F(llvm::sys::path::stem(Inputs[0].getBaseInput()));
2310 llvm::sys::path::replace_extension(F, "dwo");
2312 return Args.MakeArgString(F);
2316 static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
2317 const Tool &T, const JobAction &JA,
2318 const ArgList &Args, const InputInfo &Output,
2319 const char *OutFile) {
2320 ArgStringList ExtractArgs;
2321 ExtractArgs.push_back("--extract-dwo");
2323 ArgStringList StripArgs;
2324 StripArgs.push_back("--strip-dwo");
2326 // Grabbing the output of the earlier compile step.
2327 StripArgs.push_back(Output.getFilename());
2328 ExtractArgs.push_back(Output.getFilename());
2329 ExtractArgs.push_back(OutFile);
2332 Args.MakeArgString(TC.GetProgramPath("objcopy"));
2334 // First extract the dwo sections.
2335 C.addCommand(new Command(JA, T, Exec, ExtractArgs));
2337 // Then remove them from the original .o file.
2338 C.addCommand(new Command(JA, T, Exec, StripArgs));
2341 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2342 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2343 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2344 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2345 if (A->getOption().matches(options::OPT_O4) ||
2346 A->getOption().matches(options::OPT_Ofast))
2349 if (A->getOption().matches(options::OPT_O0))
2352 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2355 StringRef S(A->getValue());
2359 // Don't vectorize -Oz, unless it's the slp vectorizer.
2363 unsigned OptLevel = 0;
2364 if (S.getAsInteger(10, OptLevel))
2367 return OptLevel > 1;
2373 /// Add -x lang to \p CmdArgs for \p Input.
2374 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
2375 ArgStringList &CmdArgs) {
2376 // When using -verify-pch, we don't want to provide the type
2377 // 'precompiled-header' if it was inferred from the file extension
2378 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
2381 CmdArgs.push_back("-x");
2382 if (Args.hasArg(options::OPT_rewrite_objc))
2383 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
2385 CmdArgs.push_back(types::getTypeName(Input.getType()));
2388 static std::string getMSCompatibilityVersion(const char *VersionStr) {
2390 if (StringRef(VersionStr).getAsInteger(10, Version))
2394 return llvm::utostr_32(Version) + ".0";
2396 if (Version < 10000)
2397 return llvm::utostr_32(Version / 100) + "." +
2398 llvm::utostr_32(Version % 100);
2400 unsigned Build = 0, Factor = 1;
2401 for ( ; Version > 10000; Version = Version / 10, Factor = Factor * 10)
2402 Build = Build + (Version % 10) * Factor;
2403 return llvm::utostr_32(Version / 100) + "." +
2404 llvm::utostr_32(Version % 100) + "." +
2405 llvm::utostr_32(Build);
2408 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2409 const InputInfo &Output,
2410 const InputInfoList &Inputs,
2411 const ArgList &Args,
2412 const char *LinkingOutput) const {
2413 bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
2414 options::OPT_fapple_kext);
2415 const Driver &D = getToolChain().getDriver();
2416 ArgStringList CmdArgs;
2418 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
2419 bool IsWindowsCygnus =
2420 getToolChain().getTriple().isWindowsCygwinEnvironment();
2421 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
2423 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
2425 // Invoke ourselves in -cc1 mode.
2427 // FIXME: Implement custom jobs for internal actions.
2428 CmdArgs.push_back("-cc1");
2430 // Add the "effective" target triple.
2431 CmdArgs.push_back("-triple");
2432 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2433 CmdArgs.push_back(Args.MakeArgString(TripleStr));
2435 const llvm::Triple TT(TripleStr);
2436 if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
2437 TT.getArch() == llvm::Triple::thumb)) {
2438 unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
2440 TT.getArchName().substr(Offset).getAsInteger(10, Version);
2442 D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
2446 // Push all default warning arguments that are specific to
2447 // the given target. These come before user provided warning options
2449 getToolChain().addClangWarningOptions(CmdArgs);
2451 // Select the appropriate action.
2452 RewriteKind rewriteKind = RK_None;
2454 if (isa<AnalyzeJobAction>(JA)) {
2455 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2456 CmdArgs.push_back("-analyze");
2457 } else if (isa<MigrateJobAction>(JA)) {
2458 CmdArgs.push_back("-migrate");
2459 } else if (isa<PreprocessJobAction>(JA)) {
2460 if (Output.getType() == types::TY_Dependencies)
2461 CmdArgs.push_back("-Eonly");
2463 CmdArgs.push_back("-E");
2464 if (Args.hasArg(options::OPT_rewrite_objc) &&
2465 !Args.hasArg(options::OPT_g_Group))
2466 CmdArgs.push_back("-P");
2468 } else if (isa<AssembleJobAction>(JA)) {
2469 CmdArgs.push_back("-emit-obj");
2471 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2473 // Also ignore explicit -force_cpusubtype_ALL option.
2474 (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
2475 } else if (isa<PrecompileJobAction>(JA)) {
2476 // Use PCH if the user requested it.
2477 bool UsePCH = D.CCCUsePCH;
2479 if (JA.getType() == types::TY_Nothing)
2480 CmdArgs.push_back("-fsyntax-only");
2482 CmdArgs.push_back("-emit-pch");
2484 CmdArgs.push_back("-emit-pth");
2485 } else if (isa<VerifyPCHJobAction>(JA)) {
2486 CmdArgs.push_back("-verify-pch");
2488 assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
2490 if (JA.getType() == types::TY_Nothing) {
2491 CmdArgs.push_back("-fsyntax-only");
2492 } else if (JA.getType() == types::TY_LLVM_IR ||
2493 JA.getType() == types::TY_LTO_IR) {
2494 CmdArgs.push_back("-emit-llvm");
2495 } else if (JA.getType() == types::TY_LLVM_BC ||
2496 JA.getType() == types::TY_LTO_BC) {
2497 CmdArgs.push_back("-emit-llvm-bc");
2498 } else if (JA.getType() == types::TY_PP_Asm) {
2499 CmdArgs.push_back("-S");
2500 } else if (JA.getType() == types::TY_AST) {
2501 CmdArgs.push_back("-emit-pch");
2502 } else if (JA.getType() == types::TY_ModuleFile) {
2503 CmdArgs.push_back("-module-file-info");
2504 } else if (JA.getType() == types::TY_RewrittenObjC) {
2505 CmdArgs.push_back("-rewrite-objc");
2506 rewriteKind = RK_NonFragile;
2507 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2508 CmdArgs.push_back("-rewrite-objc");
2509 rewriteKind = RK_Fragile;
2511 assert(JA.getType() == types::TY_PP_Asm &&
2512 "Unexpected output type!");
2516 // We normally speed up the clang process a bit by skipping destructors at
2517 // exit, but when we're generating diagnostics we can rely on some of the
2519 if (!C.isForDiagnostics())
2520 CmdArgs.push_back("-disable-free");
2522 // Disable the verification pass in -asserts builds.
2524 CmdArgs.push_back("-disable-llvm-verifier");
2527 // Set the main file name, so that debug info works even with
2529 CmdArgs.push_back("-main-file-name");
2530 CmdArgs.push_back(getBaseInputName(Args, Inputs));
2532 // Some flags which affect the language (via preprocessor
2534 if (Args.hasArg(options::OPT_static))
2535 CmdArgs.push_back("-static-define");
2537 if (isa<AnalyzeJobAction>(JA)) {
2538 // Enable region store model by default.
2539 CmdArgs.push_back("-analyzer-store=region");
2541 // Treat blocks as analysis entry points.
2542 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2544 CmdArgs.push_back("-analyzer-eagerly-assume");
2546 // Add default argument set.
2547 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2548 CmdArgs.push_back("-analyzer-checker=core");
2551 CmdArgs.push_back("-analyzer-checker=unix");
2553 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2554 CmdArgs.push_back("-analyzer-checker=osx");
2556 CmdArgs.push_back("-analyzer-checker=deadcode");
2558 if (types::isCXX(Inputs[0].getType()))
2559 CmdArgs.push_back("-analyzer-checker=cplusplus");
2561 // Enable the following experimental checkers for testing.
2563 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
2564 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2565 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2566 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2567 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2568 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2571 // Set the output format. The default is plist, for (lame) historical
2573 CmdArgs.push_back("-analyzer-output");
2574 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2575 CmdArgs.push_back(A->getValue());
2577 CmdArgs.push_back("plist");
2579 // Disable the presentation of standard compiler warnings when
2580 // using --analyze. We only want to show static analyzer diagnostics
2581 // or frontend errors.
2582 CmdArgs.push_back("-w");
2584 // Add -Xanalyzer arguments when running as analyzer.
2585 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2588 CheckCodeGenerationOptions(D, Args);
2590 bool PIE = getToolChain().isPIEDefault();
2591 bool PIC = PIE || getToolChain().isPICDefault();
2592 bool IsPICLevelTwo = PIC;
2594 // Android-specific defaults for PIC/PIE
2595 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
2596 switch (getToolChain().getTriple().getArch()) {
2597 case llvm::Triple::arm:
2598 case llvm::Triple::armeb:
2599 case llvm::Triple::thumb:
2600 case llvm::Triple::thumbeb:
2601 case llvm::Triple::aarch64:
2602 case llvm::Triple::arm64:
2603 case llvm::Triple::mips:
2604 case llvm::Triple::mipsel:
2605 case llvm::Triple::mips64:
2606 case llvm::Triple::mips64el:
2607 PIC = true; // "-fpic"
2610 case llvm::Triple::x86:
2611 case llvm::Triple::x86_64:
2612 PIC = true; // "-fPIC"
2613 IsPICLevelTwo = true;
2621 // OpenBSD-specific defaults for PIE
2622 if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
2623 switch (getToolChain().getTriple().getArch()) {
2624 case llvm::Triple::mips64:
2625 case llvm::Triple::mips64el:
2626 case llvm::Triple::sparc:
2627 case llvm::Triple::x86:
2628 case llvm::Triple::x86_64:
2629 IsPICLevelTwo = false; // "-fpie"
2632 case llvm::Triple::ppc:
2633 case llvm::Triple::sparcv9:
2634 IsPICLevelTwo = true; // "-fPIE"
2642 // For the PIC and PIE flag options, this logic is different from the
2643 // legacy logic in very old versions of GCC, as that logic was just
2644 // a bug no one had ever fixed. This logic is both more rational and
2645 // consistent with GCC's new logic now that the bugs are fixed. The last
2646 // argument relating to either PIC or PIE wins, and no other argument is
2647 // used. If the last argument is any flavor of the '-fno-...' arguments,
2648 // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
2649 // at the same level.
2650 Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
2651 options::OPT_fpic, options::OPT_fno_pic,
2652 options::OPT_fPIE, options::OPT_fno_PIE,
2653 options::OPT_fpie, options::OPT_fno_pie);
2654 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
2655 // is forced, then neither PIC nor PIE flags will have no effect.
2656 if (!getToolChain().isPICDefaultForced()) {
2658 Option O = LastPICArg->getOption();
2659 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
2660 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
2661 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
2662 PIC = PIE || O.matches(options::OPT_fPIC) ||
2663 O.matches(options::OPT_fpic);
2664 IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
2665 O.matches(options::OPT_fPIC);
2672 // Introduce a Darwin-specific hack. If the default is PIC but the flags
2673 // specified while enabling PIC enabled level 1 PIC, just force it back to
2674 // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
2675 // informal testing).
2676 if (PIC && getToolChain().getTriple().isOSDarwin())
2677 IsPICLevelTwo |= getToolChain().isPICDefault();
2679 // Note that these flags are trump-cards. Regardless of the order w.r.t. the
2680 // PIC or PIE options above, if these show up, PIC is disabled.
2681 llvm::Triple Triple(TripleStr);
2682 if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6) ||
2683 Triple.getArch() == llvm::Triple::arm64 ||
2684 Triple.getArch() == llvm::Triple::aarch64))
2686 if (Args.hasArg(options::OPT_static))
2689 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
2690 // This is a very special mode. It trumps the other modes, almost no one
2691 // uses it, and it isn't even valid on any OS but Darwin.
2692 if (!getToolChain().getTriple().isOSDarwin())
2693 D.Diag(diag::err_drv_unsupported_opt_for_target)
2694 << A->getSpelling() << getToolChain().getTriple().str();
2696 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
2698 CmdArgs.push_back("-mrelocation-model");
2699 CmdArgs.push_back("dynamic-no-pic");
2701 // Only a forced PIC mode can cause the actual compile to have PIC defines
2702 // etc., no flags are sufficient. This behavior was selected to closely
2703 // match that of llvm-gcc and Apple GCC before that.
2704 if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
2705 CmdArgs.push_back("-pic-level");
2706 CmdArgs.push_back("2");
2709 // Currently, LLVM only knows about PIC vs. static; the PIE differences are
2710 // handled in Clang's IRGen by the -pie-level flag.
2711 CmdArgs.push_back("-mrelocation-model");
2712 CmdArgs.push_back(PIC ? "pic" : "static");
2715 CmdArgs.push_back("-pic-level");
2716 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2718 CmdArgs.push_back("-pie-level");
2719 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2724 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
2725 options::OPT_fno_merge_all_constants))
2726 CmdArgs.push_back("-fno-merge-all-constants");
2728 // LLVM Code Generator Options.
2730 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
2731 StringRef v = A->getValue();
2732 CmdArgs.push_back("-mllvm");
2733 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
2737 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2738 CmdArgs.push_back("-mregparm");
2739 CmdArgs.push_back(A->getValue());
2742 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
2743 options::OPT_freg_struct_return)) {
2744 if (getToolChain().getArch() != llvm::Triple::x86) {
2745 D.Diag(diag::err_drv_unsupported_opt_for_target)
2746 << A->getSpelling() << getToolChain().getTriple().str();
2747 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
2748 CmdArgs.push_back("-fpcc-struct-return");
2750 assert(A->getOption().matches(options::OPT_freg_struct_return));
2751 CmdArgs.push_back("-freg-struct-return");
2755 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
2756 CmdArgs.push_back("-mrtd");
2758 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
2759 CmdArgs.push_back("-mdisable-fp-elim");
2760 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
2761 options::OPT_fno_zero_initialized_in_bss))
2762 CmdArgs.push_back("-mno-zero-initialized-in-bss");
2764 bool OFastEnabled = isOptimizationLevelFast(Args);
2765 // If -Ofast is the optimization level, then -fstrict-aliasing should be
2766 // enabled. This alias option is being used to simplify the hasFlag logic.
2767 OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
2768 options::OPT_fstrict_aliasing;
2769 // We turn strict aliasing off by default if we're in CL mode, since MSVC
2770 // doesn't do any TBAA.
2771 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
2772 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
2773 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
2774 CmdArgs.push_back("-relaxed-aliasing");
2775 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
2776 options::OPT_fno_struct_path_tbaa))
2777 CmdArgs.push_back("-no-struct-path-tbaa");
2778 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
2780 CmdArgs.push_back("-fstrict-enums");
2781 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
2782 options::OPT_fno_optimize_sibling_calls))
2783 CmdArgs.push_back("-mdisable-tail-calls");
2785 // Handle segmented stacks.
2786 if (Args.hasArg(options::OPT_fsplit_stack))
2787 CmdArgs.push_back("-split-stacks");
2789 // If -Ofast is the optimization level, then -ffast-math should be enabled.
2790 // This alias option is being used to simplify the getLastArg logic.
2791 OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
2792 options::OPT_ffast_math;
2794 // Handle various floating point optimization flags, mapping them to the
2795 // appropriate LLVM code generation flags. The pattern for all of these is to
2796 // default off the codegen optimizations, and if any flag enables them and no
2797 // flag disables them after the flag enabling them, enable the codegen
2798 // optimization. This is complicated by several "umbrella" flags.
2799 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2800 options::OPT_fno_fast_math,
2801 options::OPT_ffinite_math_only,
2802 options::OPT_fno_finite_math_only,
2803 options::OPT_fhonor_infinities,
2804 options::OPT_fno_honor_infinities))
2805 if (A->getOption().getID() != options::OPT_fno_fast_math &&
2806 A->getOption().getID() != options::OPT_fno_finite_math_only &&
2807 A->getOption().getID() != options::OPT_fhonor_infinities)
2808 CmdArgs.push_back("-menable-no-infs");
2809 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2810 options::OPT_fno_fast_math,
2811 options::OPT_ffinite_math_only,
2812 options::OPT_fno_finite_math_only,
2813 options::OPT_fhonor_nans,
2814 options::OPT_fno_honor_nans))
2815 if (A->getOption().getID() != options::OPT_fno_fast_math &&
2816 A->getOption().getID() != options::OPT_fno_finite_math_only &&
2817 A->getOption().getID() != options::OPT_fhonor_nans)
2818 CmdArgs.push_back("-menable-no-nans");
2820 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2821 bool MathErrno = getToolChain().IsMathErrnoDefault();
2822 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2823 options::OPT_fno_fast_math,
2824 options::OPT_fmath_errno,
2825 options::OPT_fno_math_errno)) {
2826 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
2827 // However, turning *off* -ffast_math merely restores the toolchain default
2828 // (which may be false).
2829 if (A->getOption().getID() == options::OPT_fno_math_errno ||
2830 A->getOption().getID() == options::OPT_ffast_math ||
2831 A->getOption().getID() == options::OPT_Ofast)
2833 else if (A->getOption().getID() == options::OPT_fmath_errno)
2837 CmdArgs.push_back("-fmath-errno");
2839 // There are several flags which require disabling very specific
2840 // optimizations. Any of these being disabled forces us to turn off the
2841 // entire set of LLVM optimizations, so collect them through all the flag
2843 bool AssociativeMath = false;
2844 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2845 options::OPT_fno_fast_math,
2846 options::OPT_funsafe_math_optimizations,
2847 options::OPT_fno_unsafe_math_optimizations,
2848 options::OPT_fassociative_math,
2849 options::OPT_fno_associative_math))
2850 if (A->getOption().getID() != options::OPT_fno_fast_math &&
2851 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2852 A->getOption().getID() != options::OPT_fno_associative_math)
2853 AssociativeMath = true;
2854 bool ReciprocalMath = false;
2855 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2856 options::OPT_fno_fast_math,
2857 options::OPT_funsafe_math_optimizations,
2858 options::OPT_fno_unsafe_math_optimizations,
2859 options::OPT_freciprocal_math,
2860 options::OPT_fno_reciprocal_math))
2861 if (A->getOption().getID() != options::OPT_fno_fast_math &&
2862 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2863 A->getOption().getID() != options::OPT_fno_reciprocal_math)
2864 ReciprocalMath = true;
2865 bool SignedZeros = true;
2866 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2867 options::OPT_fno_fast_math,
2868 options::OPT_funsafe_math_optimizations,
2869 options::OPT_fno_unsafe_math_optimizations,
2870 options::OPT_fsigned_zeros,
2871 options::OPT_fno_signed_zeros))
2872 if (A->getOption().getID() != options::OPT_fno_fast_math &&
2873 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2874 A->getOption().getID() != options::OPT_fsigned_zeros)
2875 SignedZeros = false;
2876 bool TrappingMath = true;
2877 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2878 options::OPT_fno_fast_math,
2879 options::OPT_funsafe_math_optimizations,
2880 options::OPT_fno_unsafe_math_optimizations,
2881 options::OPT_ftrapping_math,
2882 options::OPT_fno_trapping_math))
2883 if (A->getOption().getID() != options::OPT_fno_fast_math &&
2884 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2885 A->getOption().getID() != options::OPT_ftrapping_math)
2886 TrappingMath = false;
2887 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2889 CmdArgs.push_back("-menable-unsafe-fp-math");
2892 // Validate and pass through -fp-contract option.
2893 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2894 options::OPT_fno_fast_math,
2895 options::OPT_ffp_contract)) {
2896 if (A->getOption().getID() == options::OPT_ffp_contract) {
2897 StringRef Val = A->getValue();
2898 if (Val == "fast" || Val == "on" || Val == "off") {
2899 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
2901 D.Diag(diag::err_drv_unsupported_option_argument)
2902 << A->getOption().getName() << Val;
2904 } else if (A->getOption().matches(options::OPT_ffast_math) ||
2905 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
2906 // If fast-math is set then set the fp-contract mode to fast.
2907 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2911 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
2912 // and if we find them, tell the frontend to provide the appropriate
2913 // preprocessor macros. This is distinct from enabling any optimizations as
2914 // these options induce language changes which must survive serialization
2915 // and deserialization, etc.
2916 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2917 options::OPT_fno_fast_math))
2918 if (!A->getOption().matches(options::OPT_fno_fast_math))
2919 CmdArgs.push_back("-ffast-math");
2920 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
2921 options::OPT_fno_fast_math))
2922 if (A->getOption().matches(options::OPT_ffinite_math_only))
2923 CmdArgs.push_back("-ffinite-math-only");
2925 // Decide whether to use verbose asm. Verbose assembly is the default on
2926 // toolchains which have the integrated assembler on by default.
2927 bool IsIntegratedAssemblerDefault =
2928 getToolChain().IsIntegratedAssemblerDefault();
2929 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2930 IsIntegratedAssemblerDefault) ||
2931 Args.hasArg(options::OPT_dA))
2932 CmdArgs.push_back("-masm-verbose");
2934 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
2935 IsIntegratedAssemblerDefault))
2936 CmdArgs.push_back("-no-integrated-as");
2938 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2939 CmdArgs.push_back("-mdebug-pass");
2940 CmdArgs.push_back("Structure");
2942 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2943 CmdArgs.push_back("-mdebug-pass");
2944 CmdArgs.push_back("Arguments");
2947 // Enable -mconstructor-aliases except on darwin, where we have to
2948 // work around a linker bug; see <rdar://problem/7651567>.
2949 if (!getToolChain().getTriple().isOSDarwin())
2950 CmdArgs.push_back("-mconstructor-aliases");
2952 // Darwin's kernel doesn't support guard variables; just die if we
2954 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2955 CmdArgs.push_back("-fforbid-guard-variables");
2957 if (Args.hasArg(options::OPT_mms_bitfields)) {
2958 CmdArgs.push_back("-mms-bitfields");
2961 // This is a coarse approximation of what llvm-gcc actually does, both
2962 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2963 // complicated ways.
2964 bool AsynchronousUnwindTables =
2965 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2966 options::OPT_fno_asynchronous_unwind_tables,
2967 (getToolChain().IsUnwindTablesDefault() ||
2968 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
2970 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2971 AsynchronousUnwindTables))
2972 CmdArgs.push_back("-munwind-tables");
2974 getToolChain().addClangTargetOptions(Args, CmdArgs);
2976 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2977 CmdArgs.push_back("-mlimit-float-precision");
2978 CmdArgs.push_back(A->getValue());
2981 // FIXME: Handle -mtune=.
2982 (void) Args.hasArg(options::OPT_mtune_EQ);
2984 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2985 CmdArgs.push_back("-mcode-model");
2986 CmdArgs.push_back(A->getValue());
2989 // Add the target cpu
2990 std::string ETripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2991 llvm::Triple ETriple(ETripleStr);
2992 std::string CPU = getCPUName(Args, ETriple);
2994 CmdArgs.push_back("-target-cpu");
2995 CmdArgs.push_back(Args.MakeArgString(CPU));
2998 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2999 CmdArgs.push_back("-mfpmath");
3000 CmdArgs.push_back(A->getValue());
3003 // Add the target features
3004 getTargetFeatures(D, ETriple, Args, CmdArgs, false);
3006 // Add target specific flags.
3007 switch(getToolChain().getArch()) {
3011 case llvm::Triple::arm:
3012 case llvm::Triple::armeb:
3013 case llvm::Triple::thumb:
3014 case llvm::Triple::thumbeb:
3015 AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
3018 case llvm::Triple::aarch64:
3019 case llvm::Triple::aarch64_be:
3020 case llvm::Triple::arm64:
3021 case llvm::Triple::arm64_be:
3022 AddAArch64TargetArgs(Args, CmdArgs);
3025 case llvm::Triple::mips:
3026 case llvm::Triple::mipsel:
3027 case llvm::Triple::mips64:
3028 case llvm::Triple::mips64el:
3029 AddMIPSTargetArgs(Args, CmdArgs);
3032 case llvm::Triple::sparc:
3033 case llvm::Triple::sparcv9:
3034 AddSparcTargetArgs(Args, CmdArgs);
3037 case llvm::Triple::x86:
3038 case llvm::Triple::x86_64:
3039 AddX86TargetArgs(Args, CmdArgs);
3042 case llvm::Triple::hexagon:
3043 AddHexagonTargetArgs(Args, CmdArgs);
3047 // Add clang-cl arguments.
3048 if (getToolChain().getDriver().IsCLMode())
3049 AddClangCLArgs(Args, CmdArgs);
3051 // Pass the linker version in use.
3052 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3053 CmdArgs.push_back("-target-linker-version");
3054 CmdArgs.push_back(A->getValue());
3057 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
3058 CmdArgs.push_back("-momit-leaf-frame-pointer");
3060 // Explicitly error on some things we know we don't support and can't just
3062 types::ID InputType = Inputs[0].getType();
3063 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3065 if (types::isCXX(InputType) &&
3066 getToolChain().getTriple().isOSDarwin() &&
3067 getToolChain().getArch() == llvm::Triple::x86) {
3068 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3069 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3070 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3071 << Unsupported->getOption().getName();
3075 Args.AddAllArgs(CmdArgs, options::OPT_v);
3076 Args.AddLastArg(CmdArgs, options::OPT_H);
3077 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3078 CmdArgs.push_back("-header-include-file");
3079 CmdArgs.push_back(D.CCPrintHeadersFilename ?
3080 D.CCPrintHeadersFilename : "-");
3082 Args.AddLastArg(CmdArgs, options::OPT_P);
3083 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3085 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3086 CmdArgs.push_back("-diagnostic-log-file");
3087 CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
3088 D.CCLogDiagnosticsFilename : "-");
3091 // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
3092 // are preserved, all other debug options are substituted with "-g".
3093 Args.ClaimAllArgs(options::OPT_g_Group);
3094 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3095 if (A->getOption().matches(options::OPT_gline_tables_only)) {
3096 // FIXME: we should support specifying dwarf version with
3097 // -gline-tables-only.
3098 CmdArgs.push_back("-gline-tables-only");
3099 // Default is dwarf-2 for Darwin, OpenBSD and FreeBSD.
3100 const llvm::Triple &Triple = getToolChain().getTriple();
3101 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3102 Triple.getOS() == llvm::Triple::FreeBSD)
3103 CmdArgs.push_back("-gdwarf-2");
3104 } else if (A->getOption().matches(options::OPT_gdwarf_2))
3105 CmdArgs.push_back("-gdwarf-2");
3106 else if (A->getOption().matches(options::OPT_gdwarf_3))
3107 CmdArgs.push_back("-gdwarf-3");
3108 else if (A->getOption().matches(options::OPT_gdwarf_4))
3109 CmdArgs.push_back("-gdwarf-4");
3110 else if (!A->getOption().matches(options::OPT_g0) &&
3111 !A->getOption().matches(options::OPT_ggdb0)) {
3112 // Default is dwarf-2 for Darwin, OpenBSD and FreeBSD.
3113 const llvm::Triple &Triple = getToolChain().getTriple();
3114 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3115 Triple.getOS() == llvm::Triple::FreeBSD)
3116 CmdArgs.push_back("-gdwarf-2");
3118 CmdArgs.push_back("-g");
3122 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
3123 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3124 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3126 CmdArgs.push_back("-dwarf-column-info");
3128 // FIXME: Move backend command line options to the module.
3129 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3130 // splitting and extraction.
3131 // FIXME: Currently only works on Linux.
3132 if (getToolChain().getTriple().isOSLinux() &&
3133 Args.hasArg(options::OPT_gsplit_dwarf)) {
3134 CmdArgs.push_back("-g");
3135 CmdArgs.push_back("-backend-option");
3136 CmdArgs.push_back("-split-dwarf=Enable");
3139 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3140 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
3141 CmdArgs.push_back("-backend-option");
3142 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
3145 // -gdwarf-aranges turns on the emission of the aranges section in the
3147 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
3148 CmdArgs.push_back("-backend-option");
3149 CmdArgs.push_back("-generate-arange-section");
3152 if (Args.hasFlag(options::OPT_fdebug_types_section,
3153 options::OPT_fno_debug_types_section, false)) {
3154 CmdArgs.push_back("-backend-option");
3155 CmdArgs.push_back("-generate-type-units");
3158 if (Args.hasFlag(options::OPT_ffunction_sections,
3159 options::OPT_fno_function_sections, false)) {
3160 CmdArgs.push_back("-ffunction-sections");
3163 if (Args.hasFlag(options::OPT_fdata_sections,
3164 options::OPT_fno_data_sections, false)) {
3165 CmdArgs.push_back("-fdata-sections");
3168 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
3170 if (Args.hasArg(options::OPT_fprofile_instr_generate) &&
3171 (Args.hasArg(options::OPT_fprofile_instr_use) ||
3172 Args.hasArg(options::OPT_fprofile_instr_use_EQ)))
3173 D.Diag(diag::err_drv_argument_not_allowed_with)
3174 << "-fprofile-instr-generate" << "-fprofile-instr-use";
3176 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3178 if (Arg *A = Args.getLastArg(options::OPT_fprofile_instr_use_EQ))
3179 A->render(Args, CmdArgs);
3180 else if (Args.hasArg(options::OPT_fprofile_instr_use))
3181 CmdArgs.push_back("-fprofile-instr-use=pgo-data");
3183 if (Args.hasArg(options::OPT_ftest_coverage) ||
3184 Args.hasArg(options::OPT_coverage))
3185 CmdArgs.push_back("-femit-coverage-notes");
3186 if (Args.hasArg(options::OPT_fprofile_arcs) ||
3187 Args.hasArg(options::OPT_coverage))
3188 CmdArgs.push_back("-femit-coverage-data");
3190 if (C.getArgs().hasArg(options::OPT_c) ||
3191 C.getArgs().hasArg(options::OPT_S)) {
3192 if (Output.isFilename()) {
3193 CmdArgs.push_back("-coverage-file");
3194 SmallString<128> CoverageFilename(Output.getFilename());
3195 if (llvm::sys::path::is_relative(CoverageFilename.str())) {
3196 SmallString<128> Pwd;
3197 if (!llvm::sys::fs::current_path(Pwd)) {
3198 llvm::sys::path::append(Pwd, CoverageFilename.str());
3199 CoverageFilename.swap(Pwd);
3202 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3206 // Pass options for controlling the default header search paths.
3207 if (Args.hasArg(options::OPT_nostdinc)) {
3208 CmdArgs.push_back("-nostdsysteminc");
3209 CmdArgs.push_back("-nobuiltininc");
3211 if (Args.hasArg(options::OPT_nostdlibinc))
3212 CmdArgs.push_back("-nostdsysteminc");
3213 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3214 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3217 // Pass the path to compiler resource files.
3218 CmdArgs.push_back("-resource-dir");
3219 CmdArgs.push_back(D.ResourceDir.c_str());
3221 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3223 bool ARCMTEnabled = false;
3224 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3225 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3226 options::OPT_ccc_arcmt_modify,
3227 options::OPT_ccc_arcmt_migrate)) {
3228 ARCMTEnabled = true;
3229 switch (A->getOption().getID()) {
3231 llvm_unreachable("missed a case");
3232 case options::OPT_ccc_arcmt_check:
3233 CmdArgs.push_back("-arcmt-check");
3235 case options::OPT_ccc_arcmt_modify:
3236 CmdArgs.push_back("-arcmt-modify");
3238 case options::OPT_ccc_arcmt_migrate:
3239 CmdArgs.push_back("-arcmt-migrate");
3240 CmdArgs.push_back("-mt-migrate-directory");
3241 CmdArgs.push_back(A->getValue());
3243 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3244 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3249 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3250 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3251 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3254 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3256 D.Diag(diag::err_drv_argument_not_allowed_with)
3257 << A->getAsString(Args) << "-ccc-arcmt-migrate";
3259 CmdArgs.push_back("-mt-migrate-directory");
3260 CmdArgs.push_back(A->getValue());
3262 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3263 options::OPT_objcmt_migrate_subscripting,
3264 options::OPT_objcmt_migrate_property)) {
3265 // None specified, means enable them all.
3266 CmdArgs.push_back("-objcmt-migrate-literals");
3267 CmdArgs.push_back("-objcmt-migrate-subscripting");
3268 CmdArgs.push_back("-objcmt-migrate-property");
3270 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3271 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3272 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3275 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3276 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3277 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3278 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3279 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3280 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3281 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3282 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3283 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3284 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3285 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3286 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3287 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3288 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3289 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3292 // Add preprocessing options like -I, -D, etc. if we are using the
3295 // FIXME: Support -fpreprocessed
3296 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3297 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3299 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3300 // that "The compiler can only warn and ignore the option if not recognized".
3301 // When building with ccache, it will pass -D options to clang even on
3302 // preprocessed inputs and configure concludes that -fPIC is not supported.
3303 Args.ClaimAllArgs(options::OPT_D);
3305 // Manually translate -O4 to -O3; let clang reject others.
3306 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3307 if (A->getOption().matches(options::OPT_O4)) {
3308 CmdArgs.push_back("-O3");
3309 D.Diag(diag::warn_O4_is_O3);
3311 A->render(Args, CmdArgs);
3315 // Warn about ignored options to clang.
3316 for (arg_iterator it = Args.filtered_begin(
3317 options::OPT_clang_ignored_gcc_optimization_f_Group),
3318 ie = Args.filtered_end(); it != ie; ++it) {
3319 D.Diag(diag::warn_ignored_gcc_optimization) << (*it)->getAsString(Args);
3322 // Don't warn about unused -flto. This can happen when we're preprocessing or
3324 Args.ClaimAllArgs(options::OPT_flto);
3326 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3327 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3328 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3329 CmdArgs.push_back("-pedantic");
3330 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3331 Args.AddLastArg(CmdArgs, options::OPT_w);
3333 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3334 // (-ansi is equivalent to -std=c89 or -std=c++98).
3336 // If a std is supplied, only add -trigraphs if it follows the
3338 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3339 if (Std->getOption().matches(options::OPT_ansi))
3340 if (types::isCXX(InputType))
3341 CmdArgs.push_back("-std=c++98");
3343 CmdArgs.push_back("-std=c89");
3345 Std->render(Args, CmdArgs);
3347 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3348 options::OPT_trigraphs))
3350 A->render(Args, CmdArgs);
3352 // Honor -std-default.
3354 // FIXME: Clang doesn't correctly handle -std= when the input language
3355 // doesn't match. For the time being just ignore this for C++ inputs;
3356 // eventually we want to do all the standard defaulting here instead of
3357 // splitting it between the driver and clang -cc1.
3358 if (!types::isCXX(InputType))
3359 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
3360 "-std=", /*Joined=*/true);
3361 else if (IsWindowsMSVC)
3362 CmdArgs.push_back("-std=c++11");
3364 Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
3367 // GCC's behavior for -Wwrite-strings is a bit strange:
3368 // * In C, this "warning flag" changes the types of string literals from
3369 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3370 // for the discarded qualifier.
3371 // * In C++, this is just a normal warning flag.
3373 // Implementing this warning correctly in C is hard, so we follow GCC's
3374 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3375 // a non-const char* in C, rather than using this crude hack.
3376 if (!types::isCXX(InputType)) {
3377 // FIXME: This should behave just like a warning flag, and thus should also
3378 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3380 Args.getLastArg(options::OPT_Wwrite_strings,
3381 options::OPT_Wno_write_strings, options::OPT_w);
3383 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3384 CmdArgs.push_back("-fconst-strings");
3387 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3388 // during C++ compilation, which it is by default. GCC keeps this define even
3389 // in the presence of '-w', match this behavior bug-for-bug.
3390 if (types::isCXX(InputType) &&
3391 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3393 CmdArgs.push_back("-fdeprecated-macro");
3396 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3397 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3398 if (Asm->getOption().matches(options::OPT_fasm))
3399 CmdArgs.push_back("-fgnu-keywords");
3401 CmdArgs.push_back("-fno-gnu-keywords");
3404 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3405 CmdArgs.push_back("-fno-dwarf-directory-asm");
3407 if (ShouldDisableAutolink(Args, getToolChain()))
3408 CmdArgs.push_back("-fno-autolink");
3410 // Add in -fdebug-compilation-dir if necessary.
3411 addDebugCompDirArg(Args, CmdArgs);
3413 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3414 options::OPT_ftemplate_depth_EQ)) {
3415 CmdArgs.push_back("-ftemplate-depth");
3416 CmdArgs.push_back(A->getValue());
3419 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3420 CmdArgs.push_back("-foperator-arrow-depth");
3421 CmdArgs.push_back(A->getValue());
3424 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3425 CmdArgs.push_back("-fconstexpr-depth");
3426 CmdArgs.push_back(A->getValue());
3429 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3430 CmdArgs.push_back("-fconstexpr-steps");
3431 CmdArgs.push_back(A->getValue());
3434 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3435 CmdArgs.push_back("-fbracket-depth");
3436 CmdArgs.push_back(A->getValue());
3439 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3440 options::OPT_Wlarge_by_value_copy_def)) {
3441 if (A->getNumValues()) {
3442 StringRef bytes = A->getValue();
3443 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3445 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3449 if (Args.hasArg(options::OPT_relocatable_pch))
3450 CmdArgs.push_back("-relocatable-pch");
3452 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3453 CmdArgs.push_back("-fconstant-string-class");
3454 CmdArgs.push_back(A->getValue());
3457 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3458 CmdArgs.push_back("-ftabstop");
3459 CmdArgs.push_back(A->getValue());
3462 CmdArgs.push_back("-ferror-limit");
3463 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3464 CmdArgs.push_back(A->getValue());
3466 CmdArgs.push_back("19");
3468 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3469 CmdArgs.push_back("-fmacro-backtrace-limit");
3470 CmdArgs.push_back(A->getValue());
3473 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3474 CmdArgs.push_back("-ftemplate-backtrace-limit");
3475 CmdArgs.push_back(A->getValue());
3478 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3479 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3480 CmdArgs.push_back(A->getValue());
3483 // Pass -fmessage-length=.
3484 CmdArgs.push_back("-fmessage-length");
3485 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3486 CmdArgs.push_back(A->getValue());
3488 // If -fmessage-length=N was not specified, determine whether this is a
3489 // terminal and, if so, implicitly define -fmessage-length appropriately.
3490 unsigned N = llvm::sys::Process::StandardErrColumns();
3491 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3494 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3495 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3496 options::OPT_fvisibility_ms_compat)) {
3497 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3498 CmdArgs.push_back("-fvisibility");
3499 CmdArgs.push_back(A->getValue());
3501 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3502 CmdArgs.push_back("-fvisibility");
3503 CmdArgs.push_back("hidden");
3504 CmdArgs.push_back("-ftype-visibility");
3505 CmdArgs.push_back("default");
3509 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3511 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3513 // -fhosted is default.
3514 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3516 CmdArgs.push_back("-ffreestanding");
3518 // Forward -f (flag) options which we can pass directly.
3519 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3520 Args.AddLastArg(CmdArgs, options::OPT_fformat_extensions);
3521 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3522 Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
3523 Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
3524 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3525 // AltiVec language extensions aren't relevant for assembling.
3526 if (!isa<PreprocessJobAction>(JA) ||
3527 Output.getType() != types::TY_PP_Asm)
3528 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
3529 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3530 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3532 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3533 Sanitize.addArgs(Args, CmdArgs);
3535 if (!Args.hasFlag(options::OPT_fsanitize_recover,
3536 options::OPT_fno_sanitize_recover,
3538 CmdArgs.push_back("-fno-sanitize-recover");
3540 if (Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
3541 options::OPT_fno_sanitize_undefined_trap_on_error, false))
3542 CmdArgs.push_back("-fsanitize-undefined-trap-on-error");
3544 // Report an error for -faltivec on anything other than PowerPC.
3545 if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
3546 if (!(getToolChain().getArch() == llvm::Triple::ppc ||
3547 getToolChain().getArch() == llvm::Triple::ppc64 ||
3548 getToolChain().getArch() == llvm::Triple::ppc64le))
3549 D.Diag(diag::err_drv_argument_only_allowed_with)
3550 << A->getAsString(Args) << "ppc/ppc64/ppc64le";
3552 if (getToolChain().SupportsProfiling())
3553 Args.AddLastArg(CmdArgs, options::OPT_pg);
3555 // -flax-vector-conversions is default.
3556 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3557 options::OPT_fno_lax_vector_conversions))
3558 CmdArgs.push_back("-fno-lax-vector-conversions");
3560 if (Args.getLastArg(options::OPT_fapple_kext))
3561 CmdArgs.push_back("-fapple-kext");
3563 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3564 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3565 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3566 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3567 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3569 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3570 CmdArgs.push_back("-ftrapv-handler");
3571 CmdArgs.push_back(A->getValue());
3574 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3576 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3577 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3578 if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
3579 options::OPT_fno_wrapv)) {
3580 if (A->getOption().matches(options::OPT_fwrapv))
3581 CmdArgs.push_back("-fwrapv");
3582 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3583 options::OPT_fno_strict_overflow)) {
3584 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3585 CmdArgs.push_back("-fwrapv");
3588 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3589 options::OPT_fno_reroll_loops))
3590 if (A->getOption().matches(options::OPT_freroll_loops))
3591 CmdArgs.push_back("-freroll-loops");
3593 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3594 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3595 options::OPT_fno_unroll_loops);
3597 Args.AddLastArg(CmdArgs, options::OPT_pthread);
3600 // -stack-protector=0 is default.
3601 unsigned StackProtectorLevel = 0;
3602 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3603 options::OPT_fstack_protector_all,
3604 options::OPT_fstack_protector_strong,
3605 options::OPT_fstack_protector)) {
3606 if (A->getOption().matches(options::OPT_fstack_protector)) {
3607 StackProtectorLevel = std::max<unsigned>(LangOptions::SSPOn,
3608 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
3609 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3610 StackProtectorLevel = LangOptions::SSPStrong;
3611 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3612 StackProtectorLevel = LangOptions::SSPReq;
3614 StackProtectorLevel =
3615 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3617 if (StackProtectorLevel) {
3618 CmdArgs.push_back("-stack-protector");
3619 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3622 // --param ssp-buffer-size=
3623 for (arg_iterator it = Args.filtered_begin(options::OPT__param),
3624 ie = Args.filtered_end(); it != ie; ++it) {
3625 StringRef Str((*it)->getValue());
3626 if (Str.startswith("ssp-buffer-size=")) {
3627 if (StackProtectorLevel) {
3628 CmdArgs.push_back("-stack-protector-buffer-size");
3629 // FIXME: Verify the argument is a valid integer.
3630 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3636 // Translate -mstackrealign
3637 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3639 CmdArgs.push_back("-backend-option");
3640 CmdArgs.push_back("-force-align-stack");
3642 if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
3644 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3647 if (Args.hasArg(options::OPT_mstack_alignment)) {
3648 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3649 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3651 // -mkernel implies -mstrict-align; don't add the redundant option.
3652 if (!KernelOrKext) {
3653 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
3654 options::OPT_munaligned_access)) {
3655 if (A->getOption().matches(options::OPT_mno_unaligned_access)) {
3656 CmdArgs.push_back("-backend-option");
3657 if (getToolChain().getTriple().getArch() == llvm::Triple::aarch64 ||
3658 getToolChain().getTriple().getArch() == llvm::Triple::aarch64_be ||
3659 getToolChain().getTriple().getArch() == llvm::Triple::arm64 ||
3660 getToolChain().getTriple().getArch() == llvm::Triple::arm64_be)
3661 CmdArgs.push_back("-aarch64-strict-align");
3663 CmdArgs.push_back("-arm-strict-align");
3665 CmdArgs.push_back("-backend-option");
3666 if (getToolChain().getTriple().getArch() == llvm::Triple::aarch64 ||
3667 getToolChain().getTriple().getArch() == llvm::Triple::aarch64_be ||
3668 getToolChain().getTriple().getArch() == llvm::Triple::arm64 ||
3669 getToolChain().getTriple().getArch() == llvm::Triple::arm64_be)
3670 CmdArgs.push_back("-aarch64-no-strict-align");
3672 CmdArgs.push_back("-arm-no-strict-align");
3677 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3678 options::OPT_mno_restrict_it)) {
3679 if (A->getOption().matches(options::OPT_mrestrict_it)) {
3680 CmdArgs.push_back("-backend-option");
3681 CmdArgs.push_back("-arm-restrict-it");
3683 CmdArgs.push_back("-backend-option");
3684 CmdArgs.push_back("-arm-no-restrict-it");
3686 } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
3687 TT.getArch() == llvm::Triple::thumb)) {
3688 // Windows on ARM expects restricted IT blocks
3689 CmdArgs.push_back("-backend-option");
3690 CmdArgs.push_back("-arm-restrict-it");
3693 if (TT.getArch() == llvm::Triple::arm ||
3694 TT.getArch() == llvm::Triple::thumb) {
3695 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
3696 options::OPT_mno_long_calls)) {
3697 if (A->getOption().matches(options::OPT_mlong_calls)) {
3698 CmdArgs.push_back("-backend-option");
3699 CmdArgs.push_back("-arm-long-calls");
3704 // Forward -f options with positive and negative forms; we translate
3706 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
3707 StringRef fname = A->getValue();
3708 if (!llvm::sys::fs::exists(fname))
3709 D.Diag(diag::err_drv_no_such_file) << fname;
3711 A->render(Args, CmdArgs);
3714 if (Args.hasArg(options::OPT_mkernel)) {
3715 if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
3716 CmdArgs.push_back("-fapple-kext");
3717 if (!Args.hasArg(options::OPT_fbuiltin))
3718 CmdArgs.push_back("-fno-builtin");
3719 Args.ClaimAllArgs(options::OPT_fno_builtin);
3721 // -fbuiltin is default.
3722 else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
3723 CmdArgs.push_back("-fno-builtin");
3725 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3726 options::OPT_fno_assume_sane_operator_new))
3727 CmdArgs.push_back("-fno-assume-sane-operator-new");
3729 // -fblocks=0 is default.
3730 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3731 getToolChain().IsBlocksDefault()) ||
3732 (Args.hasArg(options::OPT_fgnu_runtime) &&
3733 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3734 !Args.hasArg(options::OPT_fno_blocks))) {
3735 CmdArgs.push_back("-fblocks");
3737 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
3738 !getToolChain().hasBlocksRuntime())
3739 CmdArgs.push_back("-fblocks-runtime-optional");
3742 // -fmodules enables modules (off by default). However, for C++/Objective-C++,
3743 // users must also pass -fcxx-modules. The latter flag will disappear once the
3744 // modules implementation is solid for C++/Objective-C++ programs as well.
3745 bool HaveModules = false;
3746 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3747 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3748 options::OPT_fno_cxx_modules,
3750 if (AllowedInCXX || !types::isCXX(InputType)) {
3751 CmdArgs.push_back("-fmodules");
3756 // -fmodule-maps enables module map processing (off by default) for header
3757 // checking. It is implied by -fmodules.
3758 if (Args.hasFlag(options::OPT_fmodule_maps, options::OPT_fno_module_maps,
3760 CmdArgs.push_back("-fmodule-maps");
3763 // -fmodules-decluse checks that modules used are declared so (off by
3765 if (Args.hasFlag(options::OPT_fmodules_decluse,
3766 options::OPT_fno_modules_decluse,
3768 CmdArgs.push_back("-fmodules-decluse");
3771 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3772 // all #included headers are part of modules.
3773 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3774 options::OPT_fno_modules_strict_decluse,
3776 CmdArgs.push_back("-fmodules-strict-decluse");
3779 // -fmodule-name specifies the module that is currently being built (or
3780 // used for header checking by -fmodule-maps).
3781 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name))
3782 A->render(Args, CmdArgs);
3784 // -fmodule-map-file can be used to specify a file containing module
3786 if (Arg *A = Args.getLastArg(options::OPT_fmodule_map_file))
3787 A->render(Args, CmdArgs);
3789 // -fmodule-cache-path specifies where our module files should be written.
3790 SmallString<128> ModuleCachePath;
3791 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3792 ModuleCachePath = A->getValue();
3794 if (C.isForDiagnostics()) {
3795 // When generating crash reports, we want to emit the modules along with
3796 // the reproduction sources, so we ignore any provided module path.
3797 ModuleCachePath = Output.getFilename();
3798 llvm::sys::path::replace_extension(ModuleCachePath, ".cache");
3799 llvm::sys::path::append(ModuleCachePath, "modules");
3800 } else if (ModuleCachePath.empty()) {
3801 // No module path was provided: use the default.
3802 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
3804 llvm::sys::path::append(ModuleCachePath, "org.llvm.clang");
3805 llvm::sys::path::append(ModuleCachePath, "ModuleCache");
3807 const char Arg[] = "-fmodules-cache-path=";
3808 ModuleCachePath.insert(ModuleCachePath.begin(), Arg, Arg + strlen(Arg));
3809 CmdArgs.push_back(Args.MakeArgString(ModuleCachePath));
3812 // When building modules and generating crashdumps, we need to dump a module
3813 // dependency VFS alongside the output.
3814 if (HaveModules && C.isForDiagnostics()) {
3815 SmallString<128> VFSDir(Output.getFilename());
3816 llvm::sys::path::replace_extension(VFSDir, ".cache");
3817 llvm::sys::path::append(VFSDir, "vfs");
3818 CmdArgs.push_back("-module-dependency-dir");
3819 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3822 if (Arg *A = Args.getLastArg(options::OPT_fmodules_user_build_path))
3824 A->render(Args, CmdArgs);
3826 // Pass through all -fmodules-ignore-macro arguments.
3827 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3828 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3829 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3831 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3833 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3834 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp))
3835 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3837 Args.AddLastArg(CmdArgs,
3838 options::OPT_fmodules_validate_once_per_build_session);
3841 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
3843 // -faccess-control is default.
3844 if (Args.hasFlag(options::OPT_fno_access_control,
3845 options::OPT_faccess_control,
3847 CmdArgs.push_back("-fno-access-control");
3849 // -felide-constructors is the default.
3850 if (Args.hasFlag(options::OPT_fno_elide_constructors,
3851 options::OPT_felide_constructors,
3853 CmdArgs.push_back("-fno-elide-constructors");
3855 // -frtti is default.
3856 if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
3858 CmdArgs.push_back("-fno-rtti");
3860 // -fno-rtti cannot usefully be combined with -fsanitize=vptr.
3861 if (Sanitize.sanitizesVptr()) {
3862 std::string NoRttiArg =
3863 Args.getLastArg(options::OPT_mkernel,
3864 options::OPT_fapple_kext,
3865 options::OPT_fno_rtti)->getAsString(Args);
3866 D.Diag(diag::err_drv_argument_not_allowed_with)
3867 << "-fsanitize=vptr" << NoRttiArg;
3871 // -fshort-enums=0 is default for all architectures except Hexagon.
3872 if (Args.hasFlag(options::OPT_fshort_enums,
3873 options::OPT_fno_short_enums,
3874 getToolChain().getArch() ==
3875 llvm::Triple::hexagon))
3876 CmdArgs.push_back("-fshort-enums");
3878 // -fsigned-char is default.
3879 if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
3880 isSignedCharDefault(getToolChain().getTriple())))
3881 CmdArgs.push_back("-fno-signed-char");
3883 // -fthreadsafe-static is default.
3884 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3885 options::OPT_fno_threadsafe_statics))
3886 CmdArgs.push_back("-fno-threadsafe-statics");
3888 // -fuse-cxa-atexit is default.
3889 if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
3890 options::OPT_fno_use_cxa_atexit,
3891 !IsWindowsCygnus && !IsWindowsGNU &&
3892 getToolChain().getArch() != llvm::Triple::hexagon &&
3893 getToolChain().getArch() != llvm::Triple::xcore) ||
3895 CmdArgs.push_back("-fno-use-cxa-atexit");
3897 // -fms-extensions=0 is default.
3898 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3900 CmdArgs.push_back("-fms-extensions");
3902 // -fms-compatibility=0 is default.
3903 if (Args.hasFlag(options::OPT_fms_compatibility,
3904 options::OPT_fno_ms_compatibility,
3905 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
3906 options::OPT_fno_ms_extensions,
3908 CmdArgs.push_back("-fms-compatibility");
3910 // -fms-compatibility-version=17.00 is default.
3911 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3912 IsWindowsMSVC) || Args.hasArg(options::OPT_fmsc_version) ||
3913 Args.hasArg(options::OPT_fms_compatibility_version)) {
3914 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3915 const Arg *MSCompatibilityVersion =
3916 Args.getLastArg(options::OPT_fms_compatibility_version);
3918 if (MSCVersion && MSCompatibilityVersion)
3919 D.Diag(diag::err_drv_argument_not_allowed_with)
3920 << MSCVersion->getAsString(Args)
3921 << MSCompatibilityVersion->getAsString(Args);
3924 if (MSCompatibilityVersion)
3925 Ver = Args.getLastArgValue(options::OPT_fms_compatibility_version);
3926 else if (MSCVersion)
3927 Ver = getMSCompatibilityVersion(MSCVersion->getValue());
3930 CmdArgs.push_back("-fms-compatibility-version=17.00");
3932 CmdArgs.push_back(Args.MakeArgString("-fms-compatibility-version=" + Ver));
3935 // -fno-borland-extensions is default.
3936 if (Args.hasFlag(options::OPT_fborland_extensions,
3937 options::OPT_fno_borland_extensions, false))
3938 CmdArgs.push_back("-fborland-extensions");
3940 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
3942 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
3943 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
3944 CmdArgs.push_back("-fdelayed-template-parsing");
3946 // -fgnu-keywords default varies depending on language; only pass if
3948 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3949 options::OPT_fno_gnu_keywords))
3950 A->render(Args, CmdArgs);
3952 if (Args.hasFlag(options::OPT_fgnu89_inline,
3953 options::OPT_fno_gnu89_inline,
3955 CmdArgs.push_back("-fgnu89-inline");
3957 if (Args.hasArg(options::OPT_fno_inline))
3958 CmdArgs.push_back("-fno-inline");
3960 if (Args.hasArg(options::OPT_fno_inline_functions))
3961 CmdArgs.push_back("-fno-inline-functions");
3963 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3965 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3966 // legacy is the default. Except for deployment taget of 10.5,
3967 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
3968 // gets ignored silently.
3969 if (objcRuntime.isNonFragile()) {
3970 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3971 options::OPT_fno_objc_legacy_dispatch,
3972 objcRuntime.isLegacyDispatchDefaultForArch(
3973 getToolChain().getArch()))) {
3974 if (getToolChain().UseObjCMixedDispatch())
3975 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3977 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3981 // When ObjectiveC legacy runtime is in effect on MacOSX,
3982 // turn on the option to do Array/Dictionary subscripting
3984 if (getToolChain().getTriple().getArch() == llvm::Triple::x86 &&
3985 getToolChain().getTriple().isMacOSX() &&
3986 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
3987 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
3988 objcRuntime.isNeXTFamily())
3989 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3991 // -fencode-extended-block-signature=1 is default.
3992 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3993 CmdArgs.push_back("-fencode-extended-block-signature");
3996 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3997 // NOTE: This logic is duplicated in ToolChains.cpp.
3998 bool ARC = isObjCAutoRefCount(Args);
4000 getToolChain().CheckObjCARC();
4002 CmdArgs.push_back("-fobjc-arc");
4004 // FIXME: It seems like this entire block, and several around it should be
4005 // wrapped in isObjC, but for now we just use it here as this is where it
4006 // was being used previously.
4007 if (types::isCXX(InputType) && types::isObjC(InputType)) {
4008 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4009 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4011 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4014 // Allow the user to enable full exceptions code emission.
4015 // We define off for Objective-CC, on for Objective-C++.
4016 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4017 options::OPT_fno_objc_arc_exceptions,
4018 /*default*/ types::isCXX(InputType)))
4019 CmdArgs.push_back("-fobjc-arc-exceptions");
4022 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4024 if (rewriteKind != RK_None)
4025 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4027 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
4028 // takes precedence.
4029 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
4031 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
4034 D.Diag(diag::err_drv_objc_gc_arr)
4035 << GCArg->getAsString(Args);
4036 } else if (getToolChain().SupportsObjCGC()) {
4037 GCArg->render(Args, CmdArgs);
4039 // FIXME: We should move this to a hard error.
4040 D.Diag(diag::warn_drv_objc_gc_unsupported)
4041 << GCArg->getAsString(Args);
4045 // Handle GCC-style exception args.
4046 if (!C.getDriver().IsCLMode())
4047 addExceptionArgs(Args, InputType, getToolChain().getTriple(), KernelOrKext,
4048 objcRuntime, CmdArgs);
4050 if (getToolChain().UseSjLjExceptions())
4051 CmdArgs.push_back("-fsjlj-exceptions");
4053 // C++ "sane" operator new.
4054 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4055 options::OPT_fno_assume_sane_operator_new))
4056 CmdArgs.push_back("-fno-assume-sane-operator-new");
4058 // -fconstant-cfstrings is default, and may be subject to argument translation
4060 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4061 options::OPT_fno_constant_cfstrings) ||
4062 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4063 options::OPT_mno_constant_cfstrings))
4064 CmdArgs.push_back("-fno-constant-cfstrings");
4066 // -fshort-wchar default varies depending on platform; only
4067 // pass if specified.
4068 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4069 options::OPT_fno_short_wchar))
4070 A->render(Args, CmdArgs);
4072 // -fno-pascal-strings is default, only pass non-default.
4073 if (Args.hasFlag(options::OPT_fpascal_strings,
4074 options::OPT_fno_pascal_strings,
4076 CmdArgs.push_back("-fpascal-strings");
4078 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4079 // -fno-pack-struct doesn't apply to -fpack-struct=.
4080 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4081 std::string PackStructStr = "-fpack-struct=";
4082 PackStructStr += A->getValue();
4083 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4084 } else if (Args.hasFlag(options::OPT_fpack_struct,
4085 options::OPT_fno_pack_struct, false)) {
4086 CmdArgs.push_back("-fpack-struct=1");
4089 if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
4090 if (!Args.hasArg(options::OPT_fcommon))
4091 CmdArgs.push_back("-fno-common");
4092 Args.ClaimAllArgs(options::OPT_fno_common);
4095 // -fcommon is default, only pass non-default.
4096 else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
4097 CmdArgs.push_back("-fno-common");
4099 // -fsigned-bitfields is default, and clang doesn't yet support
4100 // -funsigned-bitfields.
4101 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4102 options::OPT_funsigned_bitfields))
4103 D.Diag(diag::warn_drv_clang_unsupported)
4104 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4106 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4107 if (!Args.hasFlag(options::OPT_ffor_scope,
4108 options::OPT_fno_for_scope))
4109 D.Diag(diag::err_drv_clang_unsupported)
4110 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4112 // -finput_charset=UTF-8 is default. Reject others
4113 if (Arg *inputCharset = Args.getLastArg(
4114 options::OPT_finput_charset_EQ)) {
4115 StringRef value = inputCharset->getValue();
4116 if (value != "UTF-8")
4117 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) << value;
4120 // -fcaret-diagnostics is default.
4121 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4122 options::OPT_fno_caret_diagnostics, true))
4123 CmdArgs.push_back("-fno-caret-diagnostics");
4125 // -fdiagnostics-fixit-info is default, only pass non-default.
4126 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4127 options::OPT_fno_diagnostics_fixit_info))
4128 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4130 // Enable -fdiagnostics-show-option by default.
4131 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4132 options::OPT_fno_diagnostics_show_option))
4133 CmdArgs.push_back("-fdiagnostics-show-option");
4136 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4137 CmdArgs.push_back("-fdiagnostics-show-category");
4138 CmdArgs.push_back(A->getValue());
4142 Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4143 CmdArgs.push_back("-fdiagnostics-format");
4144 CmdArgs.push_back(A->getValue());
4147 if (Arg *A = Args.getLastArg(
4148 options::OPT_fdiagnostics_show_note_include_stack,
4149 options::OPT_fno_diagnostics_show_note_include_stack)) {
4150 if (A->getOption().matches(
4151 options::OPT_fdiagnostics_show_note_include_stack))
4152 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4154 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4157 // Color diagnostics are the default, unless the terminal doesn't support
4159 // Support both clang's -f[no-]color-diagnostics and gcc's
4160 // -f[no-]diagnostics-colors[=never|always|auto].
4161 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
4162 for (const auto &Arg : Args) {
4163 const Option &O = Arg->getOption();
4164 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4165 !O.matches(options::OPT_fdiagnostics_color) &&
4166 !O.matches(options::OPT_fno_color_diagnostics) &&
4167 !O.matches(options::OPT_fno_diagnostics_color) &&
4168 !O.matches(options::OPT_fdiagnostics_color_EQ))
4172 if (O.matches(options::OPT_fcolor_diagnostics) ||
4173 O.matches(options::OPT_fdiagnostics_color)) {
4174 ShowColors = Colors_On;
4175 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
4176 O.matches(options::OPT_fno_diagnostics_color)) {
4177 ShowColors = Colors_Off;
4179 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
4180 StringRef value(Arg->getValue());
4181 if (value == "always")
4182 ShowColors = Colors_On;
4183 else if (value == "never")
4184 ShowColors = Colors_Off;
4185 else if (value == "auto")
4186 ShowColors = Colors_Auto;
4188 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4189 << ("-fdiagnostics-color=" + value).str();
4192 if (ShowColors == Colors_On ||
4193 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
4194 CmdArgs.push_back("-fcolor-diagnostics");
4196 if (Args.hasArg(options::OPT_fansi_escape_codes))
4197 CmdArgs.push_back("-fansi-escape-codes");
4199 if (!Args.hasFlag(options::OPT_fshow_source_location,
4200 options::OPT_fno_show_source_location))
4201 CmdArgs.push_back("-fno-show-source-location");
4203 if (!Args.hasFlag(options::OPT_fshow_column,
4204 options::OPT_fno_show_column,
4206 CmdArgs.push_back("-fno-show-column");
4208 if (!Args.hasFlag(options::OPT_fspell_checking,
4209 options::OPT_fno_spell_checking))
4210 CmdArgs.push_back("-fno-spell-checking");
4213 // -fno-asm-blocks is default.
4214 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4216 CmdArgs.push_back("-fasm-blocks");
4218 // Enable vectorization per default according to the optimization level
4219 // selected. For optimization levels that want vectorization we use the alias
4220 // option to simplify the hasFlag logic.
4221 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4222 OptSpecifier VectorizeAliasOption = EnableVec ? options::OPT_O_Group :
4223 options::OPT_fvectorize;
4224 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4225 options::OPT_fno_vectorize, EnableVec))
4226 CmdArgs.push_back("-vectorize-loops");
4228 // -fslp-vectorize is enabled based on the optimization level selected.
4229 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4230 OptSpecifier SLPVectAliasOption = EnableSLPVec ? options::OPT_O_Group :
4231 options::OPT_fslp_vectorize;
4232 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4233 options::OPT_fno_slp_vectorize, EnableSLPVec))
4234 CmdArgs.push_back("-vectorize-slp");
4236 // -fno-slp-vectorize-aggressive is default.
4237 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4238 options::OPT_fno_slp_vectorize_aggressive, false))
4239 CmdArgs.push_back("-vectorize-slp-aggressive");
4241 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4242 A->render(Args, CmdArgs);
4244 // -fdollars-in-identifiers default varies depending on platform and
4245 // language; only pass if specified.
4246 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4247 options::OPT_fno_dollars_in_identifiers)) {
4248 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4249 CmdArgs.push_back("-fdollars-in-identifiers");
4251 CmdArgs.push_back("-fno-dollars-in-identifiers");
4254 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4255 // practical purposes.
4256 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4257 options::OPT_fno_unit_at_a_time)) {
4258 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4259 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4262 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4263 options::OPT_fno_apple_pragma_pack, false))
4264 CmdArgs.push_back("-fapple-pragma-pack");
4266 // le32-specific flags:
4267 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4269 if (getToolChain().getArch() == llvm::Triple::le32) {
4270 CmdArgs.push_back("-fno-math-builtin");
4273 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4275 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
4277 if (getToolChain().getTriple().isOSDarwin() &&
4278 (getToolChain().getArch() == llvm::Triple::arm ||
4279 getToolChain().getArch() == llvm::Triple::thumb)) {
4280 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4281 CmdArgs.push_back("-fno-builtin-strcat");
4282 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4283 CmdArgs.push_back("-fno-builtin-strcpy");
4287 // Enable rewrite includes if the user's asked for it or if we're generating
4289 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4290 // nice to enable this when doing a crashdump for modules as well.
4291 if (Args.hasFlag(options::OPT_frewrite_includes,
4292 options::OPT_fno_rewrite_includes, false) ||
4293 (C.isForDiagnostics() && !HaveModules))
4294 CmdArgs.push_back("-frewrite-includes");
4296 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4297 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4298 options::OPT_traditional_cpp)) {
4299 if (isa<PreprocessJobAction>(JA))
4300 CmdArgs.push_back("-traditional-cpp");
4302 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4305 Args.AddLastArg(CmdArgs, options::OPT_dM);
4306 Args.AddLastArg(CmdArgs, options::OPT_dD);
4308 // Handle serialized diagnostics.
4309 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4310 CmdArgs.push_back("-serialize-diagnostic-file");
4311 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4314 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4315 CmdArgs.push_back("-fretain-comments-from-system-headers");
4317 // Forward -fcomment-block-commands to -cc1.
4318 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4319 // Forward -fparse-all-comments to -cc1.
4320 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4322 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4324 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4325 for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
4326 ie = Args.filtered_end(); it != ie; ++it) {
4329 // We translate this by hand to the -cc1 argument, since nightly test uses
4330 // it and developers have been trained to spell it with -mllvm.
4331 if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns")
4332 CmdArgs.push_back("-disable-llvm-optzns");
4334 (*it)->render(Args, CmdArgs);
4337 if (Output.getType() == types::TY_Dependencies) {
4338 // Handled with other dependency code.
4339 } else if (Output.isFilename()) {
4340 CmdArgs.push_back("-o");
4341 CmdArgs.push_back(Output.getFilename());
4343 assert(Output.isNothing() && "Invalid output.");
4346 for (const auto &II : Inputs) {
4347 addDashXForInput(Args, II, CmdArgs);
4349 if (II.isFilename())
4350 CmdArgs.push_back(II.getFilename());
4352 II.getInputArg().renderAsInput(Args, CmdArgs);
4355 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4357 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4359 // Optionally embed the -cc1 level arguments into the debug info, for build
4361 if (getToolChain().UseDwarfDebugFlags()) {
4362 ArgStringList OriginalArgs;
4363 for (const auto &Arg : Args)
4364 Arg->render(Args, OriginalArgs);
4366 SmallString<256> Flags;
4368 for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
4370 Flags += OriginalArgs[i];
4372 CmdArgs.push_back("-dwarf-debug-flags");
4373 CmdArgs.push_back(Args.MakeArgString(Flags.str()));
4376 // Add the split debug info name to the command lines here so we
4377 // can propagate it to the backend.
4378 bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
4379 getToolChain().getTriple().isOSLinux() &&
4380 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA));
4381 const char *SplitDwarfOut;
4383 CmdArgs.push_back("-split-dwarf-file");
4384 SplitDwarfOut = SplitDebugName(Args, Inputs);
4385 CmdArgs.push_back(SplitDwarfOut);
4388 // Finally add the compile command to the compilation.
4389 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4390 Output.getType() == types::TY_Object &&
4391 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4392 Command *CLCommand = getCLFallback()->GetCommand(C, JA, Output, Inputs,
4393 Args, LinkingOutput);
4394 C.addCommand(new FallbackCommand(JA, *this, Exec, CmdArgs, CLCommand));
4396 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4400 // Handle the debug info splitting at object creation time if we're
4401 // creating an object.
4402 // TODO: Currently only works on linux with newer objcopy.
4403 if (SplitDwarf && !isa<CompileJobAction>(JA))
4404 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4406 if (Arg *A = Args.getLastArg(options::OPT_pg))
4407 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4408 D.Diag(diag::err_drv_argument_not_allowed_with)
4409 << "-fomit-frame-pointer" << A->getAsString(Args);
4411 // Claim some arguments which clang supports automatically.
4413 // -fpch-preprocess is used with gcc to add a special marker in the output to
4414 // include the PCH file. Clang's PTH solution is completely transparent, so we
4415 // do not need to deal with it at all.
4416 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4418 // Claim some arguments which clang doesn't support, but we don't
4419 // care to warn the user about.
4420 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4421 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4423 // Disable warnings for clang -E -emit-llvm foo.c
4424 Args.ClaimAllArgs(options::OPT_emit_llvm);
4427 /// Add options related to the Objective-C runtime/ABI.
4429 /// Returns true if the runtime is non-fragile.
4430 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4431 ArgStringList &cmdArgs,
4432 RewriteKind rewriteKind) const {
4433 // Look for the controlling runtime option.
4434 Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
4435 options::OPT_fgnu_runtime,
4436 options::OPT_fobjc_runtime_EQ);
4438 // Just forward -fobjc-runtime= to the frontend. This supercedes
4439 // options about fragility.
4441 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4442 ObjCRuntime runtime;
4443 StringRef value = runtimeArg->getValue();
4444 if (runtime.tryParse(value)) {
4445 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4449 runtimeArg->render(args, cmdArgs);
4453 // Otherwise, we'll need the ABI "version". Version numbers are
4454 // slightly confusing for historical reasons:
4455 // 1 - Traditional "fragile" ABI
4456 // 2 - Non-fragile ABI, version 1
4457 // 3 - Non-fragile ABI, version 2
4458 unsigned objcABIVersion = 1;
4459 // If -fobjc-abi-version= is present, use that to set the version.
4460 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4461 StringRef value = abiArg->getValue();
4464 else if (value == "2")
4466 else if (value == "3")
4469 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4472 // Otherwise, determine if we are using the non-fragile ABI.
4473 bool nonFragileABIIsDefault =
4474 (rewriteKind == RK_NonFragile ||
4475 (rewriteKind == RK_None &&
4476 getToolChain().IsObjCNonFragileABIDefault()));
4477 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4478 options::OPT_fno_objc_nonfragile_abi,
4479 nonFragileABIIsDefault)) {
4480 // Determine the non-fragile ABI version to use.
4481 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4482 unsigned nonFragileABIVersion = 1;
4484 unsigned nonFragileABIVersion = 2;
4487 if (Arg *abiArg = args.getLastArg(
4488 options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4489 StringRef value = abiArg->getValue();
4491 nonFragileABIVersion = 1;
4492 else if (value == "2")
4493 nonFragileABIVersion = 2;
4495 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4499 objcABIVersion = 1 + nonFragileABIVersion;
4505 // We don't actually care about the ABI version other than whether
4506 // it's non-fragile.
4507 bool isNonFragile = objcABIVersion != 1;
4509 // If we have no runtime argument, ask the toolchain for its default runtime.
4510 // However, the rewriter only really supports the Mac runtime, so assume that.
4511 ObjCRuntime runtime;
4513 switch (rewriteKind) {
4515 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4518 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4521 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4526 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4527 // On Darwin, make this use the default behavior for the toolchain.
4528 if (getToolChain().getTriple().isOSDarwin()) {
4529 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4531 // Otherwise, build for a generic macosx port.
4533 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4538 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4539 // Legacy behaviour is to target the gnustep runtime if we are i
4540 // non-fragile mode or the GCC runtime in fragile mode.
4542 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
4544 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4547 cmdArgs.push_back(args.MakeArgString(
4548 "-fobjc-runtime=" + runtime.getAsString()));
4552 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4553 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4559 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
4565 /// /EH controls whether to run destructor cleanups when exceptions are
4566 /// thrown. There are three modifiers:
4567 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4568 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4569 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4570 /// - c: Assume that extern "C" functions are implicitly noexcept. This
4571 /// modifier is an optimization, so we ignore it for now.
4572 /// The default is /EHs-c-, meaning cleanups are disabled.
4573 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4575 std::vector<std::string> EHArgs = Args.getAllArgValues(options::OPT__SLASH_EH);
4576 for (auto EHVal : EHArgs) {
4577 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4579 case 'a': EH.Asynch = maybeConsumeDash(EHVal, I); continue;
4580 case 'c': EH.NoExceptC = maybeConsumeDash(EHVal, I); continue;
4581 case 's': EH.Synch = maybeConsumeDash(EHVal, I); continue;
4584 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4591 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
4592 unsigned RTOptionID = options::OPT__SLASH_MT;
4594 if (Args.hasArg(options::OPT__SLASH_LDd))
4595 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4596 // but defining _DEBUG is sticky.
4597 RTOptionID = options::OPT__SLASH_MTd;
4599 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4600 RTOptionID = A->getOption().getID();
4602 switch(RTOptionID) {
4603 case options::OPT__SLASH_MD:
4604 if (Args.hasArg(options::OPT__SLASH_LDd))
4605 CmdArgs.push_back("-D_DEBUG");
4606 CmdArgs.push_back("-D_MT");
4607 CmdArgs.push_back("-D_DLL");
4608 CmdArgs.push_back("--dependent-lib=msvcrt");
4610 case options::OPT__SLASH_MDd:
4611 CmdArgs.push_back("-D_DEBUG");
4612 CmdArgs.push_back("-D_MT");
4613 CmdArgs.push_back("-D_DLL");
4614 CmdArgs.push_back("--dependent-lib=msvcrtd");
4616 case options::OPT__SLASH_MT:
4617 if (Args.hasArg(options::OPT__SLASH_LDd))
4618 CmdArgs.push_back("-D_DEBUG");
4619 CmdArgs.push_back("-D_MT");
4620 CmdArgs.push_back("--dependent-lib=libcmt");
4622 case options::OPT__SLASH_MTd:
4623 CmdArgs.push_back("-D_DEBUG");
4624 CmdArgs.push_back("-D_MT");
4625 CmdArgs.push_back("--dependent-lib=libcmtd");
4628 llvm_unreachable("Unexpected option ID.");
4631 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4632 // users want. The /Za flag to cl.exe turns this off, but it's not
4633 // implemented in clang.
4634 CmdArgs.push_back("--dependent-lib=oldnames");
4636 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4637 // would produce interleaved output, so ignore /showIncludes in such cases.
4638 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
4639 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4640 A->render(Args, CmdArgs);
4642 // This controls whether or not we emit RTTI data for polymorphic types.
4643 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4645 CmdArgs.push_back("-fno-rtti-data");
4647 const Driver &D = getToolChain().getDriver();
4648 EHFlags EH = parseClangCLEHFlags(D, Args);
4649 // FIXME: Do something with NoExceptC.
4650 if (EH.Synch || EH.Asynch) {
4651 CmdArgs.push_back("-fexceptions");
4652 CmdArgs.push_back("-fcxx-exceptions");
4655 // /EP should expand to -E -P.
4656 if (Args.hasArg(options::OPT__SLASH_EP)) {
4657 CmdArgs.push_back("-E");
4658 CmdArgs.push_back("-P");
4661 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
4662 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
4663 if (MostGeneralArg && BestCaseArg)
4664 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4665 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
4667 if (MostGeneralArg) {
4668 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
4669 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
4670 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
4672 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
4673 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
4674 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
4675 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4676 << FirstConflict->getAsString(Args)
4677 << SecondConflict->getAsString(Args);
4680 CmdArgs.push_back("-fms-memptr-rep=single");
4681 else if (MultipleArg)
4682 CmdArgs.push_back("-fms-memptr-rep=multiple");
4684 CmdArgs.push_back("-fms-memptr-rep=virtual");
4687 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
4688 A->render(Args, CmdArgs);
4690 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
4691 CmdArgs.push_back("-fdiagnostics-format");
4692 if (Args.hasArg(options::OPT__SLASH_fallback))
4693 CmdArgs.push_back("msvc-fallback");
4695 CmdArgs.push_back("msvc");
4699 visualstudio::Compile *Clang::getCLFallback() const {
4701 CLFallback.reset(new visualstudio::Compile(getToolChain()));
4702 return CLFallback.get();
4705 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
4706 const InputInfo &Output,
4707 const InputInfoList &Inputs,
4708 const ArgList &Args,
4709 const char *LinkingOutput) const {
4710 ArgStringList CmdArgs;
4712 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4713 const InputInfo &Input = Inputs[0];
4715 // Don't warn about "clang -w -c foo.s"
4716 Args.ClaimAllArgs(options::OPT_w);
4717 // and "clang -emit-llvm -c foo.s"
4718 Args.ClaimAllArgs(options::OPT_emit_llvm);
4720 // Invoke ourselves in -cc1as mode.
4722 // FIXME: Implement custom jobs for internal actions.
4723 CmdArgs.push_back("-cc1as");
4725 // Add the "effective" target triple.
4726 CmdArgs.push_back("-triple");
4727 std::string TripleStr =
4728 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
4729 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4731 // Set the output mode, we currently only expect to be used as a real
4733 CmdArgs.push_back("-filetype");
4734 CmdArgs.push_back("obj");
4736 // Set the main file name, so that debug info works even with
4737 // -save-temps or preprocessed assembly.
4738 CmdArgs.push_back("-main-file-name");
4739 CmdArgs.push_back(Clang::getBaseInputName(Args, Inputs));
4741 // Add the target cpu
4742 const llvm::Triple &Triple = getToolChain().getTriple();
4743 std::string CPU = getCPUName(Args, Triple);
4745 CmdArgs.push_back("-target-cpu");
4746 CmdArgs.push_back(Args.MakeArgString(CPU));
4749 // Add the target features
4750 const Driver &D = getToolChain().getDriver();
4751 getTargetFeatures(D, Triple, Args, CmdArgs, true);
4753 // Ignore explicit -force_cpusubtype_ALL option.
4754 (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
4756 // Determine the original source input.
4757 const Action *SourceAction = &JA;
4758 while (SourceAction->getKind() != Action::InputClass) {
4759 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4760 SourceAction = SourceAction->getInputs()[0];
4763 // Forward -g and handle debug info related flags, assuming we are dealing
4764 // with an actual assembly file.
4765 if (SourceAction->getType() == types::TY_Asm ||
4766 SourceAction->getType() == types::TY_PP_Asm) {
4767 Args.ClaimAllArgs(options::OPT_g_Group);
4768 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
4769 if (!A->getOption().matches(options::OPT_g0))
4770 CmdArgs.push_back("-g");
4772 if (Args.hasArg(options::OPT_gdwarf_2))
4773 CmdArgs.push_back("-gdwarf-2");
4774 if (Args.hasArg(options::OPT_gdwarf_3))
4775 CmdArgs.push_back("-gdwarf-3");
4776 if (Args.hasArg(options::OPT_gdwarf_4))
4777 CmdArgs.push_back("-gdwarf-4");
4779 // Add the -fdebug-compilation-dir flag if needed.
4780 addDebugCompDirArg(Args, CmdArgs);
4782 // Set the AT_producer to the clang version when using the integrated
4783 // assembler on assembly source files.
4784 CmdArgs.push_back("-dwarf-debug-producer");
4785 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
4788 // Optionally embed the -cc1as level arguments into the debug info, for build
4790 if (getToolChain().UseDwarfDebugFlags()) {
4791 ArgStringList OriginalArgs;
4792 for (const auto &Arg : Args)
4793 Arg->render(Args, OriginalArgs);
4795 SmallString<256> Flags;
4796 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4798 for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
4800 Flags += OriginalArgs[i];
4802 CmdArgs.push_back("-dwarf-debug-flags");
4803 CmdArgs.push_back(Args.MakeArgString(Flags.str()));
4806 // FIXME: Add -static support, once we have it.
4808 // Consume all the warning flags. Usually this would be handled more
4809 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
4810 // doesn't handle that so rather than warning about unused flags that are
4811 // actually used, we'll lie by omission instead.
4812 // FIXME: Stop lying and consume only the appropriate driver flags
4813 for (arg_iterator it = Args.filtered_begin(options::OPT_W_Group),
4814 ie = Args.filtered_end();
4818 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
4819 getToolChain().getDriver());
4821 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
4823 assert(Output.isFilename() && "Unexpected lipo output.");
4824 CmdArgs.push_back("-o");
4825 CmdArgs.push_back(Output.getFilename());
4827 assert(Input.isFilename() && "Invalid input.");
4828 CmdArgs.push_back(Input.getFilename());
4830 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4831 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4833 // Handle the debug info splitting at object creation time if we're
4834 // creating an object.
4835 // TODO: Currently only works on linux with newer objcopy.
4836 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
4837 getToolChain().getTriple().isOSLinux())
4838 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
4839 SplitDebugName(Args, Inputs));
4842 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
4843 const InputInfo &Output,
4844 const InputInfoList &Inputs,
4845 const ArgList &Args,
4846 const char *LinkingOutput) const {
4847 const Driver &D = getToolChain().getDriver();
4848 ArgStringList CmdArgs;
4850 for (const auto &A : Args) {
4851 if (forwardToGCC(A->getOption())) {
4852 // Don't forward any -g arguments to assembly steps.
4853 if (isa<AssembleJobAction>(JA) &&
4854 A->getOption().matches(options::OPT_g_Group))
4857 // Don't forward any -W arguments to assembly and link steps.
4858 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
4859 A->getOption().matches(options::OPT_W_Group))
4862 // It is unfortunate that we have to claim here, as this means
4863 // we will basically never report anything interesting for
4864 // platforms using a generic gcc, even if we are just using gcc
4865 // to get to the assembler.
4867 A->render(Args, CmdArgs);
4871 RenderExtraToolArgs(JA, CmdArgs);
4873 // If using a driver driver, force the arch.
4874 llvm::Triple::ArchType Arch = getToolChain().getArch();
4875 if (getToolChain().getTriple().isOSDarwin()) {
4876 CmdArgs.push_back("-arch");
4878 // FIXME: Remove these special cases.
4879 if (Arch == llvm::Triple::ppc)
4880 CmdArgs.push_back("ppc");
4881 else if (Arch == llvm::Triple::ppc64)
4882 CmdArgs.push_back("ppc64");
4883 else if (Arch == llvm::Triple::ppc64le)
4884 CmdArgs.push_back("ppc64le");
4886 CmdArgs.push_back(Args.MakeArgString(getToolChain().getArchName()));
4889 // Try to force gcc to match the tool chain we want, if we recognize
4892 // FIXME: The triple class should directly provide the information we want
4894 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
4895 CmdArgs.push_back("-m32");
4896 else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
4897 Arch == llvm::Triple::ppc64le)
4898 CmdArgs.push_back("-m64");
4900 if (Output.isFilename()) {
4901 CmdArgs.push_back("-o");
4902 CmdArgs.push_back(Output.getFilename());
4904 assert(Output.isNothing() && "Unexpected output");
4905 CmdArgs.push_back("-fsyntax-only");
4908 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4909 options::OPT_Xassembler);
4911 // Only pass -x if gcc will understand it; otherwise hope gcc
4912 // understands the suffix correctly. The main use case this would go
4913 // wrong in is for linker inputs if they happened to have an odd
4914 // suffix; really the only way to get this to happen is a command
4915 // like '-x foobar a.c' which will treat a.c like a linker input.
4917 // FIXME: For the linker case specifically, can we safely convert
4918 // inputs into '-Wl,' options?
4919 for (const auto &II : Inputs) {
4920 // Don't try to pass LLVM or AST inputs to a generic gcc.
4921 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
4922 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
4923 D.Diag(diag::err_drv_no_linker_llvm_support)
4924 << getToolChain().getTripleString();
4925 else if (II.getType() == types::TY_AST)
4926 D.Diag(diag::err_drv_no_ast_support)
4927 << getToolChain().getTripleString();
4928 else if (II.getType() == types::TY_ModuleFile)
4929 D.Diag(diag::err_drv_no_module_support)
4930 << getToolChain().getTripleString();
4932 if (types::canTypeBeUserSpecified(II.getType())) {
4933 CmdArgs.push_back("-x");
4934 CmdArgs.push_back(types::getTypeName(II.getType()));
4937 if (II.isFilename())
4938 CmdArgs.push_back(II.getFilename());
4940 const Arg &A = II.getInputArg();
4942 // Reverse translate some rewritten options.
4943 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
4944 CmdArgs.push_back("-lstdc++");
4948 // Don't render as input, we need gcc to do the translations.
4949 A.render(Args, CmdArgs);
4953 const std::string customGCCName = D.getCCCGenericGCCName();
4954 const char *GCCName;
4955 if (!customGCCName.empty())
4956 GCCName = customGCCName.c_str();
4957 else if (D.CCCIsCXX()) {
4963 Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
4964 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4967 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
4968 ArgStringList &CmdArgs) const {
4969 CmdArgs.push_back("-E");
4972 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
4973 ArgStringList &CmdArgs) const {
4974 const Driver &D = getToolChain().getDriver();
4976 // If -flto, etc. are present then make sure not to force assembly output.
4977 if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
4978 JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
4979 CmdArgs.push_back("-c");
4981 if (JA.getType() != types::TY_PP_Asm)
4982 D.Diag(diag::err_drv_invalid_gcc_output_type)
4983 << getTypeName(JA.getType());
4985 CmdArgs.push_back("-S");
4989 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
4990 ArgStringList &CmdArgs) const {
4991 // The types are (hopefully) good enough.
4994 // Hexagon tools start.
4995 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
4996 ArgStringList &CmdArgs) const {
4999 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5000 const InputInfo &Output,
5001 const InputInfoList &Inputs,
5002 const ArgList &Args,
5003 const char *LinkingOutput) const {
5005 const Driver &D = getToolChain().getDriver();
5006 ArgStringList CmdArgs;
5008 std::string MarchString = "-march=";
5009 MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
5010 CmdArgs.push_back(Args.MakeArgString(MarchString));
5012 RenderExtraToolArgs(JA, CmdArgs);
5014 if (Output.isFilename()) {
5015 CmdArgs.push_back("-o");
5016 CmdArgs.push_back(Output.getFilename());
5018 assert(Output.isNothing() && "Unexpected output");
5019 CmdArgs.push_back("-fsyntax-only");
5022 std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
5023 if (!SmallDataThreshold.empty())
5025 Args.MakeArgString(std::string("-G") + SmallDataThreshold));
5027 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5028 options::OPT_Xassembler);
5030 // Only pass -x if gcc will understand it; otherwise hope gcc
5031 // understands the suffix correctly. The main use case this would go
5032 // wrong in is for linker inputs if they happened to have an odd
5033 // suffix; really the only way to get this to happen is a command
5034 // like '-x foobar a.c' which will treat a.c like a linker input.
5036 // FIXME: For the linker case specifically, can we safely convert
5037 // inputs into '-Wl,' options?
5038 for (const auto &II : Inputs) {
5039 // Don't try to pass LLVM or AST inputs to a generic gcc.
5040 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5041 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5042 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
5043 << getToolChain().getTripleString();
5044 else if (II.getType() == types::TY_AST)
5045 D.Diag(clang::diag::err_drv_no_ast_support)
5046 << getToolChain().getTripleString();
5047 else if (II.getType() == types::TY_ModuleFile)
5048 D.Diag(diag::err_drv_no_module_support)
5049 << getToolChain().getTripleString();
5051 if (II.isFilename())
5052 CmdArgs.push_back(II.getFilename());
5054 // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
5055 II.getInputArg().render(Args, CmdArgs);
5058 const char *GCCName = "hexagon-as";
5059 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5060 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5063 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
5064 ArgStringList &CmdArgs) const {
5065 // The types are (hopefully) good enough.
5068 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
5069 const InputInfo &Output,
5070 const InputInfoList &Inputs,
5071 const ArgList &Args,
5072 const char *LinkingOutput) const {
5074 const toolchains::Hexagon_TC& ToolChain =
5075 static_cast<const toolchains::Hexagon_TC&>(getToolChain());
5076 const Driver &D = ToolChain.getDriver();
5078 ArgStringList CmdArgs;
5080 //----------------------------------------------------------------------------
5082 //----------------------------------------------------------------------------
5083 bool hasStaticArg = Args.hasArg(options::OPT_static);
5084 bool buildingLib = Args.hasArg(options::OPT_shared);
5085 bool buildPIE = Args.hasArg(options::OPT_pie);
5086 bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
5087 bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
5088 bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
5089 bool useShared = buildingLib && !hasStaticArg;
5091 //----------------------------------------------------------------------------
5092 // Silence warnings for various options
5093 //----------------------------------------------------------------------------
5095 Args.ClaimAllArgs(options::OPT_g_Group);
5096 Args.ClaimAllArgs(options::OPT_emit_llvm);
5097 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
5098 // handled somewhere else.
5099 Args.ClaimAllArgs(options::OPT_static_libgcc);
5101 //----------------------------------------------------------------------------
5103 //----------------------------------------------------------------------------
5104 for (const auto &Opt : ToolChain.ExtraOpts)
5105 CmdArgs.push_back(Opt.c_str());
5107 std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
5108 CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
5111 CmdArgs.push_back("-shared");
5112 CmdArgs.push_back("-call_shared"); // should be the default, but doing as
5117 CmdArgs.push_back("-static");
5119 if (buildPIE && !buildingLib)
5120 CmdArgs.push_back("-pie");
5122 std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
5123 if (!SmallDataThreshold.empty()) {
5125 Args.MakeArgString(std::string("-G") + SmallDataThreshold));
5128 //----------------------------------------------------------------------------
5130 //----------------------------------------------------------------------------
5131 CmdArgs.push_back("-o");
5132 CmdArgs.push_back(Output.getFilename());
5134 const std::string MarchSuffix = "/" + MarchString;
5135 const std::string G0Suffix = "/G0";
5136 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
5137 const std::string RootDir = toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir)
5139 const std::string StartFilesDir = RootDir
5142 ? MarchG0Suffix : MarchSuffix);
5144 //----------------------------------------------------------------------------
5146 //----------------------------------------------------------------------------
5147 std::vector<std::string> oslibs;
5148 bool hasStandalone= false;
5150 for (arg_iterator it = Args.filtered_begin(options::OPT_moslib_EQ),
5151 ie = Args.filtered_end(); it != ie; ++it) {
5153 oslibs.push_back((*it)->getValue());
5154 hasStandalone = hasStandalone || (oslibs.back() == "standalone");
5156 if (oslibs.empty()) {
5157 oslibs.push_back("standalone");
5158 hasStandalone = true;
5161 //----------------------------------------------------------------------------
5163 //----------------------------------------------------------------------------
5164 if (incStdLib && incStartFiles) {
5167 if (hasStandalone) {
5169 Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
5171 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
5173 std::string initObj = useShared ? "/initS.o" : "/init.o";
5174 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
5177 //----------------------------------------------------------------------------
5178 // Library Search Paths
5179 //----------------------------------------------------------------------------
5180 const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
5181 for (const auto &LibPath : LibPaths)
5182 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
5184 //----------------------------------------------------------------------------
5186 //----------------------------------------------------------------------------
5187 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5188 Args.AddAllArgs(CmdArgs, options::OPT_e);
5189 Args.AddAllArgs(CmdArgs, options::OPT_s);
5190 Args.AddAllArgs(CmdArgs, options::OPT_t);
5191 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5193 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5195 //----------------------------------------------------------------------------
5197 //----------------------------------------------------------------------------
5198 if (incStdLib && incDefLibs) {
5200 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5201 CmdArgs.push_back("-lm");
5204 CmdArgs.push_back("--start-group");
5207 for(std::vector<std::string>::iterator i = oslibs.begin(),
5208 e = oslibs.end(); i != e; ++i)
5209 CmdArgs.push_back(Args.MakeArgString("-l" + *i));
5210 CmdArgs.push_back("-lc");
5212 CmdArgs.push_back("-lgcc");
5214 CmdArgs.push_back("--end-group");
5217 //----------------------------------------------------------------------------
5219 //----------------------------------------------------------------------------
5220 if (incStdLib && incStartFiles) {
5221 std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
5222 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
5225 std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
5226 C.addCommand(new Command(JA, *this, Args.MakeArgString(Linker), CmdArgs));
5228 // Hexagon tools end.
5230 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
5231 const char *arm::getARMCPUForMArch(const ArgList &Args,
5232 const llvm::Triple &Triple) {
5234 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
5235 // Otherwise, if we have -march= choose the base CPU for that arch.
5236 MArch = A->getValue();
5238 // Otherwise, use the Arch from the triple.
5239 MArch = Triple.getArchName();
5242 // Handle -march=native.
5243 if (MArch == "native") {
5244 std::string CPU = llvm::sys::getHostCPUName();
5245 if (CPU != "generic") {
5246 // Translate the native cpu into the architecture. The switch below will
5247 // then chose the minimum cpu for that arch.
5248 MArch = std::string("arm") + arm::getLLVMArchSuffixForARM(CPU);
5252 return Triple.getARMCPUForArch(MArch);
5255 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
5256 StringRef arm::getARMTargetCPU(const ArgList &Args,
5257 const llvm::Triple &Triple) {
5258 // FIXME: Warn on inconsistent use of -mcpu and -march.
5259 // If we have -mcpu=, use that.
5260 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
5261 StringRef MCPU = A->getValue();
5262 // Handle -mcpu=native.
5263 if (MCPU == "native")
5264 return llvm::sys::getHostCPUName();
5269 return getARMCPUForMArch(Args, Triple);
5272 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
5275 // FIXME: This is redundant with -mcpu, why does LLVM use this.
5276 // FIXME: tblgen this, or kill it!
5277 const char *arm::getLLVMArchSuffixForARM(StringRef CPU) {
5278 return llvm::StringSwitch<const char *>(CPU)
5279 .Case("strongarm", "v4")
5280 .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
5281 .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
5282 .Cases("arm920", "arm920t", "arm922t", "v4t")
5283 .Cases("arm940t", "ep9312","v4t")
5284 .Cases("arm10tdmi", "arm1020t", "v5")
5285 .Cases("arm9e", "arm926ej-s", "arm946e-s", "v5e")
5286 .Cases("arm966e-s", "arm968e-s", "arm10e", "v5e")
5287 .Cases("arm1020e", "arm1022e", "xscale", "iwmmxt", "v5e")
5288 .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "v6")
5289 .Cases("arm1176jzf-s", "mpcorenovfp", "mpcore", "v6")
5290 .Cases("arm1156t2-s", "arm1156t2f-s", "v6t2")
5291 .Cases("cortex-a5", "cortex-a7", "cortex-a8", "cortex-a9-mp", "v7")
5292 .Cases("cortex-a9", "cortex-a12", "cortex-a15", "krait", "v7")
5293 .Cases("cortex-r4", "cortex-r5", "v7r")
5294 .Case("cortex-m0", "v6m")
5295 .Case("cortex-m3", "v7m")
5296 .Case("cortex-m4", "v7em")
5297 .Case("swift", "v7s")
5298 .Case("cyclone", "v8")
5299 .Cases("cortex-a53", "cortex-a57", "v8")
5303 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
5304 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
5305 return A && (A->getValue() == StringRef(Value));
5308 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
5309 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
5310 return llvm::StringSwitch<bool>(NaNArg->getValue())
5312 .Case("legacy", false)
5315 // NaN2008 is the default for MIPS32r6/MIPS64r6.
5316 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
5317 .Cases("mips32r6", "mips64r6", true)
5323 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
5324 StringRef ABIName) {
5325 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
5326 Triple.getVendor() != llvm::Triple::MipsTechnologies)
5329 if (ABIName != "32")
5332 return llvm::StringSwitch<bool>(CPUName)
5333 .Cases("mips2", "mips3", "mips4", "mips5", true)
5334 .Cases("mips32", "mips32r2", true)
5335 .Cases("mips64", "mips64r2", true)
5339 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
5340 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
5341 // archs which Darwin doesn't use.
5343 // The matching this routine does is fairly pointless, since it is neither the
5344 // complete architecture list, nor a reasonable subset. The problem is that
5345 // historically the driver driver accepts this and also ties its -march=
5346 // handling to the architecture name, so we need to be careful before removing
5349 // This code must be kept in sync with Clang's Darwin specific argument
5352 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
5353 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
5354 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
5355 .Case("ppc64", llvm::Triple::ppc64)
5356 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
5357 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
5359 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
5360 // This is derived from the driver driver.
5361 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
5362 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
5363 .Cases("armv7s", "xscale", llvm::Triple::arm)
5364 .Case("arm64", llvm::Triple::arm64)
5365 .Case("r600", llvm::Triple::r600)
5366 .Case("nvptx", llvm::Triple::nvptx)
5367 .Case("nvptx64", llvm::Triple::nvptx64)
5368 .Case("amdil", llvm::Triple::amdil)
5369 .Case("spir", llvm::Triple::spir)
5370 .Default(llvm::Triple::UnknownArch);
5373 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
5374 llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
5377 if (Str == "x86_64h")
5379 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
5380 T.setOS(llvm::Triple::UnknownOS);
5381 T.setObjectFormat(llvm::Triple::MachO);
5385 const char *Clang::getBaseInputName(const ArgList &Args,
5386 const InputInfoList &Inputs) {
5387 return Args.MakeArgString(
5388 llvm::sys::path::filename(Inputs[0].getBaseInput()));
5391 const char *Clang::getBaseInputStem(const ArgList &Args,
5392 const InputInfoList &Inputs) {
5393 const char *Str = getBaseInputName(Args, Inputs);
5395 if (const char *End = strrchr(Str, '.'))
5396 return Args.MakeArgString(std::string(Str, End));
5401 const char *Clang::getDependencyFileName(const ArgList &Args,
5402 const InputInfoList &Inputs) {
5403 // FIXME: Think about this more.
5406 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5407 std::string Str(OutputOpt->getValue());
5408 Res = Str.substr(0, Str.rfind('.'));
5410 Res = getBaseInputStem(Args, Inputs);
5412 return Args.MakeArgString(Res + ".d");
5415 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5416 const InputInfo &Output,
5417 const InputInfoList &Inputs,
5418 const ArgList &Args,
5419 const char *LinkingOutput) const {
5420 ArgStringList CmdArgs;
5422 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5423 const InputInfo &Input = Inputs[0];
5425 // Determine the original source input.
5426 const Action *SourceAction = &JA;
5427 while (SourceAction->getKind() != Action::InputClass) {
5428 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5429 SourceAction = SourceAction->getInputs()[0];
5432 // If -fno_integrated_as is used add -Q to the darwin assember driver to make
5433 // sure it runs its system assembler not clang's integrated assembler.
5434 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
5435 // FIXME: at run-time detect assembler capabilities or rely on version
5436 // information forwarded by -target-assembler-version (future)
5437 if (Args.hasArg(options::OPT_fno_integrated_as)) {
5438 const llvm::Triple &T(getToolChain().getTriple());
5439 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
5440 CmdArgs.push_back("-Q");
5443 // Forward -g, assuming we are dealing with an actual assembly file.
5444 if (SourceAction->getType() == types::TY_Asm ||
5445 SourceAction->getType() == types::TY_PP_Asm) {
5446 if (Args.hasArg(options::OPT_gstabs))
5447 CmdArgs.push_back("--gstabs");
5448 else if (Args.hasArg(options::OPT_g_Group))
5449 CmdArgs.push_back("-g");
5452 // Derived from asm spec.
5453 AddMachOArch(Args, CmdArgs);
5455 // Use -force_cpusubtype_ALL on x86 by default.
5456 if (getToolChain().getArch() == llvm::Triple::x86 ||
5457 getToolChain().getArch() == llvm::Triple::x86_64 ||
5458 Args.hasArg(options::OPT_force__cpusubtype__ALL))
5459 CmdArgs.push_back("-force_cpusubtype_ALL");
5461 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
5462 (((Args.hasArg(options::OPT_mkernel) ||
5463 Args.hasArg(options::OPT_fapple_kext)) &&
5464 getMachOToolChain().isKernelStatic()) ||
5465 Args.hasArg(options::OPT_static)))
5466 CmdArgs.push_back("-static");
5468 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5469 options::OPT_Xassembler);
5471 assert(Output.isFilename() && "Unexpected lipo output.");
5472 CmdArgs.push_back("-o");
5473 CmdArgs.push_back(Output.getFilename());
5475 assert(Input.isFilename() && "Invalid input.");
5476 CmdArgs.push_back(Input.getFilename());
5478 // asm_final spec is empty.
5481 Args.MakeArgString(getToolChain().GetProgramPath("as"));
5482 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5485 void darwin::MachOTool::anchor() {}
5487 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
5488 ArgStringList &CmdArgs) const {
5489 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
5491 // Derived from darwin_arch spec.
5492 CmdArgs.push_back("-arch");
5493 CmdArgs.push_back(Args.MakeArgString(ArchName));
5495 // FIXME: Is this needed anymore?
5496 if (ArchName == "arm")
5497 CmdArgs.push_back("-force_cpusubtype_ALL");
5500 bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
5501 // We only need to generate a temp path for LTO if we aren't compiling object
5502 // files. When compiling source files, we run 'dsymutil' after linking. We
5503 // don't run 'dsymutil' when compiling object files.
5504 for (const auto &Input : Inputs)
5505 if (Input.getType() != types::TY_Object)
5511 void darwin::Link::AddLinkArgs(Compilation &C,
5512 const ArgList &Args,
5513 ArgStringList &CmdArgs,
5514 const InputInfoList &Inputs) const {
5515 const Driver &D = getToolChain().getDriver();
5516 const toolchains::MachO &MachOTC = getMachOToolChain();
5518 unsigned Version[3] = { 0, 0, 0 };
5519 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5521 if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
5522 Version[1], Version[2], HadExtra) ||
5524 D.Diag(diag::err_drv_invalid_version_number)
5525 << A->getAsString(Args);
5528 // Newer linkers support -demangle. Pass it if supported and not disabled by
5530 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
5531 CmdArgs.push_back("-demangle");
5533 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
5534 CmdArgs.push_back("-export_dynamic");
5536 // If we are using LTO, then automatically create a temporary file path for
5537 // the linker to use, so that it's lifetime will extend past a possible
5539 if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
5540 const char *TmpPath = C.getArgs().MakeArgString(
5541 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
5542 C.addTempFile(TmpPath);
5543 CmdArgs.push_back("-object_path_lto");
5544 CmdArgs.push_back(TmpPath);
5547 // Derived from the "link" spec.
5548 Args.AddAllArgs(CmdArgs, options::OPT_static);
5549 if (!Args.hasArg(options::OPT_static))
5550 CmdArgs.push_back("-dynamic");
5551 if (Args.hasArg(options::OPT_fgnu_runtime)) {
5552 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
5553 // here. How do we wish to handle such things?
5556 if (!Args.hasArg(options::OPT_dynamiclib)) {
5557 AddMachOArch(Args, CmdArgs);
5558 // FIXME: Why do this only on this path?
5559 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
5561 Args.AddLastArg(CmdArgs, options::OPT_bundle);
5562 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
5563 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
5566 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
5567 (A = Args.getLastArg(options::OPT_current__version)) ||
5568 (A = Args.getLastArg(options::OPT_install__name)))
5569 D.Diag(diag::err_drv_argument_only_allowed_with)
5570 << A->getAsString(Args) << "-dynamiclib";
5572 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
5573 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
5574 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
5576 CmdArgs.push_back("-dylib");
5579 if ((A = Args.getLastArg(options::OPT_bundle)) ||
5580 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
5581 (A = Args.getLastArg(options::OPT_client__name)) ||
5582 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
5583 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
5584 (A = Args.getLastArg(options::OPT_private__bundle)))
5585 D.Diag(diag::err_drv_argument_not_allowed_with)
5586 << A->getAsString(Args) << "-dynamiclib";
5588 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
5589 "-dylib_compatibility_version");
5590 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
5591 "-dylib_current_version");
5593 AddMachOArch(Args, CmdArgs);
5595 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
5596 "-dylib_install_name");
5599 Args.AddLastArg(CmdArgs, options::OPT_all__load);
5600 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
5601 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
5602 if (MachOTC.isTargetIOSBased())
5603 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
5604 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
5605 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
5606 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
5607 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
5608 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
5609 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
5610 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
5611 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
5612 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
5613 Args.AddAllArgs(CmdArgs, options::OPT_init);
5615 // Add the deployment target.
5616 MachOTC.addMinVersionArgs(Args, CmdArgs);
5618 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
5619 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
5620 Args.AddLastArg(CmdArgs, options::OPT_single__module);
5621 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
5622 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
5624 if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
5625 options::OPT_fno_pie,
5626 options::OPT_fno_PIE)) {
5627 if (A->getOption().matches(options::OPT_fpie) ||
5628 A->getOption().matches(options::OPT_fPIE))
5629 CmdArgs.push_back("-pie");
5631 CmdArgs.push_back("-no_pie");
5634 Args.AddLastArg(CmdArgs, options::OPT_prebind);
5635 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
5636 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
5637 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
5638 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
5639 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
5640 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
5641 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
5642 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
5643 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
5644 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
5645 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
5646 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
5647 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
5648 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
5649 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
5651 // Give --sysroot= preference, over the Apple specific behavior to also use
5652 // --isysroot as the syslibroot.
5653 StringRef sysroot = C.getSysRoot();
5654 if (sysroot != "") {
5655 CmdArgs.push_back("-syslibroot");
5656 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
5657 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
5658 CmdArgs.push_back("-syslibroot");
5659 CmdArgs.push_back(A->getValue());
5662 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
5663 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
5664 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
5665 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
5666 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
5667 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
5668 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
5669 Args.AddAllArgs(CmdArgs, options::OPT_y);
5670 Args.AddLastArg(CmdArgs, options::OPT_w);
5671 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
5672 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
5673 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
5674 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
5675 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
5676 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
5677 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
5678 Args.AddLastArg(CmdArgs, options::OPT_whyload);
5679 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
5680 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
5681 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
5682 Args.AddLastArg(CmdArgs, options::OPT_Mach);
5691 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
5692 const InputInfo &Output,
5693 const InputInfoList &Inputs,
5694 const ArgList &Args,
5695 const char *LinkingOutput) const {
5696 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
5698 // The logic here is derived from gcc's behavior; most of which
5699 // comes from specs (starting with link_command). Consult gcc for
5700 // more information.
5701 ArgStringList CmdArgs;
5703 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
5704 if (Args.hasArg(options::OPT_ccc_arcmt_check,
5705 options::OPT_ccc_arcmt_migrate)) {
5706 for (const auto &Arg : Args)
5709 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
5710 CmdArgs.push_back(Output.getFilename());
5711 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5715 // I'm not sure why this particular decomposition exists in gcc, but
5716 // we follow suite for ease of comparison.
5717 AddLinkArgs(C, Args, CmdArgs, Inputs);
5719 Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
5720 Args.AddAllArgs(CmdArgs, options::OPT_s);
5721 Args.AddAllArgs(CmdArgs, options::OPT_t);
5722 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5723 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5724 Args.AddLastArg(CmdArgs, options::OPT_e);
5725 Args.AddAllArgs(CmdArgs, options::OPT_r);
5727 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
5728 // members of static archive libraries which implement Objective-C classes or
5730 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
5731 CmdArgs.push_back("-ObjC");
5733 CmdArgs.push_back("-o");
5734 CmdArgs.push_back(Output.getFilename());
5736 if (!Args.hasArg(options::OPT_nostdlib) &&
5737 !Args.hasArg(options::OPT_nostartfiles))
5738 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
5740 Args.AddAllArgs(CmdArgs, options::OPT_L);
5742 LibOpenMP UsedOpenMPLib = LibUnknown;
5743 if (Args.hasArg(options::OPT_fopenmp)) {
5744 UsedOpenMPLib = LibGOMP;
5745 } else if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
5746 UsedOpenMPLib = llvm::StringSwitch<LibOpenMP>(A->getValue())
5747 .Case("libgomp", LibGOMP)
5748 .Case("libiomp5", LibIOMP5)
5749 .Default(LibUnknown);
5750 if (UsedOpenMPLib == LibUnknown)
5751 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5752 << A->getOption().getName() << A->getValue();
5754 switch (UsedOpenMPLib) {
5756 CmdArgs.push_back("-lgomp");
5759 CmdArgs.push_back("-liomp5");
5765 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5767 if (isObjCRuntimeLinked(Args) &&
5768 !Args.hasArg(options::OPT_nostdlib) &&
5769 !Args.hasArg(options::OPT_nodefaultlibs)) {
5770 // We use arclite library for both ARC and subscripting support.
5771 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
5773 CmdArgs.push_back("-framework");
5774 CmdArgs.push_back("Foundation");
5776 CmdArgs.push_back("-lobjc");
5779 if (LinkingOutput) {
5780 CmdArgs.push_back("-arch_multiple");
5781 CmdArgs.push_back("-final_output");
5782 CmdArgs.push_back(LinkingOutput);
5785 if (Args.hasArg(options::OPT_fnested_functions))
5786 CmdArgs.push_back("-allow_stack_execute");
5788 if (!Args.hasArg(options::OPT_nostdlib) &&
5789 !Args.hasArg(options::OPT_nodefaultlibs)) {
5790 if (getToolChain().getDriver().CCCIsCXX())
5791 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5793 // link_ssp spec is empty.
5795 // Let the tool chain choose which runtime library to link.
5796 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
5799 if (!Args.hasArg(options::OPT_nostdlib) &&
5800 !Args.hasArg(options::OPT_nostartfiles)) {
5801 // endfile_spec is empty.
5804 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5805 Args.AddAllArgs(CmdArgs, options::OPT_F);
5808 Args.MakeArgString(getToolChain().GetLinkerPath());
5809 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5812 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
5813 const InputInfo &Output,
5814 const InputInfoList &Inputs,
5815 const ArgList &Args,
5816 const char *LinkingOutput) const {
5817 ArgStringList CmdArgs;
5819 CmdArgs.push_back("-create");
5820 assert(Output.isFilename() && "Unexpected lipo output.");
5822 CmdArgs.push_back("-output");
5823 CmdArgs.push_back(Output.getFilename());
5825 for (const auto &II : Inputs) {
5826 assert(II.isFilename() && "Unexpected lipo input.");
5827 CmdArgs.push_back(II.getFilename());
5830 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
5831 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5834 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
5835 const InputInfo &Output,
5836 const InputInfoList &Inputs,
5837 const ArgList &Args,
5838 const char *LinkingOutput) const {
5839 ArgStringList CmdArgs;
5841 CmdArgs.push_back("-o");
5842 CmdArgs.push_back(Output.getFilename());
5844 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5845 const InputInfo &Input = Inputs[0];
5846 assert(Input.isFilename() && "Unexpected dsymutil input.");
5847 CmdArgs.push_back(Input.getFilename());
5850 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
5851 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5854 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
5855 const InputInfo &Output,
5856 const InputInfoList &Inputs,
5857 const ArgList &Args,
5858 const char *LinkingOutput) const {
5859 ArgStringList CmdArgs;
5860 CmdArgs.push_back("--verify");
5861 CmdArgs.push_back("--debug-info");
5862 CmdArgs.push_back("--eh-frame");
5863 CmdArgs.push_back("--quiet");
5865 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5866 const InputInfo &Input = Inputs[0];
5867 assert(Input.isFilename() && "Unexpected verify input");
5869 // Grabbing the output of the earlier dsymutil run.
5870 CmdArgs.push_back(Input.getFilename());
5873 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
5874 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5877 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5878 const InputInfo &Output,
5879 const InputInfoList &Inputs,
5880 const ArgList &Args,
5881 const char *LinkingOutput) const {
5882 ArgStringList CmdArgs;
5884 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5885 options::OPT_Xassembler);
5887 CmdArgs.push_back("-o");
5888 CmdArgs.push_back(Output.getFilename());
5890 for (const auto &II : Inputs)
5891 CmdArgs.push_back(II.getFilename());
5893 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
5894 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5897 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
5898 const InputInfo &Output,
5899 const InputInfoList &Inputs,
5900 const ArgList &Args,
5901 const char *LinkingOutput) const {
5902 // FIXME: Find a real GCC, don't hard-code versions here
5903 std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
5904 const llvm::Triple &T = getToolChain().getTriple();
5905 std::string LibPath = "/usr/lib/";
5906 llvm::Triple::ArchType Arch = T.getArch();
5908 case llvm::Triple::x86:
5910 ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
5912 case llvm::Triple::x86_64:
5913 GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
5914 GCCLibPath += "/4.5.2/amd64/";
5915 LibPath += "amd64/";
5918 llvm_unreachable("Unsupported architecture");
5921 ArgStringList CmdArgs;
5923 // Demangle C++ names in errors
5924 CmdArgs.push_back("-C");
5926 if ((!Args.hasArg(options::OPT_nostdlib)) &&
5927 (!Args.hasArg(options::OPT_shared))) {
5928 CmdArgs.push_back("-e");
5929 CmdArgs.push_back("_start");
5932 if (Args.hasArg(options::OPT_static)) {
5933 CmdArgs.push_back("-Bstatic");
5934 CmdArgs.push_back("-dn");
5936 CmdArgs.push_back("-Bdynamic");
5937 if (Args.hasArg(options::OPT_shared)) {
5938 CmdArgs.push_back("-shared");
5940 CmdArgs.push_back("--dynamic-linker");
5941 CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
5945 if (Output.isFilename()) {
5946 CmdArgs.push_back("-o");
5947 CmdArgs.push_back(Output.getFilename());
5949 assert(Output.isNothing() && "Invalid output.");
5952 if (!Args.hasArg(options::OPT_nostdlib) &&
5953 !Args.hasArg(options::OPT_nostartfiles)) {
5954 if (!Args.hasArg(options::OPT_shared)) {
5955 CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
5956 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
5957 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
5958 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
5960 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
5961 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
5962 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
5964 if (getToolChain().getDriver().CCCIsCXX())
5965 CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
5968 CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
5970 Args.AddAllArgs(CmdArgs, options::OPT_L);
5971 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5972 Args.AddAllArgs(CmdArgs, options::OPT_e);
5973 Args.AddAllArgs(CmdArgs, options::OPT_r);
5975 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5977 if (!Args.hasArg(options::OPT_nostdlib) &&
5978 !Args.hasArg(options::OPT_nodefaultlibs)) {
5979 if (getToolChain().getDriver().CCCIsCXX())
5980 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5981 CmdArgs.push_back("-lgcc_s");
5982 if (!Args.hasArg(options::OPT_shared)) {
5983 CmdArgs.push_back("-lgcc");
5984 CmdArgs.push_back("-lc");
5985 CmdArgs.push_back("-lm");
5989 if (!Args.hasArg(options::OPT_nostdlib) &&
5990 !Args.hasArg(options::OPT_nostartfiles)) {
5991 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
5993 CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
5995 addProfileRT(getToolChain(), Args, CmdArgs);
5998 Args.MakeArgString(getToolChain().GetLinkerPath());
5999 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6002 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6003 const InputInfo &Output,
6004 const InputInfoList &Inputs,
6005 const ArgList &Args,
6006 const char *LinkingOutput) const {
6007 ArgStringList CmdArgs;
6009 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6010 options::OPT_Xassembler);
6012 CmdArgs.push_back("-o");
6013 CmdArgs.push_back(Output.getFilename());
6015 for (const auto &II : Inputs)
6016 CmdArgs.push_back(II.getFilename());
6018 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("gas"));
6019 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6022 void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
6023 const InputInfo &Output,
6024 const InputInfoList &Inputs,
6025 const ArgList &Args,
6026 const char *LinkingOutput) const {
6027 ArgStringList CmdArgs;
6029 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6030 (!Args.hasArg(options::OPT_shared))) {
6031 CmdArgs.push_back("-e");
6032 CmdArgs.push_back("_start");
6035 if (Args.hasArg(options::OPT_static)) {
6036 CmdArgs.push_back("-Bstatic");
6037 CmdArgs.push_back("-dn");
6039 // CmdArgs.push_back("--eh-frame-hdr");
6040 CmdArgs.push_back("-Bdynamic");
6041 if (Args.hasArg(options::OPT_shared)) {
6042 CmdArgs.push_back("-shared");
6044 CmdArgs.push_back("--dynamic-linker");
6045 CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
6049 if (Output.isFilename()) {
6050 CmdArgs.push_back("-o");
6051 CmdArgs.push_back(Output.getFilename());
6053 assert(Output.isNothing() && "Invalid output.");
6056 if (!Args.hasArg(options::OPT_nostdlib) &&
6057 !Args.hasArg(options::OPT_nostartfiles)) {
6058 if (!Args.hasArg(options::OPT_shared)) {
6059 CmdArgs.push_back(Args.MakeArgString(
6060 getToolChain().GetFilePath("crt1.o")));
6061 CmdArgs.push_back(Args.MakeArgString(
6062 getToolChain().GetFilePath("crti.o")));
6063 CmdArgs.push_back(Args.MakeArgString(
6064 getToolChain().GetFilePath("crtbegin.o")));
6066 CmdArgs.push_back(Args.MakeArgString(
6067 getToolChain().GetFilePath("crti.o")));
6069 CmdArgs.push_back(Args.MakeArgString(
6070 getToolChain().GetFilePath("crtn.o")));
6073 CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
6074 + getToolChain().getTripleString()
6077 Args.AddAllArgs(CmdArgs, options::OPT_L);
6078 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6079 Args.AddAllArgs(CmdArgs, options::OPT_e);
6081 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6083 if (!Args.hasArg(options::OPT_nostdlib) &&
6084 !Args.hasArg(options::OPT_nodefaultlibs)) {
6085 // FIXME: For some reason GCC passes -lgcc before adding
6086 // the default system libraries. Just mimic this for now.
6087 CmdArgs.push_back("-lgcc");
6089 if (Args.hasArg(options::OPT_pthread))
6090 CmdArgs.push_back("-pthread");
6091 if (!Args.hasArg(options::OPT_shared))
6092 CmdArgs.push_back("-lc");
6093 CmdArgs.push_back("-lgcc");
6096 if (!Args.hasArg(options::OPT_nostdlib) &&
6097 !Args.hasArg(options::OPT_nostartfiles)) {
6098 if (!Args.hasArg(options::OPT_shared))
6099 CmdArgs.push_back(Args.MakeArgString(
6100 getToolChain().GetFilePath("crtend.o")));
6103 addProfileRT(getToolChain(), Args, CmdArgs);
6106 Args.MakeArgString(getToolChain().GetLinkerPath());
6107 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6110 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6111 const InputInfo &Output,
6112 const InputInfoList &Inputs,
6113 const ArgList &Args,
6114 const char *LinkingOutput) const {
6115 ArgStringList CmdArgs;
6116 bool NeedsKPIC = false;
6118 switch (getToolChain().getArch()) {
6119 case llvm::Triple::x86:
6120 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
6121 // instruct as in the base system to assemble 32-bit code.
6122 CmdArgs.push_back("--32");
6125 case llvm::Triple::ppc:
6126 CmdArgs.push_back("-mppc");
6127 CmdArgs.push_back("-many");
6130 case llvm::Triple::sparc:
6131 CmdArgs.push_back("-32");
6135 case llvm::Triple::sparcv9:
6136 CmdArgs.push_back("-64");
6137 CmdArgs.push_back("-Av9a");
6141 case llvm::Triple::mips64:
6142 case llvm::Triple::mips64el: {
6145 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6147 CmdArgs.push_back("-mabi");
6148 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6150 if (getToolChain().getArch() == llvm::Triple::mips64)
6151 CmdArgs.push_back("-EB");
6153 CmdArgs.push_back("-EL");
6164 addAssemblerKPIC(Args, CmdArgs);
6166 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6167 options::OPT_Xassembler);
6169 CmdArgs.push_back("-o");
6170 CmdArgs.push_back(Output.getFilename());
6172 for (const auto &II : Inputs)
6173 CmdArgs.push_back(II.getFilename());
6176 Args.MakeArgString(getToolChain().GetProgramPath("as"));
6177 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6180 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6181 const InputInfo &Output,
6182 const InputInfoList &Inputs,
6183 const ArgList &Args,
6184 const char *LinkingOutput) const {
6185 const Driver &D = getToolChain().getDriver();
6186 ArgStringList CmdArgs;
6188 // Silence warning for "clang -g foo.o -o foo"
6189 Args.ClaimAllArgs(options::OPT_g_Group);
6190 // and "clang -emit-llvm foo.o -o foo"
6191 Args.ClaimAllArgs(options::OPT_emit_llvm);
6192 // and for "clang -w foo.o -o foo". Other warning options are already
6193 // handled somewhere else.
6194 Args.ClaimAllArgs(options::OPT_w);
6196 if (getToolChain().getArch() == llvm::Triple::mips64)
6197 CmdArgs.push_back("-EB");
6198 else if (getToolChain().getArch() == llvm::Triple::mips64el)
6199 CmdArgs.push_back("-EL");
6201 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6202 (!Args.hasArg(options::OPT_shared))) {
6203 CmdArgs.push_back("-e");
6204 CmdArgs.push_back("__start");
6207 if (Args.hasArg(options::OPT_static)) {
6208 CmdArgs.push_back("-Bstatic");
6210 if (Args.hasArg(options::OPT_rdynamic))
6211 CmdArgs.push_back("-export-dynamic");
6212 CmdArgs.push_back("--eh-frame-hdr");
6213 CmdArgs.push_back("-Bdynamic");
6214 if (Args.hasArg(options::OPT_shared)) {
6215 CmdArgs.push_back("-shared");
6217 CmdArgs.push_back("-dynamic-linker");
6218 CmdArgs.push_back("/usr/libexec/ld.so");
6222 if (Args.hasArg(options::OPT_nopie))
6223 CmdArgs.push_back("-nopie");
6225 if (Output.isFilename()) {
6226 CmdArgs.push_back("-o");
6227 CmdArgs.push_back(Output.getFilename());
6229 assert(Output.isNothing() && "Invalid output.");
6232 if (!Args.hasArg(options::OPT_nostdlib) &&
6233 !Args.hasArg(options::OPT_nostartfiles)) {
6234 if (!Args.hasArg(options::OPT_shared)) {
6235 if (Args.hasArg(options::OPT_pg))
6236 CmdArgs.push_back(Args.MakeArgString(
6237 getToolChain().GetFilePath("gcrt0.o")));
6239 CmdArgs.push_back(Args.MakeArgString(
6240 getToolChain().GetFilePath("crt0.o")));
6241 CmdArgs.push_back(Args.MakeArgString(
6242 getToolChain().GetFilePath("crtbegin.o")));
6244 CmdArgs.push_back(Args.MakeArgString(
6245 getToolChain().GetFilePath("crtbeginS.o")));
6249 std::string Triple = getToolChain().getTripleString();
6250 if (Triple.substr(0, 6) == "x86_64")
6251 Triple.replace(0, 6, "amd64");
6252 CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
6255 Args.AddAllArgs(CmdArgs, options::OPT_L);
6256 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6257 Args.AddAllArgs(CmdArgs, options::OPT_e);
6258 Args.AddAllArgs(CmdArgs, options::OPT_s);
6259 Args.AddAllArgs(CmdArgs, options::OPT_t);
6260 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6261 Args.AddAllArgs(CmdArgs, options::OPT_r);
6263 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6265 if (!Args.hasArg(options::OPT_nostdlib) &&
6266 !Args.hasArg(options::OPT_nodefaultlibs)) {
6268 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6269 if (Args.hasArg(options::OPT_pg))
6270 CmdArgs.push_back("-lm_p");
6272 CmdArgs.push_back("-lm");
6275 // FIXME: For some reason GCC passes -lgcc before adding
6276 // the default system libraries. Just mimic this for now.
6277 CmdArgs.push_back("-lgcc");
6279 if (Args.hasArg(options::OPT_pthread)) {
6280 if (!Args.hasArg(options::OPT_shared) &&
6281 Args.hasArg(options::OPT_pg))
6282 CmdArgs.push_back("-lpthread_p");
6284 CmdArgs.push_back("-lpthread");
6287 if (!Args.hasArg(options::OPT_shared)) {
6288 if (Args.hasArg(options::OPT_pg))
6289 CmdArgs.push_back("-lc_p");
6291 CmdArgs.push_back("-lc");
6294 CmdArgs.push_back("-lgcc");
6297 if (!Args.hasArg(options::OPT_nostdlib) &&
6298 !Args.hasArg(options::OPT_nostartfiles)) {
6299 if (!Args.hasArg(options::OPT_shared))
6300 CmdArgs.push_back(Args.MakeArgString(
6301 getToolChain().GetFilePath("crtend.o")));
6303 CmdArgs.push_back(Args.MakeArgString(
6304 getToolChain().GetFilePath("crtendS.o")));
6308 Args.MakeArgString(getToolChain().GetLinkerPath());
6309 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6312 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6313 const InputInfo &Output,
6314 const InputInfoList &Inputs,
6315 const ArgList &Args,
6316 const char *LinkingOutput) const {
6317 ArgStringList CmdArgs;
6319 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6320 options::OPT_Xassembler);
6322 CmdArgs.push_back("-o");
6323 CmdArgs.push_back(Output.getFilename());
6325 for (const auto &II : Inputs)
6326 CmdArgs.push_back(II.getFilename());
6328 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6329 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6332 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
6333 const InputInfo &Output,
6334 const InputInfoList &Inputs,
6335 const ArgList &Args,
6336 const char *LinkingOutput) const {
6337 const Driver &D = getToolChain().getDriver();
6338 ArgStringList CmdArgs;
6340 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6341 (!Args.hasArg(options::OPT_shared))) {
6342 CmdArgs.push_back("-e");
6343 CmdArgs.push_back("__start");
6346 if (Args.hasArg(options::OPT_static)) {
6347 CmdArgs.push_back("-Bstatic");
6349 if (Args.hasArg(options::OPT_rdynamic))
6350 CmdArgs.push_back("-export-dynamic");
6351 CmdArgs.push_back("--eh-frame-hdr");
6352 CmdArgs.push_back("-Bdynamic");
6353 if (Args.hasArg(options::OPT_shared)) {
6354 CmdArgs.push_back("-shared");
6356 CmdArgs.push_back("-dynamic-linker");
6357 CmdArgs.push_back("/usr/libexec/ld.so");
6361 if (Output.isFilename()) {
6362 CmdArgs.push_back("-o");
6363 CmdArgs.push_back(Output.getFilename());
6365 assert(Output.isNothing() && "Invalid output.");
6368 if (!Args.hasArg(options::OPT_nostdlib) &&
6369 !Args.hasArg(options::OPT_nostartfiles)) {
6370 if (!Args.hasArg(options::OPT_shared)) {
6371 if (Args.hasArg(options::OPT_pg))
6372 CmdArgs.push_back(Args.MakeArgString(
6373 getToolChain().GetFilePath("gcrt0.o")));
6375 CmdArgs.push_back(Args.MakeArgString(
6376 getToolChain().GetFilePath("crt0.o")));
6377 CmdArgs.push_back(Args.MakeArgString(
6378 getToolChain().GetFilePath("crtbegin.o")));
6380 CmdArgs.push_back(Args.MakeArgString(
6381 getToolChain().GetFilePath("crtbeginS.o")));
6385 Args.AddAllArgs(CmdArgs, options::OPT_L);
6386 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6387 Args.AddAllArgs(CmdArgs, options::OPT_e);
6389 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6391 if (!Args.hasArg(options::OPT_nostdlib) &&
6392 !Args.hasArg(options::OPT_nodefaultlibs)) {
6394 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6395 if (Args.hasArg(options::OPT_pg))
6396 CmdArgs.push_back("-lm_p");
6398 CmdArgs.push_back("-lm");
6401 if (Args.hasArg(options::OPT_pthread)) {
6402 if (!Args.hasArg(options::OPT_shared) &&
6403 Args.hasArg(options::OPT_pg))
6404 CmdArgs.push_back("-lpthread_p");
6406 CmdArgs.push_back("-lpthread");
6409 if (!Args.hasArg(options::OPT_shared)) {
6410 if (Args.hasArg(options::OPT_pg))
6411 CmdArgs.push_back("-lc_p");
6413 CmdArgs.push_back("-lc");
6417 switch (getToolChain().getTriple().getArch()) {
6418 case llvm::Triple::arm:
6421 case llvm::Triple::x86:
6424 case llvm::Triple::x86_64:
6428 llvm_unreachable("Unsupported architecture");
6430 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
6433 if (!Args.hasArg(options::OPT_nostdlib) &&
6434 !Args.hasArg(options::OPT_nostartfiles)) {
6435 if (!Args.hasArg(options::OPT_shared))
6436 CmdArgs.push_back(Args.MakeArgString(
6437 getToolChain().GetFilePath("crtend.o")));
6439 CmdArgs.push_back(Args.MakeArgString(
6440 getToolChain().GetFilePath("crtendS.o")));
6444 Args.MakeArgString(getToolChain().GetLinkerPath());
6445 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6448 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6449 const InputInfo &Output,
6450 const InputInfoList &Inputs,
6451 const ArgList &Args,
6452 const char *LinkingOutput) const {
6453 ArgStringList CmdArgs;
6455 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
6456 // instruct as in the base system to assemble 32-bit code.
6457 if (getToolChain().getArch() == llvm::Triple::x86)
6458 CmdArgs.push_back("--32");
6459 else if (getToolChain().getArch() == llvm::Triple::ppc)
6460 CmdArgs.push_back("-a32");
6461 else if (getToolChain().getArch() == llvm::Triple::mips ||
6462 getToolChain().getArch() == llvm::Triple::mipsel ||
6463 getToolChain().getArch() == llvm::Triple::mips64 ||
6464 getToolChain().getArch() == llvm::Triple::mips64el) {
6467 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6469 CmdArgs.push_back("-march");
6470 CmdArgs.push_back(CPUName.data());
6472 CmdArgs.push_back("-mabi");
6473 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6475 if (getToolChain().getArch() == llvm::Triple::mips ||
6476 getToolChain().getArch() == llvm::Triple::mips64)
6477 CmdArgs.push_back("-EB");
6479 CmdArgs.push_back("-EL");
6481 addAssemblerKPIC(Args, CmdArgs);
6482 } else if (getToolChain().getArch() == llvm::Triple::arm ||
6483 getToolChain().getArch() == llvm::Triple::armeb ||
6484 getToolChain().getArch() == llvm::Triple::thumb ||
6485 getToolChain().getArch() == llvm::Triple::thumbeb) {
6486 const Driver &D = getToolChain().getDriver();
6487 const llvm::Triple &Triple = getToolChain().getTriple();
6488 StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
6490 if (FloatABI == "hard") {
6491 CmdArgs.push_back("-mfpu=vfp");
6493 CmdArgs.push_back("-mfpu=softvfp");
6496 switch(getToolChain().getTriple().getEnvironment()) {
6497 case llvm::Triple::GNUEABIHF:
6498 case llvm::Triple::GNUEABI:
6499 case llvm::Triple::EABI:
6500 CmdArgs.push_back("-meabi=5");
6504 CmdArgs.push_back("-matpcs");
6506 } else if (getToolChain().getArch() == llvm::Triple::sparc ||
6507 getToolChain().getArch() == llvm::Triple::sparcv9) {
6508 if (getToolChain().getArch() == llvm::Triple::sparc)
6509 CmdArgs.push_back("-Av8plusa");
6511 CmdArgs.push_back("-Av9a");
6513 addAssemblerKPIC(Args, CmdArgs);
6516 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6517 options::OPT_Xassembler);
6519 CmdArgs.push_back("-o");
6520 CmdArgs.push_back(Output.getFilename());
6522 for (const auto &II : Inputs)
6523 CmdArgs.push_back(II.getFilename());
6525 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6526 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6529 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6530 const InputInfo &Output,
6531 const InputInfoList &Inputs,
6532 const ArgList &Args,
6533 const char *LinkingOutput) const {
6534 const toolchains::FreeBSD& ToolChain =
6535 static_cast<const toolchains::FreeBSD&>(getToolChain());
6536 const Driver &D = ToolChain.getDriver();
6538 !Args.hasArg(options::OPT_shared) &&
6539 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
6540 ArgStringList CmdArgs;
6542 // Silence warning for "clang -g foo.o -o foo"
6543 Args.ClaimAllArgs(options::OPT_g_Group);
6544 // and "clang -emit-llvm foo.o -o foo"
6545 Args.ClaimAllArgs(options::OPT_emit_llvm);
6546 // and for "clang -w foo.o -o foo". Other warning options are already
6547 // handled somewhere else.
6548 Args.ClaimAllArgs(options::OPT_w);
6550 if (!D.SysRoot.empty())
6551 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6554 CmdArgs.push_back("-pie");
6556 if (Args.hasArg(options::OPT_static)) {
6557 CmdArgs.push_back("-Bstatic");
6559 if (Args.hasArg(options::OPT_rdynamic))
6560 CmdArgs.push_back("-export-dynamic");
6561 CmdArgs.push_back("--eh-frame-hdr");
6562 if (Args.hasArg(options::OPT_shared)) {
6563 CmdArgs.push_back("-Bshareable");
6565 CmdArgs.push_back("-dynamic-linker");
6566 CmdArgs.push_back("/libexec/ld-elf.so.1");
6568 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
6569 llvm::Triple::ArchType Arch = ToolChain.getArch();
6570 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
6571 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6572 CmdArgs.push_back("--hash-style=both");
6575 CmdArgs.push_back("--enable-new-dtags");
6578 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
6579 // instruct ld in the base system to link 32-bit code.
6580 if (ToolChain.getArch() == llvm::Triple::x86) {
6581 CmdArgs.push_back("-m");
6582 CmdArgs.push_back("elf_i386_fbsd");
6585 if (ToolChain.getArch() == llvm::Triple::ppc) {
6586 CmdArgs.push_back("-m");
6587 CmdArgs.push_back("elf32ppc_fbsd");
6590 if (Output.isFilename()) {
6591 CmdArgs.push_back("-o");
6592 CmdArgs.push_back(Output.getFilename());
6594 assert(Output.isNothing() && "Invalid output.");
6597 if (!Args.hasArg(options::OPT_nostdlib) &&
6598 !Args.hasArg(options::OPT_nostartfiles)) {
6599 const char *crt1 = nullptr;
6600 if (!Args.hasArg(options::OPT_shared)) {
6601 if (Args.hasArg(options::OPT_pg))
6609 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
6611 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
6613 const char *crtbegin = nullptr;
6614 if (Args.hasArg(options::OPT_static))
6615 crtbegin = "crtbeginT.o";
6616 else if (Args.hasArg(options::OPT_shared) || IsPIE)
6617 crtbegin = "crtbeginS.o";
6619 crtbegin = "crtbegin.o";
6621 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
6624 Args.AddAllArgs(CmdArgs, options::OPT_L);
6625 const ToolChain::path_list Paths = ToolChain.getFilePaths();
6626 for (const auto &Path : Paths)
6627 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
6628 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6629 Args.AddAllArgs(CmdArgs, options::OPT_e);
6630 Args.AddAllArgs(CmdArgs, options::OPT_s);
6631 Args.AddAllArgs(CmdArgs, options::OPT_t);
6632 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6633 Args.AddAllArgs(CmdArgs, options::OPT_r);
6635 if (D.IsUsingLTO(Args))
6636 AddGoldPlugin(ToolChain, Args, CmdArgs);
6638 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6640 if (!Args.hasArg(options::OPT_nostdlib) &&
6641 !Args.hasArg(options::OPT_nodefaultlibs)) {
6643 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6644 if (Args.hasArg(options::OPT_pg))
6645 CmdArgs.push_back("-lm_p");
6647 CmdArgs.push_back("-lm");
6649 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
6650 // the default system libraries. Just mimic this for now.
6651 if (Args.hasArg(options::OPT_pg))
6652 CmdArgs.push_back("-lgcc_p");
6654 CmdArgs.push_back("-lgcc");
6655 if (Args.hasArg(options::OPT_static)) {
6656 CmdArgs.push_back("-lgcc_eh");
6657 } else if (Args.hasArg(options::OPT_pg)) {
6658 CmdArgs.push_back("-lgcc_eh_p");
6660 CmdArgs.push_back("--as-needed");
6661 CmdArgs.push_back("-lgcc_s");
6662 CmdArgs.push_back("--no-as-needed");
6665 if (Args.hasArg(options::OPT_pthread)) {
6666 if (Args.hasArg(options::OPT_pg))
6667 CmdArgs.push_back("-lpthread_p");
6669 CmdArgs.push_back("-lpthread");
6672 if (Args.hasArg(options::OPT_pg)) {
6673 if (Args.hasArg(options::OPT_shared))
6674 CmdArgs.push_back("-lc");
6676 CmdArgs.push_back("-lc_p");
6677 CmdArgs.push_back("-lgcc_p");
6679 CmdArgs.push_back("-lc");
6680 CmdArgs.push_back("-lgcc");
6683 if (Args.hasArg(options::OPT_static)) {
6684 CmdArgs.push_back("-lgcc_eh");
6685 } else if (Args.hasArg(options::OPT_pg)) {
6686 CmdArgs.push_back("-lgcc_eh_p");
6688 CmdArgs.push_back("--as-needed");
6689 CmdArgs.push_back("-lgcc_s");
6690 CmdArgs.push_back("--no-as-needed");
6694 if (!Args.hasArg(options::OPT_nostdlib) &&
6695 !Args.hasArg(options::OPT_nostartfiles)) {
6696 if (Args.hasArg(options::OPT_shared) || IsPIE)
6697 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
6699 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6700 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6703 addSanitizerRuntimes(getToolChain(), Args, CmdArgs);
6705 addProfileRT(ToolChain, Args, CmdArgs);
6708 Args.MakeArgString(getToolChain().GetLinkerPath());
6709 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6712 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6713 const InputInfo &Output,
6714 const InputInfoList &Inputs,
6715 const ArgList &Args,
6716 const char *LinkingOutput) const {
6717 ArgStringList CmdArgs;
6719 // GNU as needs different flags for creating the correct output format
6720 // on architectures with different ABIs or optional feature sets.
6721 switch (getToolChain().getArch()) {
6722 case llvm::Triple::x86:
6723 CmdArgs.push_back("--32");
6725 case llvm::Triple::arm:
6726 case llvm::Triple::armeb:
6727 case llvm::Triple::thumb:
6728 case llvm::Triple::thumbeb: {
6729 std::string MArch(arm::getARMTargetCPU(Args, getToolChain().getTriple()));
6730 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
6734 case llvm::Triple::mips:
6735 case llvm::Triple::mipsel:
6736 case llvm::Triple::mips64:
6737 case llvm::Triple::mips64el: {
6740 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6742 CmdArgs.push_back("-march");
6743 CmdArgs.push_back(CPUName.data());
6745 CmdArgs.push_back("-mabi");
6746 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6748 if (getToolChain().getArch() == llvm::Triple::mips ||
6749 getToolChain().getArch() == llvm::Triple::mips64)
6750 CmdArgs.push_back("-EB");
6752 CmdArgs.push_back("-EL");
6754 addAssemblerKPIC(Args, CmdArgs);
6758 case llvm::Triple::sparc:
6759 CmdArgs.push_back("-32");
6760 addAssemblerKPIC(Args, CmdArgs);
6763 case llvm::Triple::sparcv9:
6764 CmdArgs.push_back("-64");
6765 CmdArgs.push_back("-Av9");
6766 addAssemblerKPIC(Args, CmdArgs);
6773 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6774 options::OPT_Xassembler);
6776 CmdArgs.push_back("-o");
6777 CmdArgs.push_back(Output.getFilename());
6779 for (const auto &II : Inputs)
6780 CmdArgs.push_back(II.getFilename());
6782 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
6783 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6786 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6787 const InputInfo &Output,
6788 const InputInfoList &Inputs,
6789 const ArgList &Args,
6790 const char *LinkingOutput) const {
6791 const Driver &D = getToolChain().getDriver();
6792 ArgStringList CmdArgs;
6794 if (!D.SysRoot.empty())
6795 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6797 CmdArgs.push_back("--eh-frame-hdr");
6798 if (Args.hasArg(options::OPT_static)) {
6799 CmdArgs.push_back("-Bstatic");
6801 if (Args.hasArg(options::OPT_rdynamic))
6802 CmdArgs.push_back("-export-dynamic");
6803 if (Args.hasArg(options::OPT_shared)) {
6804 CmdArgs.push_back("-Bshareable");
6806 CmdArgs.push_back("-dynamic-linker");
6807 CmdArgs.push_back("/libexec/ld.elf_so");
6811 // Many NetBSD architectures support more than one ABI.
6812 // Determine the correct emulation for ld.
6813 switch (getToolChain().getArch()) {
6814 case llvm::Triple::x86:
6815 CmdArgs.push_back("-m");
6816 CmdArgs.push_back("elf_i386");
6818 case llvm::Triple::arm:
6819 case llvm::Triple::armeb:
6820 case llvm::Triple::thumb:
6821 case llvm::Triple::thumbeb:
6822 CmdArgs.push_back("-m");
6823 switch (getToolChain().getTriple().getEnvironment()) {
6824 case llvm::Triple::EABI:
6825 case llvm::Triple::GNUEABI:
6826 CmdArgs.push_back("armelf_nbsd_eabi");
6828 case llvm::Triple::EABIHF:
6829 case llvm::Triple::GNUEABIHF:
6830 CmdArgs.push_back("armelf_nbsd_eabihf");
6833 CmdArgs.push_back("armelf_nbsd");
6837 case llvm::Triple::mips64:
6838 case llvm::Triple::mips64el:
6839 if (mips::hasMipsAbiArg(Args, "32")) {
6840 CmdArgs.push_back("-m");
6841 if (getToolChain().getArch() == llvm::Triple::mips64)
6842 CmdArgs.push_back("elf32btsmip");
6844 CmdArgs.push_back("elf32ltsmip");
6845 } else if (mips::hasMipsAbiArg(Args, "64")) {
6846 CmdArgs.push_back("-m");
6847 if (getToolChain().getArch() == llvm::Triple::mips64)
6848 CmdArgs.push_back("elf64btsmip");
6850 CmdArgs.push_back("elf64ltsmip");
6854 case llvm::Triple::sparc:
6855 CmdArgs.push_back("-m");
6856 CmdArgs.push_back("elf32_sparc");
6859 case llvm::Triple::sparcv9:
6860 CmdArgs.push_back("-m");
6861 CmdArgs.push_back("elf64_sparc");
6868 if (Output.isFilename()) {
6869 CmdArgs.push_back("-o");
6870 CmdArgs.push_back(Output.getFilename());
6872 assert(Output.isNothing() && "Invalid output.");
6875 if (!Args.hasArg(options::OPT_nostdlib) &&
6876 !Args.hasArg(options::OPT_nostartfiles)) {
6877 if (!Args.hasArg(options::OPT_shared)) {
6878 CmdArgs.push_back(Args.MakeArgString(
6879 getToolChain().GetFilePath("crt0.o")));
6880 CmdArgs.push_back(Args.MakeArgString(
6881 getToolChain().GetFilePath("crti.o")));
6882 CmdArgs.push_back(Args.MakeArgString(
6883 getToolChain().GetFilePath("crtbegin.o")));
6885 CmdArgs.push_back(Args.MakeArgString(
6886 getToolChain().GetFilePath("crti.o")));
6887 CmdArgs.push_back(Args.MakeArgString(
6888 getToolChain().GetFilePath("crtbeginS.o")));
6892 Args.AddAllArgs(CmdArgs, options::OPT_L);
6893 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6894 Args.AddAllArgs(CmdArgs, options::OPT_e);
6895 Args.AddAllArgs(CmdArgs, options::OPT_s);
6896 Args.AddAllArgs(CmdArgs, options::OPT_t);
6897 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6898 Args.AddAllArgs(CmdArgs, options::OPT_r);
6900 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6902 unsigned Major, Minor, Micro;
6903 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
6904 bool useLibgcc = true;
6905 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 40) || Major == 0) {
6906 switch(getToolChain().getArch()) {
6907 case llvm::Triple::arm:
6908 case llvm::Triple::armeb:
6909 case llvm::Triple::thumb:
6910 case llvm::Triple::thumbeb:
6911 case llvm::Triple::x86:
6912 case llvm::Triple::x86_64:
6920 if (!Args.hasArg(options::OPT_nostdlib) &&
6921 !Args.hasArg(options::OPT_nodefaultlibs)) {
6923 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6924 CmdArgs.push_back("-lm");
6926 if (Args.hasArg(options::OPT_pthread))
6927 CmdArgs.push_back("-lpthread");
6928 CmdArgs.push_back("-lc");
6931 if (Args.hasArg(options::OPT_static)) {
6932 // libgcc_eh depends on libc, so resolve as much as possible,
6933 // pull in any new requirements from libc and then get the rest
6935 CmdArgs.push_back("-lgcc_eh");
6936 CmdArgs.push_back("-lc");
6937 CmdArgs.push_back("-lgcc");
6939 CmdArgs.push_back("-lgcc");
6940 CmdArgs.push_back("--as-needed");
6941 CmdArgs.push_back("-lgcc_s");
6942 CmdArgs.push_back("--no-as-needed");
6947 if (!Args.hasArg(options::OPT_nostdlib) &&
6948 !Args.hasArg(options::OPT_nostartfiles)) {
6949 if (!Args.hasArg(options::OPT_shared))
6950 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6953 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6955 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6959 addProfileRT(getToolChain(), Args, CmdArgs);
6961 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6962 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6965 void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6966 const InputInfo &Output,
6967 const InputInfoList &Inputs,
6968 const ArgList &Args,
6969 const char *LinkingOutput) const {
6970 ArgStringList CmdArgs;
6971 bool NeedsKPIC = false;
6973 // Add --32/--64 to make sure we get the format we want.
6974 // This is incomplete
6975 if (getToolChain().getArch() == llvm::Triple::x86) {
6976 CmdArgs.push_back("--32");
6977 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
6978 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
6979 CmdArgs.push_back("--x32");
6981 CmdArgs.push_back("--64");
6982 } else if (getToolChain().getArch() == llvm::Triple::ppc) {
6983 CmdArgs.push_back("-a32");
6984 CmdArgs.push_back("-mppc");
6985 CmdArgs.push_back("-many");
6986 } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
6987 CmdArgs.push_back("-a64");
6988 CmdArgs.push_back("-mppc64");
6989 CmdArgs.push_back("-many");
6990 } else if (getToolChain().getArch() == llvm::Triple::ppc64le) {
6991 CmdArgs.push_back("-a64");
6992 CmdArgs.push_back("-mppc64");
6993 CmdArgs.push_back("-many");
6994 CmdArgs.push_back("-mlittle-endian");
6995 } else if (getToolChain().getArch() == llvm::Triple::sparc) {
6996 CmdArgs.push_back("-32");
6997 CmdArgs.push_back("-Av8plusa");
6999 } else if (getToolChain().getArch() == llvm::Triple::sparcv9) {
7000 CmdArgs.push_back("-64");
7001 CmdArgs.push_back("-Av9a");
7003 } else if (getToolChain().getArch() == llvm::Triple::arm ||
7004 getToolChain().getArch() == llvm::Triple::armeb) {
7005 StringRef MArch = getToolChain().getArchName();
7006 if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
7007 CmdArgs.push_back("-mfpu=neon");
7008 if (MArch == "armv8" || MArch == "armv8a" || MArch == "armv8-a" ||
7009 MArch == "armebv8" || MArch == "armebv8a" || MArch == "armebv8-a")
7010 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
7012 StringRef ARMFloatABI = tools::arm::getARMFloatABI(
7013 getToolChain().getDriver(), Args, getToolChain().getTriple());
7014 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
7016 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
7018 // FIXME: remove krait check when GNU tools support krait cpu
7019 // for now replace it with -march=armv7-a to avoid a lower
7020 // march from being picked in the absence of a cpu flag.
7022 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
7023 StringRef(A->getValue()) == "krait")
7024 CmdArgs.push_back("-march=armv7-a");
7026 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
7027 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
7028 } else if (getToolChain().getArch() == llvm::Triple::mips ||
7029 getToolChain().getArch() == llvm::Triple::mipsel ||
7030 getToolChain().getArch() == llvm::Triple::mips64 ||
7031 getToolChain().getArch() == llvm::Triple::mips64el) {
7034 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7035 ABIName = getGnuCompatibleMipsABIName(ABIName);
7037 CmdArgs.push_back("-march");
7038 CmdArgs.push_back(CPUName.data());
7040 CmdArgs.push_back("-mabi");
7041 CmdArgs.push_back(ABIName.data());
7043 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
7044 // or -mshared (not implemented) is in effect.
7045 bool IsPicOrPie = false;
7046 if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
7047 options::OPT_fpic, options::OPT_fno_pic,
7048 options::OPT_fPIE, options::OPT_fno_PIE,
7049 options::OPT_fpie, options::OPT_fno_pie)) {
7050 if (A->getOption().matches(options::OPT_fPIC) ||
7051 A->getOption().matches(options::OPT_fpic) ||
7052 A->getOption().matches(options::OPT_fPIE) ||
7053 A->getOption().matches(options::OPT_fpie))
7057 CmdArgs.push_back("-mno-shared");
7059 // LLVM doesn't support -mplt yet and acts as if it is always given.
7060 // However, -mplt has no effect with the N64 ABI.
7061 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
7063 if (getToolChain().getArch() == llvm::Triple::mips ||
7064 getToolChain().getArch() == llvm::Triple::mips64)
7065 CmdArgs.push_back("-EB");
7067 CmdArgs.push_back("-EL");
7069 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
7070 if (StringRef(A->getValue()) == "2008")
7071 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
7074 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
7075 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
7076 options::OPT_mfp64)) {
7078 A->render(Args, CmdArgs);
7079 } else if (mips::isFPXXDefault(getToolChain().getTriple(), CPUName,
7081 CmdArgs.push_back("-mfpxx");
7083 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
7084 // -mno-mips16 is actually -no-mips16.
7085 if (Arg *A = Args.getLastArg(options::OPT_mips16,
7086 options::OPT_mno_mips16)) {
7087 if (A->getOption().matches(options::OPT_mips16)) {
7089 A->render(Args, CmdArgs);
7092 CmdArgs.push_back("-no-mips16");
7096 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
7097 options::OPT_mno_micromips);
7098 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
7099 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
7101 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
7102 // Do not use AddLastArg because not all versions of MIPS assembler
7103 // support -mmsa / -mno-msa options.
7104 if (A->getOption().matches(options::OPT_mmsa))
7105 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
7108 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
7109 options::OPT_msoft_float);
7111 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
7112 options::OPT_mno_odd_spreg);
7115 } else if (getToolChain().getArch() == llvm::Triple::systemz) {
7116 // Always pass an -march option, since our default of z10 is later
7117 // than the GNU assembler's default.
7118 StringRef CPUName = getSystemZTargetCPU(Args);
7119 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
7123 addAssemblerKPIC(Args, CmdArgs);
7125 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7126 options::OPT_Xassembler);
7128 CmdArgs.push_back("-o");
7129 CmdArgs.push_back(Output.getFilename());
7131 for (const auto &II : Inputs)
7132 CmdArgs.push_back(II.getFilename());
7134 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7135 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7137 // Handle the debug info splitting at object creation time if we're
7138 // creating an object.
7139 // TODO: Currently only works on linux with newer objcopy.
7140 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7141 getToolChain().getTriple().isOSLinux())
7142 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7143 SplitDebugName(Args, Inputs));
7146 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
7147 ArgStringList &CmdArgs, const ArgList &Args) {
7148 bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
7149 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
7150 Args.hasArg(options::OPT_static);
7152 CmdArgs.push_back("-lgcc");
7154 if (StaticLibgcc || isAndroid) {
7156 CmdArgs.push_back("-lgcc");
7159 CmdArgs.push_back("--as-needed");
7160 CmdArgs.push_back("-lgcc_s");
7162 CmdArgs.push_back("--no-as-needed");
7165 if (StaticLibgcc && !isAndroid)
7166 CmdArgs.push_back("-lgcc_eh");
7167 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
7168 CmdArgs.push_back("-lgcc");
7170 // According to Android ABI, we have to link with libdl if we are
7171 // linking with non-static libgcc.
7173 // NOTE: This fixes a link error on Android MIPS as well. The non-static
7174 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
7175 if (isAndroid && !StaticLibgcc)
7176 CmdArgs.push_back("-ldl");
7179 static StringRef getLinuxDynamicLinker(const ArgList &Args,
7180 const toolchains::Linux &ToolChain) {
7181 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
7182 if (ToolChain.getTriple().isArch64Bit())
7183 return "/system/bin/linker64";
7185 return "/system/bin/linker";
7186 } else if (ToolChain.getArch() == llvm::Triple::x86 ||
7187 ToolChain.getArch() == llvm::Triple::sparc)
7188 return "/lib/ld-linux.so.2";
7189 else if (ToolChain.getArch() == llvm::Triple::aarch64 ||
7190 ToolChain.getArch() == llvm::Triple::arm64)
7191 return "/lib/ld-linux-aarch64.so.1";
7192 else if (ToolChain.getArch() == llvm::Triple::aarch64_be ||
7193 ToolChain.getArch() == llvm::Triple::arm64_be)
7194 return "/lib/ld-linux-aarch64_be.so.1";
7195 else if (ToolChain.getArch() == llvm::Triple::arm ||
7196 ToolChain.getArch() == llvm::Triple::thumb) {
7197 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7198 return "/lib/ld-linux-armhf.so.3";
7200 return "/lib/ld-linux.so.3";
7201 } else if (ToolChain.getArch() == llvm::Triple::armeb ||
7202 ToolChain.getArch() == llvm::Triple::thumbeb) {
7203 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7204 return "/lib/ld-linux-armhf.so.3"; /* TODO: check which dynamic linker name. */
7206 return "/lib/ld-linux.so.3"; /* TODO: check which dynamic linker name. */
7207 } else if (ToolChain.getArch() == llvm::Triple::mips ||
7208 ToolChain.getArch() == llvm::Triple::mipsel) {
7209 if (mips::isNaN2008(Args, ToolChain.getTriple()))
7210 return "/lib/ld-linux-mipsn8.so.1";
7211 return "/lib/ld.so.1";
7212 } else if (ToolChain.getArch() == llvm::Triple::mips64 ||
7213 ToolChain.getArch() == llvm::Triple::mips64el) {
7214 if (mips::hasMipsAbiArg(Args, "n32"))
7215 return mips::isNaN2008(Args, ToolChain.getTriple())
7216 ? "/lib32/ld-linux-mipsn8.so.1" : "/lib32/ld.so.1";
7217 return mips::isNaN2008(Args, ToolChain.getTriple())
7218 ? "/lib64/ld-linux-mipsn8.so.1" : "/lib64/ld.so.1";
7219 } else if (ToolChain.getArch() == llvm::Triple::ppc)
7220 return "/lib/ld.so.1";
7221 else if (ToolChain.getArch() == llvm::Triple::ppc64 ||
7222 ToolChain.getArch() == llvm::Triple::systemz)
7223 return "/lib64/ld64.so.1";
7224 else if (ToolChain.getArch() == llvm::Triple::ppc64le)
7225 return "/lib64/ld64.so.2";
7226 else if (ToolChain.getArch() == llvm::Triple::sparcv9)
7227 return "/lib64/ld-linux.so.2";
7228 else if (ToolChain.getArch() == llvm::Triple::x86_64 &&
7229 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
7230 return "/libx32/ld-linux-x32.so.2";
7232 return "/lib64/ld-linux-x86-64.so.2";
7235 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
7236 ArgStringList &CmdArgs, const ArgList &Args) {
7237 // Make use of compiler-rt if --rtlib option is used
7238 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
7241 case ToolChain::RLT_CompilerRT:
7242 addClangRTLinux(TC, Args, CmdArgs);
7244 case ToolChain::RLT_Libgcc:
7245 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
7250 void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
7251 const InputInfo &Output,
7252 const InputInfoList &Inputs,
7253 const ArgList &Args,
7254 const char *LinkingOutput) const {
7255 const toolchains::Linux& ToolChain =
7256 static_cast<const toolchains::Linux&>(getToolChain());
7257 const Driver &D = ToolChain.getDriver();
7258 const bool isAndroid =
7259 ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
7261 !Args.hasArg(options::OPT_shared) &&
7262 !Args.hasArg(options::OPT_static) &&
7263 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault() ||
7264 // On Android every code is PIC so every executable is PIE
7265 // Cannot use isPIEDefault here since otherwise
7266 // PIE only logic will be enabled during compilation
7269 ArgStringList CmdArgs;
7271 // Silence warning for "clang -g foo.o -o foo"
7272 Args.ClaimAllArgs(options::OPT_g_Group);
7273 // and "clang -emit-llvm foo.o -o foo"
7274 Args.ClaimAllArgs(options::OPT_emit_llvm);
7275 // and for "clang -w foo.o -o foo". Other warning options are already
7276 // handled somewhere else.
7277 Args.ClaimAllArgs(options::OPT_w);
7279 if (!D.SysRoot.empty())
7280 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7283 CmdArgs.push_back("-pie");
7285 if (Args.hasArg(options::OPT_rdynamic))
7286 CmdArgs.push_back("-export-dynamic");
7288 if (Args.hasArg(options::OPT_s))
7289 CmdArgs.push_back("-s");
7291 for (const auto &Opt : ToolChain.ExtraOpts)
7292 CmdArgs.push_back(Opt.c_str());
7294 if (!Args.hasArg(options::OPT_static)) {
7295 CmdArgs.push_back("--eh-frame-hdr");
7298 CmdArgs.push_back("-m");
7299 if (ToolChain.getArch() == llvm::Triple::x86)
7300 CmdArgs.push_back("elf_i386");
7301 else if (ToolChain.getArch() == llvm::Triple::aarch64 ||
7302 ToolChain.getArch() == llvm::Triple::arm64)
7303 CmdArgs.push_back("aarch64linux");
7304 else if (ToolChain.getArch() == llvm::Triple::aarch64_be ||
7305 ToolChain.getArch() == llvm::Triple::arm64_be)
7306 CmdArgs.push_back("aarch64_be_linux");
7307 else if (ToolChain.getArch() == llvm::Triple::arm
7308 || ToolChain.getArch() == llvm::Triple::thumb)
7309 CmdArgs.push_back("armelf_linux_eabi");
7310 else if (ToolChain.getArch() == llvm::Triple::armeb
7311 || ToolChain.getArch() == llvm::Triple::thumbeb)
7312 CmdArgs.push_back("armebelf_linux_eabi"); /* TODO: check which NAME. */
7313 else if (ToolChain.getArch() == llvm::Triple::ppc)
7314 CmdArgs.push_back("elf32ppclinux");
7315 else if (ToolChain.getArch() == llvm::Triple::ppc64)
7316 CmdArgs.push_back("elf64ppc");
7317 else if (ToolChain.getArch() == llvm::Triple::ppc64le)
7318 CmdArgs.push_back("elf64lppc");
7319 else if (ToolChain.getArch() == llvm::Triple::sparc)
7320 CmdArgs.push_back("elf32_sparc");
7321 else if (ToolChain.getArch() == llvm::Triple::sparcv9)
7322 CmdArgs.push_back("elf64_sparc");
7323 else if (ToolChain.getArch() == llvm::Triple::mips)
7324 CmdArgs.push_back("elf32btsmip");
7325 else if (ToolChain.getArch() == llvm::Triple::mipsel)
7326 CmdArgs.push_back("elf32ltsmip");
7327 else if (ToolChain.getArch() == llvm::Triple::mips64) {
7328 if (mips::hasMipsAbiArg(Args, "n32"))
7329 CmdArgs.push_back("elf32btsmipn32");
7331 CmdArgs.push_back("elf64btsmip");
7333 else if (ToolChain.getArch() == llvm::Triple::mips64el) {
7334 if (mips::hasMipsAbiArg(Args, "n32"))
7335 CmdArgs.push_back("elf32ltsmipn32");
7337 CmdArgs.push_back("elf64ltsmip");
7339 else if (ToolChain.getArch() == llvm::Triple::systemz)
7340 CmdArgs.push_back("elf64_s390");
7341 else if (ToolChain.getArch() == llvm::Triple::x86_64 &&
7342 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
7343 CmdArgs.push_back("elf32_x86_64");
7345 CmdArgs.push_back("elf_x86_64");
7347 if (Args.hasArg(options::OPT_static)) {
7348 if (ToolChain.getArch() == llvm::Triple::arm ||
7349 ToolChain.getArch() == llvm::Triple::armeb ||
7350 ToolChain.getArch() == llvm::Triple::thumb ||
7351 ToolChain.getArch() == llvm::Triple::thumbeb)
7352 CmdArgs.push_back("-Bstatic");
7354 CmdArgs.push_back("-static");
7355 } else if (Args.hasArg(options::OPT_shared)) {
7356 CmdArgs.push_back("-shared");
7359 if (ToolChain.getArch() == llvm::Triple::arm ||
7360 ToolChain.getArch() == llvm::Triple::armeb ||
7361 ToolChain.getArch() == llvm::Triple::thumb ||
7362 ToolChain.getArch() == llvm::Triple::thumbeb ||
7363 (!Args.hasArg(options::OPT_static) &&
7364 !Args.hasArg(options::OPT_shared))) {
7365 CmdArgs.push_back("-dynamic-linker");
7366 CmdArgs.push_back(Args.MakeArgString(
7367 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
7370 CmdArgs.push_back("-o");
7371 CmdArgs.push_back(Output.getFilename());
7373 if (!Args.hasArg(options::OPT_nostdlib) &&
7374 !Args.hasArg(options::OPT_nostartfiles)) {
7376 const char *crt1 = nullptr;
7377 if (!Args.hasArg(options::OPT_shared)){
7378 if (Args.hasArg(options::OPT_pg))
7386 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7388 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7391 const char *crtbegin;
7392 if (Args.hasArg(options::OPT_static))
7393 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
7394 else if (Args.hasArg(options::OPT_shared))
7395 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
7397 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
7399 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
7400 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7402 // Add crtfastmath.o if available and fast math is enabled.
7403 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
7406 Args.AddAllArgs(CmdArgs, options::OPT_L);
7407 Args.AddAllArgs(CmdArgs, options::OPT_u);
7409 const ToolChain::path_list Paths = ToolChain.getFilePaths();
7411 for (const auto &Path : Paths)
7412 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
7414 if (D.IsUsingLTO(Args))
7415 AddGoldPlugin(ToolChain, Args, CmdArgs);
7417 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7418 CmdArgs.push_back("--no-demangle");
7420 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7422 addSanitizerRuntimes(getToolChain(), Args, CmdArgs);
7423 // The profile runtime also needs access to system libraries.
7424 addProfileRT(getToolChain(), Args, CmdArgs);
7427 !Args.hasArg(options::OPT_nostdlib) &&
7428 !Args.hasArg(options::OPT_nodefaultlibs)) {
7429 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
7430 !Args.hasArg(options::OPT_static);
7431 if (OnlyLibstdcxxStatic)
7432 CmdArgs.push_back("-Bstatic");
7433 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7434 if (OnlyLibstdcxxStatic)
7435 CmdArgs.push_back("-Bdynamic");
7436 CmdArgs.push_back("-lm");
7439 if (!Args.hasArg(options::OPT_nostdlib)) {
7440 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
7441 if (Args.hasArg(options::OPT_static))
7442 CmdArgs.push_back("--start-group");
7444 LibOpenMP UsedOpenMPLib = LibUnknown;
7445 if (Args.hasArg(options::OPT_fopenmp)) {
7446 UsedOpenMPLib = LibGOMP;
7447 } else if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
7448 UsedOpenMPLib = llvm::StringSwitch<LibOpenMP>(A->getValue())
7449 .Case("libgomp", LibGOMP)
7450 .Case("libiomp5", LibIOMP5)
7451 .Default(LibUnknown);
7452 if (UsedOpenMPLib == LibUnknown)
7453 D.Diag(diag::err_drv_unsupported_option_argument)
7454 << A->getOption().getName() << A->getValue();
7456 switch (UsedOpenMPLib) {
7458 CmdArgs.push_back("-lgomp");
7460 // FIXME: Exclude this for platforms with libgomp that don't require
7461 // librt. Most modern Linux platforms require it, but some may not.
7462 CmdArgs.push_back("-lrt");
7465 CmdArgs.push_back("-liomp5");
7470 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
7472 if ((Args.hasArg(options::OPT_pthread) ||
7473 Args.hasArg(options::OPT_pthreads) || UsedOpenMPLib != LibUnknown) &&
7475 CmdArgs.push_back("-lpthread");
7477 CmdArgs.push_back("-lc");
7479 if (Args.hasArg(options::OPT_static))
7480 CmdArgs.push_back("--end-group");
7482 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
7485 if (!Args.hasArg(options::OPT_nostartfiles)) {
7487 if (Args.hasArg(options::OPT_shared))
7488 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
7490 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
7492 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
7494 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
7496 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7500 C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
7503 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7504 const InputInfo &Output,
7505 const InputInfoList &Inputs,
7506 const ArgList &Args,
7507 const char *LinkingOutput) const {
7508 ArgStringList CmdArgs;
7510 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7512 CmdArgs.push_back("-o");
7513 CmdArgs.push_back(Output.getFilename());
7515 for (const auto &II : Inputs)
7516 CmdArgs.push_back(II.getFilename());
7518 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7519 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7522 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
7523 const InputInfo &Output,
7524 const InputInfoList &Inputs,
7525 const ArgList &Args,
7526 const char *LinkingOutput) const {
7527 const Driver &D = getToolChain().getDriver();
7528 ArgStringList CmdArgs;
7530 if (Output.isFilename()) {
7531 CmdArgs.push_back("-o");
7532 CmdArgs.push_back(Output.getFilename());
7534 assert(Output.isNothing() && "Invalid output.");
7537 if (!Args.hasArg(options::OPT_nostdlib) &&
7538 !Args.hasArg(options::OPT_nostartfiles)) {
7539 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7540 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7541 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7542 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7545 Args.AddAllArgs(CmdArgs, options::OPT_L);
7546 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7547 Args.AddAllArgs(CmdArgs, options::OPT_e);
7549 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7551 addProfileRT(getToolChain(), Args, CmdArgs);
7553 if (!Args.hasArg(options::OPT_nostdlib) &&
7554 !Args.hasArg(options::OPT_nodefaultlibs)) {
7556 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7557 CmdArgs.push_back("-lm");
7561 if (!Args.hasArg(options::OPT_nostdlib) &&
7562 !Args.hasArg(options::OPT_nostartfiles)) {
7563 if (Args.hasArg(options::OPT_pthread))
7564 CmdArgs.push_back("-lpthread");
7565 CmdArgs.push_back("-lc");
7566 CmdArgs.push_back("-lCompilerRT-Generic");
7567 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
7569 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7572 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7573 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7578 // For now, DragonFly Assemble does just about the same as for
7579 // FreeBSD, but this may change soon.
7580 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7581 const InputInfo &Output,
7582 const InputInfoList &Inputs,
7583 const ArgList &Args,
7584 const char *LinkingOutput) const {
7585 ArgStringList CmdArgs;
7587 // When building 32-bit code on DragonFly/pc64, we have to explicitly
7588 // instruct as in the base system to assemble 32-bit code.
7589 if (getToolChain().getArch() == llvm::Triple::x86)
7590 CmdArgs.push_back("--32");
7592 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7594 CmdArgs.push_back("-o");
7595 CmdArgs.push_back(Output.getFilename());
7597 for (const auto &II : Inputs)
7598 CmdArgs.push_back(II.getFilename());
7600 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7601 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7604 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
7605 const InputInfo &Output,
7606 const InputInfoList &Inputs,
7607 const ArgList &Args,
7608 const char *LinkingOutput) const {
7609 bool UseGCC47 = false;
7610 const Driver &D = getToolChain().getDriver();
7611 ArgStringList CmdArgs;
7613 if (llvm::sys::fs::exists("/usr/lib/gcc47", UseGCC47))
7616 if (!D.SysRoot.empty())
7617 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7619 CmdArgs.push_back("--eh-frame-hdr");
7620 if (Args.hasArg(options::OPT_static)) {
7621 CmdArgs.push_back("-Bstatic");
7623 if (Args.hasArg(options::OPT_rdynamic))
7624 CmdArgs.push_back("-export-dynamic");
7625 if (Args.hasArg(options::OPT_shared))
7626 CmdArgs.push_back("-Bshareable");
7628 CmdArgs.push_back("-dynamic-linker");
7629 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
7631 CmdArgs.push_back("--hash-style=both");
7634 // When building 32-bit code on DragonFly/pc64, we have to explicitly
7635 // instruct ld in the base system to link 32-bit code.
7636 if (getToolChain().getArch() == llvm::Triple::x86) {
7637 CmdArgs.push_back("-m");
7638 CmdArgs.push_back("elf_i386");
7641 if (Output.isFilename()) {
7642 CmdArgs.push_back("-o");
7643 CmdArgs.push_back(Output.getFilename());
7645 assert(Output.isNothing() && "Invalid output.");
7648 if (!Args.hasArg(options::OPT_nostdlib) &&
7649 !Args.hasArg(options::OPT_nostartfiles)) {
7650 if (!Args.hasArg(options::OPT_shared)) {
7651 if (Args.hasArg(options::OPT_pg))
7652 CmdArgs.push_back(Args.MakeArgString(
7653 getToolChain().GetFilePath("gcrt1.o")));
7655 if (Args.hasArg(options::OPT_pie))
7656 CmdArgs.push_back(Args.MakeArgString(
7657 getToolChain().GetFilePath("Scrt1.o")));
7659 CmdArgs.push_back(Args.MakeArgString(
7660 getToolChain().GetFilePath("crt1.o")));
7663 CmdArgs.push_back(Args.MakeArgString(
7664 getToolChain().GetFilePath("crti.o")));
7665 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
7666 CmdArgs.push_back(Args.MakeArgString(
7667 getToolChain().GetFilePath("crtbeginS.o")));
7669 CmdArgs.push_back(Args.MakeArgString(
7670 getToolChain().GetFilePath("crtbegin.o")));
7673 Args.AddAllArgs(CmdArgs, options::OPT_L);
7674 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7675 Args.AddAllArgs(CmdArgs, options::OPT_e);
7677 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7679 if (!Args.hasArg(options::OPT_nostdlib) &&
7680 !Args.hasArg(options::OPT_nodefaultlibs)) {
7681 // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
7684 CmdArgs.push_back("-L/usr/lib/gcc47");
7686 CmdArgs.push_back("-L/usr/lib/gcc44");
7688 if (!Args.hasArg(options::OPT_static)) {
7690 CmdArgs.push_back("-rpath");
7691 CmdArgs.push_back("/usr/lib/gcc47");
7693 CmdArgs.push_back("-rpath");
7694 CmdArgs.push_back("/usr/lib/gcc44");
7699 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7700 CmdArgs.push_back("-lm");
7703 if (Args.hasArg(options::OPT_pthread))
7704 CmdArgs.push_back("-lpthread");
7706 if (!Args.hasArg(options::OPT_nolibc)) {
7707 CmdArgs.push_back("-lc");
7711 if (Args.hasArg(options::OPT_static) ||
7712 Args.hasArg(options::OPT_static_libgcc)) {
7713 CmdArgs.push_back("-lgcc");
7714 CmdArgs.push_back("-lgcc_eh");
7716 if (Args.hasArg(options::OPT_shared_libgcc)) {
7717 CmdArgs.push_back("-lgcc_pic");
7718 if (!Args.hasArg(options::OPT_shared))
7719 CmdArgs.push_back("-lgcc");
7721 CmdArgs.push_back("-lgcc");
7722 CmdArgs.push_back("--as-needed");
7723 CmdArgs.push_back("-lgcc_pic");
7724 CmdArgs.push_back("--no-as-needed");
7728 if (Args.hasArg(options::OPT_shared)) {
7729 CmdArgs.push_back("-lgcc_pic");
7731 CmdArgs.push_back("-lgcc");
7736 if (!Args.hasArg(options::OPT_nostdlib) &&
7737 !Args.hasArg(options::OPT_nostartfiles)) {
7738 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
7739 CmdArgs.push_back(Args.MakeArgString(
7740 getToolChain().GetFilePath("crtendS.o")));
7742 CmdArgs.push_back(Args.MakeArgString(
7743 getToolChain().GetFilePath("crtend.o")));
7744 CmdArgs.push_back(Args.MakeArgString(
7745 getToolChain().GetFilePath("crtn.o")));
7748 addProfileRT(getToolChain(), Args, CmdArgs);
7750 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7751 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7754 static void addSanitizerRTWindows(const ToolChain &TC, const ArgList &Args,
7755 ArgStringList &CmdArgs,
7756 const StringRef RTName) {
7757 SmallString<128> LibSanitizer(getCompilerRTLibDir(TC));
7758 llvm::sys::path::append(LibSanitizer,
7759 Twine("clang_rt.") + RTName + ".lib");
7760 CmdArgs.push_back(Args.MakeArgString(LibSanitizer));
7763 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
7764 const InputInfo &Output,
7765 const InputInfoList &Inputs,
7766 const ArgList &Args,
7767 const char *LinkingOutput) const {
7768 ArgStringList CmdArgs;
7770 if (Output.isFilename()) {
7771 CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
7772 Output.getFilename()));
7774 assert(Output.isNothing() && "Invalid output.");
7777 if (!Args.hasArg(options::OPT_nostdlib) &&
7778 !Args.hasArg(options::OPT_nostartfiles) &&
7779 !C.getDriver().IsCLMode()) {
7780 CmdArgs.push_back("-defaultlib:libcmt");
7783 CmdArgs.push_back("-nologo");
7785 if (Args.hasArg(options::OPT_g_Group)) {
7786 CmdArgs.push_back("-debug");
7789 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd);
7792 CmdArgs.push_back(Args.MakeArgString("-dll"));
7794 SmallString<128> ImplibName(Output.getFilename());
7795 llvm::sys::path::replace_extension(ImplibName, "lib");
7796 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") +
7800 if (getToolChain().getSanitizerArgs().needsAsanRt()) {
7801 CmdArgs.push_back(Args.MakeArgString("-debug"));
7802 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
7803 // FIXME: Handle 64-bit.
7805 addSanitizerRTWindows(getToolChain(), Args, CmdArgs,
7806 "asan_dll_thunk-i386");
7808 addSanitizerRTWindows(getToolChain(), Args, CmdArgs, "asan-i386");
7809 addSanitizerRTWindows(getToolChain(), Args, CmdArgs, "asan_cxx-i386");
7813 Args.AddAllArgValues(CmdArgs, options::OPT_l);
7814 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
7816 // Add filenames immediately.
7817 for (const auto &Input : Inputs)
7818 if (Input.isFilename())
7819 CmdArgs.push_back(Input.getFilename());
7821 Input.getInputArg().renderAsInput(Args, CmdArgs);
7824 Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
7825 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7828 void visualstudio::Compile::ConstructJob(Compilation &C, const JobAction &JA,
7829 const InputInfo &Output,
7830 const InputInfoList &Inputs,
7831 const ArgList &Args,
7832 const char *LinkingOutput) const {
7833 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
7836 // Try to find FallbackName on PATH that is not identical to ClangProgramPath.
7837 // If one cannot be found, return FallbackName.
7838 // We do this special search to prevent clang-cl from falling back onto itself
7839 // if it's available as cl.exe on the path.
7840 static std::string FindFallback(const char *FallbackName,
7841 const char *ClangProgramPath) {
7842 llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
7843 if (!OptPath.hasValue())
7844 return FallbackName;
7846 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
7847 SmallVector<StringRef, 8> PathSegments;
7848 llvm::SplitString(OptPath.getValue(), PathSegments, EnvPathSeparatorStr);
7850 for (size_t i = 0, e = PathSegments.size(); i != e; ++i) {
7851 const StringRef &PathSegment = PathSegments[i];
7852 if (PathSegment.empty())
7855 SmallString<128> FilePath(PathSegment);
7856 llvm::sys::path::append(FilePath, FallbackName);
7857 if (llvm::sys::fs::can_execute(Twine(FilePath)) &&
7858 !llvm::sys::fs::equivalent(Twine(FilePath), ClangProgramPath))
7859 return FilePath.str();
7862 return FallbackName;
7865 Command *visualstudio::Compile::GetCommand(Compilation &C, const JobAction &JA,
7866 const InputInfo &Output,
7867 const InputInfoList &Inputs,
7868 const ArgList &Args,
7869 const char *LinkingOutput) const {
7870 ArgStringList CmdArgs;
7871 CmdArgs.push_back("/nologo");
7872 CmdArgs.push_back("/c"); // Compile only.
7873 CmdArgs.push_back("/W0"); // No warnings.
7875 // The goal is to be able to invoke this tool correctly based on
7876 // any flag accepted by clang-cl.
7878 // These are spelled the same way in clang and cl.exe,.
7879 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
7880 Args.AddAllArgs(CmdArgs, options::OPT_I);
7882 // Optimization level.
7883 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
7884 if (A->getOption().getID() == options::OPT_O0) {
7885 CmdArgs.push_back("/Od");
7887 StringRef OptLevel = A->getValue();
7888 if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
7889 A->render(Args, CmdArgs);
7890 else if (OptLevel == "3")
7891 CmdArgs.push_back("/Ox");
7895 // Flags for which clang-cl have an alias.
7896 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
7898 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7900 CmdArgs.push_back("/GR-");
7901 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
7902 options::OPT_fno_function_sections))
7903 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
7906 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
7907 options::OPT_fno_data_sections))
7909 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
7910 if (Args.hasArg(options::OPT_fsyntax_only))
7911 CmdArgs.push_back("/Zs");
7912 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
7913 CmdArgs.push_back("/Z7");
7915 std::vector<std::string> Includes = Args.getAllArgValues(options::OPT_include);
7916 for (const auto &Include : Includes)
7917 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
7919 // Flags that can simply be passed through.
7920 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
7921 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
7922 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
7924 // The order of these flags is relevant, so pick the last one.
7925 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
7926 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
7927 A->render(Args, CmdArgs);
7931 assert(Inputs.size() == 1);
7932 const InputInfo &II = Inputs[0];
7933 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
7934 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
7935 if (II.isFilename())
7936 CmdArgs.push_back(II.getFilename());
7938 II.getInputArg().renderAsInput(Args, CmdArgs);
7941 assert(Output.getType() == types::TY_Object);
7942 const char *Fo = Args.MakeArgString(std::string("/Fo") +
7943 Output.getFilename());
7944 CmdArgs.push_back(Fo);
7946 const Driver &D = getToolChain().getDriver();
7947 std::string Exec = FindFallback("cl.exe", D.getClangProgramPath());
7948 return new Command(JA, *this, Args.MakeArgString(Exec), CmdArgs);
7953 // We pass assemble and link construction to the xcc tool.
7955 void XCore::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7956 const InputInfo &Output,
7957 const InputInfoList &Inputs,
7958 const ArgList &Args,
7959 const char *LinkingOutput) const {
7960 ArgStringList CmdArgs;
7962 CmdArgs.push_back("-o");
7963 CmdArgs.push_back(Output.getFilename());
7965 CmdArgs.push_back("-c");
7967 if (Args.hasArg(options::OPT_v))
7968 CmdArgs.push_back("-v");
7970 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
7971 if (!A->getOption().matches(options::OPT_g0))
7972 CmdArgs.push_back("-g");
7974 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
7976 CmdArgs.push_back("-fverbose-asm");
7978 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7979 options::OPT_Xassembler);
7981 for (const auto &II : Inputs)
7982 CmdArgs.push_back(II.getFilename());
7984 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
7985 C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7988 void XCore::Link::ConstructJob(Compilation &C, const JobAction &JA,
7989 const InputInfo &Output,
7990 const InputInfoList &Inputs,
7991 const ArgList &Args,
7992 const char *LinkingOutput) const {
7993 ArgStringList CmdArgs;
7995 if (Output.isFilename()) {
7996 CmdArgs.push_back("-o");
7997 CmdArgs.push_back(Output.getFilename());
7999 assert(Output.isNothing() && "Invalid output.");
8002 if (Args.hasArg(options::OPT_v))
8003 CmdArgs.push_back("-v");
8005 ExceptionSettings EH = exceptionSettings(Args, getToolChain().getTriple());
8006 if (EH.ShouldUseExceptionTables)
8007 CmdArgs.push_back("-fexceptions");
8009 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8011 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
8012 C.addCommand(new Command(JA, *this, Exec, CmdArgs));