blob: 02d64f87bfee28b7083983ed3ae79f73d2442fbd [file] [log] [blame]
David L. Jonesf561aba2017-03-08 01:02:16 +00001//===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "CommonArgs.h"
11#include "InputInfo.h"
12#include "Hexagon.h"
13#include "Arch/AArch64.h"
14#include "Arch/ARM.h"
15#include "Arch/Mips.h"
16#include "Arch/PPC.h"
17#include "Arch/SystemZ.h"
18#include "Arch/X86.h"
19#include "clang/Basic/CharInfo.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Basic/ObjCRuntime.h"
22#include "clang/Basic/Version.h"
23#include "clang/Basic/VirtualFileSystem.h"
24#include "clang/Config/config.h"
25#include "clang/Driver/Action.h"
26#include "clang/Driver/Compilation.h"
27#include "clang/Driver/Driver.h"
28#include "clang/Driver/DriverDiagnostic.h"
29#include "clang/Driver/Job.h"
30#include "clang/Driver/Options.h"
31#include "clang/Driver/SanitizerArgs.h"
32#include "clang/Driver/ToolChain.h"
33#include "clang/Driver/Util.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/ADT/StringSwitch.h"
38#include "llvm/ADT/Twine.h"
39#include "llvm/Option/Arg.h"
40#include "llvm/Option/ArgList.h"
41#include "llvm/Option/Option.h"
42#include "llvm/Support/CodeGen.h"
43#include "llvm/Support/Compression.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/FileSystem.h"
46#include "llvm/Support/Host.h"
47#include "llvm/Support/Path.h"
48#include "llvm/Support/Process.h"
49#include "llvm/Support/Program.h"
50#include "llvm/Support/ScopedPrinter.h"
51#include "llvm/Support/TargetParser.h"
52#include "llvm/Support/YAMLParser.h"
53
54using namespace clang::driver;
55using namespace clang::driver::tools;
56using namespace clang;
57using namespace llvm::opt;
58
59void tools::addPathIfExists(const Driver &D, const Twine &Path,
60 ToolChain::path_list &Paths) {
61 if (D.getVFS().exists(Path))
62 Paths.push_back(Path.str());
63}
64
65void tools::handleTargetFeaturesGroup(const ArgList &Args,
66 std::vector<StringRef> &Features,
67 OptSpecifier Group) {
68 for (const Arg *A : Args.filtered(Group)) {
69 StringRef Name = A->getOption().getName();
70 A->claim();
71
72 // Skip over "-m".
73 assert(Name.startswith("m") && "Invalid feature name.");
74 Name = Name.substr(1);
75
76 bool IsNegative = Name.startswith("no-");
77 if (IsNegative)
78 Name = Name.substr(3);
79 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
80 }
81}
82
83void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
84 const char *ArgName, const char *EnvVar) {
85 const char *DirList = ::getenv(EnvVar);
86 bool CombinedArg = false;
87
88 if (!DirList)
89 return; // Nothing to do.
90
91 StringRef Name(ArgName);
92 if (Name.equals("-I") || Name.equals("-L"))
93 CombinedArg = true;
94
95 StringRef Dirs(DirList);
96 if (Dirs.empty()) // Empty string should not add '.'.
97 return;
98
99 StringRef::size_type Delim;
100 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
101 if (Delim == 0) { // Leading colon.
102 if (CombinedArg) {
103 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
104 } else {
105 CmdArgs.push_back(ArgName);
106 CmdArgs.push_back(".");
107 }
108 } else {
109 if (CombinedArg) {
110 CmdArgs.push_back(
111 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
112 } else {
113 CmdArgs.push_back(ArgName);
114 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
115 }
116 }
117 Dirs = Dirs.substr(Delim + 1);
118 }
119
120 if (Dirs.empty()) { // Trailing colon.
121 if (CombinedArg) {
122 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
123 } else {
124 CmdArgs.push_back(ArgName);
125 CmdArgs.push_back(".");
126 }
127 } else { // Add the last path.
128 if (CombinedArg) {
129 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
130 } else {
131 CmdArgs.push_back(ArgName);
132 CmdArgs.push_back(Args.MakeArgString(Dirs));
133 }
134 }
135}
136
137void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
138 const ArgList &Args, ArgStringList &CmdArgs,
139 const JobAction &JA) {
140 const Driver &D = TC.getDriver();
141
142 // Add extra linker input arguments which are not treated as inputs
143 // (constructed via -Xarch_).
144 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
145
146 for (const auto &II : Inputs) {
147 // If the current tool chain refers to an OpenMP offloading host, we should
148 // ignore inputs that refer to OpenMP offloading devices - they will be
149 // embedded according to a proper linker script.
150 if (auto *IA = II.getAction())
151 if (JA.isHostOffloading(Action::OFK_OpenMP) &&
152 IA->isDeviceOffloading(Action::OFK_OpenMP))
153 continue;
154
155 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
156 // Don't try to pass LLVM inputs unless we have native support.
157 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
158
159 // Add filenames immediately.
160 if (II.isFilename()) {
161 CmdArgs.push_back(II.getFilename());
162 continue;
163 }
164
165 // Otherwise, this is a linker input argument.
166 const Arg &A = II.getInputArg();
167
168 // Handle reserved library options.
169 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
170 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
171 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
172 TC.AddCCKextLibArgs(Args, CmdArgs);
173 else if (A.getOption().matches(options::OPT_z)) {
174 // Pass -z prefix for gcc linker compatibility.
175 A.claim();
176 A.render(Args, CmdArgs);
177 } else {
178 A.renderAsInput(Args, CmdArgs);
179 }
180 }
181
182 // LIBRARY_PATH - included following the user specified library paths.
183 // and only supported on native toolchains.
184 if (!TC.isCrossCompiling()) {
185 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
186 }
187}
188
189void tools::AddTargetFeature(const ArgList &Args,
190 std::vector<StringRef> &Features,
191 OptSpecifier OnOpt, OptSpecifier OffOpt,
192 StringRef FeatureName) {
193 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
194 if (A->getOption().matches(OnOpt))
195 Features.push_back(Args.MakeArgString("+" + FeatureName));
196 else
197 Features.push_back(Args.MakeArgString("-" + FeatureName));
198 }
199}
200
201/// Get the (LLVM) name of the R600 gpu we are targeting.
202static std::string getR600TargetGPU(const ArgList &Args) {
203 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
204 const char *GPUName = A->getValue();
205 return llvm::StringSwitch<const char *>(GPUName)
206 .Cases("rv630", "rv635", "r600")
207 .Cases("rv610", "rv620", "rs780", "rs880")
208 .Case("rv740", "rv770")
209 .Case("palm", "cedar")
210 .Cases("sumo", "sumo2", "sumo")
211 .Case("hemlock", "cypress")
212 .Case("aruba", "cayman")
213 .Default(GPUName);
214 }
215 return "";
216}
217
Nikolai Bozhenov35d3c352017-06-27 09:48:24 +0000218static std::string getNios2TargetCPU(const ArgList &Args) {
219 Arg *A = Args.getLastArg(options::OPT_mcpu_EQ);
220 if (!A)
221 A = Args.getLastArg(options::OPT_march_EQ);
222
223 if (!A)
224 return "";
225
226 const char *name = A->getValue();
227 return llvm::StringSwitch<const char *>(name)
228 .Case("r1", "nios2r1")
229 .Case("r2", "nios2r2")
230 .Default(name);
231}
232
David L. Jonesf561aba2017-03-08 01:02:16 +0000233static std::string getLanaiTargetCPU(const ArgList &Args) {
234 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
235 return A->getValue();
236 }
237 return "";
238}
239
240/// Get the (LLVM) name of the WebAssembly cpu we are targeting.
241static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
242 // If we have -mcpu=, use that.
243 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
244 StringRef CPU = A->getValue();
245
246#ifdef __wasm__
247 // Handle "native" by examining the host. "native" isn't meaningful when
248 // cross compiling, so only support this when the host is also WebAssembly.
249 if (CPU == "native")
250 return llvm::sys::getHostCPUName();
251#endif
252
253 return CPU;
254 }
255
256 return "generic";
257}
258
259std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
260 bool FromAs) {
261 Arg *A;
262
263 switch (T.getArch()) {
264 default:
265 return "";
266
267 case llvm::Triple::aarch64:
268 case llvm::Triple::aarch64_be:
269 return aarch64::getAArch64TargetCPU(Args, A);
270
271 case llvm::Triple::arm:
272 case llvm::Triple::armeb:
273 case llvm::Triple::thumb:
274 case llvm::Triple::thumbeb: {
275 StringRef MArch, MCPU;
276 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
277 return arm::getARMTargetCPU(MCPU, MArch, T);
278 }
Leslie Zhaiff041092017-04-20 04:23:24 +0000279
280 case llvm::Triple::avr:
281 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
282 return A->getValue();
283 return "";
284
Nikolai Bozhenov35d3c352017-06-27 09:48:24 +0000285 case llvm::Triple::nios2: {
286 return getNios2TargetCPU(Args);
287 }
288
David L. Jonesf561aba2017-03-08 01:02:16 +0000289 case llvm::Triple::mips:
290 case llvm::Triple::mipsel:
291 case llvm::Triple::mips64:
292 case llvm::Triple::mips64el: {
293 StringRef CPUName;
294 StringRef ABIName;
295 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
296 return CPUName;
297 }
298
299 case llvm::Triple::nvptx:
300 case llvm::Triple::nvptx64:
301 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
302 return A->getValue();
303 return "";
304
305 case llvm::Triple::ppc:
306 case llvm::Triple::ppc64:
307 case llvm::Triple::ppc64le: {
308 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
309 // LLVM may default to generating code for the native CPU,
310 // but, like gcc, we default to a more generic option for
311 // each architecture. (except on Darwin)
312 if (TargetCPUName.empty() && !T.isOSDarwin()) {
313 if (T.getArch() == llvm::Triple::ppc64)
314 TargetCPUName = "ppc64";
315 else if (T.getArch() == llvm::Triple::ppc64le)
316 TargetCPUName = "ppc64le";
317 else
318 TargetCPUName = "ppc";
319 }
320 return TargetCPUName;
321 }
322
323 case llvm::Triple::sparc:
324 case llvm::Triple::sparcel:
325 case llvm::Triple::sparcv9:
326 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
327 return A->getValue();
328 return "";
329
330 case llvm::Triple::x86:
331 case llvm::Triple::x86_64:
332 return x86::getX86TargetCPU(Args, T);
333
334 case llvm::Triple::hexagon:
335 return "hexagon" +
336 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
337
338 case llvm::Triple::lanai:
339 return getLanaiTargetCPU(Args);
340
341 case llvm::Triple::systemz:
342 return systemz::getSystemZTargetCPU(Args);
343
344 case llvm::Triple::r600:
345 case llvm::Triple::amdgcn:
346 return getR600TargetGPU(Args);
347
348 case llvm::Triple::wasm32:
349 case llvm::Triple::wasm64:
350 return getWebAssemblyTargetCPU(Args);
351 }
352}
353
354unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
355 unsigned Parallelism = 0;
356 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
357 if (LtoJobsArg &&
358 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
359 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
360 << LtoJobsArg->getValue();
361 return Parallelism;
362}
363
364// CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
365// default.
366bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
367 return Triple.getOS() == llvm::Triple::CloudABI ||
368 Triple.getArch() == llvm::Triple::wasm32 ||
369 Triple.getArch() == llvm::Triple::wasm64;
370}
371
372void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
373 ArgStringList &CmdArgs, bool IsThinLTO,
374 const Driver &D) {
375 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
376 // as gold requires -plugin to come before any -plugin-opt that -Wl might
377 // forward.
378 CmdArgs.push_back("-plugin");
Dan Albert5671b892017-08-15 23:57:34 +0000379 std::string Plugin =
380 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
David L. Jonesf561aba2017-03-08 01:02:16 +0000381 CmdArgs.push_back(Args.MakeArgString(Plugin));
382
383 // Try to pass driver level flags relevant to LTO code generation down to
384 // the plugin.
385
386 // Handle flags for selecting CPU variants.
387 std::string CPU = getCPUName(Args, ToolChain.getTriple());
388 if (!CPU.empty())
389 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
390
391 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
392 StringRef OOpt;
393 if (A->getOption().matches(options::OPT_O4) ||
394 A->getOption().matches(options::OPT_Ofast))
395 OOpt = "3";
396 else if (A->getOption().matches(options::OPT_O))
397 OOpt = A->getValue();
398 else if (A->getOption().matches(options::OPT_O0))
399 OOpt = "0";
400 if (!OOpt.empty())
401 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
402 }
403
404 if (IsThinLTO)
405 CmdArgs.push_back("-plugin-opt=thinlto");
406
407 if (unsigned Parallelism = getLTOParallelism(Args, D))
408 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
409 llvm::to_string(Parallelism)));
410
411 // If an explicit debugger tuning argument appeared, pass it along.
412 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
413 options::OPT_ggdbN_Group)) {
414 if (A->getOption().matches(options::OPT_glldb))
415 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
416 else if (A->getOption().matches(options::OPT_gsce))
417 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
418 else
419 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
420 }
421
422 bool UseSeparateSections =
423 isUseSeparateSections(ToolChain.getEffectiveTriple());
424
425 if (Args.hasFlag(options::OPT_ffunction_sections,
426 options::OPT_fno_function_sections, UseSeparateSections)) {
427 CmdArgs.push_back("-plugin-opt=-function-sections");
428 }
429
430 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
431 UseSeparateSections)) {
432 CmdArgs.push_back("-plugin-opt=-data-sections");
433 }
434
Dehao Chenea4b78f2017-03-21 21:40:53 +0000435 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000436 StringRef FName = A->getValue();
437 if (!llvm::sys::fs::exists(FName))
438 D.Diag(diag::err_drv_no_such_file) << FName;
439 else
440 CmdArgs.push_back(
441 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
442 }
443}
444
445void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
446 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000447 std::string CandidateRPath = TC.getArchSpecificLibPath();
448 if (TC.getVFS().exists(CandidateRPath)) {
449 CmdArgs.push_back("-rpath");
450 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
451 }
452}
453
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000454bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
455 const ArgList &Args, bool IsOffloadingHost,
456 bool GompNeedsRT) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000457 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
458 options::OPT_fno_openmp, false))
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000459 return false;
David L. Jonesf561aba2017-03-08 01:02:16 +0000460
461 switch (TC.getDriver().getOpenMPRuntime(Args)) {
462 case Driver::OMPRT_OMP:
463 CmdArgs.push_back("-lomp");
464 break;
465 case Driver::OMPRT_GOMP:
466 CmdArgs.push_back("-lgomp");
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000467
468 if (GompNeedsRT)
469 CmdArgs.push_back("-lrt");
David L. Jonesf561aba2017-03-08 01:02:16 +0000470 break;
471 case Driver::OMPRT_IOMP5:
472 CmdArgs.push_back("-liomp5");
473 break;
474 case Driver::OMPRT_Unknown:
475 // Already diagnosed.
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000476 return false;
David L. Jonesf561aba2017-03-08 01:02:16 +0000477 }
478
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000479 if (IsOffloadingHost)
480 CmdArgs.push_back("-lomptarget");
481
David L. Jonesf561aba2017-03-08 01:02:16 +0000482 addArchSpecificRPath(TC, Args, CmdArgs);
Jonas Hahnfeld8ea76fa2017-04-19 13:55:39 +0000483
484 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +0000485}
486
487static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
488 ArgStringList &CmdArgs, StringRef Sanitizer,
489 bool IsShared, bool IsWhole) {
490 // Wrap any static runtimes that must be forced into executable in
491 // whole-archive.
492 if (IsWhole) CmdArgs.push_back("-whole-archive");
493 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
494 if (IsWhole) CmdArgs.push_back("-no-whole-archive");
495
496 if (IsShared) {
497 addArchSpecificRPath(TC, Args, CmdArgs);
498 }
499}
500
501// Tries to use a file with the list of dynamic symbols that need to be exported
502// from the runtime library. Returns true if the file was found.
503static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
504 ArgStringList &CmdArgs,
505 StringRef Sanitizer) {
506 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
507 if (llvm::sys::fs::exists(SanRT + ".syms")) {
508 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
509 return true;
510 }
511 return false;
512}
513
514void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
515 ArgStringList &CmdArgs) {
516 // Force linking against the system libraries sanitizers depends on
517 // (see PR15823 why this is necessary).
518 CmdArgs.push_back("--no-as-needed");
519 // There's no libpthread or librt on RTEMS.
520 if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
521 CmdArgs.push_back("-lpthread");
522 CmdArgs.push_back("-lrt");
523 }
524 CmdArgs.push_back("-lm");
525 // There's no libdl on FreeBSD or RTEMS.
526 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
Kamil Rytarowski2eef4752017-07-04 19:55:56 +0000527 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
David L. Jonesf561aba2017-03-08 01:02:16 +0000528 TC.getTriple().getOS() != llvm::Triple::RTEMS)
529 CmdArgs.push_back("-ldl");
530}
531
532static void
533collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
534 SmallVectorImpl<StringRef> &SharedRuntimes,
535 SmallVectorImpl<StringRef> &StaticRuntimes,
536 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
537 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
538 SmallVectorImpl<StringRef> &RequiredSymbols) {
539 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
540 // Collect shared runtimes.
541 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
542 SharedRuntimes.push_back("asan");
543 }
544 // The stats_client library is also statically linked into DSOs.
545 if (SanArgs.needsStatsRt())
546 StaticRuntimes.push_back("stats_client");
547
548 // Collect static runtimes.
549 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
550 // Don't link static runtimes into DSOs or if compiling for Android.
551 return;
552 }
553 if (SanArgs.needsAsanRt()) {
554 if (SanArgs.needsSharedAsanRt()) {
555 HelperStaticRuntimes.push_back("asan-preinit");
556 } else {
557 StaticRuntimes.push_back("asan");
558 if (SanArgs.linkCXXRuntimes())
559 StaticRuntimes.push_back("asan_cxx");
560 }
561 }
562 if (SanArgs.needsDfsanRt())
563 StaticRuntimes.push_back("dfsan");
564 if (SanArgs.needsLsanRt())
565 StaticRuntimes.push_back("lsan");
566 if (SanArgs.needsMsanRt()) {
567 StaticRuntimes.push_back("msan");
568 if (SanArgs.linkCXXRuntimes())
569 StaticRuntimes.push_back("msan_cxx");
570 }
571 if (SanArgs.needsTsanRt()) {
572 StaticRuntimes.push_back("tsan");
573 if (SanArgs.linkCXXRuntimes())
574 StaticRuntimes.push_back("tsan_cxx");
575 }
576 if (SanArgs.needsUbsanRt()) {
577 StaticRuntimes.push_back("ubsan_standalone");
578 if (SanArgs.linkCXXRuntimes())
579 StaticRuntimes.push_back("ubsan_standalone_cxx");
580 }
581 if (SanArgs.needsSafeStackRt()) {
582 NonWholeStaticRuntimes.push_back("safestack");
583 RequiredSymbols.push_back("__safestack_init");
584 }
585 if (SanArgs.needsCfiRt())
586 StaticRuntimes.push_back("cfi");
587 if (SanArgs.needsCfiDiagRt()) {
588 StaticRuntimes.push_back("cfi_diag");
589 if (SanArgs.linkCXXRuntimes())
590 StaticRuntimes.push_back("ubsan_standalone_cxx");
591 }
592 if (SanArgs.needsStatsRt()) {
593 NonWholeStaticRuntimes.push_back("stats");
594 RequiredSymbols.push_back("__sanitizer_stats_register");
595 }
596 if (SanArgs.needsEsanRt())
597 StaticRuntimes.push_back("esan");
598}
599
600// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
601// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
602bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
603 ArgStringList &CmdArgs) {
604 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
605 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
606 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
607 NonWholeStaticRuntimes, HelperStaticRuntimes,
608 RequiredSymbols);
George Karpenkov9f6f74c2017-08-21 23:25:19 +0000609
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000610 // Inject libfuzzer dependencies.
George Karpenkov2363fdd2017-06-29 19:52:33 +0000611 if (TC.getSanitizerArgs().needsFuzzer()
612 && !Args.hasArg(options::OPT_shared)) {
George Karpenkov9f6f74c2017-08-21 23:25:19 +0000613
614 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
615 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
616 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000617 }
618
David L. Jonesf561aba2017-03-08 01:02:16 +0000619 for (auto RT : SharedRuntimes)
620 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
621 for (auto RT : HelperStaticRuntimes)
622 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
623 bool AddExportDynamic = false;
624 for (auto RT : StaticRuntimes) {
625 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
626 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
627 }
628 for (auto RT : NonWholeStaticRuntimes) {
629 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
630 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
631 }
632 for (auto S : RequiredSymbols) {
633 CmdArgs.push_back("-u");
634 CmdArgs.push_back(Args.MakeArgString(S));
635 }
636 // If there is a static runtime with no dynamic list, force all the symbols
637 // to be dynamic to be sure we export sanitizer interface functions.
638 if (AddExportDynamic)
639 CmdArgs.push_back("-export-dynamic");
640
641 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
642 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
643 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
644
645 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
646}
647
648bool tools::areOptimizationsEnabled(const ArgList &Args) {
649 // Find the last -O arg and see if it is non-zero.
650 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
651 return !A->getOption().matches(options::OPT_O0);
652 // Defaults to -O0.
653 return false;
654}
655
656const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
657 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
658 if (FinalOutput && Args.hasArg(options::OPT_c)) {
659 SmallString<128> T(FinalOutput->getValue());
660 llvm::sys::path::replace_extension(T, "dwo");
661 return Args.MakeArgString(T);
662 } else {
663 // Use the compilation dir.
664 SmallString<128> T(
665 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
666 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
667 llvm::sys::path::replace_extension(F, "dwo");
668 T += F;
669 return Args.MakeArgString(F);
670 }
671}
672
673void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
674 const JobAction &JA, const ArgList &Args,
675 const InputInfo &Output, const char *OutFile) {
676 ArgStringList ExtractArgs;
677 ExtractArgs.push_back("--extract-dwo");
678
679 ArgStringList StripArgs;
680 StripArgs.push_back("--strip-dwo");
681
682 // Grabbing the output of the earlier compile step.
683 StripArgs.push_back(Output.getFilename());
684 ExtractArgs.push_back(Output.getFilename());
685 ExtractArgs.push_back(OutFile);
686
687 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
688 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
689
690 // First extract the dwo sections.
691 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
692
693 // Then remove them from the original .o file.
694 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
695}
696
697// Claim options we don't want to warn if they are unused. We do this for
698// options that build systems might add but are unused when assembling or only
699// running the preprocessor for example.
700void tools::claimNoWarnArgs(const ArgList &Args) {
701 // Don't warn about unused -f(no-)?lto. This can happen when we're
702 // preprocessing, precompiling or assembling.
703 Args.ClaimAllArgs(options::OPT_flto_EQ);
704 Args.ClaimAllArgs(options::OPT_flto);
705 Args.ClaimAllArgs(options::OPT_fno_lto);
706}
707
708Arg *tools::getLastProfileUseArg(const ArgList &Args) {
709 auto *ProfileUseArg = Args.getLastArg(
710 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
711 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
712 options::OPT_fno_profile_instr_use);
713
714 if (ProfileUseArg &&
715 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
716 ProfileUseArg = nullptr;
717
718 return ProfileUseArg;
719}
720
Dehao Chenea4b78f2017-03-21 21:40:53 +0000721Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
722 auto *ProfileSampleUseArg = Args.getLastArg(
723 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
724 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
725 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
726
727 if (ProfileSampleUseArg &&
728 (ProfileSampleUseArg->getOption().matches(
729 options::OPT_fno_profile_sample_use) ||
730 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
731 return nullptr;
732
733 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
734 options::OPT_fauto_profile_EQ);
735}
736
David L. Jonesf561aba2017-03-08 01:02:16 +0000737/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
738/// smooshes them together with platform defaults, to decide whether
739/// this compile should be using PIC mode or not. Returns a tuple of
740/// (RelocationModel, PICLevel, IsPIE).
741std::tuple<llvm::Reloc::Model, unsigned, bool>
742tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
743 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
744 const llvm::Triple &Triple = ToolChain.getTriple();
745
746 bool PIE = ToolChain.isPIEDefault();
747 bool PIC = PIE || ToolChain.isPICDefault();
748 // The Darwin/MachO default to use PIC does not apply when using -static.
749 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
750 PIE = PIC = false;
751 bool IsPICLevelTwo = PIC;
752
753 bool KernelOrKext =
754 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
755
756 // Android-specific defaults for PIC/PIE
757 if (Triple.isAndroid()) {
758 switch (Triple.getArch()) {
759 case llvm::Triple::arm:
760 case llvm::Triple::armeb:
761 case llvm::Triple::thumb:
762 case llvm::Triple::thumbeb:
763 case llvm::Triple::aarch64:
764 case llvm::Triple::mips:
765 case llvm::Triple::mipsel:
766 case llvm::Triple::mips64:
767 case llvm::Triple::mips64el:
768 PIC = true; // "-fpic"
769 break;
770
771 case llvm::Triple::x86:
772 case llvm::Triple::x86_64:
773 PIC = true; // "-fPIC"
774 IsPICLevelTwo = true;
775 break;
776
777 default:
778 break;
779 }
780 }
781
782 // OpenBSD-specific defaults for PIE
783 if (Triple.getOS() == llvm::Triple::OpenBSD) {
784 switch (ToolChain.getArch()) {
Brad Smith3f2b1d72017-03-31 22:13:17 +0000785 case llvm::Triple::arm:
786 case llvm::Triple::aarch64:
David L. Jonesf561aba2017-03-08 01:02:16 +0000787 case llvm::Triple::mips64:
788 case llvm::Triple::mips64el:
David L. Jonesf561aba2017-03-08 01:02:16 +0000789 case llvm::Triple::x86:
790 case llvm::Triple::x86_64:
791 IsPICLevelTwo = false; // "-fpie"
792 break;
793
794 case llvm::Triple::ppc:
795 case llvm::Triple::sparc:
Brad Smith3f2b1d72017-03-31 22:13:17 +0000796 case llvm::Triple::sparcel:
David L. Jonesf561aba2017-03-08 01:02:16 +0000797 case llvm::Triple::sparcv9:
798 IsPICLevelTwo = true; // "-fPIE"
799 break;
800
801 default:
802 break;
803 }
804 }
805
806 // The last argument relating to either PIC or PIE wins, and no
807 // other argument is used. If the last argument is any flavor of the
808 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
809 // option implicitly enables PIC at the same level.
810 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
811 options::OPT_fpic, options::OPT_fno_pic,
812 options::OPT_fPIE, options::OPT_fno_PIE,
813 options::OPT_fpie, options::OPT_fno_pie);
814 if (Triple.isOSWindows() && LastPICArg &&
815 LastPICArg ==
816 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
817 options::OPT_fPIE, options::OPT_fpie)) {
818 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
819 << LastPICArg->getSpelling() << Triple.str();
820 if (Triple.getArch() == llvm::Triple::x86_64)
821 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
822 return std::make_tuple(llvm::Reloc::Static, 0U, false);
823 }
824
825 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
826 // is forced, then neither PIC nor PIE flags will have no effect.
827 if (!ToolChain.isPICDefaultForced()) {
828 if (LastPICArg) {
829 Option O = LastPICArg->getOption();
830 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
831 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
832 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
833 PIC =
834 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
835 IsPICLevelTwo =
836 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
837 } else {
838 PIE = PIC = false;
839 if (EffectiveTriple.isPS4CPU()) {
840 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
841 StringRef Model = ModelArg ? ModelArg->getValue() : "";
842 if (Model != "kernel") {
843 PIC = true;
844 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
845 << LastPICArg->getSpelling();
846 }
847 }
848 }
849 }
850 }
851
852 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
853 // PIC level would've been set to level 1, force it back to level 2 PIC
854 // instead.
855 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
856 IsPICLevelTwo |= ToolChain.isPICDefault();
857
858 // This kernel flags are a trump-card: they will disable PIC/PIE
859 // generation, independent of the argument order.
860 if (KernelOrKext &&
861 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
862 !EffectiveTriple.isWatchOS()))
863 PIC = PIE = false;
864
865 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
866 // This is a very special mode. It trumps the other modes, almost no one
867 // uses it, and it isn't even valid on any OS but Darwin.
868 if (!Triple.isOSDarwin())
869 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
870 << A->getSpelling() << Triple.str();
871
872 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
873
874 // Only a forced PIC mode can cause the actual compile to have PIC defines
875 // etc., no flags are sufficient. This behavior was selected to closely
876 // match that of llvm-gcc and Apple GCC before that.
877 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
878
879 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
880 }
881
882 bool EmbeddedPISupported;
883 switch (Triple.getArch()) {
884 case llvm::Triple::arm:
885 case llvm::Triple::armeb:
886 case llvm::Triple::thumb:
887 case llvm::Triple::thumbeb:
888 EmbeddedPISupported = true;
889 break;
890 default:
891 EmbeddedPISupported = false;
892 break;
893 }
894
895 bool ROPI = false, RWPI = false;
896 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
897 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
898 if (!EmbeddedPISupported)
899 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
900 << LastROPIArg->getSpelling() << Triple.str();
901 ROPI = true;
902 }
903 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
904 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
905 if (!EmbeddedPISupported)
906 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
907 << LastRWPIArg->getSpelling() << Triple.str();
908 RWPI = true;
909 }
910
911 // ROPI and RWPI are not comaptible with PIC or PIE.
912 if ((ROPI || RWPI) && (PIC || PIE))
913 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
914
915 // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
916 // used.
917 if ((Triple.getArch() == llvm::Triple::mips64 ||
918 Triple.getArch() == llvm::Triple::mips64el) &&
919 Args.hasArg(options::OPT_mno_abicalls))
920 return std::make_tuple(llvm::Reloc::Static, 0U, false);
921
922 if (PIC)
923 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
924
925 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
926 if (ROPI && RWPI)
927 RelocM = llvm::Reloc::ROPI_RWPI;
928 else if (ROPI)
929 RelocM = llvm::Reloc::ROPI;
930 else if (RWPI)
931 RelocM = llvm::Reloc::RWPI;
932
933 return std::make_tuple(RelocM, 0U, false);
934}
935
936void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
937 ArgStringList &CmdArgs) {
938 llvm::Reloc::Model RelocationModel;
939 unsigned PICLevel;
940 bool IsPIE;
941 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
942
943 if (RelocationModel != llvm::Reloc::Static)
944 CmdArgs.push_back("-KPIC");
945}
946
947/// \brief Determine whether Objective-C automated reference counting is
948/// enabled.
949bool tools::isObjCAutoRefCount(const ArgList &Args) {
950 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
951}
952
953static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
954 ArgStringList &CmdArgs, const ArgList &Args) {
955 bool isAndroid = Triple.isAndroid();
956 bool isCygMing = Triple.isOSCygMing();
957 bool IsIAMCU = Triple.isOSIAMCU();
958 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
959 Args.hasArg(options::OPT_static);
960 if (!D.CCCIsCXX())
961 CmdArgs.push_back("-lgcc");
962
963 if (StaticLibgcc || isAndroid) {
964 if (D.CCCIsCXX())
965 CmdArgs.push_back("-lgcc");
966 } else {
967 if (!D.CCCIsCXX() && !isCygMing)
968 CmdArgs.push_back("--as-needed");
969 CmdArgs.push_back("-lgcc_s");
970 if (!D.CCCIsCXX() && !isCygMing)
971 CmdArgs.push_back("--no-as-needed");
972 }
973
974 if (StaticLibgcc && !isAndroid && !IsIAMCU)
975 CmdArgs.push_back("-lgcc_eh");
976 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
977 CmdArgs.push_back("-lgcc");
978
979 // According to Android ABI, we have to link with libdl if we are
980 // linking with non-static libgcc.
981 //
982 // NOTE: This fixes a link error on Android MIPS as well. The non-static
983 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
984 if (isAndroid && !StaticLibgcc)
985 CmdArgs.push_back("-ldl");
986}
987
988void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
989 ArgStringList &CmdArgs, const ArgList &Args) {
990 // Make use of compiler-rt if --rtlib option is used
991 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
992
993 switch (RLT) {
994 case ToolChain::RLT_CompilerRT:
995 switch (TC.getTriple().getOS()) {
996 default:
997 llvm_unreachable("unsupported OS");
998 case llvm::Triple::Win32:
999 case llvm::Triple::Linux:
1000 case llvm::Triple::Fuchsia:
1001 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1002 break;
1003 }
1004 break;
1005 case ToolChain::RLT_Libgcc:
1006 // Make sure libgcc is not used under MSVC environment by default
1007 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1008 // Issue error diagnostic if libgcc is explicitly specified
1009 // through command line as --rtlib option argument.
1010 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1011 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1012 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1013 }
1014 } else
1015 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1016 break;
1017 }
1018}
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +00001019
1020/// Add OpenMP linker script arguments at the end of the argument list so that
1021/// the fat binary is built by embedding each of the device images into the
1022/// host. The linker script also defines a few symbols required by the code
1023/// generation so that the images can be easily retrieved at runtime by the
1024/// offloading library. This should be used only in tool chains that support
1025/// linker scripts.
1026void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1027 const InputInfo &Output,
1028 const InputInfoList &Inputs,
1029 const ArgList &Args, ArgStringList &CmdArgs,
1030 const JobAction &JA) {
1031
1032 // If this is not an OpenMP host toolchain, we don't need to do anything.
1033 if (!JA.isHostOffloading(Action::OFK_OpenMP))
1034 return;
1035
1036 // Create temporary linker script. Keep it if save-temps is enabled.
1037 const char *LKS;
1038 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1039 if (C.getDriver().isSaveTempsEnabled()) {
1040 llvm::sys::path::replace_extension(Name, "lk");
1041 LKS = C.getArgs().MakeArgString(Name.c_str());
1042 } else {
1043 llvm::sys::path::replace_extension(Name, "");
1044 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1045 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1046 }
1047
1048 // Add linker script option to the command.
1049 CmdArgs.push_back("-T");
1050 CmdArgs.push_back(LKS);
1051
1052 // Create a buffer to write the contents of the linker script.
1053 std::string LksBuffer;
1054 llvm::raw_string_ostream LksStream(LksBuffer);
1055
1056 // Get the OpenMP offload tool chains so that we can extract the triple
1057 // associated with each device input.
1058 auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1059 assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1060 "No OpenMP toolchains??");
1061
1062 // Track the input file name and device triple in order to build the script,
1063 // inserting binaries in the designated sections.
1064 SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1065
1066 // Add commands to embed target binaries. We ensure that each section and
1067 // image is 16-byte aligned. This is not mandatory, but increases the
1068 // likelihood of data to be aligned with a cache block in several main host
1069 // machines.
1070 LksStream << "/*\n";
1071 LksStream << " OpenMP Offload Linker Script\n";
1072 LksStream << " *** Automatically generated by Clang ***\n";
1073 LksStream << "*/\n";
1074 LksStream << "TARGET(binary)\n";
1075 auto DTC = OpenMPToolChains.first;
1076 for (auto &II : Inputs) {
1077 const Action *A = II.getAction();
1078 // Is this a device linking action?
1079 if (A && isa<LinkJobAction>(A) &&
1080 A->isDeviceOffloading(Action::OFK_OpenMP)) {
1081 assert(DTC != OpenMPToolChains.second &&
1082 "More device inputs than device toolchains??");
1083 InputBinaryInfo.push_back(std::make_pair(
1084 DTC->second->getTriple().normalize(), II.getFilename()));
1085 ++DTC;
1086 LksStream << "INPUT(" << II.getFilename() << ")\n";
1087 }
1088 }
1089
1090 assert(DTC == OpenMPToolChains.second &&
1091 "Less device inputs than device toolchains??");
1092
1093 LksStream << "SECTIONS\n";
1094 LksStream << "{\n";
1095
1096 // Put each target binary into a separate section.
1097 for (const auto &BI : InputBinaryInfo) {
1098 LksStream << " .omp_offloading." << BI.first << " :\n";
1099 LksStream << " ALIGN(0x10)\n";
1100 LksStream << " {\n";
1101 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1102 << " = .);\n";
1103 LksStream << " " << BI.second << "\n";
1104 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1105 << " = .);\n";
1106 LksStream << " }\n";
1107 }
1108
1109 // Add commands to define host entries begin and end. We use 1-byte subalign
1110 // so that the linker does not add any padding and the elements in this
1111 // section form an array.
1112 LksStream << " .omp_offloading.entries :\n";
1113 LksStream << " ALIGN(0x10)\n";
1114 LksStream << " SUBALIGN(0x01)\n";
1115 LksStream << " {\n";
1116 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1117 LksStream << " *(.omp_offloading.entries)\n";
1118 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1119 LksStream << " }\n";
1120 LksStream << "}\n";
1121 LksStream << "INSERT BEFORE .data\n";
1122 LksStream.flush();
1123
1124 // Dump the contents of the linker script if the user requested that. We
1125 // support this option to enable testing of behavior with -###.
1126 if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1127 llvm::errs() << LksBuffer;
1128
1129 // If this is a dry run, do not create the linker script file.
1130 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1131 return;
1132
1133 // Open script file and write the contents.
1134 std::error_code EC;
1135 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1136
1137 if (EC) {
1138 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1139 return;
1140 }
1141
1142 Lksf << LksBuffer;
1143}