1 //===--- 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 "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"
17 #include "HIP.h"
18 #include "Hexagon.h"
19 #include "InputInfo.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/ObjCRuntime.h"
23 #include "clang/Basic/Version.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 "clang/Driver/XRayArgs.h"
35 #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"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/Process.h"
51 #include "llvm/Support/Program.h"
52 #include "llvm/Support/ScopedPrinter.h"
53 #include "llvm/Support/TargetParser.h"
54 #include "llvm/Support/VirtualFileSystem.h"
55 #include "llvm/Support/YAMLParser.h"
56
57 using namespace clang::driver;
58 using namespace clang::driver::tools;
59 using namespace clang;
60 using namespace llvm::opt;
61
addPathIfExists(const Driver & D,const Twine & Path,ToolChain::path_list & Paths)62 void 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
handleTargetFeaturesGroup(const ArgList & Args,std::vector<StringRef> & Features,OptSpecifier Group)68 void 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
addDirectoryList(const ArgList & Args,ArgStringList & CmdArgs,const char * ArgName,const char * EnvVar)86 void 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
AddLinkerInputs(const ToolChain & TC,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)140 void 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) {
150 // 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.
153 if (auto *IA = II.getAction())
154 if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
155 IA->isDeviceOffloading(Action::OFK_OpenMP)) ||
156 (JA.isHostOffloading(Action::OFK_HIP) &&
157 IA->isDeviceOffloading(Action::OFK_HIP)))
158 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()) {
166 CmdArgs.push_back(II.getFilename());
167 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
AddTargetFeature(const ArgList & Args,std::vector<StringRef> & Features,OptSpecifier OnOpt,OptSpecifier OffOpt,StringRef FeatureName)194 void 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.
getR600TargetGPU(const ArgList & Args)207 static 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
getLanaiTargetCPU(const ArgList & Args)223 static std::string getLanaiTargetCPU(const ArgList &Args) {
224 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
225 return A->getValue();
226 }
227 return "";
228 }
229
230 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
getWebAssemblyTargetCPU(const ArgList & Args)231 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
232 // If we have -mcpu=, use that.
233 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
234 StringRef CPU = A->getValue();
235
236 #ifdef __wasm__
237 // Handle "native" by examining the host. "native" isn't meaningful when
238 // cross compiling, so only support this when the host is also WebAssembly.
239 if (CPU == "native")
240 return llvm::sys::getHostCPUName();
241 #endif
242
243 return CPU;
244 }
245
246 return "generic";
247 }
248
getCPUName(const ArgList & Args,const llvm::Triple & T,bool FromAs)249 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
250 bool FromAs) {
251 Arg *A;
252
253 switch (T.getArch()) {
254 default:
255 return "";
256
257 case llvm::Triple::aarch64:
258 case llvm::Triple::aarch64_be:
259 return aarch64::getAArch64TargetCPU(Args, T, A);
260
261 case llvm::Triple::arm:
262 case llvm::Triple::armeb:
263 case llvm::Triple::thumb:
264 case llvm::Triple::thumbeb: {
265 StringRef MArch, MCPU;
266 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
267 return arm::getARMTargetCPU(MCPU, MArch, T);
268 }
269
270 case llvm::Triple::avr:
271 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
272 return A->getValue();
273 return "";
274
275 case llvm::Triple::mips:
276 case llvm::Triple::mipsel:
277 case llvm::Triple::mips64:
278 case llvm::Triple::mips64el: {
279 StringRef CPUName;
280 StringRef ABIName;
281 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
282 return CPUName;
283 }
284
285 case llvm::Triple::nvptx:
286 case llvm::Triple::nvptx64:
287 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
288 return A->getValue();
289 return "";
290
291 case llvm::Triple::ppc:
292 case llvm::Triple::ppc64:
293 case llvm::Triple::ppc64le: {
294 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
295 // LLVM may default to generating code for the native CPU,
296 // but, like gcc, we default to a more generic option for
297 // each architecture. (except on Darwin)
298 if (TargetCPUName.empty() && !T.isOSDarwin()) {
299 if (T.getArch() == llvm::Triple::ppc64)
300 TargetCPUName = "ppc64";
301 else if (T.getArch() == llvm::Triple::ppc64le)
302 TargetCPUName = "ppc64le";
303 else
304 TargetCPUName = "ppc";
305 }
306 return TargetCPUName;
307 }
308
309 case llvm::Triple::bpfel:
310 case llvm::Triple::bpfeb:
311 case llvm::Triple::sparc:
312 case llvm::Triple::sparcel:
313 case llvm::Triple::sparcv9:
314 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
315 return A->getValue();
316 return "";
317
318 case llvm::Triple::x86:
319 case llvm::Triple::x86_64:
320 return x86::getX86TargetCPU(Args, T);
321
322 case llvm::Triple::hexagon:
323 return "hexagon" +
324 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
325
326 case llvm::Triple::lanai:
327 return getLanaiTargetCPU(Args);
328
329 case llvm::Triple::systemz:
330 return systemz::getSystemZTargetCPU(Args);
331
332 case llvm::Triple::r600:
333 case llvm::Triple::amdgcn:
334 return getR600TargetGPU(Args);
335
336 case llvm::Triple::wasm32:
337 case llvm::Triple::wasm64:
338 return getWebAssemblyTargetCPU(Args);
339 }
340 }
341
getLTOParallelism(const ArgList & Args,const Driver & D)342 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
343 unsigned Parallelism = 0;
344 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
345 if (LtoJobsArg &&
346 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
347 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
348 << LtoJobsArg->getValue();
349 return Parallelism;
350 }
351
352 // CloudABI uses -ffunction-sections and -fdata-sections by default.
isUseSeparateSections(const llvm::Triple & Triple)353 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
354 return Triple.getOS() == llvm::Triple::CloudABI;
355 }
356
AddGoldPlugin(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfo & Input,bool IsThinLTO)357 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
358 ArgStringList &CmdArgs, const InputInfo &Output,
359 const InputInfo &Input, bool IsThinLTO) {
360 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
361 // as gold requires -plugin to come before any -plugin-opt that -Wl might
362 // forward.
363 CmdArgs.push_back("-plugin");
364
365 #if defined(_WIN32)
366 const char *Suffix = ".dll";
367 #elif defined(__APPLE__)
368 const char *Suffix = ".dylib";
369 #else
370 const char *Suffix = ".so";
371 #endif
372
373 SmallString<1024> Plugin;
374 llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
375 "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
376 Suffix,
377 Plugin);
378 CmdArgs.push_back(Args.MakeArgString(Plugin));
379
380 // Try to pass driver level flags relevant to LTO code generation down to
381 // the plugin.
382
383 // Handle flags for selecting CPU variants.
384 std::string CPU = getCPUName(Args, ToolChain.getTriple());
385 if (!CPU.empty())
386 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
387
388 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
389 StringRef OOpt;
390 if (A->getOption().matches(options::OPT_O4) ||
391 A->getOption().matches(options::OPT_Ofast))
392 OOpt = "3";
393 else if (A->getOption().matches(options::OPT_O))
394 OOpt = A->getValue();
395 else if (A->getOption().matches(options::OPT_O0))
396 OOpt = "0";
397 if (!OOpt.empty())
398 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
399 }
400
401 if (Args.hasArg(options::OPT_gsplit_dwarf)) {
402 CmdArgs.push_back(
403 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
404 Output.getFilename() + "_dwo"));
405 }
406
407 if (IsThinLTO)
408 CmdArgs.push_back("-plugin-opt=thinlto");
409
410 if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver()))
411 CmdArgs.push_back(
412 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
413
414 // If an explicit debugger tuning argument appeared, pass it along.
415 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
416 options::OPT_ggdbN_Group)) {
417 if (A->getOption().matches(options::OPT_glldb))
418 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
419 else if (A->getOption().matches(options::OPT_gsce))
420 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
421 else
422 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
423 }
424
425 bool UseSeparateSections =
426 isUseSeparateSections(ToolChain.getEffectiveTriple());
427
428 if (Args.hasFlag(options::OPT_ffunction_sections,
429 options::OPT_fno_function_sections, UseSeparateSections)) {
430 CmdArgs.push_back("-plugin-opt=-function-sections");
431 }
432
433 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
434 UseSeparateSections)) {
435 CmdArgs.push_back("-plugin-opt=-data-sections");
436 }
437
438 if (Arg *A = getLastProfileSampleUseArg(Args)) {
439 StringRef FName = A->getValue();
440 if (!llvm::sys::fs::exists(FName))
441 ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName;
442 else
443 CmdArgs.push_back(
444 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
445 }
446
447 // Need this flag to turn on new pass manager via Gold plugin.
448 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
449 options::OPT_fno_experimental_new_pass_manager,
450 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
451 CmdArgs.push_back("-plugin-opt=new-pass-manager");
452 }
453
454 // Setup statistics file output.
455 SmallString<128> StatsFile =
456 getStatsFileName(Args, Output, Input, ToolChain.getDriver());
457 if (!StatsFile.empty())
458 CmdArgs.push_back(
459 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
460 }
461
addArchSpecificRPath(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)462 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
463 ArgStringList &CmdArgs) {
464 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
465 options::OPT_fno_rtlib_add_rpath, false))
466 return;
467
468 std::string CandidateRPath = TC.getArchSpecificLibPath();
469 if (TC.getVFS().exists(CandidateRPath)) {
470 CmdArgs.push_back("-rpath");
471 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
472 }
473 }
474
addOpenMPRuntime(ArgStringList & CmdArgs,const ToolChain & TC,const ArgList & Args,bool IsOffloadingHost,bool GompNeedsRT)475 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
476 const ArgList &Args, bool IsOffloadingHost,
477 bool GompNeedsRT) {
478 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
479 options::OPT_fno_openmp, false))
480 return false;
481
482 switch (TC.getDriver().getOpenMPRuntime(Args)) {
483 case Driver::OMPRT_OMP:
484 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD || TC.isCrossCompiling() || !llvm::sys::fs::exists("/usr/local/llvm80/lib/libomp.so"))
485 CmdArgs.push_back("-lomp");
486 else
487 CmdArgs.push_back("/usr/local/llvm80/lib/libomp.so");
488 break;
489 case Driver::OMPRT_GOMP:
490 CmdArgs.push_back("-lgomp");
491
492 if (GompNeedsRT)
493 CmdArgs.push_back("-lrt");
494 break;
495 case Driver::OMPRT_IOMP5:
496 CmdArgs.push_back("-liomp5");
497 break;
498 case Driver::OMPRT_Unknown:
499 // Already diagnosed.
500 return false;
501 }
502
503 if (IsOffloadingHost)
504 CmdArgs.push_back("-lomptarget");
505
506 addArchSpecificRPath(TC, Args, CmdArgs);
507
508 return true;
509 }
510
addSanitizerRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer,bool IsShared,bool IsWhole)511 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
512 ArgStringList &CmdArgs, StringRef Sanitizer,
513 bool IsShared, bool IsWhole) {
514 // Wrap any static runtimes that must be forced into executable in
515 // whole-archive.
516 if (IsWhole) CmdArgs.push_back("--whole-archive");
517 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
518 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
519
520 if (IsShared) {
521 addArchSpecificRPath(TC, Args, CmdArgs);
522 }
523 }
524
525 // Tries to use a file with the list of dynamic symbols that need to be exported
526 // from the runtime library. Returns true if the file was found.
addSanitizerDynamicList(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer)527 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
528 ArgStringList &CmdArgs,
529 StringRef Sanitizer) {
530 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
531 // the option, so don't try to pass it.
532 if (TC.getTriple().getOS() == llvm::Triple::Solaris)
533 return true;
534 // Myriad is static linking only. Furthermore, some versions of its
535 // linker have the bug where --export-dynamic overrides -static, so
536 // don't use --export-dynamic on that platform.
537 if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
538 return true;
539 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
540 if (llvm::sys::fs::exists(SanRT + ".syms")) {
541 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
542 return true;
543 }
544 return false;
545 }
546
addSanitizerLibPath(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Name)547 static void addSanitizerLibPath(const ToolChain &TC, const ArgList &Args,
548 ArgStringList &CmdArgs, StringRef Name) {
549 for (const auto &LibPath : TC.getLibraryPaths()) {
550 if (!LibPath.empty()) {
551 SmallString<128> P(LibPath);
552 llvm::sys::path::append(P, Name);
553 if (TC.getVFS().exists(P))
554 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
555 }
556 }
557 }
558
addSanitizerPathLibArgs(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)559 void tools::addSanitizerPathLibArgs(const ToolChain &TC, const ArgList &Args,
560 ArgStringList &CmdArgs) {
561 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
562 if (SanArgs.needsAsanRt()) {
563 addSanitizerLibPath(TC, Args, CmdArgs, "asan");
564 }
565 if (SanArgs.needsHwasanRt()) {
566 addSanitizerLibPath(TC, Args, CmdArgs, "hwasan");
567 }
568 if (SanArgs.needsLsanRt()) {
569 addSanitizerLibPath(TC, Args, CmdArgs, "lsan");
570 }
571 if (SanArgs.needsMsanRt()) {
572 addSanitizerLibPath(TC, Args, CmdArgs, "msan");
573 }
574 if (SanArgs.needsTsanRt()) {
575 addSanitizerLibPath(TC, Args, CmdArgs, "tsan");
576 }
577 }
578
579
580
linkSanitizerRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)581 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
582 ArgStringList &CmdArgs) {
583 // Force linking against the system libraries sanitizers depends on
584 // (see PR15823 why this is necessary).
585 CmdArgs.push_back("--no-as-needed");
586 // There's no libpthread or librt on RTEMS & Android.
587 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
588 !TC.getTriple().isAndroid()) {
589 CmdArgs.push_back("-lpthread");
590 if (!TC.getTriple().isOSOpenBSD())
591 CmdArgs.push_back("-lrt");
592 }
593 CmdArgs.push_back("-lm");
594 // There's no libdl on all OSes.
595 if (!TC.getTriple().isOSFreeBSD() &&
596 !TC.getTriple().isOSNetBSD() &&
597 !TC.getTriple().isOSOpenBSD() &&
598 TC.getTriple().getOS() != llvm::Triple::RTEMS)
599 CmdArgs.push_back("-ldl");
600 // Required for backtrace on some OSes
601 if (TC.getTriple().isOSFreeBSD() ||
602 TC.getTriple().isOSNetBSD())
603 CmdArgs.push_back("-lexecinfo");
604 }
605
606 static void
collectSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,SmallVectorImpl<StringRef> & SharedRuntimes,SmallVectorImpl<StringRef> & StaticRuntimes,SmallVectorImpl<StringRef> & NonWholeStaticRuntimes,SmallVectorImpl<StringRef> & HelperStaticRuntimes,SmallVectorImpl<StringRef> & RequiredSymbols)607 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
608 SmallVectorImpl<StringRef> &SharedRuntimes,
609 SmallVectorImpl<StringRef> &StaticRuntimes,
610 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
611 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
612 SmallVectorImpl<StringRef> &RequiredSymbols) {
613 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
614 // Collect shared runtimes.
615 if (SanArgs.needsSharedRt()) {
616 if (SanArgs.needsAsanRt()) {
617 SharedRuntimes.push_back("asan");
618 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
619 HelperStaticRuntimes.push_back("asan-preinit");
620 }
621 if (SanArgs.needsUbsanRt()) {
622 if (SanArgs.requiresMinimalRuntime())
623 SharedRuntimes.push_back("ubsan_minimal");
624 else
625 SharedRuntimes.push_back("ubsan_standalone");
626 }
627 if (SanArgs.needsScudoRt()) {
628 if (SanArgs.requiresMinimalRuntime())
629 SharedRuntimes.push_back("scudo_minimal");
630 else
631 SharedRuntimes.push_back("scudo");
632 }
633 if (SanArgs.needsHwasanRt())
634 SharedRuntimes.push_back("hwasan");
635 }
636
637 // The stats_client library is also statically linked into DSOs.
638 if (SanArgs.needsStatsRt())
639 StaticRuntimes.push_back("stats_client");
640
641 // Collect static runtimes.
642 if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
643 // Don't link static runtimes into DSOs or if -shared-libasan.
644 return;
645 }
646 if (SanArgs.needsAsanRt()) {
647 StaticRuntimes.push_back("asan");
648 if (SanArgs.linkCXXRuntimes())
649 StaticRuntimes.push_back("asan_cxx");
650 }
651
652 if (SanArgs.needsHwasanRt()) {
653 StaticRuntimes.push_back("hwasan");
654 if (SanArgs.linkCXXRuntimes())
655 StaticRuntimes.push_back("hwasan_cxx");
656 }
657 if (SanArgs.needsDfsanRt())
658 StaticRuntimes.push_back("dfsan");
659 if (SanArgs.needsLsanRt())
660 StaticRuntimes.push_back("lsan");
661 if (SanArgs.needsMsanRt()) {
662 StaticRuntimes.push_back("msan");
663 if (SanArgs.linkCXXRuntimes())
664 StaticRuntimes.push_back("msan_cxx");
665 }
666 if (SanArgs.needsTsanRt()) {
667 StaticRuntimes.push_back("tsan");
668 if (SanArgs.linkCXXRuntimes())
669 StaticRuntimes.push_back("tsan_cxx");
670 }
671 if (SanArgs.needsUbsanRt()) {
672 if (SanArgs.requiresMinimalRuntime()) {
673 StaticRuntimes.push_back("ubsan_minimal");
674 } else {
675 StaticRuntimes.push_back("ubsan_standalone");
676 if (SanArgs.linkCXXRuntimes())
677 StaticRuntimes.push_back("ubsan_standalone_cxx");
678 }
679 }
680 if (SanArgs.needsSafeStackRt()) {
681 NonWholeStaticRuntimes.push_back("safestack");
682 RequiredSymbols.push_back("__safestack_init");
683 }
684 if (SanArgs.needsCfiRt())
685 StaticRuntimes.push_back("cfi");
686 if (SanArgs.needsCfiDiagRt()) {
687 StaticRuntimes.push_back("cfi_diag");
688 if (SanArgs.linkCXXRuntimes())
689 StaticRuntimes.push_back("ubsan_standalone_cxx");
690 }
691 if (SanArgs.needsStatsRt()) {
692 NonWholeStaticRuntimes.push_back("stats");
693 RequiredSymbols.push_back("__sanitizer_stats_register");
694 }
695 if (SanArgs.needsEsanRt())
696 StaticRuntimes.push_back("esan");
697 if (SanArgs.needsScudoRt()) {
698 if (SanArgs.requiresMinimalRuntime()) {
699 StaticRuntimes.push_back("scudo_minimal");
700 if (SanArgs.linkCXXRuntimes())
701 StaticRuntimes.push_back("scudo_cxx_minimal");
702 } else {
703 StaticRuntimes.push_back("scudo");
704 if (SanArgs.linkCXXRuntimes())
705 StaticRuntimes.push_back("scudo_cxx");
706 }
707 }
708 }
709
710 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
711 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
addSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)712 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
713 ArgStringList &CmdArgs) {
714 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
715 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
716 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
717 NonWholeStaticRuntimes, HelperStaticRuntimes,
718 RequiredSymbols);
719
720 // Inject libfuzzer dependencies.
721 if (TC.getSanitizerArgs().needsFuzzer()
722 && !Args.hasArg(options::OPT_shared)) {
723
724 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
725 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
726 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
727 }
728
729 for (auto RT : SharedRuntimes)
730 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
731 for (auto RT : HelperStaticRuntimes)
732 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
733 bool AddExportDynamic = false;
734 for (auto RT : StaticRuntimes) {
735 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
736 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
737 }
738 for (auto RT : NonWholeStaticRuntimes) {
739 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
740 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
741 }
742 for (auto S : RequiredSymbols) {
743 CmdArgs.push_back("-u");
744 CmdArgs.push_back(Args.MakeArgString(S));
745 }
746 // If there is a static runtime with no dynamic list, force all the symbols
747 // to be dynamic to be sure we export sanitizer interface functions.
748 if (AddExportDynamic)
749 CmdArgs.push_back("--export-dynamic");
750
751 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
752 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
753 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
754
755 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
756 }
757
addXRayRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)758 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
759 if (Args.hasArg(options::OPT_shared))
760 return false;
761
762 if (TC.getXRayArgs().needsXRayRt()) {
763 CmdArgs.push_back("-whole-archive");
764 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
765 for (const auto &Mode : TC.getXRayArgs().modeList())
766 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode, false));
767 CmdArgs.push_back("-no-whole-archive");
768 return true;
769 }
770
771 return false;
772 }
773
linkXRayRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)774 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
775 CmdArgs.push_back("--no-as-needed");
776 CmdArgs.push_back("-lpthread");
777 if (!TC.getTriple().isOSOpenBSD())
778 CmdArgs.push_back("-lrt");
779 CmdArgs.push_back("-lm");
780
781 if (!TC.getTriple().isOSFreeBSD() &&
782 !TC.getTriple().isOSNetBSD() &&
783 !TC.getTriple().isOSOpenBSD())
784 CmdArgs.push_back("-ldl");
785 }
786
areOptimizationsEnabled(const ArgList & Args)787 bool tools::areOptimizationsEnabled(const ArgList &Args) {
788 // Find the last -O arg and see if it is non-zero.
789 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
790 return !A->getOption().matches(options::OPT_O0);
791 // Defaults to -O0.
792 return false;
793 }
794
SplitDebugName(const ArgList & Args,const InputInfo & Output)795 const char *tools::SplitDebugName(const ArgList &Args,
796 const InputInfo &Output) {
797 SmallString<128> F(Output.isFilename()
798 ? Output.getFilename()
799 : llvm::sys::path::stem(Output.getBaseInput()));
800
801 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
802 if (StringRef(A->getValue()) == "single")
803 return Args.MakeArgString(F);
804
805 llvm::sys::path::replace_extension(F, "dwo");
806 return Args.MakeArgString(F);
807 }
808
SplitDebugInfo(const ToolChain & TC,Compilation & C,const Tool & T,const JobAction & JA,const ArgList & Args,const InputInfo & Output,const char * OutFile)809 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
810 const JobAction &JA, const ArgList &Args,
811 const InputInfo &Output, const char *OutFile) {
812 ArgStringList ExtractArgs;
813 ExtractArgs.push_back("--extract-dwo");
814
815 ArgStringList StripArgs;
816 StripArgs.push_back("--strip-dwo");
817
818 // Grabbing the output of the earlier compile step.
819 StripArgs.push_back(Output.getFilename());
820 ExtractArgs.push_back(Output.getFilename());
821 ExtractArgs.push_back(OutFile);
822
823 const char *Exec =
824 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
825 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
826
827 // First extract the dwo sections.
828 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
829
830 // Then remove them from the original .o file.
831 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
832 }
833
834 // Claim options we don't want to warn if they are unused. We do this for
835 // options that build systems might add but are unused when assembling or only
836 // running the preprocessor for example.
claimNoWarnArgs(const ArgList & Args)837 void tools::claimNoWarnArgs(const ArgList &Args) {
838 // Don't warn about unused -f(no-)?lto. This can happen when we're
839 // preprocessing, precompiling or assembling.
840 Args.ClaimAllArgs(options::OPT_flto_EQ);
841 Args.ClaimAllArgs(options::OPT_flto);
842 Args.ClaimAllArgs(options::OPT_fno_lto);
843 }
844
getLastProfileUseArg(const ArgList & Args)845 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
846 auto *ProfileUseArg = Args.getLastArg(
847 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
848 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
849 options::OPT_fno_profile_instr_use);
850
851 if (ProfileUseArg &&
852 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
853 ProfileUseArg = nullptr;
854
855 return ProfileUseArg;
856 }
857
getLastProfileSampleUseArg(const ArgList & Args)858 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
859 auto *ProfileSampleUseArg = Args.getLastArg(
860 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
861 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
862 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
863
864 if (ProfileSampleUseArg &&
865 (ProfileSampleUseArg->getOption().matches(
866 options::OPT_fno_profile_sample_use) ||
867 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
868 return nullptr;
869
870 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
871 options::OPT_fauto_profile_EQ);
872 }
873
874 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
875 /// smooshes them together with platform defaults, to decide whether
876 /// this compile should be using PIC mode or not. Returns a tuple of
877 /// (RelocationModel, PICLevel, IsPIE).
878 std::tuple<llvm::Reloc::Model, unsigned, bool>
ParsePICArgs(const ToolChain & ToolChain,const ArgList & Args)879 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
880 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
881 const llvm::Triple &Triple = ToolChain.getTriple();
882
883 bool PIE = ToolChain.isPIEDefault();
884 bool PIC = PIE || ToolChain.isPICDefault();
885 // The Darwin/MachO default to use PIC does not apply when using -static.
886 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
887 PIE = PIC = false;
888 bool IsPICLevelTwo = PIC;
889
890 bool KernelOrKext =
891 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
892
893 // Android-specific defaults for PIC/PIE
894 if (Triple.isAndroid()) {
895 switch (Triple.getArch()) {
896 case llvm::Triple::arm:
897 case llvm::Triple::armeb:
898 case llvm::Triple::thumb:
899 case llvm::Triple::thumbeb:
900 case llvm::Triple::aarch64:
901 case llvm::Triple::mips:
902 case llvm::Triple::mipsel:
903 case llvm::Triple::mips64:
904 case llvm::Triple::mips64el:
905 PIC = true; // "-fpic"
906 break;
907
908 case llvm::Triple::x86:
909 case llvm::Triple::x86_64:
910 PIC = true; // "-fPIC"
911 IsPICLevelTwo = true;
912 break;
913
914 default:
915 break;
916 }
917 }
918
919 // OpenBSD-specific defaults for PIE
920 if (Triple.isOSOpenBSD()) {
921 switch (ToolChain.getArch()) {
922 case llvm::Triple::arm:
923 case llvm::Triple::aarch64:
924 case llvm::Triple::mips64:
925 case llvm::Triple::mips64el:
926 case llvm::Triple::x86:
927 case llvm::Triple::x86_64:
928 IsPICLevelTwo = false; // "-fpie"
929 break;
930
931 case llvm::Triple::ppc:
932 case llvm::Triple::sparc:
933 case llvm::Triple::sparcel:
934 case llvm::Triple::sparcv9:
935 IsPICLevelTwo = true; // "-fPIE"
936 break;
937
938 default:
939 break;
940 }
941 }
942
943 // AMDGPU-specific defaults for PIC.
944 if (Triple.getArch() == llvm::Triple::amdgcn)
945 PIC = true;
946
947 // The last argument relating to either PIC or PIE wins, and no
948 // other argument is used. If the last argument is any flavor of the
949 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
950 // option implicitly enables PIC at the same level.
951 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
952 options::OPT_fpic, options::OPT_fno_pic,
953 options::OPT_fPIE, options::OPT_fno_PIE,
954 options::OPT_fpie, options::OPT_fno_pie);
955 if (Triple.isOSWindows() && LastPICArg &&
956 LastPICArg ==
957 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
958 options::OPT_fPIE, options::OPT_fpie)) {
959 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
960 << LastPICArg->getSpelling() << Triple.str();
961 if (Triple.getArch() == llvm::Triple::x86_64)
962 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
963 return std::make_tuple(llvm::Reloc::Static, 0U, false);
964 }
965
966 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
967 // is forced, then neither PIC nor PIE flags will have no effect.
968 if (!ToolChain.isPICDefaultForced()) {
969 if (LastPICArg) {
970 Option O = LastPICArg->getOption();
971 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
972 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
973 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
974 PIC =
975 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
976 IsPICLevelTwo =
977 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
978 } else {
979 PIE = PIC = false;
980 if (EffectiveTriple.isPS4CPU()) {
981 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
982 StringRef Model = ModelArg ? ModelArg->getValue() : "";
983 if (Model != "kernel") {
984 PIC = true;
985 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
986 << LastPICArg->getSpelling();
987 }
988 }
989 }
990 }
991 }
992
993 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
994 // PIC level would've been set to level 1, force it back to level 2 PIC
995 // instead.
996 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
997 IsPICLevelTwo |= ToolChain.isPICDefault();
998
999 // This kernel flags are a trump-card: they will disable PIC/PIE
1000 // generation, independent of the argument order.
1001 if (KernelOrKext &&
1002 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1003 !EffectiveTriple.isWatchOS()))
1004 PIC = PIE = false;
1005
1006 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1007 // This is a very special mode. It trumps the other modes, almost no one
1008 // uses it, and it isn't even valid on any OS but Darwin.
1009 if (!Triple.isOSDarwin())
1010 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1011 << A->getSpelling() << Triple.str();
1012
1013 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1014
1015 // Only a forced PIC mode can cause the actual compile to have PIC defines
1016 // etc., no flags are sufficient. This behavior was selected to closely
1017 // match that of llvm-gcc and Apple GCC before that.
1018 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1019
1020 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1021 }
1022
1023 bool EmbeddedPISupported;
1024 switch (Triple.getArch()) {
1025 case llvm::Triple::arm:
1026 case llvm::Triple::armeb:
1027 case llvm::Triple::thumb:
1028 case llvm::Triple::thumbeb:
1029 EmbeddedPISupported = true;
1030 break;
1031 default:
1032 EmbeddedPISupported = false;
1033 break;
1034 }
1035
1036 bool ROPI = false, RWPI = false;
1037 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1038 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1039 if (!EmbeddedPISupported)
1040 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1041 << LastROPIArg->getSpelling() << Triple.str();
1042 ROPI = true;
1043 }
1044 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1045 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1046 if (!EmbeddedPISupported)
1047 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1048 << LastRWPIArg->getSpelling() << Triple.str();
1049 RWPI = true;
1050 }
1051
1052 // ROPI and RWPI are not compatible with PIC or PIE.
1053 if ((ROPI || RWPI) && (PIC || PIE))
1054 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1055
1056 if (Triple.isMIPS()) {
1057 StringRef CPUName;
1058 StringRef ABIName;
1059 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1060 // When targeting the N64 ABI, PIC is the default, except in the case
1061 // when the -mno-abicalls option is used. In that case we exit
1062 // at next check regardless of PIC being set below.
1063 if (ABIName == "n64")
1064 PIC = true;
1065 // When targettng MIPS with -mno-abicalls, it's always static.
1066 if(Args.hasArg(options::OPT_mno_abicalls))
1067 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1068 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1069 // does not use PIC level 2 for historical reasons.
1070 IsPICLevelTwo = false;
1071 }
1072
1073 if (PIC)
1074 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1075
1076 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1077 if (ROPI && RWPI)
1078 RelocM = llvm::Reloc::ROPI_RWPI;
1079 else if (ROPI)
1080 RelocM = llvm::Reloc::ROPI;
1081 else if (RWPI)
1082 RelocM = llvm::Reloc::RWPI;
1083
1084 return std::make_tuple(RelocM, 0U, false);
1085 }
1086
1087 // `-falign-functions` indicates that the functions should be aligned to a
1088 // 16-byte boundary.
1089 //
1090 // `-falign-functions=1` is the same as `-fno-align-functions`.
1091 //
1092 // The scalar `n` in `-falign-functions=n` must be an integral value between
1093 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1094 // the nearest power-of-two.
1095 //
1096 // If we return `0`, the frontend will default to the backend's preferred
1097 // alignment.
1098 //
1099 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1100 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1101 // alignment. For unaligned functions, we default to the backend's preferred
1102 // alignment.
ParseFunctionAlignment(const ToolChain & TC,const ArgList & Args)1103 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1104 const ArgList &Args) {
1105 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1106 options::OPT_falign_functions_EQ,
1107 options::OPT_fno_align_functions);
1108 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1109 return 0;
1110
1111 if (A->getOption().matches(options::OPT_falign_functions))
1112 return 0;
1113
1114 unsigned Value = 0;
1115 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1116 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1117 << A->getAsString(Args) << A->getValue();
1118 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1119 }
1120
AddAssemblerKPIC(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs)1121 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1122 ArgStringList &CmdArgs) {
1123 llvm::Reloc::Model RelocationModel;
1124 unsigned PICLevel;
1125 bool IsPIE;
1126 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1127
1128 if (RelocationModel != llvm::Reloc::Static)
1129 CmdArgs.push_back("-KPIC");
1130 }
1131
1132 /// Determine whether Objective-C automated reference counting is
1133 /// enabled.
isObjCAutoRefCount(const ArgList & Args)1134 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1135 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1136 }
1137
AddLibgcc(const llvm::Triple & Triple,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)1138 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1139 ArgStringList &CmdArgs, const ArgList &Args) {
1140 bool isAndroid = Triple.isAndroid();
1141 bool isCygMing = Triple.isOSCygMing();
1142 bool IsIAMCU = Triple.isOSIAMCU();
1143 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1144 Args.hasArg(options::OPT_static);
1145
1146 bool SharedLibgcc = Args.hasArg(options::OPT_shared_libgcc);
1147 bool UnspecifiedLibgcc = !StaticLibgcc && !SharedLibgcc;
1148
1149 // Gcc adds libgcc arguments in various ways:
1150 //
1151 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
1152 // g++ <none>: -lgcc_s -lgcc
1153 // gcc shared: -lgcc_s -lgcc
1154 // g++ shared: -lgcc_s -lgcc
1155 // gcc static: -lgcc -lgcc_eh
1156 // g++ static: -lgcc -lgcc_eh
1157 //
1158 // Also, certain targets need additional adjustments.
1159
1160 bool LibGccFirst = (D.CCCIsCC() && UnspecifiedLibgcc) || StaticLibgcc;
1161 if (LibGccFirst)
1162 CmdArgs.push_back("-lgcc");
1163
1164 bool AsNeeded = D.CCCIsCC() && UnspecifiedLibgcc && !isAndroid && !isCygMing;
1165 if (AsNeeded)
1166 CmdArgs.push_back("--as-needed");
1167
1168 if ((UnspecifiedLibgcc || SharedLibgcc) && !isAndroid)
1169 CmdArgs.push_back("-lgcc_s");
1170
1171 else if (StaticLibgcc && !isAndroid && !IsIAMCU)
1172 CmdArgs.push_back("-lgcc_eh");
1173
1174 if (AsNeeded)
1175 CmdArgs.push_back("--no-as-needed");
1176
1177 if (!LibGccFirst)
1178 CmdArgs.push_back("-lgcc");
1179
1180 // According to Android ABI, we have to link with libdl if we are
1181 // linking with non-static libgcc.
1182 //
1183 // NOTE: This fixes a link error on Android MIPS as well. The non-static
1184 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1185 if (isAndroid && !StaticLibgcc)
1186 CmdArgs.push_back("-ldl");
1187 }
1188
AddRunTimeLibs(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)1189 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1190 ArgStringList &CmdArgs, const ArgList &Args) {
1191 // Make use of compiler-rt if --rtlib option is used
1192 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1193
1194 switch (RLT) {
1195 case ToolChain::RLT_CompilerRT:
1196 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1197 break;
1198 case ToolChain::RLT_Libgcc:
1199 // Make sure libgcc is not used under MSVC environment by default
1200 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1201 // Issue error diagnostic if libgcc is explicitly specified
1202 // through command line as --rtlib option argument.
1203 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1204 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1205 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1206 }
1207 } else
1208 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1209 break;
1210 }
1211 }
1212
1213 /// Add OpenMP linker script arguments at the end of the argument list so that
1214 /// the fat binary is built by embedding each of the device images into the
1215 /// host. The linker script also defines a few symbols required by the code
1216 /// generation so that the images can be easily retrieved at runtime by the
1217 /// offloading library. This should be used only in tool chains that support
1218 /// linker scripts.
AddOpenMPLinkerScript(const ToolChain & TC,Compilation & C,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)1219 void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1220 const InputInfo &Output,
1221 const InputInfoList &Inputs,
1222 const ArgList &Args, ArgStringList &CmdArgs,
1223 const JobAction &JA) {
1224
1225 // If this is not an OpenMP host toolchain, we don't need to do anything.
1226 if (!JA.isHostOffloading(Action::OFK_OpenMP))
1227 return;
1228
1229 // Create temporary linker script. Keep it if save-temps is enabled.
1230 const char *LKS;
1231 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1232 if (C.getDriver().isSaveTempsEnabled()) {
1233 llvm::sys::path::replace_extension(Name, "lk");
1234 LKS = C.getArgs().MakeArgString(Name.c_str());
1235 } else {
1236 llvm::sys::path::replace_extension(Name, "");
1237 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1238 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1239 }
1240
1241 // Add linker script option to the command.
1242 CmdArgs.push_back("-T");
1243 CmdArgs.push_back(LKS);
1244
1245 // Create a buffer to write the contents of the linker script.
1246 std::string LksBuffer;
1247 llvm::raw_string_ostream LksStream(LksBuffer);
1248
1249 // Get the OpenMP offload tool chains so that we can extract the triple
1250 // associated with each device input.
1251 auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1252 assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1253 "No OpenMP toolchains??");
1254
1255 // Track the input file name and device triple in order to build the script,
1256 // inserting binaries in the designated sections.
1257 SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1258
1259 // Add commands to embed target binaries. We ensure that each section and
1260 // image is 16-byte aligned. This is not mandatory, but increases the
1261 // likelihood of data to be aligned with a cache block in several main host
1262 // machines.
1263 LksStream << "/*\n";
1264 LksStream << " OpenMP Offload Linker Script\n";
1265 LksStream << " *** Automatically generated by Clang ***\n";
1266 LksStream << "*/\n";
1267 LksStream << "TARGET(binary)\n";
1268 auto DTC = OpenMPToolChains.first;
1269 for (auto &II : Inputs) {
1270 const Action *A = II.getAction();
1271 // Is this a device linking action?
1272 if (A && isa<LinkJobAction>(A) &&
1273 A->isDeviceOffloading(Action::OFK_OpenMP)) {
1274 assert(DTC != OpenMPToolChains.second &&
1275 "More device inputs than device toolchains??");
1276 InputBinaryInfo.push_back(std::make_pair(
1277 DTC->second->getTriple().normalize(), II.getFilename()));
1278 ++DTC;
1279 LksStream << "INPUT(" << II.getFilename() << ")\n";
1280 }
1281 }
1282
1283 assert(DTC == OpenMPToolChains.second &&
1284 "Less device inputs than device toolchains??");
1285
1286 LksStream << "SECTIONS\n";
1287 LksStream << "{\n";
1288
1289 // Put each target binary into a separate section.
1290 for (const auto &BI : InputBinaryInfo) {
1291 LksStream << " .omp_offloading." << BI.first << " :\n";
1292 LksStream << " ALIGN(0x10)\n";
1293 LksStream << " {\n";
1294 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1295 << " = .);\n";
1296 LksStream << " " << BI.second << "\n";
1297 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1298 << " = .);\n";
1299 LksStream << " }\n";
1300 }
1301
1302 // Add commands to define host entries begin and end. We use 1-byte subalign
1303 // so that the linker does not add any padding and the elements in this
1304 // section form an array.
1305 LksStream << " .omp_offloading.entries :\n";
1306 LksStream << " ALIGN(0x10)\n";
1307 LksStream << " SUBALIGN(0x01)\n";
1308 LksStream << " {\n";
1309 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1310 LksStream << " *(.omp_offloading.entries)\n";
1311 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1312 LksStream << " }\n";
1313 LksStream << "}\n";
1314 LksStream << "INSERT BEFORE .data\n";
1315 LksStream.flush();
1316
1317 // Dump the contents of the linker script if the user requested that. We
1318 // support this option to enable testing of behavior with -###.
1319 if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1320 llvm::errs() << LksBuffer;
1321
1322 // If this is a dry run, do not create the linker script file.
1323 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1324 return;
1325
1326 // Open script file and write the contents.
1327 std::error_code EC;
1328 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1329
1330 if (EC) {
1331 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1332 return;
1333 }
1334
1335 Lksf << LksBuffer;
1336 }
1337
1338 /// Add HIP linker script arguments at the end of the argument list so that
1339 /// the fat binary is built by embedding the device images into the host. The
1340 /// linker script also defines a symbol required by the code generation so that
1341 /// the image can be retrieved at runtime. This should be used only in tool
1342 /// chains that support linker scripts.
AddHIPLinkerScript(const ToolChain & TC,Compilation & C,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA,const Tool & T)1343 void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C,
1344 const InputInfo &Output,
1345 const InputInfoList &Inputs, const ArgList &Args,
1346 ArgStringList &CmdArgs, const JobAction &JA,
1347 const Tool &T) {
1348
1349 // If this is not a HIP host toolchain, we don't need to do anything.
1350 if (!JA.isHostOffloading(Action::OFK_HIP))
1351 return;
1352
1353 InputInfoList DeviceInputs;
1354 for (const auto &II : Inputs) {
1355 const Action *A = II.getAction();
1356 // Is this a device linking action?
1357 if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) {
1358 DeviceInputs.push_back(II);
1359 }
1360 }
1361
1362 if (DeviceInputs.empty())
1363 return;
1364
1365 // Create temporary linker script. Keep it if save-temps is enabled.
1366 const char *LKS;
1367 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1368 if (C.getDriver().isSaveTempsEnabled()) {
1369 llvm::sys::path::replace_extension(Name, "lk");
1370 LKS = C.getArgs().MakeArgString(Name.c_str());
1371 } else {
1372 llvm::sys::path::replace_extension(Name, "");
1373 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1374 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1375 }
1376
1377 // Add linker script option to the command.
1378 CmdArgs.push_back("-T");
1379 CmdArgs.push_back(LKS);
1380
1381 // Create a buffer to write the contents of the linker script.
1382 std::string LksBuffer;
1383 llvm::raw_string_ostream LksStream(LksBuffer);
1384
1385 // Get the HIP offload tool chain.
1386 auto *HIPTC = static_cast<const toolchains::CudaToolChain *>(
1387 C.getSingleOffloadToolChain<Action::OFK_HIP>());
1388 assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn &&
1389 "Wrong platform");
1390 (void)HIPTC;
1391
1392 // The output file name needs to persist through the compilation, therefore
1393 // it needs to be created through MakeArgString.
1394 std::string BundleFileName = C.getDriver().GetTemporaryPath("BUNDLE", "hipfb");
1395 const char *BundleFile =
1396 C.addTempFile(C.getArgs().MakeArgString(BundleFileName.c_str()));
1397 AMDGCN::constructHIPFatbinCommand(C, JA, BundleFile, DeviceInputs, Args, T);
1398
1399 // Add commands to embed target binaries. We ensure that each section and
1400 // image is 16-byte aligned. This is not mandatory, but increases the
1401 // likelihood of data to be aligned with a cache block in several main host
1402 // machines.
1403 LksStream << "/*\n";
1404 LksStream << " HIP Offload Linker Script\n";
1405 LksStream << " *** Automatically generated by Clang ***\n";
1406 LksStream << "*/\n";
1407 LksStream << "TARGET(binary)\n";
1408 LksStream << "INPUT(" << BundleFileName << ")\n";
1409 LksStream << "SECTIONS\n";
1410 LksStream << "{\n";
1411 LksStream << " .hip_fatbin :\n";
1412 LksStream << " ALIGN(0x10)\n";
1413 LksStream << " {\n";
1414 LksStream << " PROVIDE_HIDDEN(__hip_fatbin = .);\n";
1415 LksStream << " " << BundleFileName << "\n";
1416 LksStream << " }\n";
1417 LksStream << " /DISCARD/ :\n";
1418 LksStream << " {\n";
1419 LksStream << " * ( __CLANG_OFFLOAD_BUNDLE__* )\n";
1420 LksStream << " }\n";
1421 LksStream << "}\n";
1422 LksStream << "INSERT BEFORE .data\n";
1423 LksStream.flush();
1424
1425 // Dump the contents of the linker script if the user requested that. We
1426 // support this option to enable testing of behavior with -###.
1427 if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
1428 llvm::errs() << LksBuffer;
1429
1430 // If this is a dry run, do not create the linker script file.
1431 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1432 return;
1433
1434 // Open script file and write the contents.
1435 std::error_code EC;
1436 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1437
1438 if (EC) {
1439 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1440 return;
1441 }
1442
1443 Lksf << LksBuffer;
1444 }
1445
getStatsFileName(const llvm::opt::ArgList & Args,const InputInfo & Output,const InputInfo & Input,const Driver & D)1446 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1447 const InputInfo &Output,
1448 const InputInfo &Input,
1449 const Driver &D) {
1450 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1451 if (!A)
1452 return {};
1453
1454 StringRef SaveStats = A->getValue();
1455 SmallString<128> StatsFile;
1456 if (SaveStats == "obj" && Output.isFilename()) {
1457 StatsFile.assign(Output.getFilename());
1458 llvm::sys::path::remove_filename(StatsFile);
1459 } else if (SaveStats != "cwd") {
1460 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1461 return {};
1462 }
1463
1464 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1465 llvm::sys::path::append(StatsFile, BaseName);
1466 llvm::sys::path::replace_extension(StatsFile, "stats");
1467 return StatsFile;
1468 }
1469