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