1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CommonArgs.h"
11 #include "InputInfo.h"
13 #include "Arch/AArch64.h"
15 #include "Arch/Mips.h"
17 #include "Arch/SystemZ.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/ObjCRuntime.h"
22 #include "clang/Basic/Version.h"
23 #include "clang/Basic/VirtualFileSystem.h"
24 #include "clang/Config/config.h"
25 #include "clang/Driver/Action.h"
26 #include "clang/Driver/Compilation.h"
27 #include "clang/Driver/Driver.h"
28 #include "clang/Driver/DriverDiagnostic.h"
29 #include "clang/Driver/Job.h"
30 #include "clang/Driver/Options.h"
31 #include "clang/Driver/SanitizerArgs.h"
32 #include "clang/Driver/ToolChain.h"
33 #include "clang/Driver/Util.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/Option/Arg.h"
40 #include "llvm/Option/ArgList.h"
41 #include "llvm/Option/Option.h"
42 #include "llvm/Support/CodeGen.h"
43 #include "llvm/Support/Compression.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Process.h"
49 #include "llvm/Support/Program.h"
50 #include "llvm/Support/ScopedPrinter.h"
51 #include "llvm/Support/TargetParser.h"
52 #include "llvm/Support/YAMLParser.h"
54 using namespace clang::driver;
55 using namespace clang::driver::tools;
56 using namespace clang;
57 using namespace llvm::opt;
59 void tools::addPathIfExists(const Driver &D, const Twine &Path,
60 ToolChain::path_list &Paths) {
61 if (D.getVFS().exists(Path))
62 Paths.push_back(Path.str());
65 void tools::handleTargetFeaturesGroup(const ArgList &Args,
66 std::vector<StringRef> &Features,
68 for (const Arg *A : Args.filtered(Group)) {
69 StringRef Name = A->getOption().getName();
73 assert(Name.startswith("m") && "Invalid feature name.");
74 Name = Name.substr(1);
76 bool IsNegative = Name.startswith("no-");
78 Name = Name.substr(3);
79 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
83 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
84 const char *ArgName, const char *EnvVar) {
85 const char *DirList = ::getenv(EnvVar);
86 bool CombinedArg = false;
89 return; // Nothing to do.
91 StringRef Name(ArgName);
92 if (Name.equals("-I") || Name.equals("-L"))
95 StringRef Dirs(DirList);
96 if (Dirs.empty()) // Empty string should not add '.'.
99 StringRef::size_type Delim;
100 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
101 if (Delim == 0) { // Leading colon.
103 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
105 CmdArgs.push_back(ArgName);
106 CmdArgs.push_back(".");
111 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
113 CmdArgs.push_back(ArgName);
114 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
117 Dirs = Dirs.substr(Delim + 1);
120 if (Dirs.empty()) { // Trailing colon.
122 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
124 CmdArgs.push_back(ArgName);
125 CmdArgs.push_back(".");
127 } else { // Add the last path.
129 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
131 CmdArgs.push_back(ArgName);
132 CmdArgs.push_back(Args.MakeArgString(Dirs));
137 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
138 const ArgList &Args, ArgStringList &CmdArgs,
139 const JobAction &JA) {
140 const Driver &D = TC.getDriver();
142 // Add extra linker input arguments which are not treated as inputs
143 // (constructed via -Xarch_).
144 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
146 for (const auto &II : Inputs) {
147 // If the current tool chain refers to an OpenMP offloading host, we should
148 // ignore inputs that refer to OpenMP offloading devices - they will be
149 // embedded according to a proper linker script.
150 if (auto *IA = II.getAction())
151 if (JA.isHostOffloading(Action::OFK_OpenMP) &&
152 IA->isDeviceOffloading(Action::OFK_OpenMP))
155 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
156 // Don't try to pass LLVM inputs unless we have native support.
157 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
159 // Add filenames immediately.
160 if (II.isFilename()) {
161 CmdArgs.push_back(II.getFilename());
165 // Otherwise, this is a linker input argument.
166 const Arg &A = II.getInputArg();
168 // Handle reserved library options.
169 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
170 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
171 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
172 TC.AddCCKextLibArgs(Args, CmdArgs);
173 else if (A.getOption().matches(options::OPT_z)) {
174 // Pass -z prefix for gcc linker compatibility.
176 A.render(Args, CmdArgs);
178 A.renderAsInput(Args, CmdArgs);
182 // LIBRARY_PATH - included following the user specified library paths.
183 // and only supported on native toolchains.
184 if (!TC.isCrossCompiling()) {
185 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
189 void tools::AddTargetFeature(const ArgList &Args,
190 std::vector<StringRef> &Features,
191 OptSpecifier OnOpt, OptSpecifier OffOpt,
192 StringRef FeatureName) {
193 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
194 if (A->getOption().matches(OnOpt))
195 Features.push_back(Args.MakeArgString("+" + FeatureName));
197 Features.push_back(Args.MakeArgString("-" + FeatureName));
201 /// Get the (LLVM) name of the R600 gpu we are targeting.
202 static std::string getR600TargetGPU(const ArgList &Args) {
203 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
204 const char *GPUName = A->getValue();
205 return llvm::StringSwitch<const char *>(GPUName)
206 .Cases("rv630", "rv635", "r600")
207 .Cases("rv610", "rv620", "rs780", "rs880")
208 .Case("rv740", "rv770")
209 .Case("palm", "cedar")
210 .Cases("sumo", "sumo2", "sumo")
211 .Case("hemlock", "cypress")
212 .Case("aruba", "cayman")
218 static std::string getNios2TargetCPU(const ArgList &Args) {
219 Arg *A = Args.getLastArg(options::OPT_mcpu_EQ);
221 A = Args.getLastArg(options::OPT_march_EQ);
226 const char *name = A->getValue();
227 return llvm::StringSwitch<const char *>(name)
228 .Case("r1", "nios2r1")
229 .Case("r2", "nios2r2")
233 static std::string getLanaiTargetCPU(const ArgList &Args) {
234 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
235 return A->getValue();
240 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
241 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
242 // If we have -mcpu=, use that.
243 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
244 StringRef CPU = A->getValue();
247 // Handle "native" by examining the host. "native" isn't meaningful when
248 // cross compiling, so only support this when the host is also WebAssembly.
250 return llvm::sys::getHostCPUName();
259 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
263 switch (T.getArch()) {
267 case llvm::Triple::aarch64:
268 case llvm::Triple::aarch64_be:
269 return aarch64::getAArch64TargetCPU(Args, A);
271 case llvm::Triple::arm:
272 case llvm::Triple::armeb:
273 case llvm::Triple::thumb:
274 case llvm::Triple::thumbeb: {
275 StringRef MArch, MCPU;
276 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
277 return arm::getARMTargetCPU(MCPU, MArch, T);
280 case llvm::Triple::avr:
281 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
282 return A->getValue();
285 case llvm::Triple::nios2: {
286 return getNios2TargetCPU(Args);
289 case llvm::Triple::mips:
290 case llvm::Triple::mipsel:
291 case llvm::Triple::mips64:
292 case llvm::Triple::mips64el: {
295 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
299 case llvm::Triple::nvptx:
300 case llvm::Triple::nvptx64:
301 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
302 return A->getValue();
305 case llvm::Triple::ppc:
306 case llvm::Triple::ppc64:
307 case llvm::Triple::ppc64le: {
308 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
309 // LLVM may default to generating code for the native CPU,
310 // but, like gcc, we default to a more generic option for
311 // each architecture. (except on Darwin)
312 if (TargetCPUName.empty() && !T.isOSDarwin()) {
313 if (T.getArch() == llvm::Triple::ppc64)
314 TargetCPUName = "ppc64";
315 else if (T.getArch() == llvm::Triple::ppc64le)
316 TargetCPUName = "ppc64le";
318 TargetCPUName = "ppc";
320 return TargetCPUName;
323 case llvm::Triple::sparc:
324 case llvm::Triple::sparcel:
325 case llvm::Triple::sparcv9:
326 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
327 return A->getValue();
330 case llvm::Triple::x86:
331 case llvm::Triple::x86_64:
332 return x86::getX86TargetCPU(Args, T);
334 case llvm::Triple::hexagon:
336 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
338 case llvm::Triple::lanai:
339 return getLanaiTargetCPU(Args);
341 case llvm::Triple::systemz:
342 return systemz::getSystemZTargetCPU(Args);
344 case llvm::Triple::r600:
345 case llvm::Triple::amdgcn:
346 return getR600TargetGPU(Args);
348 case llvm::Triple::wasm32:
349 case llvm::Triple::wasm64:
350 return getWebAssemblyTargetCPU(Args);
354 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
355 unsigned Parallelism = 0;
356 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
358 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
359 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
360 << LtoJobsArg->getValue();
364 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
366 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
367 return Triple.getOS() == llvm::Triple::CloudABI ||
368 Triple.getArch() == llvm::Triple::wasm32 ||
369 Triple.getArch() == llvm::Triple::wasm64;
372 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
373 ArgStringList &CmdArgs, bool IsThinLTO,
375 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
376 // as gold requires -plugin to come before any -plugin-opt that -Wl might
378 CmdArgs.push_back("-plugin");
380 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
381 CmdArgs.push_back(Args.MakeArgString(Plugin));
383 // Try to pass driver level flags relevant to LTO code generation down to
386 // Handle flags for selecting CPU variants.
387 std::string CPU = getCPUName(Args, ToolChain.getTriple());
389 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
391 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
393 if (A->getOption().matches(options::OPT_O4) ||
394 A->getOption().matches(options::OPT_Ofast))
396 else if (A->getOption().matches(options::OPT_O))
397 OOpt = A->getValue();
398 else if (A->getOption().matches(options::OPT_O0))
401 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
405 CmdArgs.push_back("-plugin-opt=thinlto");
407 if (unsigned Parallelism = getLTOParallelism(Args, D))
408 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
409 llvm::to_string(Parallelism)));
411 // If an explicit debugger tuning argument appeared, pass it along.
412 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
413 options::OPT_ggdbN_Group)) {
414 if (A->getOption().matches(options::OPT_glldb))
415 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
416 else if (A->getOption().matches(options::OPT_gsce))
417 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
419 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
422 bool UseSeparateSections =
423 isUseSeparateSections(ToolChain.getEffectiveTriple());
425 if (Args.hasFlag(options::OPT_ffunction_sections,
426 options::OPT_fno_function_sections, UseSeparateSections)) {
427 CmdArgs.push_back("-plugin-opt=-function-sections");
430 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
431 UseSeparateSections)) {
432 CmdArgs.push_back("-plugin-opt=-data-sections");
435 if (Arg *A = getLastProfileSampleUseArg(Args)) {
436 StringRef FName = A->getValue();
437 if (!llvm::sys::fs::exists(FName))
438 D.Diag(diag::err_drv_no_such_file) << FName;
441 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
445 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
446 ArgStringList &CmdArgs) {
447 std::string CandidateRPath = TC.getArchSpecificLibPath();
448 if (TC.getVFS().exists(CandidateRPath)) {
449 CmdArgs.push_back("-rpath");
450 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
454 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
455 const ArgList &Args, bool IsOffloadingHost,
457 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
458 options::OPT_fno_openmp, false))
461 switch (TC.getDriver().getOpenMPRuntime(Args)) {
462 case Driver::OMPRT_OMP:
463 CmdArgs.push_back("-lomp");
465 case Driver::OMPRT_GOMP:
466 CmdArgs.push_back("-lgomp");
469 CmdArgs.push_back("-lrt");
471 case Driver::OMPRT_IOMP5:
472 CmdArgs.push_back("-liomp5");
474 case Driver::OMPRT_Unknown:
475 // Already diagnosed.
479 if (IsOffloadingHost)
480 CmdArgs.push_back("-lomptarget");
482 addArchSpecificRPath(TC, Args, CmdArgs);
487 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
488 ArgStringList &CmdArgs, StringRef Sanitizer,
489 bool IsShared, bool IsWhole) {
490 // Wrap any static runtimes that must be forced into executable in
492 if (IsWhole) CmdArgs.push_back("-whole-archive");
493 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
494 if (IsWhole) CmdArgs.push_back("-no-whole-archive");
497 addArchSpecificRPath(TC, Args, CmdArgs);
501 // Tries to use a file with the list of dynamic symbols that need to be exported
502 // from the runtime library. Returns true if the file was found.
503 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
504 ArgStringList &CmdArgs,
505 StringRef Sanitizer) {
506 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
507 if (llvm::sys::fs::exists(SanRT + ".syms")) {
508 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
514 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
515 ArgStringList &CmdArgs) {
516 // Force linking against the system libraries sanitizers depends on
517 // (see PR15823 why this is necessary).
518 CmdArgs.push_back("--no-as-needed");
519 // There's no libpthread or librt on RTEMS.
520 if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
521 CmdArgs.push_back("-lpthread");
522 CmdArgs.push_back("-lrt");
524 CmdArgs.push_back("-lm");
525 // There's no libdl on FreeBSD or RTEMS.
526 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
527 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
528 TC.getTriple().getOS() != llvm::Triple::RTEMS)
529 CmdArgs.push_back("-ldl");
533 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
534 SmallVectorImpl<StringRef> &SharedRuntimes,
535 SmallVectorImpl<StringRef> &StaticRuntimes,
536 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
537 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
538 SmallVectorImpl<StringRef> &RequiredSymbols) {
539 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
540 // Collect shared runtimes.
541 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
542 SharedRuntimes.push_back("asan");
544 // The stats_client library is also statically linked into DSOs.
545 if (SanArgs.needsStatsRt())
546 StaticRuntimes.push_back("stats_client");
548 // Collect static runtimes.
549 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
550 // Don't link static runtimes into DSOs or if compiling for Android.
553 if (SanArgs.needsAsanRt()) {
554 if (SanArgs.needsSharedAsanRt()) {
555 HelperStaticRuntimes.push_back("asan-preinit");
557 StaticRuntimes.push_back("asan");
558 if (SanArgs.linkCXXRuntimes())
559 StaticRuntimes.push_back("asan_cxx");
562 if (SanArgs.needsDfsanRt())
563 StaticRuntimes.push_back("dfsan");
564 if (SanArgs.needsLsanRt())
565 StaticRuntimes.push_back("lsan");
566 if (SanArgs.needsMsanRt()) {
567 StaticRuntimes.push_back("msan");
568 if (SanArgs.linkCXXRuntimes())
569 StaticRuntimes.push_back("msan_cxx");
571 if (SanArgs.needsTsanRt()) {
572 StaticRuntimes.push_back("tsan");
573 if (SanArgs.linkCXXRuntimes())
574 StaticRuntimes.push_back("tsan_cxx");
576 if (SanArgs.needsUbsanRt()) {
577 StaticRuntimes.push_back("ubsan_standalone");
578 if (SanArgs.linkCXXRuntimes())
579 StaticRuntimes.push_back("ubsan_standalone_cxx");
581 if (SanArgs.needsSafeStackRt()) {
582 NonWholeStaticRuntimes.push_back("safestack");
583 RequiredSymbols.push_back("__safestack_init");
585 if (SanArgs.needsCfiRt())
586 StaticRuntimes.push_back("cfi");
587 if (SanArgs.needsCfiDiagRt()) {
588 StaticRuntimes.push_back("cfi_diag");
589 if (SanArgs.linkCXXRuntimes())
590 StaticRuntimes.push_back("ubsan_standalone_cxx");
592 if (SanArgs.needsStatsRt()) {
593 NonWholeStaticRuntimes.push_back("stats");
594 RequiredSymbols.push_back("__sanitizer_stats_register");
596 if (SanArgs.needsEsanRt())
597 StaticRuntimes.push_back("esan");
600 static void addLibFuzzerRuntime(const ToolChain &TC,
602 ArgStringList &CmdArgs) {
603 StringRef ParentDir = llvm::sys::path::parent_path(TC.getDriver().InstalledDir);
604 SmallString<128> P(ParentDir);
605 llvm::sys::path::append(P, "lib", "libLLVMFuzzer.a");
606 CmdArgs.push_back(Args.MakeArgString(P));
607 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
611 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
612 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
613 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
614 ArgStringList &CmdArgs) {
615 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
616 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
617 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
618 NonWholeStaticRuntimes, HelperStaticRuntimes,
620 // Inject libfuzzer dependencies.
621 if (TC.getSanitizerArgs().needsFuzzer()
622 && !Args.hasArg(options::OPT_shared)) {
623 addLibFuzzerRuntime(TC, Args, CmdArgs);
626 for (auto RT : SharedRuntimes)
627 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
628 for (auto RT : HelperStaticRuntimes)
629 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
630 bool AddExportDynamic = false;
631 for (auto RT : StaticRuntimes) {
632 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
633 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
635 for (auto RT : NonWholeStaticRuntimes) {
636 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
637 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
639 for (auto S : RequiredSymbols) {
640 CmdArgs.push_back("-u");
641 CmdArgs.push_back(Args.MakeArgString(S));
643 // If there is a static runtime with no dynamic list, force all the symbols
644 // to be dynamic to be sure we export sanitizer interface functions.
645 if (AddExportDynamic)
646 CmdArgs.push_back("-export-dynamic");
648 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
649 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
650 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
652 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
655 bool tools::areOptimizationsEnabled(const ArgList &Args) {
656 // Find the last -O arg and see if it is non-zero.
657 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
658 return !A->getOption().matches(options::OPT_O0);
663 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
664 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
665 if (FinalOutput && Args.hasArg(options::OPT_c)) {
666 SmallString<128> T(FinalOutput->getValue());
667 llvm::sys::path::replace_extension(T, "dwo");
668 return Args.MakeArgString(T);
670 // Use the compilation dir.
672 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
673 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
674 llvm::sys::path::replace_extension(F, "dwo");
676 return Args.MakeArgString(F);
680 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
681 const JobAction &JA, const ArgList &Args,
682 const InputInfo &Output, const char *OutFile) {
683 ArgStringList ExtractArgs;
684 ExtractArgs.push_back("--extract-dwo");
686 ArgStringList StripArgs;
687 StripArgs.push_back("--strip-dwo");
689 // Grabbing the output of the earlier compile step.
690 StripArgs.push_back(Output.getFilename());
691 ExtractArgs.push_back(Output.getFilename());
692 ExtractArgs.push_back(OutFile);
694 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
695 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
697 // First extract the dwo sections.
698 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
700 // Then remove them from the original .o file.
701 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
704 // Claim options we don't want to warn if they are unused. We do this for
705 // options that build systems might add but are unused when assembling or only
706 // running the preprocessor for example.
707 void tools::claimNoWarnArgs(const ArgList &Args) {
708 // Don't warn about unused -f(no-)?lto. This can happen when we're
709 // preprocessing, precompiling or assembling.
710 Args.ClaimAllArgs(options::OPT_flto_EQ);
711 Args.ClaimAllArgs(options::OPT_flto);
712 Args.ClaimAllArgs(options::OPT_fno_lto);
715 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
716 auto *ProfileUseArg = Args.getLastArg(
717 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
718 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
719 options::OPT_fno_profile_instr_use);
722 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
723 ProfileUseArg = nullptr;
725 return ProfileUseArg;
728 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
729 auto *ProfileSampleUseArg = Args.getLastArg(
730 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
731 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
732 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
734 if (ProfileSampleUseArg &&
735 (ProfileSampleUseArg->getOption().matches(
736 options::OPT_fno_profile_sample_use) ||
737 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
740 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
741 options::OPT_fauto_profile_EQ);
744 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
745 /// smooshes them together with platform defaults, to decide whether
746 /// this compile should be using PIC mode or not. Returns a tuple of
747 /// (RelocationModel, PICLevel, IsPIE).
748 std::tuple<llvm::Reloc::Model, unsigned, bool>
749 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
750 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
751 const llvm::Triple &Triple = ToolChain.getTriple();
753 bool PIE = ToolChain.isPIEDefault();
754 bool PIC = PIE || ToolChain.isPICDefault();
755 // The Darwin/MachO default to use PIC does not apply when using -static.
756 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
758 bool IsPICLevelTwo = PIC;
761 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
763 // Android-specific defaults for PIC/PIE
764 if (Triple.isAndroid()) {
765 switch (Triple.getArch()) {
766 case llvm::Triple::arm:
767 case llvm::Triple::armeb:
768 case llvm::Triple::thumb:
769 case llvm::Triple::thumbeb:
770 case llvm::Triple::aarch64:
771 case llvm::Triple::mips:
772 case llvm::Triple::mipsel:
773 case llvm::Triple::mips64:
774 case llvm::Triple::mips64el:
775 PIC = true; // "-fpic"
778 case llvm::Triple::x86:
779 case llvm::Triple::x86_64:
780 PIC = true; // "-fPIC"
781 IsPICLevelTwo = true;
789 // OpenBSD-specific defaults for PIE
790 if (Triple.getOS() == llvm::Triple::OpenBSD) {
791 switch (ToolChain.getArch()) {
792 case llvm::Triple::arm:
793 case llvm::Triple::aarch64:
794 case llvm::Triple::mips64:
795 case llvm::Triple::mips64el:
796 case llvm::Triple::x86:
797 case llvm::Triple::x86_64:
798 IsPICLevelTwo = false; // "-fpie"
801 case llvm::Triple::ppc:
802 case llvm::Triple::sparc:
803 case llvm::Triple::sparcel:
804 case llvm::Triple::sparcv9:
805 IsPICLevelTwo = true; // "-fPIE"
813 // The last argument relating to either PIC or PIE wins, and no
814 // other argument is used. If the last argument is any flavor of the
815 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
816 // option implicitly enables PIC at the same level.
817 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
818 options::OPT_fpic, options::OPT_fno_pic,
819 options::OPT_fPIE, options::OPT_fno_PIE,
820 options::OPT_fpie, options::OPT_fno_pie);
821 if (Triple.isOSWindows() && LastPICArg &&
823 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
824 options::OPT_fPIE, options::OPT_fpie)) {
825 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
826 << LastPICArg->getSpelling() << Triple.str();
827 if (Triple.getArch() == llvm::Triple::x86_64)
828 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
829 return std::make_tuple(llvm::Reloc::Static, 0U, false);
832 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
833 // is forced, then neither PIC nor PIE flags will have no effect.
834 if (!ToolChain.isPICDefaultForced()) {
836 Option O = LastPICArg->getOption();
837 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
838 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
839 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
841 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
843 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
846 if (EffectiveTriple.isPS4CPU()) {
847 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
848 StringRef Model = ModelArg ? ModelArg->getValue() : "";
849 if (Model != "kernel") {
851 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
852 << LastPICArg->getSpelling();
859 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
860 // PIC level would've been set to level 1, force it back to level 2 PIC
862 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
863 IsPICLevelTwo |= ToolChain.isPICDefault();
865 // This kernel flags are a trump-card: they will disable PIC/PIE
866 // generation, independent of the argument order.
868 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
869 !EffectiveTriple.isWatchOS()))
872 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
873 // This is a very special mode. It trumps the other modes, almost no one
874 // uses it, and it isn't even valid on any OS but Darwin.
875 if (!Triple.isOSDarwin())
876 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
877 << A->getSpelling() << Triple.str();
879 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
881 // Only a forced PIC mode can cause the actual compile to have PIC defines
882 // etc., no flags are sufficient. This behavior was selected to closely
883 // match that of llvm-gcc and Apple GCC before that.
884 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
886 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
889 bool EmbeddedPISupported;
890 switch (Triple.getArch()) {
891 case llvm::Triple::arm:
892 case llvm::Triple::armeb:
893 case llvm::Triple::thumb:
894 case llvm::Triple::thumbeb:
895 EmbeddedPISupported = true;
898 EmbeddedPISupported = false;
902 bool ROPI = false, RWPI = false;
903 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
904 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
905 if (!EmbeddedPISupported)
906 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
907 << LastROPIArg->getSpelling() << Triple.str();
910 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
911 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
912 if (!EmbeddedPISupported)
913 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
914 << LastRWPIArg->getSpelling() << Triple.str();
918 // ROPI and RWPI are not comaptible with PIC or PIE.
919 if ((ROPI || RWPI) && (PIC || PIE))
920 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
922 // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
924 if ((Triple.getArch() == llvm::Triple::mips64 ||
925 Triple.getArch() == llvm::Triple::mips64el) &&
926 Args.hasArg(options::OPT_mno_abicalls))
927 return std::make_tuple(llvm::Reloc::Static, 0U, false);
930 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
932 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
934 RelocM = llvm::Reloc::ROPI_RWPI;
936 RelocM = llvm::Reloc::ROPI;
938 RelocM = llvm::Reloc::RWPI;
940 return std::make_tuple(RelocM, 0U, false);
943 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
944 ArgStringList &CmdArgs) {
945 llvm::Reloc::Model RelocationModel;
948 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
950 if (RelocationModel != llvm::Reloc::Static)
951 CmdArgs.push_back("-KPIC");
954 /// \brief Determine whether Objective-C automated reference counting is
956 bool tools::isObjCAutoRefCount(const ArgList &Args) {
957 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
960 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
961 ArgStringList &CmdArgs, const ArgList &Args) {
962 bool isAndroid = Triple.isAndroid();
963 bool isCygMing = Triple.isOSCygMing();
964 bool IsIAMCU = Triple.isOSIAMCU();
965 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
966 Args.hasArg(options::OPT_static);
968 CmdArgs.push_back("-lgcc");
970 if (StaticLibgcc || isAndroid) {
972 CmdArgs.push_back("-lgcc");
974 if (!D.CCCIsCXX() && !isCygMing)
975 CmdArgs.push_back("--as-needed");
976 CmdArgs.push_back("-lgcc_s");
977 if (!D.CCCIsCXX() && !isCygMing)
978 CmdArgs.push_back("--no-as-needed");
981 if (StaticLibgcc && !isAndroid && !IsIAMCU)
982 CmdArgs.push_back("-lgcc_eh");
983 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
984 CmdArgs.push_back("-lgcc");
986 // According to Android ABI, we have to link with libdl if we are
987 // linking with non-static libgcc.
989 // NOTE: This fixes a link error on Android MIPS as well. The non-static
990 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
991 if (isAndroid && !StaticLibgcc)
992 CmdArgs.push_back("-ldl");
995 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
996 ArgStringList &CmdArgs, const ArgList &Args) {
997 // Make use of compiler-rt if --rtlib option is used
998 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1001 case ToolChain::RLT_CompilerRT:
1002 switch (TC.getTriple().getOS()) {
1004 llvm_unreachable("unsupported OS");
1005 case llvm::Triple::Win32:
1006 case llvm::Triple::Linux:
1007 case llvm::Triple::Fuchsia:
1008 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1012 case ToolChain::RLT_Libgcc:
1013 // Make sure libgcc is not used under MSVC environment by default
1014 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1015 // Issue error diagnostic if libgcc is explicitly specified
1016 // through command line as --rtlib option argument.
1017 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1018 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1019 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1022 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);