blob: be09bc19fda2912caaa16b90666bdd3a9e34b88c [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"
David L. Jonesf561aba2017-03-08 01:02:16 +000011#include "Arch/AArch64.h"
12#include "Arch/ARM.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
15#include "Arch/SystemZ.h"
16#include "Arch/X86.h"
Florian Hahn2e081d12018-04-20 12:50:10 +000017#include "Hexagon.h"
18#include "InputInfo.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000019#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"
Dean Michael Berris62440372018-04-06 03:53:04 +000034#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000035#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/ADT/StringSwitch.h"
39#include "llvm/ADT/Twine.h"
40#include "llvm/Option/Arg.h"
41#include "llvm/Option/ArgList.h"
42#include "llvm/Option/Option.h"
43#include "llvm/Support/CodeGen.h"
44#include "llvm/Support/Compression.h"
Florian Hahn2e081d12018-04-20 12:50:10 +000045#include "llvm/Support/Debug.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000046#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Host.h"
49#include "llvm/Support/Path.h"
50#include "llvm/Support/Process.h"
51#include "llvm/Support/Program.h"
52#include "llvm/Support/ScopedPrinter.h"
53#include "llvm/Support/TargetParser.h"
54#include "llvm/Support/YAMLParser.h"
55
56using namespace clang::driver;
57using namespace clang::driver::tools;
58using namespace clang;
59using namespace llvm::opt;
60
61void tools::addPathIfExists(const Driver &D, const Twine &Path,
62 ToolChain::path_list &Paths) {
63 if (D.getVFS().exists(Path))
64 Paths.push_back(Path.str());
65}
66
67void tools::handleTargetFeaturesGroup(const ArgList &Args,
68 std::vector<StringRef> &Features,
69 OptSpecifier Group) {
70 for (const Arg *A : Args.filtered(Group)) {
71 StringRef Name = A->getOption().getName();
72 A->claim();
73
74 // Skip over "-m".
75 assert(Name.startswith("m") && "Invalid feature name.");
76 Name = Name.substr(1);
77
78 bool IsNegative = Name.startswith("no-");
79 if (IsNegative)
80 Name = Name.substr(3);
81 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
82 }
83}
84
85void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
86 const char *ArgName, const char *EnvVar) {
87 const char *DirList = ::getenv(EnvVar);
88 bool CombinedArg = false;
89
90 if (!DirList)
91 return; // Nothing to do.
92
93 StringRef Name(ArgName);
94 if (Name.equals("-I") || Name.equals("-L"))
95 CombinedArg = true;
96
97 StringRef Dirs(DirList);
98 if (Dirs.empty()) // Empty string should not add '.'.
99 return;
100
101 StringRef::size_type Delim;
102 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
103 if (Delim == 0) { // Leading colon.
104 if (CombinedArg) {
105 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
106 } else {
107 CmdArgs.push_back(ArgName);
108 CmdArgs.push_back(".");
109 }
110 } else {
111 if (CombinedArg) {
112 CmdArgs.push_back(
113 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
114 } else {
115 CmdArgs.push_back(ArgName);
116 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
117 }
118 }
119 Dirs = Dirs.substr(Delim + 1);
120 }
121
122 if (Dirs.empty()) { // Trailing colon.
123 if (CombinedArg) {
124 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
125 } else {
126 CmdArgs.push_back(ArgName);
127 CmdArgs.push_back(".");
128 }
129 } else { // Add the last path.
130 if (CombinedArg) {
131 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
132 } else {
133 CmdArgs.push_back(ArgName);
134 CmdArgs.push_back(Args.MakeArgString(Dirs));
135 }
136 }
137}
138
139void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
140 const ArgList &Args, ArgStringList &CmdArgs,
141 const JobAction &JA) {
142 const Driver &D = TC.getDriver();
143
144 // Add extra linker input arguments which are not treated as inputs
145 // (constructed via -Xarch_).
146 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
147
148 for (const auto &II : Inputs) {
149 // If the current tool chain refers to an OpenMP offloading host, we should
150 // ignore inputs that refer to OpenMP offloading devices - they will be
151 // embedded according to a proper linker script.
152 if (auto *IA = II.getAction())
153 if (JA.isHostOffloading(Action::OFK_OpenMP) &&
154 IA->isDeviceOffloading(Action::OFK_OpenMP))
155 continue;
156
157 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
158 // Don't try to pass LLVM inputs unless we have native support.
159 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
160
161 // Add filenames immediately.
162 if (II.isFilename()) {
163 CmdArgs.push_back(II.getFilename());
164 continue;
165 }
166
167 // Otherwise, this is a linker input argument.
168 const Arg &A = II.getInputArg();
169
170 // Handle reserved library options.
171 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
172 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
173 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
174 TC.AddCCKextLibArgs(Args, CmdArgs);
175 else if (A.getOption().matches(options::OPT_z)) {
176 // Pass -z prefix for gcc linker compatibility.
177 A.claim();
178 A.render(Args, CmdArgs);
179 } else {
180 A.renderAsInput(Args, CmdArgs);
181 }
182 }
183
184 // LIBRARY_PATH - included following the user specified library paths.
185 // and only supported on native toolchains.
186 if (!TC.isCrossCompiling()) {
187 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
188 }
189}
190
191void tools::AddTargetFeature(const ArgList &Args,
192 std::vector<StringRef> &Features,
193 OptSpecifier OnOpt, OptSpecifier OffOpt,
194 StringRef FeatureName) {
195 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
196 if (A->getOption().matches(OnOpt))
197 Features.push_back(Args.MakeArgString("+" + FeatureName));
198 else
199 Features.push_back(Args.MakeArgString("-" + FeatureName));
200 }
201}
202
203/// Get the (LLVM) name of the R600 gpu we are targeting.
204static std::string getR600TargetGPU(const ArgList &Args) {
205 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
206 const char *GPUName = A->getValue();
207 return llvm::StringSwitch<const char *>(GPUName)
208 .Cases("rv630", "rv635", "r600")
209 .Cases("rv610", "rv620", "rs780", "rs880")
210 .Case("rv740", "rv770")
211 .Case("palm", "cedar")
212 .Cases("sumo", "sumo2", "sumo")
213 .Case("hemlock", "cypress")
214 .Case("aruba", "cayman")
215 .Default(GPUName);
216 }
217 return "";
218}
219
Nikolai Bozhenov35d3c352017-06-27 09:48:24 +0000220static std::string getNios2TargetCPU(const ArgList &Args) {
221 Arg *A = Args.getLastArg(options::OPT_mcpu_EQ);
222 if (!A)
223 A = Args.getLastArg(options::OPT_march_EQ);
224
225 if (!A)
226 return "";
227
228 const char *name = A->getValue();
229 return llvm::StringSwitch<const char *>(name)
230 .Case("r1", "nios2r1")
231 .Case("r2", "nios2r2")
232 .Default(name);
233}
234
David L. Jonesf561aba2017-03-08 01:02:16 +0000235static std::string getLanaiTargetCPU(const ArgList &Args) {
236 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
237 return A->getValue();
238 }
239 return "";
240}
241
242/// Get the (LLVM) name of the WebAssembly cpu we are targeting.
243static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
244 // If we have -mcpu=, use that.
245 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
246 StringRef CPU = A->getValue();
247
248#ifdef __wasm__
249 // Handle "native" by examining the host. "native" isn't meaningful when
250 // cross compiling, so only support this when the host is also WebAssembly.
251 if (CPU == "native")
252 return llvm::sys::getHostCPUName();
253#endif
254
255 return CPU;
256 }
257
258 return "generic";
259}
260
261std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
262 bool FromAs) {
263 Arg *A;
264
265 switch (T.getArch()) {
266 default:
267 return "";
268
269 case llvm::Triple::aarch64:
270 case llvm::Triple::aarch64_be:
271 return aarch64::getAArch64TargetCPU(Args, A);
272
273 case llvm::Triple::arm:
274 case llvm::Triple::armeb:
275 case llvm::Triple::thumb:
276 case llvm::Triple::thumbeb: {
277 StringRef MArch, MCPU;
278 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
279 return arm::getARMTargetCPU(MCPU, MArch, T);
280 }
Leslie Zhaiff041092017-04-20 04:23:24 +0000281
282 case llvm::Triple::avr:
283 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
284 return A->getValue();
285 return "";
286
Nikolai Bozhenov35d3c352017-06-27 09:48:24 +0000287 case llvm::Triple::nios2: {
288 return getNios2TargetCPU(Args);
289 }
290
David L. Jonesf561aba2017-03-08 01:02:16 +0000291 case llvm::Triple::mips:
292 case llvm::Triple::mipsel:
293 case llvm::Triple::mips64:
294 case llvm::Triple::mips64el: {
295 StringRef CPUName;
296 StringRef ABIName;
297 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
298 return CPUName;
299 }
300
301 case llvm::Triple::nvptx:
302 case llvm::Triple::nvptx64:
303 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
304 return A->getValue();
305 return "";
306
307 case llvm::Triple::ppc:
308 case llvm::Triple::ppc64:
309 case llvm::Triple::ppc64le: {
310 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
311 // LLVM may default to generating code for the native CPU,
312 // but, like gcc, we default to a more generic option for
313 // each architecture. (except on Darwin)
314 if (TargetCPUName.empty() && !T.isOSDarwin()) {
315 if (T.getArch() == llvm::Triple::ppc64)
316 TargetCPUName = "ppc64";
317 else if (T.getArch() == llvm::Triple::ppc64le)
318 TargetCPUName = "ppc64le";
319 else
320 TargetCPUName = "ppc";
321 }
322 return TargetCPUName;
323 }
324
Yonghong Songc4ea1012017-08-23 04:26:17 +0000325 case llvm::Triple::bpfel:
326 case llvm::Triple::bpfeb:
David L. Jonesf561aba2017-03-08 01:02:16 +0000327 case llvm::Triple::sparc:
328 case llvm::Triple::sparcel:
329 case llvm::Triple::sparcv9:
330 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
331 return A->getValue();
332 return "";
333
334 case llvm::Triple::x86:
335 case llvm::Triple::x86_64:
336 return x86::getX86TargetCPU(Args, T);
337
338 case llvm::Triple::hexagon:
339 return "hexagon" +
340 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
341
342 case llvm::Triple::lanai:
343 return getLanaiTargetCPU(Args);
344
345 case llvm::Triple::systemz:
346 return systemz::getSystemZTargetCPU(Args);
347
348 case llvm::Triple::r600:
349 case llvm::Triple::amdgcn:
350 return getR600TargetGPU(Args);
351
352 case llvm::Triple::wasm32:
353 case llvm::Triple::wasm64:
354 return getWebAssemblyTargetCPU(Args);
355 }
356}
357
358unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
359 unsigned Parallelism = 0;
360 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
361 if (LtoJobsArg &&
362 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
363 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
364 << LtoJobsArg->getValue();
365 return Parallelism;
366}
367
Sam Clegg7892ae42018-01-31 18:55:22 +0000368// CloudABI uses -ffunction-sections and -fdata-sections by default.
David L. Jonesf561aba2017-03-08 01:02:16 +0000369bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
Sam Clegg7892ae42018-01-31 18:55:22 +0000370 return Triple.getOS() == llvm::Triple::CloudABI;
David L. Jonesf561aba2017-03-08 01:02:16 +0000371}
372
373void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
Florian Hahn2e081d12018-04-20 12:50:10 +0000374 ArgStringList &CmdArgs, const InputInfo &Output,
375 const InputInfo &Input, bool IsThinLTO) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000376 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
377 // as gold requires -plugin to come before any -plugin-opt that -Wl might
378 // forward.
379 CmdArgs.push_back("-plugin");
Dan Albertc3a11d52017-08-22 21:05:01 +0000380
Nico Weber1865df42018-04-27 19:11:14 +0000381#if defined(_WIN32)
Dan Albertc3a11d52017-08-22 21:05:01 +0000382 const char *Suffix = ".dll";
383#elif defined(__APPLE__)
384 const char *Suffix = ".dylib";
385#else
386 const char *Suffix = ".so";
387#endif
388
389 SmallString<1024> Plugin;
390 llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
391 "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
392 Suffix,
393 Plugin);
David L. Jonesf561aba2017-03-08 01:02:16 +0000394 CmdArgs.push_back(Args.MakeArgString(Plugin));
395
396 // Try to pass driver level flags relevant to LTO code generation down to
397 // the plugin.
398
399 // Handle flags for selecting CPU variants.
400 std::string CPU = getCPUName(Args, ToolChain.getTriple());
401 if (!CPU.empty())
402 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
403
404 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
405 StringRef OOpt;
406 if (A->getOption().matches(options::OPT_O4) ||
407 A->getOption().matches(options::OPT_Ofast))
408 OOpt = "3";
409 else if (A->getOption().matches(options::OPT_O))
410 OOpt = A->getValue();
411 else if (A->getOption().matches(options::OPT_O0))
412 OOpt = "0";
413 if (!OOpt.empty())
414 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
415 }
416
417 if (IsThinLTO)
418 CmdArgs.push_back("-plugin-opt=thinlto");
419
Florian Hahn2e081d12018-04-20 12:50:10 +0000420 if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver()))
Benjamin Kramer3a13ed62017-12-28 16:58:54 +0000421 CmdArgs.push_back(
422 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
David L. Jonesf561aba2017-03-08 01:02:16 +0000423
424 // If an explicit debugger tuning argument appeared, pass it along.
425 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
426 options::OPT_ggdbN_Group)) {
427 if (A->getOption().matches(options::OPT_glldb))
428 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
429 else if (A->getOption().matches(options::OPT_gsce))
430 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
431 else
432 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
433 }
434
435 bool UseSeparateSections =
436 isUseSeparateSections(ToolChain.getEffectiveTriple());
437
438 if (Args.hasFlag(options::OPT_ffunction_sections,
439 options::OPT_fno_function_sections, UseSeparateSections)) {
440 CmdArgs.push_back("-plugin-opt=-function-sections");
441 }
442
443 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
444 UseSeparateSections)) {
445 CmdArgs.push_back("-plugin-opt=-data-sections");
446 }
447
Dehao Chenea4b78f2017-03-21 21:40:53 +0000448 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000449 StringRef FName = A->getValue();
450 if (!llvm::sys::fs::exists(FName))
Florian Hahn2e081d12018-04-20 12:50:10 +0000451 ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName;
David L. Jonesf561aba2017-03-08 01:02:16 +0000452 else
453 CmdArgs.push_back(
454 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
455 }
Sean Fertile03e77c62017-10-05 01:50:48 +0000456
457 // Need this flag to turn on new pass manager via Gold plugin.
458 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
459 options::OPT_fno_experimental_new_pass_manager,
Petr Hosekc3aa97a2018-04-06 00:53:00 +0000460 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
Sean Fertile03e77c62017-10-05 01:50:48 +0000461 CmdArgs.push_back("-plugin-opt=new-pass-manager");
462 }
463
Florian Hahn2e081d12018-04-20 12:50:10 +0000464 // Setup statistics file output.
465 SmallString<128> StatsFile =
466 getStatsFileName(Args, Output, Input, ToolChain.getDriver());
467 if (!StatsFile.empty())
468 CmdArgs.push_back(
469 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +0000470}
471
472void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
473 ArgStringList &CmdArgs) {
Petr Hosekbae48562018-04-02 23:36:14 +0000474 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
475 options::OPT_fno_rtlib_add_rpath, false))
476 return;
477
David L. Jonesf561aba2017-03-08 01:02:16 +0000478 std::string CandidateRPath = TC.getArchSpecificLibPath();
479 if (TC.getVFS().exists(CandidateRPath)) {
480 CmdArgs.push_back("-rpath");
481 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
482 }
483}
484
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000485bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
486 const ArgList &Args, bool IsOffloadingHost,
487 bool GompNeedsRT) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000488 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
489 options::OPT_fno_openmp, false))
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000490 return false;
David L. Jonesf561aba2017-03-08 01:02:16 +0000491
492 switch (TC.getDriver().getOpenMPRuntime(Args)) {
493 case Driver::OMPRT_OMP:
494 CmdArgs.push_back("-lomp");
495 break;
496 case Driver::OMPRT_GOMP:
497 CmdArgs.push_back("-lgomp");
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000498
499 if (GompNeedsRT)
500 CmdArgs.push_back("-lrt");
David L. Jonesf561aba2017-03-08 01:02:16 +0000501 break;
502 case Driver::OMPRT_IOMP5:
503 CmdArgs.push_back("-liomp5");
504 break;
505 case Driver::OMPRT_Unknown:
506 // Already diagnosed.
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000507 return false;
David L. Jonesf561aba2017-03-08 01:02:16 +0000508 }
509
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000510 if (IsOffloadingHost)
511 CmdArgs.push_back("-lomptarget");
512
David L. Jonesf561aba2017-03-08 01:02:16 +0000513 addArchSpecificRPath(TC, Args, CmdArgs);
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000514
515 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +0000516}
517
518static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
519 ArgStringList &CmdArgs, StringRef Sanitizer,
520 bool IsShared, bool IsWhole) {
521 // Wrap any static runtimes that must be forced into executable in
522 // whole-archive.
Alex Shlyapnikov85da0f62018-02-05 23:59:13 +0000523 if (IsWhole) CmdArgs.push_back("--whole-archive");
David L. Jonesf561aba2017-03-08 01:02:16 +0000524 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
Alex Shlyapnikov85da0f62018-02-05 23:59:13 +0000525 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
David L. Jonesf561aba2017-03-08 01:02:16 +0000526
527 if (IsShared) {
528 addArchSpecificRPath(TC, Args, CmdArgs);
529 }
530}
531
532// Tries to use a file with the list of dynamic symbols that need to be exported
533// from the runtime library. Returns true if the file was found.
534static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
535 ArgStringList &CmdArgs,
536 StringRef Sanitizer) {
Alex Shlyapnikov85da0f62018-02-05 23:59:13 +0000537 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
538 // the option, so don't try to pass it.
539 if (TC.getTriple().getOS() == llvm::Triple::Solaris)
540 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +0000541 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
542 if (llvm::sys::fs::exists(SanRT + ".syms")) {
543 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
544 return true;
545 }
546 return false;
547}
548
549void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
550 ArgStringList &CmdArgs) {
551 // Force linking against the system libraries sanitizers depends on
552 // (see PR15823 why this is necessary).
553 CmdArgs.push_back("--no-as-needed");
554 // There's no libpthread or librt on RTEMS.
555 if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
556 CmdArgs.push_back("-lpthread");
Kamil Rytarowski150a3772018-03-03 11:47:27 +0000557 if (TC.getTriple().getOS() != llvm::Triple::OpenBSD)
558 CmdArgs.push_back("-lrt");
David L. Jonesf561aba2017-03-08 01:02:16 +0000559 }
560 CmdArgs.push_back("-lm");
Kamil Rytarowskibb9a8522017-12-08 17:38:25 +0000561 // There's no libdl on all OSes.
David L. Jonesf561aba2017-03-08 01:02:16 +0000562 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
Kamil Rytarowski2eef4752017-07-04 19:55:56 +0000563 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
Kamil Rytarowski150a3772018-03-03 11:47:27 +0000564 TC.getTriple().getOS() != llvm::Triple::OpenBSD &&
David L. Jonesf561aba2017-03-08 01:02:16 +0000565 TC.getTriple().getOS() != llvm::Triple::RTEMS)
566 CmdArgs.push_back("-ldl");
Kamil Rytarowskie21475e2017-12-19 07:10:33 +0000567 // Required for backtrace on some OSes
Kamil Rytarowskia7ef6a62018-01-24 23:08:49 +0000568 if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
569 TC.getTriple().getOS() == llvm::Triple::FreeBSD)
Kamil Rytarowskie21475e2017-12-19 07:10:33 +0000570 CmdArgs.push_back("-lexecinfo");
David L. Jonesf561aba2017-03-08 01:02:16 +0000571}
572
573static void
574collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
575 SmallVectorImpl<StringRef> &SharedRuntimes,
576 SmallVectorImpl<StringRef> &StaticRuntimes,
577 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
578 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
579 SmallVectorImpl<StringRef> &RequiredSymbols) {
580 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
581 // Collect shared runtimes.
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000582 if (SanArgs.needsSharedRt()) {
583 if (SanArgs.needsAsanRt()) {
584 SharedRuntimes.push_back("asan");
585 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
586 HelperStaticRuntimes.push_back("asan-preinit");
587 }
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000588 if (SanArgs.needsUbsanRt()) {
589 if (SanArgs.requiresMinimalRuntime()) {
590 SharedRuntimes.push_back("ubsan_minimal");
591 } else {
592 SharedRuntimes.push_back("ubsan_standalone");
593 }
594 }
Kostya Kortchinsky8acdc982017-11-03 17:04:13 +0000595 if (SanArgs.needsScudoRt())
596 SharedRuntimes.push_back("scudo");
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000597 if (SanArgs.needsHwasanRt())
598 SharedRuntimes.push_back("hwasan");
David L. Jonesf561aba2017-03-08 01:02:16 +0000599 }
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000600
David L. Jonesf561aba2017-03-08 01:02:16 +0000601 // The stats_client library is also statically linked into DSOs.
602 if (SanArgs.needsStatsRt())
603 StaticRuntimes.push_back("stats_client");
604
605 // Collect static runtimes.
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000606 if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
607 // Don't link static runtimes into DSOs or if -shared-libasan.
David L. Jonesf561aba2017-03-08 01:02:16 +0000608 return;
609 }
610 if (SanArgs.needsAsanRt()) {
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000611 StaticRuntimes.push_back("asan");
612 if (SanArgs.linkCXXRuntimes())
613 StaticRuntimes.push_back("asan_cxx");
David L. Jonesf561aba2017-03-08 01:02:16 +0000614 }
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000615
616 if (SanArgs.needsHwasanRt()) {
617 StaticRuntimes.push_back("hwasan");
618 if (SanArgs.linkCXXRuntimes())
619 StaticRuntimes.push_back("hwasan_cxx");
620 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000621 if (SanArgs.needsDfsanRt())
622 StaticRuntimes.push_back("dfsan");
623 if (SanArgs.needsLsanRt())
624 StaticRuntimes.push_back("lsan");
625 if (SanArgs.needsMsanRt()) {
626 StaticRuntimes.push_back("msan");
627 if (SanArgs.linkCXXRuntimes())
628 StaticRuntimes.push_back("msan_cxx");
629 }
630 if (SanArgs.needsTsanRt()) {
631 StaticRuntimes.push_back("tsan");
632 if (SanArgs.linkCXXRuntimes())
633 StaticRuntimes.push_back("tsan_cxx");
634 }
635 if (SanArgs.needsUbsanRt()) {
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000636 if (SanArgs.requiresMinimalRuntime()) {
637 StaticRuntimes.push_back("ubsan_minimal");
638 } else {
639 StaticRuntimes.push_back("ubsan_standalone");
640 if (SanArgs.linkCXXRuntimes())
641 StaticRuntimes.push_back("ubsan_standalone_cxx");
642 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000643 }
644 if (SanArgs.needsSafeStackRt()) {
645 NonWholeStaticRuntimes.push_back("safestack");
646 RequiredSymbols.push_back("__safestack_init");
647 }
648 if (SanArgs.needsCfiRt())
649 StaticRuntimes.push_back("cfi");
650 if (SanArgs.needsCfiDiagRt()) {
651 StaticRuntimes.push_back("cfi_diag");
652 if (SanArgs.linkCXXRuntimes())
653 StaticRuntimes.push_back("ubsan_standalone_cxx");
654 }
655 if (SanArgs.needsStatsRt()) {
656 NonWholeStaticRuntimes.push_back("stats");
657 RequiredSymbols.push_back("__sanitizer_stats_register");
658 }
659 if (SanArgs.needsEsanRt())
660 StaticRuntimes.push_back("esan");
Kostya Kortchinsky8acdc982017-11-03 17:04:13 +0000661 if (SanArgs.needsScudoRt()) {
662 StaticRuntimes.push_back("scudo");
663 if (SanArgs.linkCXXRuntimes())
664 StaticRuntimes.push_back("scudo_cxx");
665 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000666}
667
668// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
669// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
670bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
671 ArgStringList &CmdArgs) {
672 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
673 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
674 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
675 NonWholeStaticRuntimes, HelperStaticRuntimes,
676 RequiredSymbols);
George Karpenkov9f6f74c2017-08-21 23:25:19 +0000677
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000678 // Inject libfuzzer dependencies.
George Karpenkov2363fdd2017-06-29 19:52:33 +0000679 if (TC.getSanitizerArgs().needsFuzzer()
680 && !Args.hasArg(options::OPT_shared)) {
George Karpenkov9f6f74c2017-08-21 23:25:19 +0000681
682 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
683 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
684 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000685 }
686
David L. Jonesf561aba2017-03-08 01:02:16 +0000687 for (auto RT : SharedRuntimes)
688 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
689 for (auto RT : HelperStaticRuntimes)
690 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
691 bool AddExportDynamic = false;
692 for (auto RT : StaticRuntimes) {
693 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
694 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
695 }
696 for (auto RT : NonWholeStaticRuntimes) {
697 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
698 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
699 }
700 for (auto S : RequiredSymbols) {
701 CmdArgs.push_back("-u");
702 CmdArgs.push_back(Args.MakeArgString(S));
703 }
704 // If there is a static runtime with no dynamic list, force all the symbols
705 // to be dynamic to be sure we export sanitizer interface functions.
706 if (AddExportDynamic)
Alex Shlyapnikov85da0f62018-02-05 23:59:13 +0000707 CmdArgs.push_back("--export-dynamic");
David L. Jonesf561aba2017-03-08 01:02:16 +0000708
709 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
710 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
711 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
712
713 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
714}
715
Dean Michael Berris62440372018-04-06 03:53:04 +0000716bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
717 if (Args.hasArg(options::OPT_shared))
718 return false;
719
720 if (TC.getXRayArgs().needsXRayRt()) {
721 CmdArgs.push_back("-whole-archive");
722 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
Dean Michael Berris826e6662018-04-11 01:28:25 +0000723 for (const auto &Mode : TC.getXRayArgs().modeList())
724 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode, false));
Dean Michael Berris62440372018-04-06 03:53:04 +0000725 CmdArgs.push_back("-no-whole-archive");
726 return true;
727 }
728
729 return false;
730}
731
732void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
733 CmdArgs.push_back("--no-as-needed");
734 CmdArgs.push_back("-lpthread");
735 if (TC.getTriple().getOS() != llvm::Triple::OpenBSD)
736 CmdArgs.push_back("-lrt");
737 CmdArgs.push_back("-lm");
738
739 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
740 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
741 TC.getTriple().getOS() != llvm::Triple::OpenBSD)
742 CmdArgs.push_back("-ldl");
743}
744
David L. Jonesf561aba2017-03-08 01:02:16 +0000745bool tools::areOptimizationsEnabled(const ArgList &Args) {
746 // Find the last -O arg and see if it is non-zero.
747 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
748 return !A->getOption().matches(options::OPT_O0);
749 // Defaults to -O0.
750 return false;
751}
752
753const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
754 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
755 if (FinalOutput && Args.hasArg(options::OPT_c)) {
756 SmallString<128> T(FinalOutput->getValue());
757 llvm::sys::path::replace_extension(T, "dwo");
758 return Args.MakeArgString(T);
759 } else {
760 // Use the compilation dir.
761 SmallString<128> T(
762 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
763 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
764 llvm::sys::path::replace_extension(F, "dwo");
765 T += F;
766 return Args.MakeArgString(F);
767 }
768}
769
770void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
771 const JobAction &JA, const ArgList &Args,
772 const InputInfo &Output, const char *OutFile) {
773 ArgStringList ExtractArgs;
774 ExtractArgs.push_back("--extract-dwo");
775
776 ArgStringList StripArgs;
777 StripArgs.push_back("--strip-dwo");
778
779 // Grabbing the output of the earlier compile step.
780 StripArgs.push_back(Output.getFilename());
781 ExtractArgs.push_back(Output.getFilename());
782 ExtractArgs.push_back(OutFile);
783
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000784 const char *Exec =
785 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
David L. Jonesf561aba2017-03-08 01:02:16 +0000786 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
787
788 // First extract the dwo sections.
789 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
790
791 // Then remove them from the original .o file.
792 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
793}
794
795// Claim options we don't want to warn if they are unused. We do this for
796// options that build systems might add but are unused when assembling or only
797// running the preprocessor for example.
798void tools::claimNoWarnArgs(const ArgList &Args) {
799 // Don't warn about unused -f(no-)?lto. This can happen when we're
800 // preprocessing, precompiling or assembling.
801 Args.ClaimAllArgs(options::OPT_flto_EQ);
802 Args.ClaimAllArgs(options::OPT_flto);
803 Args.ClaimAllArgs(options::OPT_fno_lto);
804}
805
806Arg *tools::getLastProfileUseArg(const ArgList &Args) {
807 auto *ProfileUseArg = Args.getLastArg(
808 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
809 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
810 options::OPT_fno_profile_instr_use);
811
812 if (ProfileUseArg &&
813 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
814 ProfileUseArg = nullptr;
815
816 return ProfileUseArg;
817}
818
Dehao Chenea4b78f2017-03-21 21:40:53 +0000819Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
820 auto *ProfileSampleUseArg = Args.getLastArg(
821 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
822 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
823 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
824
825 if (ProfileSampleUseArg &&
826 (ProfileSampleUseArg->getOption().matches(
827 options::OPT_fno_profile_sample_use) ||
828 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
829 return nullptr;
830
831 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
832 options::OPT_fauto_profile_EQ);
833}
834
David L. Jonesf561aba2017-03-08 01:02:16 +0000835/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
836/// smooshes them together with platform defaults, to decide whether
837/// this compile should be using PIC mode or not. Returns a tuple of
838/// (RelocationModel, PICLevel, IsPIE).
839std::tuple<llvm::Reloc::Model, unsigned, bool>
840tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
841 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
842 const llvm::Triple &Triple = ToolChain.getTriple();
843
844 bool PIE = ToolChain.isPIEDefault();
845 bool PIC = PIE || ToolChain.isPICDefault();
846 // The Darwin/MachO default to use PIC does not apply when using -static.
847 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
848 PIE = PIC = false;
849 bool IsPICLevelTwo = PIC;
850
851 bool KernelOrKext =
852 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
853
854 // Android-specific defaults for PIC/PIE
855 if (Triple.isAndroid()) {
856 switch (Triple.getArch()) {
857 case llvm::Triple::arm:
858 case llvm::Triple::armeb:
859 case llvm::Triple::thumb:
860 case llvm::Triple::thumbeb:
861 case llvm::Triple::aarch64:
862 case llvm::Triple::mips:
863 case llvm::Triple::mipsel:
864 case llvm::Triple::mips64:
865 case llvm::Triple::mips64el:
866 PIC = true; // "-fpic"
867 break;
868
869 case llvm::Triple::x86:
870 case llvm::Triple::x86_64:
871 PIC = true; // "-fPIC"
872 IsPICLevelTwo = true;
873 break;
874
875 default:
876 break;
877 }
878 }
879
880 // OpenBSD-specific defaults for PIE
881 if (Triple.getOS() == llvm::Triple::OpenBSD) {
882 switch (ToolChain.getArch()) {
Brad Smith3f2b1d72017-03-31 22:13:17 +0000883 case llvm::Triple::arm:
884 case llvm::Triple::aarch64:
David L. Jonesf561aba2017-03-08 01:02:16 +0000885 case llvm::Triple::mips64:
886 case llvm::Triple::mips64el:
David L. Jonesf561aba2017-03-08 01:02:16 +0000887 case llvm::Triple::x86:
888 case llvm::Triple::x86_64:
889 IsPICLevelTwo = false; // "-fpie"
890 break;
891
892 case llvm::Triple::ppc:
893 case llvm::Triple::sparc:
Brad Smith3f2b1d72017-03-31 22:13:17 +0000894 case llvm::Triple::sparcel:
David L. Jonesf561aba2017-03-08 01:02:16 +0000895 case llvm::Triple::sparcv9:
896 IsPICLevelTwo = true; // "-fPIE"
897 break;
898
899 default:
900 break;
901 }
902 }
903
Konstantin Zhuravlyovb4c83a02018-02-15 01:01:53 +0000904 // AMDGPU-specific defaults for PIC.
905 if (Triple.getArch() == llvm::Triple::amdgcn)
906 PIC = true;
907
David L. Jonesf561aba2017-03-08 01:02:16 +0000908 // The last argument relating to either PIC or PIE wins, and no
909 // other argument is used. If the last argument is any flavor of the
910 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
911 // option implicitly enables PIC at the same level.
912 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
913 options::OPT_fpic, options::OPT_fno_pic,
914 options::OPT_fPIE, options::OPT_fno_PIE,
915 options::OPT_fpie, options::OPT_fno_pie);
916 if (Triple.isOSWindows() && LastPICArg &&
917 LastPICArg ==
918 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
919 options::OPT_fPIE, options::OPT_fpie)) {
920 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
921 << LastPICArg->getSpelling() << Triple.str();
922 if (Triple.getArch() == llvm::Triple::x86_64)
923 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
924 return std::make_tuple(llvm::Reloc::Static, 0U, false);
925 }
926
927 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
928 // is forced, then neither PIC nor PIE flags will have no effect.
929 if (!ToolChain.isPICDefaultForced()) {
930 if (LastPICArg) {
931 Option O = LastPICArg->getOption();
932 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
933 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
934 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
935 PIC =
936 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
937 IsPICLevelTwo =
938 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
939 } else {
940 PIE = PIC = false;
941 if (EffectiveTriple.isPS4CPU()) {
942 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
943 StringRef Model = ModelArg ? ModelArg->getValue() : "";
944 if (Model != "kernel") {
945 PIC = true;
946 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
947 << LastPICArg->getSpelling();
948 }
949 }
950 }
951 }
952 }
953
954 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
955 // PIC level would've been set to level 1, force it back to level 2 PIC
956 // instead.
957 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
958 IsPICLevelTwo |= ToolChain.isPICDefault();
959
960 // This kernel flags are a trump-card: they will disable PIC/PIE
961 // generation, independent of the argument order.
962 if (KernelOrKext &&
963 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
964 !EffectiveTriple.isWatchOS()))
965 PIC = PIE = false;
966
967 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
968 // This is a very special mode. It trumps the other modes, almost no one
969 // uses it, and it isn't even valid on any OS but Darwin.
970 if (!Triple.isOSDarwin())
971 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
972 << A->getSpelling() << Triple.str();
973
974 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
975
976 // Only a forced PIC mode can cause the actual compile to have PIC defines
977 // etc., no flags are sufficient. This behavior was selected to closely
978 // match that of llvm-gcc and Apple GCC before that.
979 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
980
981 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
982 }
983
984 bool EmbeddedPISupported;
985 switch (Triple.getArch()) {
986 case llvm::Triple::arm:
987 case llvm::Triple::armeb:
988 case llvm::Triple::thumb:
989 case llvm::Triple::thumbeb:
990 EmbeddedPISupported = true;
991 break;
992 default:
993 EmbeddedPISupported = false;
994 break;
995 }
996
997 bool ROPI = false, RWPI = false;
998 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
999 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1000 if (!EmbeddedPISupported)
1001 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1002 << LastROPIArg->getSpelling() << Triple.str();
1003 ROPI = true;
1004 }
1005 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1006 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1007 if (!EmbeddedPISupported)
1008 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1009 << LastRWPIArg->getSpelling() << Triple.str();
1010 RWPI = true;
1011 }
1012
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001013 // ROPI and RWPI are not compatible with PIC or PIE.
David L. Jonesf561aba2017-03-08 01:02:16 +00001014 if ((ROPI || RWPI) && (PIC || PIE))
1015 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1016
Aleksandar Beserminji7ca42e82018-04-16 10:21:24 +00001017 if (Triple.getArch() == llvm::Triple::mips ||
1018 Triple.getArch() == llvm::Triple::mipsel ||
1019 Triple.getArch() == llvm::Triple::mips64 ||
1020 Triple.getArch() == llvm::Triple::mips64el) {
1021 // When targettng MIPS with -mno-abicalls, it's always static.
1022 if(Args.hasArg(options::OPT_mno_abicalls))
1023 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1024 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1025 // does not use PIC level 2 for historical reasons.
1026 IsPICLevelTwo = false;
1027 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001028
1029 if (PIC)
1030 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1031
1032 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1033 if (ROPI && RWPI)
1034 RelocM = llvm::Reloc::ROPI_RWPI;
1035 else if (ROPI)
1036 RelocM = llvm::Reloc::ROPI;
1037 else if (RWPI)
1038 RelocM = llvm::Reloc::RWPI;
1039
1040 return std::make_tuple(RelocM, 0U, false);
1041}
1042
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001043// `-falign-functions` indicates that the functions should be aligned to a
1044// 16-byte boundary.
1045//
1046// `-falign-functions=1` is the same as `-fno-align-functions`.
1047//
1048// The scalar `n` in `-falign-functions=n` must be an integral value between
1049// [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1050// the nearest power-of-two.
1051//
1052// If we return `0`, the frontend will default to the backend's preferred
1053// alignment.
1054//
1055// NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1056// to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1057// alignment. For unaligned functions, we default to the backend's preferred
1058// alignment.
1059unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1060 const ArgList &Args) {
1061 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1062 options::OPT_falign_functions_EQ,
1063 options::OPT_fno_align_functions);
1064 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1065 return 0;
1066
1067 if (A->getOption().matches(options::OPT_falign_functions))
1068 return 0;
1069
1070 unsigned Value = 0;
1071 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1072 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1073 << A->getAsString(Args) << A->getValue();
1074 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1075}
1076
David L. Jonesf561aba2017-03-08 01:02:16 +00001077void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1078 ArgStringList &CmdArgs) {
1079 llvm::Reloc::Model RelocationModel;
1080 unsigned PICLevel;
1081 bool IsPIE;
1082 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1083
1084 if (RelocationModel != llvm::Reloc::Static)
1085 CmdArgs.push_back("-KPIC");
1086}
1087
1088/// \brief Determine whether Objective-C automated reference counting is
1089/// enabled.
1090bool tools::isObjCAutoRefCount(const ArgList &Args) {
1091 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1092}
1093
1094static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1095 ArgStringList &CmdArgs, const ArgList &Args) {
1096 bool isAndroid = Triple.isAndroid();
1097 bool isCygMing = Triple.isOSCygMing();
1098 bool IsIAMCU = Triple.isOSIAMCU();
1099 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1100 Args.hasArg(options::OPT_static);
1101 if (!D.CCCIsCXX())
1102 CmdArgs.push_back("-lgcc");
1103
1104 if (StaticLibgcc || isAndroid) {
1105 if (D.CCCIsCXX())
1106 CmdArgs.push_back("-lgcc");
1107 } else {
1108 if (!D.CCCIsCXX() && !isCygMing)
1109 CmdArgs.push_back("--as-needed");
1110 CmdArgs.push_back("-lgcc_s");
1111 if (!D.CCCIsCXX() && !isCygMing)
1112 CmdArgs.push_back("--no-as-needed");
1113 }
1114
1115 if (StaticLibgcc && !isAndroid && !IsIAMCU)
1116 CmdArgs.push_back("-lgcc_eh");
1117 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
1118 CmdArgs.push_back("-lgcc");
1119
1120 // According to Android ABI, we have to link with libdl if we are
1121 // linking with non-static libgcc.
1122 //
1123 // NOTE: This fixes a link error on Android MIPS as well. The non-static
1124 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1125 if (isAndroid && !StaticLibgcc)
1126 CmdArgs.push_back("-ldl");
1127}
1128
1129void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1130 ArgStringList &CmdArgs, const ArgList &Args) {
1131 // Make use of compiler-rt if --rtlib option is used
1132 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1133
1134 switch (RLT) {
1135 case ToolChain::RLT_CompilerRT:
Sam Clegga08631e2017-10-27 00:26:07 +00001136 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001137 break;
1138 case ToolChain::RLT_Libgcc:
1139 // Make sure libgcc is not used under MSVC environment by default
1140 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1141 // Issue error diagnostic if libgcc is explicitly specified
1142 // through command line as --rtlib option argument.
1143 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1144 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1145 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1146 }
1147 } else
1148 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1149 break;
1150 }
1151}
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +00001152
1153/// Add OpenMP linker script arguments at the end of the argument list so that
1154/// the fat binary is built by embedding each of the device images into the
1155/// host. The linker script also defines a few symbols required by the code
1156/// generation so that the images can be easily retrieved at runtime by the
1157/// offloading library. This should be used only in tool chains that support
1158/// linker scripts.
1159void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1160 const InputInfo &Output,
1161 const InputInfoList &Inputs,
1162 const ArgList &Args, ArgStringList &CmdArgs,
1163 const JobAction &JA) {
1164
1165 // If this is not an OpenMP host toolchain, we don't need to do anything.
1166 if (!JA.isHostOffloading(Action::OFK_OpenMP))
1167 return;
1168
1169 // Create temporary linker script. Keep it if save-temps is enabled.
1170 const char *LKS;
1171 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1172 if (C.getDriver().isSaveTempsEnabled()) {
1173 llvm::sys::path::replace_extension(Name, "lk");
1174 LKS = C.getArgs().MakeArgString(Name.c_str());
1175 } else {
1176 llvm::sys::path::replace_extension(Name, "");
1177 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1178 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1179 }
1180
1181 // Add linker script option to the command.
1182 CmdArgs.push_back("-T");
1183 CmdArgs.push_back(LKS);
1184
1185 // Create a buffer to write the contents of the linker script.
1186 std::string LksBuffer;
1187 llvm::raw_string_ostream LksStream(LksBuffer);
1188
1189 // Get the OpenMP offload tool chains so that we can extract the triple
1190 // associated with each device input.
1191 auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1192 assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1193 "No OpenMP toolchains??");
1194
1195 // Track the input file name and device triple in order to build the script,
1196 // inserting binaries in the designated sections.
1197 SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1198
1199 // Add commands to embed target binaries. We ensure that each section and
1200 // image is 16-byte aligned. This is not mandatory, but increases the
1201 // likelihood of data to be aligned with a cache block in several main host
1202 // machines.
1203 LksStream << "/*\n";
1204 LksStream << " OpenMP Offload Linker Script\n";
1205 LksStream << " *** Automatically generated by Clang ***\n";
1206 LksStream << "*/\n";
1207 LksStream << "TARGET(binary)\n";
1208 auto DTC = OpenMPToolChains.first;
1209 for (auto &II : Inputs) {
1210 const Action *A = II.getAction();
1211 // Is this a device linking action?
1212 if (A && isa<LinkJobAction>(A) &&
1213 A->isDeviceOffloading(Action::OFK_OpenMP)) {
1214 assert(DTC != OpenMPToolChains.second &&
1215 "More device inputs than device toolchains??");
1216 InputBinaryInfo.push_back(std::make_pair(
1217 DTC->second->getTriple().normalize(), II.getFilename()));
1218 ++DTC;
1219 LksStream << "INPUT(" << II.getFilename() << ")\n";
1220 }
1221 }
1222
1223 assert(DTC == OpenMPToolChains.second &&
1224 "Less device inputs than device toolchains??");
1225
1226 LksStream << "SECTIONS\n";
1227 LksStream << "{\n";
1228
1229 // Put each target binary into a separate section.
1230 for (const auto &BI : InputBinaryInfo) {
1231 LksStream << " .omp_offloading." << BI.first << " :\n";
1232 LksStream << " ALIGN(0x10)\n";
1233 LksStream << " {\n";
1234 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1235 << " = .);\n";
1236 LksStream << " " << BI.second << "\n";
1237 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1238 << " = .);\n";
1239 LksStream << " }\n";
1240 }
1241
1242 // Add commands to define host entries begin and end. We use 1-byte subalign
1243 // so that the linker does not add any padding and the elements in this
1244 // section form an array.
1245 LksStream << " .omp_offloading.entries :\n";
1246 LksStream << " ALIGN(0x10)\n";
1247 LksStream << " SUBALIGN(0x01)\n";
1248 LksStream << " {\n";
1249 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1250 LksStream << " *(.omp_offloading.entries)\n";
1251 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1252 LksStream << " }\n";
1253 LksStream << "}\n";
1254 LksStream << "INSERT BEFORE .data\n";
1255 LksStream.flush();
1256
1257 // Dump the contents of the linker script if the user requested that. We
1258 // support this option to enable testing of behavior with -###.
1259 if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1260 llvm::errs() << LksBuffer;
1261
1262 // If this is a dry run, do not create the linker script file.
1263 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1264 return;
1265
1266 // Open script file and write the contents.
1267 std::error_code EC;
1268 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1269
1270 if (EC) {
1271 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1272 return;
1273 }
1274
1275 Lksf << LksBuffer;
1276}
Florian Hahn2e081d12018-04-20 12:50:10 +00001277
1278SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1279 const InputInfo &Output,
1280 const InputInfo &Input,
1281 const Driver &D) {
1282 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1283 if (!A)
1284 return {};
1285
1286 StringRef SaveStats = A->getValue();
1287 SmallString<128> StatsFile;
1288 if (SaveStats == "obj" && Output.isFilename()) {
1289 StatsFile.assign(Output.getFilename());
1290 llvm::sys::path::remove_filename(StatsFile);
1291 } else if (SaveStats != "cwd") {
1292 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1293 return {};
1294 }
1295
1296 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1297 llvm::sys::path::append(StatsFile, BaseName);
1298 llvm::sys::path::replace_extension(StatsFile, "stats");
1299 return StatsFile;
1300}