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