blob: e802ce7a8c02b01071b3f5124cce511308eba57c [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"
Yaxun Liu97670892018-10-02 17:48:54 +000017#include "HIP.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000018#include "Hexagon.h"
Florian Hahn2e081d12018-04-20 12:50:10 +000019#include "InputInfo.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000020#include "clang/Basic/CharInfo.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/ObjCRuntime.h"
23#include "clang/Basic/Version.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000024#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"
Jonas Devliegherefc514902018-10-10 13:27:25 +000054#include "llvm/Support/VirtualFileSystem.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000055#include "llvm/Support/YAMLParser.h"
56
57using namespace clang::driver;
58using namespace clang::driver::tools;
59using namespace clang;
60using namespace llvm::opt;
61
62void tools::addPathIfExists(const Driver &D, const Twine &Path,
63 ToolChain::path_list &Paths) {
64 if (D.getVFS().exists(Path))
65 Paths.push_back(Path.str());
66}
67
68void tools::handleTargetFeaturesGroup(const ArgList &Args,
69 std::vector<StringRef> &Features,
70 OptSpecifier Group) {
71 for (const Arg *A : Args.filtered(Group)) {
72 StringRef Name = A->getOption().getName();
73 A->claim();
74
75 // Skip over "-m".
76 assert(Name.startswith("m") && "Invalid feature name.");
77 Name = Name.substr(1);
78
79 bool IsNegative = Name.startswith("no-");
80 if (IsNegative)
81 Name = Name.substr(3);
82 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
83 }
84}
85
86void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
87 const char *ArgName, const char *EnvVar) {
88 const char *DirList = ::getenv(EnvVar);
89 bool CombinedArg = false;
90
91 if (!DirList)
92 return; // Nothing to do.
93
94 StringRef Name(ArgName);
95 if (Name.equals("-I") || Name.equals("-L"))
96 CombinedArg = true;
97
98 StringRef Dirs(DirList);
99 if (Dirs.empty()) // Empty string should not add '.'.
100 return;
101
102 StringRef::size_type Delim;
103 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
104 if (Delim == 0) { // Leading colon.
105 if (CombinedArg) {
106 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
107 } else {
108 CmdArgs.push_back(ArgName);
109 CmdArgs.push_back(".");
110 }
111 } else {
112 if (CombinedArg) {
113 CmdArgs.push_back(
114 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
115 } else {
116 CmdArgs.push_back(ArgName);
117 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
118 }
119 }
120 Dirs = Dirs.substr(Delim + 1);
121 }
122
123 if (Dirs.empty()) { // Trailing colon.
124 if (CombinedArg) {
125 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
126 } else {
127 CmdArgs.push_back(ArgName);
128 CmdArgs.push_back(".");
129 }
130 } else { // Add the last path.
131 if (CombinedArg) {
132 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
133 } else {
134 CmdArgs.push_back(ArgName);
135 CmdArgs.push_back(Args.MakeArgString(Dirs));
136 }
137 }
138}
139
140void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
141 const ArgList &Args, ArgStringList &CmdArgs,
142 const JobAction &JA) {
143 const Driver &D = TC.getDriver();
144
145 // Add extra linker input arguments which are not treated as inputs
146 // (constructed via -Xarch_).
147 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
148
149 for (const auto &II : Inputs) {
Yaxun Liu29155b02018-05-18 15:07:56 +0000150 // If the current tool chain refers to an OpenMP or HIP offloading host, we
151 // should ignore inputs that refer to OpenMP or HIP offloading devices -
152 // they will be embedded according to a proper linker script.
David L. Jonesf561aba2017-03-08 01:02:16 +0000153 if (auto *IA = II.getAction())
Yaxun Liu29155b02018-05-18 15:07:56 +0000154 if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
155 IA->isDeviceOffloading(Action::OFK_OpenMP)) ||
156 (JA.isHostOffloading(Action::OFK_HIP) &&
157 IA->isDeviceOffloading(Action::OFK_HIP)))
David L. Jonesf561aba2017-03-08 01:02:16 +0000158 continue;
159
160 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
161 // Don't try to pass LLVM inputs unless we have native support.
162 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
163
164 // Add filenames immediately.
165 if (II.isFilename()) {
Martin Storsjob547ef22018-10-26 08:33:29 +0000166 CmdArgs.push_back(II.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +0000167 continue;
168 }
169
170 // Otherwise, this is a linker input argument.
171 const Arg &A = II.getInputArg();
172
173 // Handle reserved library options.
174 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
175 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
176 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
177 TC.AddCCKextLibArgs(Args, CmdArgs);
178 else if (A.getOption().matches(options::OPT_z)) {
179 // Pass -z prefix for gcc linker compatibility.
180 A.claim();
181 A.render(Args, CmdArgs);
182 } else {
183 A.renderAsInput(Args, CmdArgs);
184 }
185 }
186
187 // LIBRARY_PATH - included following the user specified library paths.
188 // and only supported on native toolchains.
189 if (!TC.isCrossCompiling()) {
190 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
191 }
192}
193
194void tools::AddTargetFeature(const ArgList &Args,
195 std::vector<StringRef> &Features,
196 OptSpecifier OnOpt, OptSpecifier OffOpt,
197 StringRef FeatureName) {
198 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
199 if (A->getOption().matches(OnOpt))
200 Features.push_back(Args.MakeArgString("+" + FeatureName));
201 else
202 Features.push_back(Args.MakeArgString("-" + FeatureName));
203 }
204}
205
206/// Get the (LLVM) name of the R600 gpu we are targeting.
207static std::string getR600TargetGPU(const ArgList &Args) {
208 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
209 const char *GPUName = A->getValue();
210 return llvm::StringSwitch<const char *>(GPUName)
211 .Cases("rv630", "rv635", "r600")
212 .Cases("rv610", "rv620", "rs780", "rs880")
213 .Case("rv740", "rv770")
214 .Case("palm", "cedar")
215 .Cases("sumo", "sumo2", "sumo")
216 .Case("hemlock", "cypress")
217 .Case("aruba", "cayman")
218 .Default(GPUName);
219 }
220 return "";
221}
222
Nikolai Bozhenov35d3c352017-06-27 09:48:24 +0000223static std::string getNios2TargetCPU(const ArgList &Args) {
224 Arg *A = Args.getLastArg(options::OPT_mcpu_EQ);
225 if (!A)
226 A = Args.getLastArg(options::OPT_march_EQ);
227
228 if (!A)
229 return "";
230
231 const char *name = A->getValue();
232 return llvm::StringSwitch<const char *>(name)
233 .Case("r1", "nios2r1")
234 .Case("r2", "nios2r2")
235 .Default(name);
236}
237
David L. Jonesf561aba2017-03-08 01:02:16 +0000238static std::string getLanaiTargetCPU(const ArgList &Args) {
239 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
240 return A->getValue();
241 }
242 return "";
243}
244
245/// Get the (LLVM) name of the WebAssembly cpu we are targeting.
246static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
247 // If we have -mcpu=, use that.
248 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
249 StringRef CPU = A->getValue();
250
251#ifdef __wasm__
252 // Handle "native" by examining the host. "native" isn't meaningful when
253 // cross compiling, so only support this when the host is also WebAssembly.
254 if (CPU == "native")
255 return llvm::sys::getHostCPUName();
256#endif
257
258 return CPU;
259 }
260
261 return "generic";
262}
263
264std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
265 bool FromAs) {
266 Arg *A;
267
268 switch (T.getArch()) {
269 default:
270 return "";
271
272 case llvm::Triple::aarch64:
273 case llvm::Triple::aarch64_be:
274 return aarch64::getAArch64TargetCPU(Args, A);
275
276 case llvm::Triple::arm:
277 case llvm::Triple::armeb:
278 case llvm::Triple::thumb:
279 case llvm::Triple::thumbeb: {
280 StringRef MArch, MCPU;
281 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
282 return arm::getARMTargetCPU(MCPU, MArch, T);
283 }
Leslie Zhaiff041092017-04-20 04:23:24 +0000284
285 case llvm::Triple::avr:
286 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
287 return A->getValue();
288 return "";
289
Nikolai Bozhenov35d3c352017-06-27 09:48:24 +0000290 case llvm::Triple::nios2: {
291 return getNios2TargetCPU(Args);
292 }
293
David L. Jonesf561aba2017-03-08 01:02:16 +0000294 case llvm::Triple::mips:
295 case llvm::Triple::mipsel:
296 case llvm::Triple::mips64:
297 case llvm::Triple::mips64el: {
298 StringRef CPUName;
299 StringRef ABIName;
300 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
301 return CPUName;
302 }
303
304 case llvm::Triple::nvptx:
305 case llvm::Triple::nvptx64:
306 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
307 return A->getValue();
308 return "";
309
310 case llvm::Triple::ppc:
311 case llvm::Triple::ppc64:
312 case llvm::Triple::ppc64le: {
313 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
314 // LLVM may default to generating code for the native CPU,
315 // but, like gcc, we default to a more generic option for
316 // each architecture. (except on Darwin)
317 if (TargetCPUName.empty() && !T.isOSDarwin()) {
318 if (T.getArch() == llvm::Triple::ppc64)
319 TargetCPUName = "ppc64";
320 else if (T.getArch() == llvm::Triple::ppc64le)
321 TargetCPUName = "ppc64le";
322 else
323 TargetCPUName = "ppc";
324 }
325 return TargetCPUName;
326 }
327
Yonghong Songc4ea1012017-08-23 04:26:17 +0000328 case llvm::Triple::bpfel:
329 case llvm::Triple::bpfeb:
David L. Jonesf561aba2017-03-08 01:02:16 +0000330 case llvm::Triple::sparc:
331 case llvm::Triple::sparcel:
332 case llvm::Triple::sparcv9:
333 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
334 return A->getValue();
335 return "";
336
337 case llvm::Triple::x86:
338 case llvm::Triple::x86_64:
339 return x86::getX86TargetCPU(Args, T);
340
341 case llvm::Triple::hexagon:
342 return "hexagon" +
343 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
344
345 case llvm::Triple::lanai:
346 return getLanaiTargetCPU(Args);
347
348 case llvm::Triple::systemz:
349 return systemz::getSystemZTargetCPU(Args);
350
351 case llvm::Triple::r600:
352 case llvm::Triple::amdgcn:
353 return getR600TargetGPU(Args);
354
355 case llvm::Triple::wasm32:
356 case llvm::Triple::wasm64:
357 return getWebAssemblyTargetCPU(Args);
358 }
359}
360
361unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
362 unsigned Parallelism = 0;
363 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
364 if (LtoJobsArg &&
365 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
366 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
367 << LtoJobsArg->getValue();
368 return Parallelism;
369}
370
Sam Clegg7892ae42018-01-31 18:55:22 +0000371// CloudABI uses -ffunction-sections and -fdata-sections by default.
David L. Jonesf561aba2017-03-08 01:02:16 +0000372bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
Sam Clegg7892ae42018-01-31 18:55:22 +0000373 return Triple.getOS() == llvm::Triple::CloudABI;
David L. Jonesf561aba2017-03-08 01:02:16 +0000374}
375
376void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
Florian Hahn2e081d12018-04-20 12:50:10 +0000377 ArgStringList &CmdArgs, const InputInfo &Output,
378 const InputInfo &Input, bool IsThinLTO) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000379 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
380 // as gold requires -plugin to come before any -plugin-opt that -Wl might
381 // forward.
382 CmdArgs.push_back("-plugin");
Dan Albertc3a11d52017-08-22 21:05:01 +0000383
Nico Weber1865df42018-04-27 19:11:14 +0000384#if defined(_WIN32)
Dan Albertc3a11d52017-08-22 21:05:01 +0000385 const char *Suffix = ".dll";
386#elif defined(__APPLE__)
387 const char *Suffix = ".dylib";
388#else
389 const char *Suffix = ".so";
390#endif
391
392 SmallString<1024> Plugin;
393 llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
394 "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
395 Suffix,
396 Plugin);
David L. Jonesf561aba2017-03-08 01:02:16 +0000397 CmdArgs.push_back(Args.MakeArgString(Plugin));
398
399 // Try to pass driver level flags relevant to LTO code generation down to
400 // the plugin.
401
402 // Handle flags for selecting CPU variants.
403 std::string CPU = getCPUName(Args, ToolChain.getTriple());
404 if (!CPU.empty())
405 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
406
407 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
408 StringRef OOpt;
409 if (A->getOption().matches(options::OPT_O4) ||
410 A->getOption().matches(options::OPT_Ofast))
411 OOpt = "3";
412 else if (A->getOption().matches(options::OPT_O))
413 OOpt = A->getValue();
414 else if (A->getOption().matches(options::OPT_O0))
415 OOpt = "0";
416 if (!OOpt.empty())
417 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
418 }
419
Yunlian Jiang87c88cc2018-06-25 23:05:27 +0000420 if (Args.hasArg(options::OPT_gsplit_dwarf)) {
421 CmdArgs.push_back(
422 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
423 Output.getFilename() + "_dwo"));
424 }
425
David L. Jonesf561aba2017-03-08 01:02:16 +0000426 if (IsThinLTO)
427 CmdArgs.push_back("-plugin-opt=thinlto");
428
Florian Hahn2e081d12018-04-20 12:50:10 +0000429 if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver()))
Benjamin Kramer3a13ed62017-12-28 16:58:54 +0000430 CmdArgs.push_back(
431 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
David L. Jonesf561aba2017-03-08 01:02:16 +0000432
433 // If an explicit debugger tuning argument appeared, pass it along.
434 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
435 options::OPT_ggdbN_Group)) {
436 if (A->getOption().matches(options::OPT_glldb))
437 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
438 else if (A->getOption().matches(options::OPT_gsce))
439 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
440 else
441 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
442 }
443
444 bool UseSeparateSections =
445 isUseSeparateSections(ToolChain.getEffectiveTriple());
446
447 if (Args.hasFlag(options::OPT_ffunction_sections,
448 options::OPT_fno_function_sections, UseSeparateSections)) {
449 CmdArgs.push_back("-plugin-opt=-function-sections");
450 }
451
452 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
453 UseSeparateSections)) {
454 CmdArgs.push_back("-plugin-opt=-data-sections");
455 }
456
Dehao Chenea4b78f2017-03-21 21:40:53 +0000457 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000458 StringRef FName = A->getValue();
459 if (!llvm::sys::fs::exists(FName))
Florian Hahn2e081d12018-04-20 12:50:10 +0000460 ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName;
David L. Jonesf561aba2017-03-08 01:02:16 +0000461 else
462 CmdArgs.push_back(
463 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
464 }
Sean Fertile03e77c62017-10-05 01:50:48 +0000465
466 // Need this flag to turn on new pass manager via Gold plugin.
467 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
468 options::OPT_fno_experimental_new_pass_manager,
Petr Hosekc3aa97a2018-04-06 00:53:00 +0000469 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
Sean Fertile03e77c62017-10-05 01:50:48 +0000470 CmdArgs.push_back("-plugin-opt=new-pass-manager");
471 }
472
Florian Hahn2e081d12018-04-20 12:50:10 +0000473 // Setup statistics file output.
474 SmallString<128> StatsFile =
475 getStatsFileName(Args, Output, Input, ToolChain.getDriver());
476 if (!StatsFile.empty())
477 CmdArgs.push_back(
478 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +0000479}
480
481void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
482 ArgStringList &CmdArgs) {
Petr Hosekbae48562018-04-02 23:36:14 +0000483 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
484 options::OPT_fno_rtlib_add_rpath, false))
485 return;
486
David L. Jonesf561aba2017-03-08 01:02:16 +0000487 std::string CandidateRPath = TC.getArchSpecificLibPath();
488 if (TC.getVFS().exists(CandidateRPath)) {
489 CmdArgs.push_back("-rpath");
490 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
491 }
492}
493
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000494bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
495 const ArgList &Args, bool IsOffloadingHost,
496 bool GompNeedsRT) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000497 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
498 options::OPT_fno_openmp, false))
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000499 return false;
David L. Jonesf561aba2017-03-08 01:02:16 +0000500
501 switch (TC.getDriver().getOpenMPRuntime(Args)) {
502 case Driver::OMPRT_OMP:
503 CmdArgs.push_back("-lomp");
504 break;
505 case Driver::OMPRT_GOMP:
506 CmdArgs.push_back("-lgomp");
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000507
508 if (GompNeedsRT)
509 CmdArgs.push_back("-lrt");
David L. Jonesf561aba2017-03-08 01:02:16 +0000510 break;
511 case Driver::OMPRT_IOMP5:
512 CmdArgs.push_back("-liomp5");
513 break;
514 case Driver::OMPRT_Unknown:
515 // Already diagnosed.
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000516 return false;
David L. Jonesf561aba2017-03-08 01:02:16 +0000517 }
518
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000519 if (IsOffloadingHost)
520 CmdArgs.push_back("-lomptarget");
521
David L. Jonesf561aba2017-03-08 01:02:16 +0000522 addArchSpecificRPath(TC, Args, CmdArgs);
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000523
524 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +0000525}
526
527static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
528 ArgStringList &CmdArgs, StringRef Sanitizer,
529 bool IsShared, bool IsWhole) {
530 // Wrap any static runtimes that must be forced into executable in
531 // whole-archive.
Alex Shlyapnikov85da0f62018-02-05 23:59:13 +0000532 if (IsWhole) CmdArgs.push_back("--whole-archive");
David L. Jonesf561aba2017-03-08 01:02:16 +0000533 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
Alex Shlyapnikov85da0f62018-02-05 23:59:13 +0000534 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
David L. Jonesf561aba2017-03-08 01:02:16 +0000535
536 if (IsShared) {
537 addArchSpecificRPath(TC, Args, CmdArgs);
538 }
539}
540
541// Tries to use a file with the list of dynamic symbols that need to be exported
542// from the runtime library. Returns true if the file was found.
543static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
544 ArgStringList &CmdArgs,
545 StringRef Sanitizer) {
Alex Shlyapnikov85da0f62018-02-05 23:59:13 +0000546 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
547 // the option, so don't try to pass it.
548 if (TC.getTriple().getOS() == llvm::Triple::Solaris)
549 return true;
Walter Leea5cc2222018-05-17 18:04:39 +0000550 // Myriad is static linking only. Furthermore, some versions of its
551 // linker have the bug where --export-dynamic overrides -static, so
552 // don't use --export-dynamic on that platform.
553 if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
554 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +0000555 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
556 if (llvm::sys::fs::exists(SanRT + ".syms")) {
557 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
558 return true;
559 }
560 return false;
561}
562
Petr Hosek4b9940b2018-10-29 20:37:52 +0000563static void addSanitizerLibPath(const ToolChain &TC, const ArgList &Args,
564 ArgStringList &CmdArgs, StringRef Name) {
565 for (const auto &LibPath : TC.getLibraryPaths()) {
566 if (!LibPath.empty()) {
567 SmallString<128> P(LibPath);
568 llvm::sys::path::append(P, Name);
569 if (TC.getVFS().exists(P))
570 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
571 }
572 }
573}
574
575void tools::addSanitizerPathLibArgs(const ToolChain &TC, const ArgList &Args,
576 ArgStringList &CmdArgs) {
577 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
578 if (SanArgs.needsAsanRt()) {
579 addSanitizerLibPath(TC, Args, CmdArgs, "asan");
580 }
581 if (SanArgs.needsHwasanRt()) {
582 addSanitizerLibPath(TC, Args, CmdArgs, "hwasan");
583 }
584 if (SanArgs.needsLsanRt()) {
585 addSanitizerLibPath(TC, Args, CmdArgs, "lsan");
586 }
587 if (SanArgs.needsMsanRt()) {
588 addSanitizerLibPath(TC, Args, CmdArgs, "msan");
589 }
590 if (SanArgs.needsTsanRt()) {
591 addSanitizerLibPath(TC, Args, CmdArgs, "tsan");
592 }
593}
594
595
596
David L. Jonesf561aba2017-03-08 01:02:16 +0000597void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
598 ArgStringList &CmdArgs) {
599 // Force linking against the system libraries sanitizers depends on
600 // (see PR15823 why this is necessary).
601 CmdArgs.push_back("--no-as-needed");
Kostya Kortchinsky1969c9a2018-06-26 16:14:35 +0000602 // There's no libpthread or librt on RTEMS & Android.
603 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
604 !TC.getTriple().isAndroid()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000605 CmdArgs.push_back("-lpthread");
Kamil Rytarowski150a3772018-03-03 11:47:27 +0000606 if (TC.getTriple().getOS() != llvm::Triple::OpenBSD)
607 CmdArgs.push_back("-lrt");
David L. Jonesf561aba2017-03-08 01:02:16 +0000608 }
609 CmdArgs.push_back("-lm");
Kamil Rytarowskibb9a8522017-12-08 17:38:25 +0000610 // There's no libdl on all OSes.
David L. Jonesf561aba2017-03-08 01:02:16 +0000611 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
Kamil Rytarowski2eef4752017-07-04 19:55:56 +0000612 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
Kamil Rytarowski150a3772018-03-03 11:47:27 +0000613 TC.getTriple().getOS() != llvm::Triple::OpenBSD &&
David L. Jonesf561aba2017-03-08 01:02:16 +0000614 TC.getTriple().getOS() != llvm::Triple::RTEMS)
615 CmdArgs.push_back("-ldl");
Kamil Rytarowskie21475e2017-12-19 07:10:33 +0000616 // Required for backtrace on some OSes
Kamil Rytarowskia7ef6a62018-01-24 23:08:49 +0000617 if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
618 TC.getTriple().getOS() == llvm::Triple::FreeBSD)
Kamil Rytarowskie21475e2017-12-19 07:10:33 +0000619 CmdArgs.push_back("-lexecinfo");
David L. Jonesf561aba2017-03-08 01:02:16 +0000620}
621
622static void
623collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
624 SmallVectorImpl<StringRef> &SharedRuntimes,
625 SmallVectorImpl<StringRef> &StaticRuntimes,
626 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
627 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
628 SmallVectorImpl<StringRef> &RequiredSymbols) {
629 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
630 // Collect shared runtimes.
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000631 if (SanArgs.needsSharedRt()) {
632 if (SanArgs.needsAsanRt()) {
633 SharedRuntimes.push_back("asan");
634 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
635 HelperStaticRuntimes.push_back("asan-preinit");
636 }
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000637 if (SanArgs.needsUbsanRt()) {
Kostya Kortchinsky64d80932018-06-22 14:31:30 +0000638 if (SanArgs.requiresMinimalRuntime())
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000639 SharedRuntimes.push_back("ubsan_minimal");
Kostya Kortchinsky64d80932018-06-22 14:31:30 +0000640 else
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000641 SharedRuntimes.push_back("ubsan_standalone");
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000642 }
Kostya Kortchinsky64d80932018-06-22 14:31:30 +0000643 if (SanArgs.needsScudoRt()) {
644 if (SanArgs.requiresMinimalRuntime())
645 SharedRuntimes.push_back("scudo_minimal");
646 else
647 SharedRuntimes.push_back("scudo");
648 }
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000649 if (SanArgs.needsHwasanRt())
650 SharedRuntimes.push_back("hwasan");
David L. Jonesf561aba2017-03-08 01:02:16 +0000651 }
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000652
David L. Jonesf561aba2017-03-08 01:02:16 +0000653 // The stats_client library is also statically linked into DSOs.
654 if (SanArgs.needsStatsRt())
655 StaticRuntimes.push_back("stats_client");
656
657 // Collect static runtimes.
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000658 if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
659 // Don't link static runtimes into DSOs or if -shared-libasan.
David L. Jonesf561aba2017-03-08 01:02:16 +0000660 return;
661 }
662 if (SanArgs.needsAsanRt()) {
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000663 StaticRuntimes.push_back("asan");
664 if (SanArgs.linkCXXRuntimes())
665 StaticRuntimes.push_back("asan_cxx");
David L. Jonesf561aba2017-03-08 01:02:16 +0000666 }
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000667
668 if (SanArgs.needsHwasanRt()) {
669 StaticRuntimes.push_back("hwasan");
670 if (SanArgs.linkCXXRuntimes())
671 StaticRuntimes.push_back("hwasan_cxx");
672 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000673 if (SanArgs.needsDfsanRt())
674 StaticRuntimes.push_back("dfsan");
675 if (SanArgs.needsLsanRt())
676 StaticRuntimes.push_back("lsan");
677 if (SanArgs.needsMsanRt()) {
678 StaticRuntimes.push_back("msan");
679 if (SanArgs.linkCXXRuntimes())
680 StaticRuntimes.push_back("msan_cxx");
681 }
682 if (SanArgs.needsTsanRt()) {
683 StaticRuntimes.push_back("tsan");
684 if (SanArgs.linkCXXRuntimes())
685 StaticRuntimes.push_back("tsan_cxx");
686 }
687 if (SanArgs.needsUbsanRt()) {
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000688 if (SanArgs.requiresMinimalRuntime()) {
689 StaticRuntimes.push_back("ubsan_minimal");
690 } else {
691 StaticRuntimes.push_back("ubsan_standalone");
692 if (SanArgs.linkCXXRuntimes())
693 StaticRuntimes.push_back("ubsan_standalone_cxx");
694 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000695 }
696 if (SanArgs.needsSafeStackRt()) {
697 NonWholeStaticRuntimes.push_back("safestack");
698 RequiredSymbols.push_back("__safestack_init");
699 }
700 if (SanArgs.needsCfiRt())
701 StaticRuntimes.push_back("cfi");
702 if (SanArgs.needsCfiDiagRt()) {
703 StaticRuntimes.push_back("cfi_diag");
704 if (SanArgs.linkCXXRuntimes())
705 StaticRuntimes.push_back("ubsan_standalone_cxx");
706 }
707 if (SanArgs.needsStatsRt()) {
708 NonWholeStaticRuntimes.push_back("stats");
709 RequiredSymbols.push_back("__sanitizer_stats_register");
710 }
711 if (SanArgs.needsEsanRt())
712 StaticRuntimes.push_back("esan");
Kostya Kortchinsky8acdc982017-11-03 17:04:13 +0000713 if (SanArgs.needsScudoRt()) {
Kostya Kortchinsky64d80932018-06-22 14:31:30 +0000714 if (SanArgs.requiresMinimalRuntime()) {
715 StaticRuntimes.push_back("scudo_minimal");
716 if (SanArgs.linkCXXRuntimes())
717 StaticRuntimes.push_back("scudo_cxx_minimal");
718 } else {
719 StaticRuntimes.push_back("scudo");
720 if (SanArgs.linkCXXRuntimes())
721 StaticRuntimes.push_back("scudo_cxx");
722 }
Kostya Kortchinsky8acdc982017-11-03 17:04:13 +0000723 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000724}
725
726// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
727// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
728bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
729 ArgStringList &CmdArgs) {
730 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
731 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
732 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
733 NonWholeStaticRuntimes, HelperStaticRuntimes,
734 RequiredSymbols);
George Karpenkov9f6f74c2017-08-21 23:25:19 +0000735
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000736 // Inject libfuzzer dependencies.
George Karpenkov2363fdd2017-06-29 19:52:33 +0000737 if (TC.getSanitizerArgs().needsFuzzer()
738 && !Args.hasArg(options::OPT_shared)) {
George Karpenkov9f6f74c2017-08-21 23:25:19 +0000739
740 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
741 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
742 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000743 }
744
David L. Jonesf561aba2017-03-08 01:02:16 +0000745 for (auto RT : SharedRuntimes)
746 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
747 for (auto RT : HelperStaticRuntimes)
748 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
749 bool AddExportDynamic = false;
750 for (auto RT : StaticRuntimes) {
751 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
752 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
753 }
754 for (auto RT : NonWholeStaticRuntimes) {
755 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
756 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
757 }
758 for (auto S : RequiredSymbols) {
759 CmdArgs.push_back("-u");
760 CmdArgs.push_back(Args.MakeArgString(S));
761 }
762 // If there is a static runtime with no dynamic list, force all the symbols
763 // to be dynamic to be sure we export sanitizer interface functions.
764 if (AddExportDynamic)
Alex Shlyapnikov85da0f62018-02-05 23:59:13 +0000765 CmdArgs.push_back("--export-dynamic");
David L. Jonesf561aba2017-03-08 01:02:16 +0000766
767 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
768 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
769 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
770
771 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
772}
773
Dean Michael Berris62440372018-04-06 03:53:04 +0000774bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
775 if (Args.hasArg(options::OPT_shared))
776 return false;
777
778 if (TC.getXRayArgs().needsXRayRt()) {
779 CmdArgs.push_back("-whole-archive");
780 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
Dean Michael Berris826e6662018-04-11 01:28:25 +0000781 for (const auto &Mode : TC.getXRayArgs().modeList())
782 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode, false));
Dean Michael Berris62440372018-04-06 03:53:04 +0000783 CmdArgs.push_back("-no-whole-archive");
784 return true;
785 }
786
787 return false;
788}
789
790void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
791 CmdArgs.push_back("--no-as-needed");
792 CmdArgs.push_back("-lpthread");
793 if (TC.getTriple().getOS() != llvm::Triple::OpenBSD)
794 CmdArgs.push_back("-lrt");
795 CmdArgs.push_back("-lm");
796
797 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
798 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
799 TC.getTriple().getOS() != llvm::Triple::OpenBSD)
800 CmdArgs.push_back("-ldl");
801}
802
David L. Jonesf561aba2017-03-08 01:02:16 +0000803bool tools::areOptimizationsEnabled(const ArgList &Args) {
804 // Find the last -O arg and see if it is non-zero.
805 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
806 return !A->getOption().matches(options::OPT_O0);
807 // Defaults to -O0.
808 return false;
809}
810
George Rimar91829ee2018-11-14 09:22:16 +0000811const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input,
812 const InputInfo &Output) {
813 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
814 if (StringRef(A->getValue()) == "single")
815 return Args.MakeArgString(Output.getFilename());
816
David L. Jonesf561aba2017-03-08 01:02:16 +0000817 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
818 if (FinalOutput && Args.hasArg(options::OPT_c)) {
819 SmallString<128> T(FinalOutput->getValue());
820 llvm::sys::path::replace_extension(T, "dwo");
821 return Args.MakeArgString(T);
822 } else {
823 // Use the compilation dir.
824 SmallString<128> T(
825 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
826 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
827 llvm::sys::path::replace_extension(F, "dwo");
828 T += F;
829 return Args.MakeArgString(F);
830 }
831}
832
833void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
834 const JobAction &JA, const ArgList &Args,
835 const InputInfo &Output, const char *OutFile) {
836 ArgStringList ExtractArgs;
837 ExtractArgs.push_back("--extract-dwo");
838
839 ArgStringList StripArgs;
840 StripArgs.push_back("--strip-dwo");
841
842 // Grabbing the output of the earlier compile step.
843 StripArgs.push_back(Output.getFilename());
844 ExtractArgs.push_back(Output.getFilename());
845 ExtractArgs.push_back(OutFile);
846
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000847 const char *Exec =
848 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
David L. Jonesf561aba2017-03-08 01:02:16 +0000849 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
850
851 // First extract the dwo sections.
852 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
853
854 // Then remove them from the original .o file.
855 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
856}
857
858// Claim options we don't want to warn if they are unused. We do this for
859// options that build systems might add but are unused when assembling or only
860// running the preprocessor for example.
861void tools::claimNoWarnArgs(const ArgList &Args) {
862 // Don't warn about unused -f(no-)?lto. This can happen when we're
863 // preprocessing, precompiling or assembling.
864 Args.ClaimAllArgs(options::OPT_flto_EQ);
865 Args.ClaimAllArgs(options::OPT_flto);
866 Args.ClaimAllArgs(options::OPT_fno_lto);
867}
868
869Arg *tools::getLastProfileUseArg(const ArgList &Args) {
870 auto *ProfileUseArg = Args.getLastArg(
871 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
872 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
873 options::OPT_fno_profile_instr_use);
874
875 if (ProfileUseArg &&
876 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
877 ProfileUseArg = nullptr;
878
879 return ProfileUseArg;
880}
881
Dehao Chenea4b78f2017-03-21 21:40:53 +0000882Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
883 auto *ProfileSampleUseArg = Args.getLastArg(
884 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
885 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
886 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
887
888 if (ProfileSampleUseArg &&
889 (ProfileSampleUseArg->getOption().matches(
890 options::OPT_fno_profile_sample_use) ||
891 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
892 return nullptr;
893
894 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
895 options::OPT_fauto_profile_EQ);
896}
897
David L. Jonesf561aba2017-03-08 01:02:16 +0000898/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
899/// smooshes them together with platform defaults, to decide whether
900/// this compile should be using PIC mode or not. Returns a tuple of
901/// (RelocationModel, PICLevel, IsPIE).
902std::tuple<llvm::Reloc::Model, unsigned, bool>
903tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
904 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
905 const llvm::Triple &Triple = ToolChain.getTriple();
906
907 bool PIE = ToolChain.isPIEDefault();
908 bool PIC = PIE || ToolChain.isPICDefault();
909 // The Darwin/MachO default to use PIC does not apply when using -static.
910 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
911 PIE = PIC = false;
912 bool IsPICLevelTwo = PIC;
913
914 bool KernelOrKext =
915 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
916
917 // Android-specific defaults for PIC/PIE
918 if (Triple.isAndroid()) {
919 switch (Triple.getArch()) {
920 case llvm::Triple::arm:
921 case llvm::Triple::armeb:
922 case llvm::Triple::thumb:
923 case llvm::Triple::thumbeb:
924 case llvm::Triple::aarch64:
925 case llvm::Triple::mips:
926 case llvm::Triple::mipsel:
927 case llvm::Triple::mips64:
928 case llvm::Triple::mips64el:
929 PIC = true; // "-fpic"
930 break;
931
932 case llvm::Triple::x86:
933 case llvm::Triple::x86_64:
934 PIC = true; // "-fPIC"
935 IsPICLevelTwo = true;
936 break;
937
938 default:
939 break;
940 }
941 }
942
943 // OpenBSD-specific defaults for PIE
944 if (Triple.getOS() == llvm::Triple::OpenBSD) {
945 switch (ToolChain.getArch()) {
Brad Smith3f2b1d72017-03-31 22:13:17 +0000946 case llvm::Triple::arm:
947 case llvm::Triple::aarch64:
David L. Jonesf561aba2017-03-08 01:02:16 +0000948 case llvm::Triple::mips64:
949 case llvm::Triple::mips64el:
David L. Jonesf561aba2017-03-08 01:02:16 +0000950 case llvm::Triple::x86:
951 case llvm::Triple::x86_64:
952 IsPICLevelTwo = false; // "-fpie"
953 break;
954
955 case llvm::Triple::ppc:
956 case llvm::Triple::sparc:
Brad Smith3f2b1d72017-03-31 22:13:17 +0000957 case llvm::Triple::sparcel:
David L. Jonesf561aba2017-03-08 01:02:16 +0000958 case llvm::Triple::sparcv9:
959 IsPICLevelTwo = true; // "-fPIE"
960 break;
961
962 default:
963 break;
964 }
965 }
966
Konstantin Zhuravlyovb4c83a02018-02-15 01:01:53 +0000967 // AMDGPU-specific defaults for PIC.
968 if (Triple.getArch() == llvm::Triple::amdgcn)
969 PIC = true;
970
David L. Jonesf561aba2017-03-08 01:02:16 +0000971 // The last argument relating to either PIC or PIE wins, and no
972 // other argument is used. If the last argument is any flavor of the
973 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
974 // option implicitly enables PIC at the same level.
975 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
976 options::OPT_fpic, options::OPT_fno_pic,
977 options::OPT_fPIE, options::OPT_fno_PIE,
978 options::OPT_fpie, options::OPT_fno_pie);
979 if (Triple.isOSWindows() && LastPICArg &&
980 LastPICArg ==
981 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
982 options::OPT_fPIE, options::OPT_fpie)) {
983 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
984 << LastPICArg->getSpelling() << Triple.str();
985 if (Triple.getArch() == llvm::Triple::x86_64)
986 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
987 return std::make_tuple(llvm::Reloc::Static, 0U, false);
988 }
989
990 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
991 // is forced, then neither PIC nor PIE flags will have no effect.
992 if (!ToolChain.isPICDefaultForced()) {
993 if (LastPICArg) {
994 Option O = LastPICArg->getOption();
995 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
996 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
997 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
998 PIC =
999 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1000 IsPICLevelTwo =
1001 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1002 } else {
1003 PIE = PIC = false;
1004 if (EffectiveTriple.isPS4CPU()) {
1005 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1006 StringRef Model = ModelArg ? ModelArg->getValue() : "";
1007 if (Model != "kernel") {
1008 PIC = true;
1009 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
1010 << LastPICArg->getSpelling();
1011 }
1012 }
1013 }
1014 }
1015 }
1016
1017 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
1018 // PIC level would've been set to level 1, force it back to level 2 PIC
1019 // instead.
1020 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
1021 IsPICLevelTwo |= ToolChain.isPICDefault();
1022
1023 // This kernel flags are a trump-card: they will disable PIC/PIE
1024 // generation, independent of the argument order.
1025 if (KernelOrKext &&
1026 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1027 !EffectiveTriple.isWatchOS()))
1028 PIC = PIE = false;
1029
1030 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1031 // This is a very special mode. It trumps the other modes, almost no one
1032 // uses it, and it isn't even valid on any OS but Darwin.
1033 if (!Triple.isOSDarwin())
1034 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1035 << A->getSpelling() << Triple.str();
1036
1037 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1038
1039 // Only a forced PIC mode can cause the actual compile to have PIC defines
1040 // etc., no flags are sufficient. This behavior was selected to closely
1041 // match that of llvm-gcc and Apple GCC before that.
1042 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1043
1044 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1045 }
1046
1047 bool EmbeddedPISupported;
1048 switch (Triple.getArch()) {
1049 case llvm::Triple::arm:
1050 case llvm::Triple::armeb:
1051 case llvm::Triple::thumb:
1052 case llvm::Triple::thumbeb:
1053 EmbeddedPISupported = true;
1054 break;
1055 default:
1056 EmbeddedPISupported = false;
1057 break;
1058 }
1059
1060 bool ROPI = false, RWPI = false;
1061 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1062 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1063 if (!EmbeddedPISupported)
1064 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1065 << LastROPIArg->getSpelling() << Triple.str();
1066 ROPI = true;
1067 }
1068 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1069 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1070 if (!EmbeddedPISupported)
1071 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1072 << LastRWPIArg->getSpelling() << Triple.str();
1073 RWPI = true;
1074 }
1075
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001076 // ROPI and RWPI are not compatible with PIC or PIE.
David L. Jonesf561aba2017-03-08 01:02:16 +00001077 if ((ROPI || RWPI) && (PIC || PIE))
1078 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1079
Alexander Richardson742553d2018-06-25 16:49:52 +00001080 if (Triple.isMIPS()) {
Aleksandar Beserminji20d603b2018-05-07 14:30:49 +00001081 StringRef CPUName;
1082 StringRef ABIName;
1083 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1084 // When targeting the N64 ABI, PIC is the default, except in the case
1085 // when the -mno-abicalls option is used. In that case we exit
1086 // at next check regardless of PIC being set below.
1087 if (ABIName == "n64")
1088 PIC = true;
Aleksandar Beserminji7ca42e82018-04-16 10:21:24 +00001089 // When targettng MIPS with -mno-abicalls, it's always static.
1090 if(Args.hasArg(options::OPT_mno_abicalls))
1091 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1092 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1093 // does not use PIC level 2 for historical reasons.
1094 IsPICLevelTwo = false;
1095 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001096
1097 if (PIC)
1098 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1099
1100 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1101 if (ROPI && RWPI)
1102 RelocM = llvm::Reloc::ROPI_RWPI;
1103 else if (ROPI)
1104 RelocM = llvm::Reloc::ROPI;
1105 else if (RWPI)
1106 RelocM = llvm::Reloc::RWPI;
1107
1108 return std::make_tuple(RelocM, 0U, false);
1109}
1110
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001111// `-falign-functions` indicates that the functions should be aligned to a
1112// 16-byte boundary.
1113//
1114// `-falign-functions=1` is the same as `-fno-align-functions`.
1115//
1116// The scalar `n` in `-falign-functions=n` must be an integral value between
1117// [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1118// the nearest power-of-two.
1119//
1120// If we return `0`, the frontend will default to the backend's preferred
1121// alignment.
1122//
1123// NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1124// to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1125// alignment. For unaligned functions, we default to the backend's preferred
1126// alignment.
1127unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1128 const ArgList &Args) {
1129 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1130 options::OPT_falign_functions_EQ,
1131 options::OPT_fno_align_functions);
1132 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1133 return 0;
1134
1135 if (A->getOption().matches(options::OPT_falign_functions))
1136 return 0;
1137
1138 unsigned Value = 0;
1139 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1140 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1141 << A->getAsString(Args) << A->getValue();
1142 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1143}
1144
David L. Jonesf561aba2017-03-08 01:02:16 +00001145void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1146 ArgStringList &CmdArgs) {
1147 llvm::Reloc::Model RelocationModel;
1148 unsigned PICLevel;
1149 bool IsPIE;
1150 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1151
1152 if (RelocationModel != llvm::Reloc::Static)
1153 CmdArgs.push_back("-KPIC");
1154}
1155
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001156/// Determine whether Objective-C automated reference counting is
David L. Jonesf561aba2017-03-08 01:02:16 +00001157/// enabled.
1158bool tools::isObjCAutoRefCount(const ArgList &Args) {
1159 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1160}
1161
1162static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1163 ArgStringList &CmdArgs, const ArgList &Args) {
1164 bool isAndroid = Triple.isAndroid();
1165 bool isCygMing = Triple.isOSCygMing();
1166 bool IsIAMCU = Triple.isOSIAMCU();
1167 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1168 Args.hasArg(options::OPT_static);
Sterling Augustine1c04e1f2018-08-31 17:59:03 +00001169
1170 // The driver ignores -shared-libgcc and therefore treats such cases as
1171 // unspecified. Breaking out the two variables as below makes the current
1172 // behavior explicit.
1173 bool UnspecifiedLibgcc = !StaticLibgcc;
1174 bool SharedLibgcc = !StaticLibgcc;
1175
1176 // Gcc adds libgcc arguments in various ways:
1177 //
1178 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
1179 // g++ <none>: -lgcc_s -lgcc
1180 // gcc shared: -lgcc_s -lgcc
1181 // g++ shared: -lgcc_s -lgcc
1182 // gcc static: -lgcc -lgcc_eh
1183 // g++ static: -lgcc -lgcc_eh
1184 //
1185 // Also, certain targets need additional adjustments.
1186
1187 bool LibGccFirst = (D.CCCIsCC() && UnspecifiedLibgcc) || StaticLibgcc;
1188 if (LibGccFirst)
David L. Jonesf561aba2017-03-08 01:02:16 +00001189 CmdArgs.push_back("-lgcc");
1190
Sterling Augustine1c04e1f2018-08-31 17:59:03 +00001191 bool AsNeeded = D.CCCIsCC() && !StaticLibgcc && !isAndroid && !isCygMing;
1192 if (AsNeeded)
1193 CmdArgs.push_back("--as-needed");
Sterling Augustinecbe4fc32018-08-30 20:07:23 +00001194
Sterling Augustine1c04e1f2018-08-31 17:59:03 +00001195 if ((UnspecifiedLibgcc || SharedLibgcc) && !isAndroid)
1196 CmdArgs.push_back("-lgcc_s");
1197
1198 else if (StaticLibgcc && !isAndroid && !IsIAMCU)
David L. Jonesf561aba2017-03-08 01:02:16 +00001199 CmdArgs.push_back("-lgcc_eh");
Sterling Augustine1c04e1f2018-08-31 17:59:03 +00001200
1201 if (AsNeeded)
1202 CmdArgs.push_back("--no-as-needed");
1203
1204 if (!LibGccFirst)
David L. Jonesf561aba2017-03-08 01:02:16 +00001205 CmdArgs.push_back("-lgcc");
1206
1207 // According to Android ABI, we have to link with libdl if we are
1208 // linking with non-static libgcc.
1209 //
1210 // NOTE: This fixes a link error on Android MIPS as well. The non-static
1211 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1212 if (isAndroid && !StaticLibgcc)
1213 CmdArgs.push_back("-ldl");
1214}
1215
1216void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1217 ArgStringList &CmdArgs, const ArgList &Args) {
1218 // Make use of compiler-rt if --rtlib option is used
1219 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1220
1221 switch (RLT) {
1222 case ToolChain::RLT_CompilerRT:
Sam Clegga08631e2017-10-27 00:26:07 +00001223 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001224 break;
1225 case ToolChain::RLT_Libgcc:
1226 // Make sure libgcc is not used under MSVC environment by default
1227 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1228 // Issue error diagnostic if libgcc is explicitly specified
1229 // through command line as --rtlib option argument.
1230 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1231 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1232 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1233 }
1234 } else
1235 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1236 break;
1237 }
1238}
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +00001239
1240/// Add OpenMP linker script arguments at the end of the argument list so that
1241/// the fat binary is built by embedding each of the device images into the
1242/// host. The linker script also defines a few symbols required by the code
1243/// generation so that the images can be easily retrieved at runtime by the
1244/// offloading library. This should be used only in tool chains that support
1245/// linker scripts.
1246void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1247 const InputInfo &Output,
1248 const InputInfoList &Inputs,
1249 const ArgList &Args, ArgStringList &CmdArgs,
1250 const JobAction &JA) {
1251
1252 // If this is not an OpenMP host toolchain, we don't need to do anything.
1253 if (!JA.isHostOffloading(Action::OFK_OpenMP))
1254 return;
1255
1256 // Create temporary linker script. Keep it if save-temps is enabled.
1257 const char *LKS;
1258 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1259 if (C.getDriver().isSaveTempsEnabled()) {
1260 llvm::sys::path::replace_extension(Name, "lk");
1261 LKS = C.getArgs().MakeArgString(Name.c_str());
1262 } else {
1263 llvm::sys::path::replace_extension(Name, "");
1264 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1265 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1266 }
1267
1268 // Add linker script option to the command.
1269 CmdArgs.push_back("-T");
1270 CmdArgs.push_back(LKS);
1271
1272 // Create a buffer to write the contents of the linker script.
1273 std::string LksBuffer;
1274 llvm::raw_string_ostream LksStream(LksBuffer);
1275
1276 // Get the OpenMP offload tool chains so that we can extract the triple
1277 // associated with each device input.
1278 auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1279 assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1280 "No OpenMP toolchains??");
1281
1282 // Track the input file name and device triple in order to build the script,
1283 // inserting binaries in the designated sections.
1284 SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1285
1286 // Add commands to embed target binaries. We ensure that each section and
1287 // image is 16-byte aligned. This is not mandatory, but increases the
1288 // likelihood of data to be aligned with a cache block in several main host
1289 // machines.
1290 LksStream << "/*\n";
1291 LksStream << " OpenMP Offload Linker Script\n";
1292 LksStream << " *** Automatically generated by Clang ***\n";
1293 LksStream << "*/\n";
1294 LksStream << "TARGET(binary)\n";
1295 auto DTC = OpenMPToolChains.first;
1296 for (auto &II : Inputs) {
1297 const Action *A = II.getAction();
1298 // Is this a device linking action?
1299 if (A && isa<LinkJobAction>(A) &&
1300 A->isDeviceOffloading(Action::OFK_OpenMP)) {
1301 assert(DTC != OpenMPToolChains.second &&
1302 "More device inputs than device toolchains??");
1303 InputBinaryInfo.push_back(std::make_pair(
1304 DTC->second->getTriple().normalize(), II.getFilename()));
1305 ++DTC;
1306 LksStream << "INPUT(" << II.getFilename() << ")\n";
1307 }
1308 }
1309
1310 assert(DTC == OpenMPToolChains.second &&
1311 "Less device inputs than device toolchains??");
1312
1313 LksStream << "SECTIONS\n";
1314 LksStream << "{\n";
1315
1316 // Put each target binary into a separate section.
1317 for (const auto &BI : InputBinaryInfo) {
1318 LksStream << " .omp_offloading." << BI.first << " :\n";
1319 LksStream << " ALIGN(0x10)\n";
1320 LksStream << " {\n";
1321 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1322 << " = .);\n";
1323 LksStream << " " << BI.second << "\n";
1324 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1325 << " = .);\n";
1326 LksStream << " }\n";
1327 }
1328
1329 // Add commands to define host entries begin and end. We use 1-byte subalign
1330 // so that the linker does not add any padding and the elements in this
1331 // section form an array.
1332 LksStream << " .omp_offloading.entries :\n";
1333 LksStream << " ALIGN(0x10)\n";
1334 LksStream << " SUBALIGN(0x01)\n";
1335 LksStream << " {\n";
1336 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1337 LksStream << " *(.omp_offloading.entries)\n";
1338 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1339 LksStream << " }\n";
1340 LksStream << "}\n";
1341 LksStream << "INSERT BEFORE .data\n";
1342 LksStream.flush();
1343
1344 // Dump the contents of the linker script if the user requested that. We
1345 // support this option to enable testing of behavior with -###.
1346 if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1347 llvm::errs() << LksBuffer;
1348
1349 // If this is a dry run, do not create the linker script file.
1350 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1351 return;
1352
1353 // Open script file and write the contents.
1354 std::error_code EC;
1355 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1356
1357 if (EC) {
1358 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1359 return;
1360 }
1361
1362 Lksf << LksBuffer;
1363}
Florian Hahn2e081d12018-04-20 12:50:10 +00001364
Yaxun Liu29155b02018-05-18 15:07:56 +00001365/// Add HIP linker script arguments at the end of the argument list so that
1366/// the fat binary is built by embedding the device images into the host. The
1367/// linker script also defines a symbol required by the code generation so that
1368/// the image can be retrieved at runtime. This should be used only in tool
1369/// chains that support linker scripts.
1370void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C,
1371 const InputInfo &Output,
1372 const InputInfoList &Inputs, const ArgList &Args,
1373 ArgStringList &CmdArgs, const JobAction &JA,
1374 const Tool &T) {
1375
1376 // If this is not a HIP host toolchain, we don't need to do anything.
1377 if (!JA.isHostOffloading(Action::OFK_HIP))
1378 return;
1379
Yaxun Liu97670892018-10-02 17:48:54 +00001380 InputInfoList DeviceInputs;
1381 for (const auto &II : Inputs) {
1382 const Action *A = II.getAction();
1383 // Is this a device linking action?
1384 if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) {
1385 DeviceInputs.push_back(II);
1386 }
1387 }
1388
1389 if (DeviceInputs.empty())
1390 return;
1391
Yaxun Liu29155b02018-05-18 15:07:56 +00001392 // Create temporary linker script. Keep it if save-temps is enabled.
1393 const char *LKS;
1394 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1395 if (C.getDriver().isSaveTempsEnabled()) {
1396 llvm::sys::path::replace_extension(Name, "lk");
1397 LKS = C.getArgs().MakeArgString(Name.c_str());
1398 } else {
1399 llvm::sys::path::replace_extension(Name, "");
1400 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1401 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1402 }
1403
1404 // Add linker script option to the command.
1405 CmdArgs.push_back("-T");
1406 CmdArgs.push_back(LKS);
1407
1408 // Create a buffer to write the contents of the linker script.
1409 std::string LksBuffer;
1410 llvm::raw_string_ostream LksStream(LksBuffer);
1411
1412 // Get the HIP offload tool chain.
1413 auto *HIPTC = static_cast<const toolchains::CudaToolChain *>(
1414 C.getSingleOffloadToolChain<Action::OFK_HIP>());
1415 assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn &&
1416 "Wrong platform");
Eric Liu7112fe62018-05-18 16:29:42 +00001417 (void)HIPTC;
Yaxun Liu29155b02018-05-18 15:07:56 +00001418
Yaxun Liu97670892018-10-02 17:48:54 +00001419 // The output file name needs to persist through the compilation, therefore
1420 // it needs to be created through MakeArgString.
1421 std::string BundleFileName = C.getDriver().GetTemporaryPath("BUNDLE", "hipfb");
Yaxun Liu29155b02018-05-18 15:07:56 +00001422 const char *BundleFile =
1423 C.addTempFile(C.getArgs().MakeArgString(BundleFileName.c_str()));
Yaxun Liu97670892018-10-02 17:48:54 +00001424 AMDGCN::constructHIPFatbinCommand(C, JA, BundleFile, DeviceInputs, Args, T);
Yaxun Liu29155b02018-05-18 15:07:56 +00001425
1426 // Add commands to embed target binaries. We ensure that each section and
1427 // image is 16-byte aligned. This is not mandatory, but increases the
1428 // likelihood of data to be aligned with a cache block in several main host
1429 // machines.
1430 LksStream << "/*\n";
1431 LksStream << " HIP Offload Linker Script\n";
1432 LksStream << " *** Automatically generated by Clang ***\n";
1433 LksStream << "*/\n";
1434 LksStream << "TARGET(binary)\n";
1435 LksStream << "INPUT(" << BundleFileName << ")\n";
1436 LksStream << "SECTIONS\n";
1437 LksStream << "{\n";
1438 LksStream << " .hip_fatbin :\n";
1439 LksStream << " ALIGN(0x10)\n";
1440 LksStream << " {\n";
1441 LksStream << " PROVIDE_HIDDEN(__hip_fatbin = .);\n";
1442 LksStream << " " << BundleFileName << "\n";
1443 LksStream << " }\n";
Yaxun Liu92a04832018-11-09 18:52:05 +00001444 LksStream << " /DISCARD/ :\n";
1445 LksStream << " {\n";
1446 LksStream << " * ( __CLANG_OFFLOAD_BUNDLE__* )\n";
1447 LksStream << " }\n";
Yaxun Liu29155b02018-05-18 15:07:56 +00001448 LksStream << "}\n";
1449 LksStream << "INSERT BEFORE .data\n";
1450 LksStream.flush();
1451
1452 // Dump the contents of the linker script if the user requested that. We
1453 // support this option to enable testing of behavior with -###.
1454 if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
1455 llvm::errs() << LksBuffer;
1456
1457 // If this is a dry run, do not create the linker script file.
1458 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1459 return;
1460
1461 // Open script file and write the contents.
1462 std::error_code EC;
1463 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1464
1465 if (EC) {
1466 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1467 return;
1468 }
1469
1470 Lksf << LksBuffer;
1471}
1472
Florian Hahn2e081d12018-04-20 12:50:10 +00001473SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1474 const InputInfo &Output,
1475 const InputInfo &Input,
1476 const Driver &D) {
1477 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1478 if (!A)
1479 return {};
1480
1481 StringRef SaveStats = A->getValue();
1482 SmallString<128> StatsFile;
1483 if (SaveStats == "obj" && Output.isFilename()) {
1484 StatsFile.assign(Output.getFilename());
1485 llvm::sys::path::remove_filename(StatsFile);
1486 } else if (SaveStats != "cwd") {
1487 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1488 return {};
1489 }
1490
1491 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1492 llvm::sys::path::append(StatsFile, BaseName);
1493 llvm::sys::path::replace_extension(StatsFile, "stats");
1494 return StatsFile;
1495}