blob: 5afe13586572b0a4020330590009cdfa864008da [file] [log] [blame]
David L. Jonesf561aba2017-03-08 01:02:16 +00001//===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "CommonArgs.h"
11#include "InputInfo.h"
12#include "Hexagon.h"
13#include "Arch/AArch64.h"
14#include "Arch/ARM.h"
15#include "Arch/Mips.h"
16#include "Arch/PPC.h"
17#include "Arch/SystemZ.h"
18#include "Arch/X86.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"
53
54using namespace clang::driver;
55using namespace clang::driver::tools;
56using namespace clang;
57using namespace llvm::opt;
58
59void 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());
63}
64
65void tools::handleTargetFeaturesGroup(const ArgList &Args,
66 std::vector<StringRef> &Features,
67 OptSpecifier Group) {
68 for (const Arg *A : Args.filtered(Group)) {
69 StringRef Name = A->getOption().getName();
70 A->claim();
71
72 // Skip over "-m".
73 assert(Name.startswith("m") && "Invalid feature name.");
74 Name = Name.substr(1);
75
76 bool IsNegative = Name.startswith("no-");
77 if (IsNegative)
78 Name = Name.substr(3);
79 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
80 }
81}
82
83void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
84 const char *ArgName, const char *EnvVar) {
85 const char *DirList = ::getenv(EnvVar);
86 bool CombinedArg = false;
87
88 if (!DirList)
89 return; // Nothing to do.
90
91 StringRef Name(ArgName);
92 if (Name.equals("-I") || Name.equals("-L"))
93 CombinedArg = true;
94
95 StringRef Dirs(DirList);
96 if (Dirs.empty()) // Empty string should not add '.'.
97 return;
98
99 StringRef::size_type Delim;
100 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
101 if (Delim == 0) { // Leading colon.
102 if (CombinedArg) {
103 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
104 } else {
105 CmdArgs.push_back(ArgName);
106 CmdArgs.push_back(".");
107 }
108 } else {
109 if (CombinedArg) {
110 CmdArgs.push_back(
111 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
112 } else {
113 CmdArgs.push_back(ArgName);
114 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
115 }
116 }
117 Dirs = Dirs.substr(Delim + 1);
118 }
119
120 if (Dirs.empty()) { // Trailing colon.
121 if (CombinedArg) {
122 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
123 } else {
124 CmdArgs.push_back(ArgName);
125 CmdArgs.push_back(".");
126 }
127 } else { // Add the last path.
128 if (CombinedArg) {
129 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
130 } else {
131 CmdArgs.push_back(ArgName);
132 CmdArgs.push_back(Args.MakeArgString(Dirs));
133 }
134 }
135}
136
137void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
138 const ArgList &Args, ArgStringList &CmdArgs,
139 const JobAction &JA) {
140 const Driver &D = TC.getDriver();
141
142 // Add extra linker input arguments which are not treated as inputs
143 // (constructed via -Xarch_).
144 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
145
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))
153 continue;
154
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();
158
159 // Add filenames immediately.
160 if (II.isFilename()) {
161 CmdArgs.push_back(II.getFilename());
162 continue;
163 }
164
165 // Otherwise, this is a linker input argument.
166 const Arg &A = II.getInputArg();
167
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.
175 A.claim();
176 A.render(Args, CmdArgs);
177 } else {
178 A.renderAsInput(Args, CmdArgs);
179 }
180 }
181
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");
186 }
187}
188
189void 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));
196 else
197 Features.push_back(Args.MakeArgString("-" + FeatureName));
198 }
199}
200
201/// Get the (LLVM) name of the R600 gpu we are targeting.
202static 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")
213 .Default(GPUName);
214 }
215 return "";
216}
217
218static std::string getLanaiTargetCPU(const ArgList &Args) {
219 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
220 return A->getValue();
221 }
222 return "";
223}
224
225/// Get the (LLVM) name of the WebAssembly cpu we are targeting.
226static 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();
230
231#ifdef __wasm__
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.
234 if (CPU == "native")
235 return llvm::sys::getHostCPUName();
236#endif
237
238 return CPU;
239 }
240
241 return "generic";
242}
243
244std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
245 bool FromAs) {
246 Arg *A;
247
248 switch (T.getArch()) {
249 default:
250 return "";
251
252 case llvm::Triple::aarch64:
253 case llvm::Triple::aarch64_be:
254 return aarch64::getAArch64TargetCPU(Args, A);
255
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);
263 }
264 case llvm::Triple::mips:
265 case llvm::Triple::mipsel:
266 case llvm::Triple::mips64:
267 case llvm::Triple::mips64el: {
268 StringRef CPUName;
269 StringRef ABIName;
270 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
271 return CPUName;
272 }
273
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();
278 return "";
279
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";
292 else
293 TargetCPUName = "ppc";
294 }
295 return TargetCPUName;
296 }
297
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();
303 return "";
304
305 case llvm::Triple::x86:
306 case llvm::Triple::x86_64:
307 return x86::getX86TargetCPU(Args, T);
308
309 case llvm::Triple::hexagon:
310 return "hexagon" +
311 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
312
313 case llvm::Triple::lanai:
314 return getLanaiTargetCPU(Args);
315
316 case llvm::Triple::systemz:
317 return systemz::getSystemZTargetCPU(Args);
318
319 case llvm::Triple::r600:
320 case llvm::Triple::amdgcn:
321 return getR600TargetGPU(Args);
322
323 case llvm::Triple::wasm32:
324 case llvm::Triple::wasm64:
325 return getWebAssemblyTargetCPU(Args);
326 }
327}
328
329unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
330 unsigned Parallelism = 0;
331 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
332 if (LtoJobsArg &&
333 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
334 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
335 << LtoJobsArg->getValue();
336 return Parallelism;
337}
338
339// CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
340// default.
341bool 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;
345}
346
347void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
348 ArgStringList &CmdArgs, bool IsThinLTO,
349 const Driver &D) {
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
352 // forward.
353 CmdArgs.push_back("-plugin");
354 std::string Plugin =
355 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
356 CmdArgs.push_back(Args.MakeArgString(Plugin));
357
358 // Try to pass driver level flags relevant to LTO code generation down to
359 // the plugin.
360
361 // Handle flags for selecting CPU variants.
362 std::string CPU = getCPUName(Args, ToolChain.getTriple());
363 if (!CPU.empty())
364 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
365
366 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
367 StringRef OOpt;
368 if (A->getOption().matches(options::OPT_O4) ||
369 A->getOption().matches(options::OPT_Ofast))
370 OOpt = "3";
371 else if (A->getOption().matches(options::OPT_O))
372 OOpt = A->getValue();
373 else if (A->getOption().matches(options::OPT_O0))
374 OOpt = "0";
375 if (!OOpt.empty())
376 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
377 }
378
379 if (IsThinLTO)
380 CmdArgs.push_back("-plugin-opt=thinlto");
381
382 if (unsigned Parallelism = getLTOParallelism(Args, D))
383 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
384 llvm::to_string(Parallelism)));
385
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");
393 else
394 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
395 }
396
397 bool UseSeparateSections =
398 isUseSeparateSections(ToolChain.getEffectiveTriple());
399
400 if (Args.hasFlag(options::OPT_ffunction_sections,
401 options::OPT_fno_function_sections, UseSeparateSections)) {
402 CmdArgs.push_back("-plugin-opt=-function-sections");
403 }
404
405 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
406 UseSeparateSections)) {
407 CmdArgs.push_back("-plugin-opt=-data-sections");
408 }
409
410 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
411 StringRef FName = A->getValue();
412 if (!llvm::sys::fs::exists(FName))
413 D.Diag(diag::err_drv_no_such_file) << FName;
414 else
415 CmdArgs.push_back(
416 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
417 }
418}
419
420void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
421 ArgStringList &CmdArgs) {
422 // In the cross-compilation case, arch-specific library path is likely
423 // unavailable at runtime.
424 if (TC.isCrossCompiling()) return;
425
426 std::string CandidateRPath = TC.getArchSpecificLibPath();
427 if (TC.getVFS().exists(CandidateRPath)) {
428 CmdArgs.push_back("-rpath");
429 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
430 }
431}
432
433void tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
434 const ArgList &Args) {
435 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
436 options::OPT_fno_openmp, false))
437 return;
438
439 switch (TC.getDriver().getOpenMPRuntime(Args)) {
440 case Driver::OMPRT_OMP:
441 CmdArgs.push_back("-lomp");
442 break;
443 case Driver::OMPRT_GOMP:
444 CmdArgs.push_back("-lgomp");
445 break;
446 case Driver::OMPRT_IOMP5:
447 CmdArgs.push_back("-liomp5");
448 break;
449 case Driver::OMPRT_Unknown:
450 // Already diagnosed.
451 break;
452 }
453
454 addArchSpecificRPath(TC, Args, CmdArgs);
455}
456
457static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
458 ArgStringList &CmdArgs, StringRef Sanitizer,
459 bool IsShared, bool IsWhole) {
460 // Wrap any static runtimes that must be forced into executable in
461 // whole-archive.
462 if (IsWhole) CmdArgs.push_back("-whole-archive");
463 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
464 if (IsWhole) CmdArgs.push_back("-no-whole-archive");
465
466 if (IsShared) {
467 addArchSpecificRPath(TC, Args, CmdArgs);
468 }
469}
470
471// Tries to use a file with the list of dynamic symbols that need to be exported
472// from the runtime library. Returns true if the file was found.
473static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
474 ArgStringList &CmdArgs,
475 StringRef Sanitizer) {
476 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
477 if (llvm::sys::fs::exists(SanRT + ".syms")) {
478 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
479 return true;
480 }
481 return false;
482}
483
484void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
485 ArgStringList &CmdArgs) {
486 // Force linking against the system libraries sanitizers depends on
487 // (see PR15823 why this is necessary).
488 CmdArgs.push_back("--no-as-needed");
489 // There's no libpthread or librt on RTEMS.
490 if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
491 CmdArgs.push_back("-lpthread");
492 CmdArgs.push_back("-lrt");
493 }
494 CmdArgs.push_back("-lm");
495 // There's no libdl on FreeBSD or RTEMS.
496 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
497 TC.getTriple().getOS() != llvm::Triple::RTEMS)
498 CmdArgs.push_back("-ldl");
499}
500
501static void
502collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
503 SmallVectorImpl<StringRef> &SharedRuntimes,
504 SmallVectorImpl<StringRef> &StaticRuntimes,
505 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
506 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
507 SmallVectorImpl<StringRef> &RequiredSymbols) {
508 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
509 // Collect shared runtimes.
510 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
511 SharedRuntimes.push_back("asan");
512 }
513 // The stats_client library is also statically linked into DSOs.
514 if (SanArgs.needsStatsRt())
515 StaticRuntimes.push_back("stats_client");
516
517 // Collect static runtimes.
518 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
519 // Don't link static runtimes into DSOs or if compiling for Android.
520 return;
521 }
522 if (SanArgs.needsAsanRt()) {
523 if (SanArgs.needsSharedAsanRt()) {
524 HelperStaticRuntimes.push_back("asan-preinit");
525 } else {
526 StaticRuntimes.push_back("asan");
527 if (SanArgs.linkCXXRuntimes())
528 StaticRuntimes.push_back("asan_cxx");
529 }
530 }
531 if (SanArgs.needsDfsanRt())
532 StaticRuntimes.push_back("dfsan");
533 if (SanArgs.needsLsanRt())
534 StaticRuntimes.push_back("lsan");
535 if (SanArgs.needsMsanRt()) {
536 StaticRuntimes.push_back("msan");
537 if (SanArgs.linkCXXRuntimes())
538 StaticRuntimes.push_back("msan_cxx");
539 }
540 if (SanArgs.needsTsanRt()) {
541 StaticRuntimes.push_back("tsan");
542 if (SanArgs.linkCXXRuntimes())
543 StaticRuntimes.push_back("tsan_cxx");
544 }
545 if (SanArgs.needsUbsanRt()) {
546 StaticRuntimes.push_back("ubsan_standalone");
547 if (SanArgs.linkCXXRuntimes())
548 StaticRuntimes.push_back("ubsan_standalone_cxx");
549 }
550 if (SanArgs.needsSafeStackRt()) {
551 NonWholeStaticRuntimes.push_back("safestack");
552 RequiredSymbols.push_back("__safestack_init");
553 }
554 if (SanArgs.needsCfiRt())
555 StaticRuntimes.push_back("cfi");
556 if (SanArgs.needsCfiDiagRt()) {
557 StaticRuntimes.push_back("cfi_diag");
558 if (SanArgs.linkCXXRuntimes())
559 StaticRuntimes.push_back("ubsan_standalone_cxx");
560 }
561 if (SanArgs.needsStatsRt()) {
562 NonWholeStaticRuntimes.push_back("stats");
563 RequiredSymbols.push_back("__sanitizer_stats_register");
564 }
565 if (SanArgs.needsEsanRt())
566 StaticRuntimes.push_back("esan");
567}
568
569// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
570// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
571bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
572 ArgStringList &CmdArgs) {
573 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
574 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
575 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
576 NonWholeStaticRuntimes, HelperStaticRuntimes,
577 RequiredSymbols);
578 for (auto RT : SharedRuntimes)
579 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
580 for (auto RT : HelperStaticRuntimes)
581 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
582 bool AddExportDynamic = false;
583 for (auto RT : StaticRuntimes) {
584 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
585 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
586 }
587 for (auto RT : NonWholeStaticRuntimes) {
588 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
589 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
590 }
591 for (auto S : RequiredSymbols) {
592 CmdArgs.push_back("-u");
593 CmdArgs.push_back(Args.MakeArgString(S));
594 }
595 // If there is a static runtime with no dynamic list, force all the symbols
596 // to be dynamic to be sure we export sanitizer interface functions.
597 if (AddExportDynamic)
598 CmdArgs.push_back("-export-dynamic");
599
600 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
601 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
602 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
603
604 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
605}
606
607bool tools::areOptimizationsEnabled(const ArgList &Args) {
608 // Find the last -O arg and see if it is non-zero.
609 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
610 return !A->getOption().matches(options::OPT_O0);
611 // Defaults to -O0.
612 return false;
613}
614
615const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
616 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
617 if (FinalOutput && Args.hasArg(options::OPT_c)) {
618 SmallString<128> T(FinalOutput->getValue());
619 llvm::sys::path::replace_extension(T, "dwo");
620 return Args.MakeArgString(T);
621 } else {
622 // Use the compilation dir.
623 SmallString<128> T(
624 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
625 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
626 llvm::sys::path::replace_extension(F, "dwo");
627 T += F;
628 return Args.MakeArgString(F);
629 }
630}
631
632void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
633 const JobAction &JA, const ArgList &Args,
634 const InputInfo &Output, const char *OutFile) {
635 ArgStringList ExtractArgs;
636 ExtractArgs.push_back("--extract-dwo");
637
638 ArgStringList StripArgs;
639 StripArgs.push_back("--strip-dwo");
640
641 // Grabbing the output of the earlier compile step.
642 StripArgs.push_back(Output.getFilename());
643 ExtractArgs.push_back(Output.getFilename());
644 ExtractArgs.push_back(OutFile);
645
646 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
647 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
648
649 // First extract the dwo sections.
650 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
651
652 // Then remove them from the original .o file.
653 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
654}
655
656// Claim options we don't want to warn if they are unused. We do this for
657// options that build systems might add but are unused when assembling or only
658// running the preprocessor for example.
659void tools::claimNoWarnArgs(const ArgList &Args) {
660 // Don't warn about unused -f(no-)?lto. This can happen when we're
661 // preprocessing, precompiling or assembling.
662 Args.ClaimAllArgs(options::OPT_flto_EQ);
663 Args.ClaimAllArgs(options::OPT_flto);
664 Args.ClaimAllArgs(options::OPT_fno_lto);
665}
666
667Arg *tools::getLastProfileUseArg(const ArgList &Args) {
668 auto *ProfileUseArg = Args.getLastArg(
669 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
670 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
671 options::OPT_fno_profile_instr_use);
672
673 if (ProfileUseArg &&
674 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
675 ProfileUseArg = nullptr;
676
677 return ProfileUseArg;
678}
679
680/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
681/// smooshes them together with platform defaults, to decide whether
682/// this compile should be using PIC mode or not. Returns a tuple of
683/// (RelocationModel, PICLevel, IsPIE).
684std::tuple<llvm::Reloc::Model, unsigned, bool>
685tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
686 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
687 const llvm::Triple &Triple = ToolChain.getTriple();
688
689 bool PIE = ToolChain.isPIEDefault();
690 bool PIC = PIE || ToolChain.isPICDefault();
691 // The Darwin/MachO default to use PIC does not apply when using -static.
692 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
693 PIE = PIC = false;
694 bool IsPICLevelTwo = PIC;
695
696 bool KernelOrKext =
697 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
698
699 // Android-specific defaults for PIC/PIE
700 if (Triple.isAndroid()) {
701 switch (Triple.getArch()) {
702 case llvm::Triple::arm:
703 case llvm::Triple::armeb:
704 case llvm::Triple::thumb:
705 case llvm::Triple::thumbeb:
706 case llvm::Triple::aarch64:
707 case llvm::Triple::mips:
708 case llvm::Triple::mipsel:
709 case llvm::Triple::mips64:
710 case llvm::Triple::mips64el:
711 PIC = true; // "-fpic"
712 break;
713
714 case llvm::Triple::x86:
715 case llvm::Triple::x86_64:
716 PIC = true; // "-fPIC"
717 IsPICLevelTwo = true;
718 break;
719
720 default:
721 break;
722 }
723 }
724
725 // OpenBSD-specific defaults for PIE
726 if (Triple.getOS() == llvm::Triple::OpenBSD) {
727 switch (ToolChain.getArch()) {
728 case llvm::Triple::mips64:
729 case llvm::Triple::mips64el:
730 case llvm::Triple::sparcel:
731 case llvm::Triple::x86:
732 case llvm::Triple::x86_64:
733 IsPICLevelTwo = false; // "-fpie"
734 break;
735
736 case llvm::Triple::ppc:
737 case llvm::Triple::sparc:
738 case llvm::Triple::sparcv9:
739 IsPICLevelTwo = true; // "-fPIE"
740 break;
741
742 default:
743 break;
744 }
745 }
746
747 // The last argument relating to either PIC or PIE wins, and no
748 // other argument is used. If the last argument is any flavor of the
749 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
750 // option implicitly enables PIC at the same level.
751 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
752 options::OPT_fpic, options::OPT_fno_pic,
753 options::OPT_fPIE, options::OPT_fno_PIE,
754 options::OPT_fpie, options::OPT_fno_pie);
755 if (Triple.isOSWindows() && LastPICArg &&
756 LastPICArg ==
757 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
758 options::OPT_fPIE, options::OPT_fpie)) {
759 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
760 << LastPICArg->getSpelling() << Triple.str();
761 if (Triple.getArch() == llvm::Triple::x86_64)
762 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
763 return std::make_tuple(llvm::Reloc::Static, 0U, false);
764 }
765
766 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
767 // is forced, then neither PIC nor PIE flags will have no effect.
768 if (!ToolChain.isPICDefaultForced()) {
769 if (LastPICArg) {
770 Option O = LastPICArg->getOption();
771 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
772 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
773 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
774 PIC =
775 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
776 IsPICLevelTwo =
777 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
778 } else {
779 PIE = PIC = false;
780 if (EffectiveTriple.isPS4CPU()) {
781 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
782 StringRef Model = ModelArg ? ModelArg->getValue() : "";
783 if (Model != "kernel") {
784 PIC = true;
785 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
786 << LastPICArg->getSpelling();
787 }
788 }
789 }
790 }
791 }
792
793 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
794 // PIC level would've been set to level 1, force it back to level 2 PIC
795 // instead.
796 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
797 IsPICLevelTwo |= ToolChain.isPICDefault();
798
799 // This kernel flags are a trump-card: they will disable PIC/PIE
800 // generation, independent of the argument order.
801 if (KernelOrKext &&
802 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
803 !EffectiveTriple.isWatchOS()))
804 PIC = PIE = false;
805
806 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
807 // This is a very special mode. It trumps the other modes, almost no one
808 // uses it, and it isn't even valid on any OS but Darwin.
809 if (!Triple.isOSDarwin())
810 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
811 << A->getSpelling() << Triple.str();
812
813 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
814
815 // Only a forced PIC mode can cause the actual compile to have PIC defines
816 // etc., no flags are sufficient. This behavior was selected to closely
817 // match that of llvm-gcc and Apple GCC before that.
818 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
819
820 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
821 }
822
823 bool EmbeddedPISupported;
824 switch (Triple.getArch()) {
825 case llvm::Triple::arm:
826 case llvm::Triple::armeb:
827 case llvm::Triple::thumb:
828 case llvm::Triple::thumbeb:
829 EmbeddedPISupported = true;
830 break;
831 default:
832 EmbeddedPISupported = false;
833 break;
834 }
835
836 bool ROPI = false, RWPI = false;
837 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
838 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
839 if (!EmbeddedPISupported)
840 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
841 << LastROPIArg->getSpelling() << Triple.str();
842 ROPI = true;
843 }
844 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
845 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
846 if (!EmbeddedPISupported)
847 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
848 << LastRWPIArg->getSpelling() << Triple.str();
849 RWPI = true;
850 }
851
852 // ROPI and RWPI are not comaptible with PIC or PIE.
853 if ((ROPI || RWPI) && (PIC || PIE))
854 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
855
856 // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
857 // used.
858 if ((Triple.getArch() == llvm::Triple::mips64 ||
859 Triple.getArch() == llvm::Triple::mips64el) &&
860 Args.hasArg(options::OPT_mno_abicalls))
861 return std::make_tuple(llvm::Reloc::Static, 0U, false);
862
863 if (PIC)
864 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
865
866 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
867 if (ROPI && RWPI)
868 RelocM = llvm::Reloc::ROPI_RWPI;
869 else if (ROPI)
870 RelocM = llvm::Reloc::ROPI;
871 else if (RWPI)
872 RelocM = llvm::Reloc::RWPI;
873
874 return std::make_tuple(RelocM, 0U, false);
875}
876
877void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
878 ArgStringList &CmdArgs) {
879 llvm::Reloc::Model RelocationModel;
880 unsigned PICLevel;
881 bool IsPIE;
882 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
883
884 if (RelocationModel != llvm::Reloc::Static)
885 CmdArgs.push_back("-KPIC");
886}
887
888/// \brief Determine whether Objective-C automated reference counting is
889/// enabled.
890bool tools::isObjCAutoRefCount(const ArgList &Args) {
891 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
892}
893
894static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
895 ArgStringList &CmdArgs, const ArgList &Args) {
896 bool isAndroid = Triple.isAndroid();
897 bool isCygMing = Triple.isOSCygMing();
898 bool IsIAMCU = Triple.isOSIAMCU();
899 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
900 Args.hasArg(options::OPT_static);
901 if (!D.CCCIsCXX())
902 CmdArgs.push_back("-lgcc");
903
904 if (StaticLibgcc || isAndroid) {
905 if (D.CCCIsCXX())
906 CmdArgs.push_back("-lgcc");
907 } else {
908 if (!D.CCCIsCXX() && !isCygMing)
909 CmdArgs.push_back("--as-needed");
910 CmdArgs.push_back("-lgcc_s");
911 if (!D.CCCIsCXX() && !isCygMing)
912 CmdArgs.push_back("--no-as-needed");
913 }
914
915 if (StaticLibgcc && !isAndroid && !IsIAMCU)
916 CmdArgs.push_back("-lgcc_eh");
917 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
918 CmdArgs.push_back("-lgcc");
919
920 // According to Android ABI, we have to link with libdl if we are
921 // linking with non-static libgcc.
922 //
923 // NOTE: This fixes a link error on Android MIPS as well. The non-static
924 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
925 if (isAndroid && !StaticLibgcc)
926 CmdArgs.push_back("-ldl");
927}
928
929void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
930 ArgStringList &CmdArgs, const ArgList &Args) {
931 // Make use of compiler-rt if --rtlib option is used
932 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
933
934 switch (RLT) {
935 case ToolChain::RLT_CompilerRT:
936 switch (TC.getTriple().getOS()) {
937 default:
938 llvm_unreachable("unsupported OS");
939 case llvm::Triple::Win32:
940 case llvm::Triple::Linux:
941 case llvm::Triple::Fuchsia:
942 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
943 break;
944 }
945 break;
946 case ToolChain::RLT_Libgcc:
947 // Make sure libgcc is not used under MSVC environment by default
948 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
949 // Issue error diagnostic if libgcc is explicitly specified
950 // through command line as --rtlib option argument.
951 if (Args.hasArg(options::OPT_rtlib_EQ)) {
952 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
953 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
954 }
955 } else
956 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
957 break;
958 }
959}