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 getLanaiTargetCPU(const ArgList &Args) {
219 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
220 return A->getValue();
225 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
226 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
227 // If we have -mcpu=, use that.
228 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
229 StringRef CPU = A->getValue();
232 // Handle "native" by examining the host. "native" isn't meaningful when
233 // cross compiling, so only support this when the host is also WebAssembly.
235 return llvm::sys::getHostCPUName();
244 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
248 switch (T.getArch()) {
252 case llvm::Triple::aarch64:
253 case llvm::Triple::aarch64_be:
254 return aarch64::getAArch64TargetCPU(Args, A);
256 case llvm::Triple::arm:
257 case llvm::Triple::armeb:
258 case llvm::Triple::thumb:
259 case llvm::Triple::thumbeb: {
260 StringRef MArch, MCPU;
261 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
262 return arm::getARMTargetCPU(MCPU, MArch, T);
264 case llvm::Triple::mips:
265 case llvm::Triple::mipsel:
266 case llvm::Triple::mips64:
267 case llvm::Triple::mips64el: {
270 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
274 case llvm::Triple::nvptx:
275 case llvm::Triple::nvptx64:
276 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
277 return A->getValue();
280 case llvm::Triple::ppc:
281 case llvm::Triple::ppc64:
282 case llvm::Triple::ppc64le: {
283 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
284 // LLVM may default to generating code for the native CPU,
285 // but, like gcc, we default to a more generic option for
286 // each architecture. (except on Darwin)
287 if (TargetCPUName.empty() && !T.isOSDarwin()) {
288 if (T.getArch() == llvm::Triple::ppc64)
289 TargetCPUName = "ppc64";
290 else if (T.getArch() == llvm::Triple::ppc64le)
291 TargetCPUName = "ppc64le";
293 TargetCPUName = "ppc";
295 return TargetCPUName;
298 case llvm::Triple::sparc:
299 case llvm::Triple::sparcel:
300 case llvm::Triple::sparcv9:
301 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
302 return A->getValue();
305 case llvm::Triple::x86:
306 case llvm::Triple::x86_64:
307 return x86::getX86TargetCPU(Args, T);
309 case llvm::Triple::hexagon:
311 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
313 case llvm::Triple::lanai:
314 return getLanaiTargetCPU(Args);
316 case llvm::Triple::systemz:
317 return systemz::getSystemZTargetCPU(Args);
319 case llvm::Triple::r600:
320 case llvm::Triple::amdgcn:
321 return getR600TargetGPU(Args);
323 case llvm::Triple::wasm32:
324 case llvm::Triple::wasm64:
325 return getWebAssemblyTargetCPU(Args);
329 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
330 unsigned Parallelism = 0;
331 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
333 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
334 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
335 << LtoJobsArg->getValue();
339 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
341 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
342 return Triple.getOS() == llvm::Triple::CloudABI ||
343 Triple.getArch() == llvm::Triple::wasm32 ||
344 Triple.getArch() == llvm::Triple::wasm64;
347 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
348 ArgStringList &CmdArgs, bool IsThinLTO,
350 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
351 // as gold requires -plugin to come before any -plugin-opt that -Wl might
353 CmdArgs.push_back("-plugin");
355 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
356 CmdArgs.push_back(Args.MakeArgString(Plugin));
358 // Try to pass driver level flags relevant to LTO code generation down to
361 // Handle flags for selecting CPU variants.
362 std::string CPU = getCPUName(Args, ToolChain.getTriple());
364 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
366 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
368 if (A->getOption().matches(options::OPT_O4) ||
369 A->getOption().matches(options::OPT_Ofast))
371 else if (A->getOption().matches(options::OPT_O))
372 OOpt = A->getValue();
373 else if (A->getOption().matches(options::OPT_O0))
376 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
380 CmdArgs.push_back("-plugin-opt=thinlto");
382 if (unsigned Parallelism = getLTOParallelism(Args, D))
383 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
384 llvm::to_string(Parallelism)));
386 // If an explicit debugger tuning argument appeared, pass it along.
387 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
388 options::OPT_ggdbN_Group)) {
389 if (A->getOption().matches(options::OPT_glldb))
390 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
391 else if (A->getOption().matches(options::OPT_gsce))
392 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
394 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
397 bool UseSeparateSections =
398 isUseSeparateSections(ToolChain.getEffectiveTriple());
400 if (Args.hasFlag(options::OPT_ffunction_sections,
401 options::OPT_fno_function_sections, UseSeparateSections)) {
402 CmdArgs.push_back("-plugin-opt=-function-sections");
405 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
406 UseSeparateSections)) {
407 CmdArgs.push_back("-plugin-opt=-data-sections");
410 if (Arg *A = getLastProfileSampleUseArg(Args)) {
411 StringRef FName = A->getValue();
412 if (!llvm::sys::fs::exists(FName))
413 D.Diag(diag::err_drv_no_such_file) << FName;
416 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
420 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
421 ArgStringList &CmdArgs) {
422 std::string CandidateRPath = TC.getArchSpecificLibPath();
423 if (TC.getVFS().exists(CandidateRPath)) {
424 CmdArgs.push_back("-rpath");
425 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
429 void tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
430 const ArgList &Args) {
431 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
432 options::OPT_fno_openmp, false))
435 switch (TC.getDriver().getOpenMPRuntime(Args)) {
436 case Driver::OMPRT_OMP:
437 CmdArgs.push_back("-lomp");
439 case Driver::OMPRT_GOMP:
440 CmdArgs.push_back("-lgomp");
442 case Driver::OMPRT_IOMP5:
443 CmdArgs.push_back("-liomp5");
445 case Driver::OMPRT_Unknown:
446 // Already diagnosed.
450 addArchSpecificRPath(TC, Args, CmdArgs);
453 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
454 ArgStringList &CmdArgs, StringRef Sanitizer,
455 bool IsShared, bool IsWhole) {
456 // Wrap any static runtimes that must be forced into executable in
458 if (IsWhole) CmdArgs.push_back("-whole-archive");
459 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
460 if (IsWhole) CmdArgs.push_back("-no-whole-archive");
463 addArchSpecificRPath(TC, Args, CmdArgs);
467 // Tries to use a file with the list of dynamic symbols that need to be exported
468 // from the runtime library. Returns true if the file was found.
469 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
470 ArgStringList &CmdArgs,
471 StringRef Sanitizer) {
472 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
473 if (llvm::sys::fs::exists(SanRT + ".syms")) {
474 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
480 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
481 ArgStringList &CmdArgs) {
482 // Force linking against the system libraries sanitizers depends on
483 // (see PR15823 why this is necessary).
484 CmdArgs.push_back("--no-as-needed");
485 // There's no libpthread or librt on RTEMS.
486 if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
487 CmdArgs.push_back("-lpthread");
488 CmdArgs.push_back("-lrt");
490 CmdArgs.push_back("-lm");
491 // There's no libdl on FreeBSD or RTEMS.
492 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
493 TC.getTriple().getOS() != llvm::Triple::RTEMS)
494 CmdArgs.push_back("-ldl");
498 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
499 SmallVectorImpl<StringRef> &SharedRuntimes,
500 SmallVectorImpl<StringRef> &StaticRuntimes,
501 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
502 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
503 SmallVectorImpl<StringRef> &RequiredSymbols) {
504 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
505 // Collect shared runtimes.
506 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
507 SharedRuntimes.push_back("asan");
509 // The stats_client library is also statically linked into DSOs.
510 if (SanArgs.needsStatsRt())
511 StaticRuntimes.push_back("stats_client");
513 // Collect static runtimes.
514 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
515 // Don't link static runtimes into DSOs or if compiling for Android.
518 if (SanArgs.needsAsanRt()) {
519 if (SanArgs.needsSharedAsanRt()) {
520 HelperStaticRuntimes.push_back("asan-preinit");
522 StaticRuntimes.push_back("asan");
523 if (SanArgs.linkCXXRuntimes())
524 StaticRuntimes.push_back("asan_cxx");
527 if (SanArgs.needsDfsanRt())
528 StaticRuntimes.push_back("dfsan");
529 if (SanArgs.needsLsanRt())
530 StaticRuntimes.push_back("lsan");
531 if (SanArgs.needsMsanRt()) {
532 StaticRuntimes.push_back("msan");
533 if (SanArgs.linkCXXRuntimes())
534 StaticRuntimes.push_back("msan_cxx");
536 if (SanArgs.needsTsanRt()) {
537 StaticRuntimes.push_back("tsan");
538 if (SanArgs.linkCXXRuntimes())
539 StaticRuntimes.push_back("tsan_cxx");
541 if (SanArgs.needsUbsanRt()) {
542 StaticRuntimes.push_back("ubsan_standalone");
543 if (SanArgs.linkCXXRuntimes())
544 StaticRuntimes.push_back("ubsan_standalone_cxx");
546 if (SanArgs.needsSafeStackRt()) {
547 NonWholeStaticRuntimes.push_back("safestack");
548 RequiredSymbols.push_back("__safestack_init");
550 if (SanArgs.needsCfiRt())
551 StaticRuntimes.push_back("cfi");
552 if (SanArgs.needsCfiDiagRt()) {
553 StaticRuntimes.push_back("cfi_diag");
554 if (SanArgs.linkCXXRuntimes())
555 StaticRuntimes.push_back("ubsan_standalone_cxx");
557 if (SanArgs.needsStatsRt()) {
558 NonWholeStaticRuntimes.push_back("stats");
559 RequiredSymbols.push_back("__sanitizer_stats_register");
561 if (SanArgs.needsEsanRt())
562 StaticRuntimes.push_back("esan");
565 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
566 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
567 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
568 ArgStringList &CmdArgs) {
569 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
570 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
571 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
572 NonWholeStaticRuntimes, HelperStaticRuntimes,
574 for (auto RT : SharedRuntimes)
575 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
576 for (auto RT : HelperStaticRuntimes)
577 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
578 bool AddExportDynamic = false;
579 for (auto RT : StaticRuntimes) {
580 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
581 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
583 for (auto RT : NonWholeStaticRuntimes) {
584 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
585 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
587 for (auto S : RequiredSymbols) {
588 CmdArgs.push_back("-u");
589 CmdArgs.push_back(Args.MakeArgString(S));
591 // If there is a static runtime with no dynamic list, force all the symbols
592 // to be dynamic to be sure we export sanitizer interface functions.
593 if (AddExportDynamic)
594 CmdArgs.push_back("-export-dynamic");
596 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
597 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
598 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
600 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
603 bool tools::areOptimizationsEnabled(const ArgList &Args) {
604 // Find the last -O arg and see if it is non-zero.
605 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
606 return !A->getOption().matches(options::OPT_O0);
611 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
612 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
613 if (FinalOutput && Args.hasArg(options::OPT_c)) {
614 SmallString<128> T(FinalOutput->getValue());
615 llvm::sys::path::replace_extension(T, "dwo");
616 return Args.MakeArgString(T);
618 // Use the compilation dir.
620 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
621 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
622 llvm::sys::path::replace_extension(F, "dwo");
624 return Args.MakeArgString(F);
628 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
629 const JobAction &JA, const ArgList &Args,
630 const InputInfo &Output, const char *OutFile) {
631 ArgStringList ExtractArgs;
632 ExtractArgs.push_back("--extract-dwo");
634 ArgStringList StripArgs;
635 StripArgs.push_back("--strip-dwo");
637 // Grabbing the output of the earlier compile step.
638 StripArgs.push_back(Output.getFilename());
639 ExtractArgs.push_back(Output.getFilename());
640 ExtractArgs.push_back(OutFile);
642 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
643 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
645 // First extract the dwo sections.
646 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
648 // Then remove them from the original .o file.
649 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
652 // Claim options we don't want to warn if they are unused. We do this for
653 // options that build systems might add but are unused when assembling or only
654 // running the preprocessor for example.
655 void tools::claimNoWarnArgs(const ArgList &Args) {
656 // Don't warn about unused -f(no-)?lto. This can happen when we're
657 // preprocessing, precompiling or assembling.
658 Args.ClaimAllArgs(options::OPT_flto_EQ);
659 Args.ClaimAllArgs(options::OPT_flto);
660 Args.ClaimAllArgs(options::OPT_fno_lto);
663 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
664 auto *ProfileUseArg = Args.getLastArg(
665 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
666 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
667 options::OPT_fno_profile_instr_use);
670 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
671 ProfileUseArg = nullptr;
673 return ProfileUseArg;
676 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
677 auto *ProfileSampleUseArg = Args.getLastArg(
678 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
679 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
680 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
682 if (ProfileSampleUseArg &&
683 (ProfileSampleUseArg->getOption().matches(
684 options::OPT_fno_profile_sample_use) ||
685 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
688 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
689 options::OPT_fauto_profile_EQ);
692 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
693 /// smooshes them together with platform defaults, to decide whether
694 /// this compile should be using PIC mode or not. Returns a tuple of
695 /// (RelocationModel, PICLevel, IsPIE).
696 std::tuple<llvm::Reloc::Model, unsigned, bool>
697 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
698 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
699 const llvm::Triple &Triple = ToolChain.getTriple();
701 bool PIE = ToolChain.isPIEDefault();
702 bool PIC = PIE || ToolChain.isPICDefault();
703 // The Darwin/MachO default to use PIC does not apply when using -static.
704 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
706 bool IsPICLevelTwo = PIC;
709 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
711 // Android-specific defaults for PIC/PIE
712 if (Triple.isAndroid()) {
713 switch (Triple.getArch()) {
714 case llvm::Triple::arm:
715 case llvm::Triple::armeb:
716 case llvm::Triple::thumb:
717 case llvm::Triple::thumbeb:
718 case llvm::Triple::aarch64:
719 case llvm::Triple::mips:
720 case llvm::Triple::mipsel:
721 case llvm::Triple::mips64:
722 case llvm::Triple::mips64el:
723 PIC = true; // "-fpic"
726 case llvm::Triple::x86:
727 case llvm::Triple::x86_64:
728 PIC = true; // "-fPIC"
729 IsPICLevelTwo = true;
737 // OpenBSD-specific defaults for PIE
738 if (Triple.getOS() == llvm::Triple::OpenBSD) {
739 switch (ToolChain.getArch()) {
740 case llvm::Triple::arm:
741 case llvm::Triple::aarch64:
742 case llvm::Triple::mips64:
743 case llvm::Triple::mips64el:
744 case llvm::Triple::x86:
745 case llvm::Triple::x86_64:
746 IsPICLevelTwo = false; // "-fpie"
749 case llvm::Triple::ppc:
750 case llvm::Triple::sparc:
751 case llvm::Triple::sparcel:
752 case llvm::Triple::sparcv9:
753 IsPICLevelTwo = true; // "-fPIE"
761 // The last argument relating to either PIC or PIE wins, and no
762 // other argument is used. If the last argument is any flavor of the
763 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
764 // option implicitly enables PIC at the same level.
765 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
766 options::OPT_fpic, options::OPT_fno_pic,
767 options::OPT_fPIE, options::OPT_fno_PIE,
768 options::OPT_fpie, options::OPT_fno_pie);
769 if (Triple.isOSWindows() && LastPICArg &&
771 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
772 options::OPT_fPIE, options::OPT_fpie)) {
773 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
774 << LastPICArg->getSpelling() << Triple.str();
775 if (Triple.getArch() == llvm::Triple::x86_64)
776 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
777 return std::make_tuple(llvm::Reloc::Static, 0U, false);
780 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
781 // is forced, then neither PIC nor PIE flags will have no effect.
782 if (!ToolChain.isPICDefaultForced()) {
784 Option O = LastPICArg->getOption();
785 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
786 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
787 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
789 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
791 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
794 if (EffectiveTriple.isPS4CPU()) {
795 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
796 StringRef Model = ModelArg ? ModelArg->getValue() : "";
797 if (Model != "kernel") {
799 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
800 << LastPICArg->getSpelling();
807 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
808 // PIC level would've been set to level 1, force it back to level 2 PIC
810 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
811 IsPICLevelTwo |= ToolChain.isPICDefault();
813 // This kernel flags are a trump-card: they will disable PIC/PIE
814 // generation, independent of the argument order.
816 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
817 !EffectiveTriple.isWatchOS()))
820 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
821 // This is a very special mode. It trumps the other modes, almost no one
822 // uses it, and it isn't even valid on any OS but Darwin.
823 if (!Triple.isOSDarwin())
824 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
825 << A->getSpelling() << Triple.str();
827 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
829 // Only a forced PIC mode can cause the actual compile to have PIC defines
830 // etc., no flags are sufficient. This behavior was selected to closely
831 // match that of llvm-gcc and Apple GCC before that.
832 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
834 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
837 bool EmbeddedPISupported;
838 switch (Triple.getArch()) {
839 case llvm::Triple::arm:
840 case llvm::Triple::armeb:
841 case llvm::Triple::thumb:
842 case llvm::Triple::thumbeb:
843 EmbeddedPISupported = true;
846 EmbeddedPISupported = false;
850 bool ROPI = false, RWPI = false;
851 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
852 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
853 if (!EmbeddedPISupported)
854 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
855 << LastROPIArg->getSpelling() << Triple.str();
858 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
859 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
860 if (!EmbeddedPISupported)
861 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
862 << LastRWPIArg->getSpelling() << Triple.str();
866 // ROPI and RWPI are not comaptible with PIC or PIE.
867 if ((ROPI || RWPI) && (PIC || PIE))
868 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
870 // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
872 if ((Triple.getArch() == llvm::Triple::mips64 ||
873 Triple.getArch() == llvm::Triple::mips64el) &&
874 Args.hasArg(options::OPT_mno_abicalls))
875 return std::make_tuple(llvm::Reloc::Static, 0U, false);
878 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
880 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
882 RelocM = llvm::Reloc::ROPI_RWPI;
884 RelocM = llvm::Reloc::ROPI;
886 RelocM = llvm::Reloc::RWPI;
888 return std::make_tuple(RelocM, 0U, false);
891 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
892 ArgStringList &CmdArgs) {
893 llvm::Reloc::Model RelocationModel;
896 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
898 if (RelocationModel != llvm::Reloc::Static)
899 CmdArgs.push_back("-KPIC");
902 /// \brief Determine whether Objective-C automated reference counting is
904 bool tools::isObjCAutoRefCount(const ArgList &Args) {
905 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
908 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
909 ArgStringList &CmdArgs, const ArgList &Args) {
910 bool isAndroid = Triple.isAndroid();
911 bool isCygMing = Triple.isOSCygMing();
912 bool IsIAMCU = Triple.isOSIAMCU();
913 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
914 Args.hasArg(options::OPT_static);
916 CmdArgs.push_back("-lgcc");
918 if (StaticLibgcc || isAndroid) {
920 CmdArgs.push_back("-lgcc");
922 if (!D.CCCIsCXX() && !isCygMing)
923 CmdArgs.push_back("--as-needed");
924 CmdArgs.push_back("-lgcc_s");
925 if (!D.CCCIsCXX() && !isCygMing)
926 CmdArgs.push_back("--no-as-needed");
929 if (StaticLibgcc && !isAndroid && !IsIAMCU)
930 CmdArgs.push_back("-lgcc_eh");
931 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
932 CmdArgs.push_back("-lgcc");
934 // According to Android ABI, we have to link with libdl if we are
935 // linking with non-static libgcc.
937 // NOTE: This fixes a link error on Android MIPS as well. The non-static
938 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
939 if (isAndroid && !StaticLibgcc)
940 CmdArgs.push_back("-ldl");
943 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
944 ArgStringList &CmdArgs, const ArgList &Args) {
945 // Make use of compiler-rt if --rtlib option is used
946 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
949 case ToolChain::RLT_CompilerRT:
950 switch (TC.getTriple().getOS()) {
952 llvm_unreachable("unsupported OS");
953 case llvm::Triple::Win32:
954 case llvm::Triple::Linux:
955 case llvm::Triple::Fuchsia:
956 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
960 case ToolChain::RLT_Libgcc:
961 // Make sure libgcc is not used under MSVC environment by default
962 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
963 // Issue error diagnostic if libgcc is explicitly specified
964 // through command line as --rtlib option argument.
965 if (Args.hasArg(options::OPT_rtlib_EQ)) {
966 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
967 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
970 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);