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 getNios2TargetCPU(const ArgList &Args) {
219   Arg *A = Args.getLastArg(options::OPT_mcpu_EQ);
220   if (!A)
221     A = Args.getLastArg(options::OPT_march_EQ);
222 
223   if (!A)
224     return "";
225 
226   const char *name = A->getValue();
227   return llvm::StringSwitch<const char *>(name)
228       .Case("r1", "nios2r1")
229       .Case("r2", "nios2r2")
230       .Default(name);
231 }
232 
233 static std::string getLanaiTargetCPU(const ArgList &Args) {
234   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
235     return A->getValue();
236   }
237   return "";
238 }
239 
240 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
241 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
242   // If we have -mcpu=, use that.
243   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
244     StringRef CPU = A->getValue();
245 
246 #ifdef __wasm__
247     // Handle "native" by examining the host. "native" isn't meaningful when
248     // cross compiling, so only support this when the host is also WebAssembly.
249     if (CPU == "native")
250       return llvm::sys::getHostCPUName();
251 #endif
252 
253     return CPU;
254   }
255 
256   return "generic";
257 }
258 
259 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
260                               bool FromAs) {
261   Arg *A;
262 
263   switch (T.getArch()) {
264   default:
265     return "";
266 
267   case llvm::Triple::aarch64:
268   case llvm::Triple::aarch64_be:
269     return aarch64::getAArch64TargetCPU(Args, A);
270 
271   case llvm::Triple::arm:
272   case llvm::Triple::armeb:
273   case llvm::Triple::thumb:
274   case llvm::Triple::thumbeb: {
275     StringRef MArch, MCPU;
276     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
277     return arm::getARMTargetCPU(MCPU, MArch, T);
278   }
279 
280   case llvm::Triple::avr:
281     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
282       return A->getValue();
283     return "";
284 
285   case llvm::Triple::nios2: {
286     return getNios2TargetCPU(Args);
287   }
288 
289   case llvm::Triple::mips:
290   case llvm::Triple::mipsel:
291   case llvm::Triple::mips64:
292   case llvm::Triple::mips64el: {
293     StringRef CPUName;
294     StringRef ABIName;
295     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
296     return CPUName;
297   }
298 
299   case llvm::Triple::nvptx:
300   case llvm::Triple::nvptx64:
301     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
302       return A->getValue();
303     return "";
304 
305   case llvm::Triple::ppc:
306   case llvm::Triple::ppc64:
307   case llvm::Triple::ppc64le: {
308     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
309     // LLVM may default to generating code for the native CPU,
310     // but, like gcc, we default to a more generic option for
311     // each architecture. (except on Darwin)
312     if (TargetCPUName.empty() && !T.isOSDarwin()) {
313       if (T.getArch() == llvm::Triple::ppc64)
314         TargetCPUName = "ppc64";
315       else if (T.getArch() == llvm::Triple::ppc64le)
316         TargetCPUName = "ppc64le";
317       else
318         TargetCPUName = "ppc";
319     }
320     return TargetCPUName;
321   }
322 
323   case llvm::Triple::bpfel:
324   case llvm::Triple::bpfeb:
325   case llvm::Triple::sparc:
326   case llvm::Triple::sparcel:
327   case llvm::Triple::sparcv9:
328     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
329       return A->getValue();
330     return "";
331 
332   case llvm::Triple::x86:
333   case llvm::Triple::x86_64:
334     return x86::getX86TargetCPU(Args, T);
335 
336   case llvm::Triple::hexagon:
337     return "hexagon" +
338            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
339 
340   case llvm::Triple::lanai:
341     return getLanaiTargetCPU(Args);
342 
343   case llvm::Triple::systemz:
344     return systemz::getSystemZTargetCPU(Args);
345 
346   case llvm::Triple::r600:
347   case llvm::Triple::amdgcn:
348     return getR600TargetGPU(Args);
349 
350   case llvm::Triple::wasm32:
351   case llvm::Triple::wasm64:
352     return getWebAssemblyTargetCPU(Args);
353   }
354 }
355 
356 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
357   unsigned Parallelism = 0;
358   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
359   if (LtoJobsArg &&
360       StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
361     D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
362                                             << LtoJobsArg->getValue();
363   return Parallelism;
364 }
365 
366 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
367 // default.
368 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
369   return Triple.getOS() == llvm::Triple::CloudABI ||
370          Triple.getArch() == llvm::Triple::wasm32 ||
371          Triple.getArch() == llvm::Triple::wasm64;
372 }
373 
374 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
375                           ArgStringList &CmdArgs, bool IsThinLTO,
376                           const Driver &D) {
377   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
378   // as gold requires -plugin to come before any -plugin-opt that -Wl might
379   // forward.
380   CmdArgs.push_back("-plugin");
381 
382 #if defined(LLVM_ON_WIN32)
383   const char *Suffix = ".dll";
384 #elif defined(__APPLE__)
385   const char *Suffix = ".dylib";
386 #else
387   const char *Suffix = ".so";
388 #endif
389 
390   SmallString<1024> Plugin;
391   llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
392                               "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
393                               Suffix,
394                           Plugin);
395   CmdArgs.push_back(Args.MakeArgString(Plugin));
396 
397   // Try to pass driver level flags relevant to LTO code generation down to
398   // the plugin.
399 
400   // Handle flags for selecting CPU variants.
401   std::string CPU = getCPUName(Args, ToolChain.getTriple());
402   if (!CPU.empty())
403     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
404 
405   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
406     StringRef OOpt;
407     if (A->getOption().matches(options::OPT_O4) ||
408         A->getOption().matches(options::OPT_Ofast))
409       OOpt = "3";
410     else if (A->getOption().matches(options::OPT_O))
411       OOpt = A->getValue();
412     else if (A->getOption().matches(options::OPT_O0))
413       OOpt = "0";
414     if (!OOpt.empty())
415       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
416   }
417 
418   if (IsThinLTO)
419     CmdArgs.push_back("-plugin-opt=thinlto");
420 
421   if (unsigned Parallelism = getLTOParallelism(Args, D))
422     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
423                                          llvm::to_string(Parallelism)));
424 
425   // If an explicit debugger tuning argument appeared, pass it along.
426   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
427                                options::OPT_ggdbN_Group)) {
428     if (A->getOption().matches(options::OPT_glldb))
429       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
430     else if (A->getOption().matches(options::OPT_gsce))
431       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
432     else
433       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
434   }
435 
436   bool UseSeparateSections =
437       isUseSeparateSections(ToolChain.getEffectiveTriple());
438 
439   if (Args.hasFlag(options::OPT_ffunction_sections,
440                    options::OPT_fno_function_sections, UseSeparateSections)) {
441     CmdArgs.push_back("-plugin-opt=-function-sections");
442   }
443 
444   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
445                    UseSeparateSections)) {
446     CmdArgs.push_back("-plugin-opt=-data-sections");
447   }
448 
449   if (Arg *A = getLastProfileSampleUseArg(Args)) {
450     StringRef FName = A->getValue();
451     if (!llvm::sys::fs::exists(FName))
452       D.Diag(diag::err_drv_no_such_file) << FName;
453     else
454       CmdArgs.push_back(
455           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
456   }
457 
458   // Need this flag to turn on new pass manager via Gold plugin.
459   if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
460                    options::OPT_fno_experimental_new_pass_manager,
461                    /* Default */ false)) {
462     CmdArgs.push_back("-plugin-opt=new-pass-manager");
463   }
464 
465 }
466 
467 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
468                                  ArgStringList &CmdArgs) {
469   std::string CandidateRPath = TC.getArchSpecificLibPath();
470   if (TC.getVFS().exists(CandidateRPath)) {
471     CmdArgs.push_back("-rpath");
472     CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
473   }
474 }
475 
476 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
477                              const ArgList &Args, bool IsOffloadingHost,
478                              bool GompNeedsRT) {
479   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
480                     options::OPT_fno_openmp, false))
481     return false;
482 
483   switch (TC.getDriver().getOpenMPRuntime(Args)) {
484   case Driver::OMPRT_OMP:
485     CmdArgs.push_back("-lomp");
486     break;
487   case Driver::OMPRT_GOMP:
488     CmdArgs.push_back("-lgomp");
489 
490     if (GompNeedsRT)
491       CmdArgs.push_back("-lrt");
492     break;
493   case Driver::OMPRT_IOMP5:
494     CmdArgs.push_back("-liomp5");
495     break;
496   case Driver::OMPRT_Unknown:
497     // Already diagnosed.
498     return false;
499   }
500 
501   if (IsOffloadingHost)
502     CmdArgs.push_back("-lomptarget");
503 
504   addArchSpecificRPath(TC, Args, CmdArgs);
505 
506   return true;
507 }
508 
509 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
510                                 ArgStringList &CmdArgs, StringRef Sanitizer,
511                                 bool IsShared, bool IsWhole) {
512   // Wrap any static runtimes that must be forced into executable in
513   // whole-archive.
514   if (IsWhole) CmdArgs.push_back("-whole-archive");
515   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
516   if (IsWhole) CmdArgs.push_back("-no-whole-archive");
517 
518   if (IsShared) {
519     addArchSpecificRPath(TC, Args, CmdArgs);
520   }
521 }
522 
523 // Tries to use a file with the list of dynamic symbols that need to be exported
524 // from the runtime library. Returns true if the file was found.
525 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
526                                     ArgStringList &CmdArgs,
527                                     StringRef Sanitizer) {
528   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
529   if (llvm::sys::fs::exists(SanRT + ".syms")) {
530     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
531     return true;
532   }
533   return false;
534 }
535 
536 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
537                                      ArgStringList &CmdArgs) {
538   // Force linking against the system libraries sanitizers depends on
539   // (see PR15823 why this is necessary).
540   CmdArgs.push_back("--no-as-needed");
541   // There's no libpthread or librt on RTEMS.
542   if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
543     CmdArgs.push_back("-lpthread");
544     CmdArgs.push_back("-lrt");
545   }
546   CmdArgs.push_back("-lm");
547   // There's no libdl on all OSes.
548   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
549       TC.getTriple().getOS() != llvm::Triple::NetBSD &&
550       TC.getTriple().getOS() != llvm::Triple::RTEMS)
551     CmdArgs.push_back("-ldl");
552 }
553 
554 static void
555 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
556                          SmallVectorImpl<StringRef> &SharedRuntimes,
557                          SmallVectorImpl<StringRef> &StaticRuntimes,
558                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
559                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
560                          SmallVectorImpl<StringRef> &RequiredSymbols) {
561   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
562   // Collect shared runtimes.
563   if (SanArgs.needsSharedRt()) {
564     if (SanArgs.needsAsanRt()) {
565       SharedRuntimes.push_back("asan");
566       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
567         HelperStaticRuntimes.push_back("asan-preinit");
568     }
569     if (SanArgs.needsUbsanRt()) {
570       if (SanArgs.requiresMinimalRuntime()) {
571         SharedRuntimes.push_back("ubsan_minimal");
572       } else {
573         SharedRuntimes.push_back("ubsan_standalone");
574       }
575     }
576     if (SanArgs.needsScudoRt())
577       SharedRuntimes.push_back("scudo");
578     if (SanArgs.needsHwasanRt())
579       SharedRuntimes.push_back("hwasan");
580   }
581 
582   // The stats_client library is also statically linked into DSOs.
583   if (SanArgs.needsStatsRt())
584     StaticRuntimes.push_back("stats_client");
585 
586   // Collect static runtimes.
587   if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
588     // Don't link static runtimes into DSOs or if -shared-libasan.
589     return;
590   }
591   if (SanArgs.needsAsanRt()) {
592     StaticRuntimes.push_back("asan");
593     if (SanArgs.linkCXXRuntimes())
594       StaticRuntimes.push_back("asan_cxx");
595   }
596 
597   if (SanArgs.needsHwasanRt()) {
598     StaticRuntimes.push_back("hwasan");
599     if (SanArgs.linkCXXRuntimes())
600       StaticRuntimes.push_back("hwasan_cxx");
601   }
602   if (SanArgs.needsDfsanRt())
603     StaticRuntimes.push_back("dfsan");
604   if (SanArgs.needsLsanRt())
605     StaticRuntimes.push_back("lsan");
606   if (SanArgs.needsMsanRt()) {
607     StaticRuntimes.push_back("msan");
608     if (SanArgs.linkCXXRuntimes())
609       StaticRuntimes.push_back("msan_cxx");
610   }
611   if (SanArgs.needsTsanRt()) {
612     StaticRuntimes.push_back("tsan");
613     if (SanArgs.linkCXXRuntimes())
614       StaticRuntimes.push_back("tsan_cxx");
615   }
616   if (SanArgs.needsUbsanRt()) {
617     if (SanArgs.requiresMinimalRuntime()) {
618       StaticRuntimes.push_back("ubsan_minimal");
619     } else {
620       StaticRuntimes.push_back("ubsan_standalone");
621       if (SanArgs.linkCXXRuntimes())
622         StaticRuntimes.push_back("ubsan_standalone_cxx");
623     }
624   }
625   if (SanArgs.needsSafeStackRt()) {
626     NonWholeStaticRuntimes.push_back("safestack");
627     RequiredSymbols.push_back("__safestack_init");
628   }
629   if (SanArgs.needsCfiRt())
630     StaticRuntimes.push_back("cfi");
631   if (SanArgs.needsCfiDiagRt()) {
632     StaticRuntimes.push_back("cfi_diag");
633     if (SanArgs.linkCXXRuntimes())
634       StaticRuntimes.push_back("ubsan_standalone_cxx");
635   }
636   if (SanArgs.needsStatsRt()) {
637     NonWholeStaticRuntimes.push_back("stats");
638     RequiredSymbols.push_back("__sanitizer_stats_register");
639   }
640   if (SanArgs.needsEsanRt())
641     StaticRuntimes.push_back("esan");
642   if (SanArgs.needsScudoRt()) {
643     StaticRuntimes.push_back("scudo");
644     if (SanArgs.linkCXXRuntimes())
645       StaticRuntimes.push_back("scudo_cxx");
646   }
647 }
648 
649 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
650 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
651 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
652                                  ArgStringList &CmdArgs) {
653   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
654       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
655   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
656                            NonWholeStaticRuntimes, HelperStaticRuntimes,
657                            RequiredSymbols);
658 
659   // Inject libfuzzer dependencies.
660   if (TC.getSanitizerArgs().needsFuzzer()
661       && !Args.hasArg(options::OPT_shared)) {
662 
663     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
664     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
665       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
666   }
667 
668   for (auto RT : SharedRuntimes)
669     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
670   for (auto RT : HelperStaticRuntimes)
671     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
672   bool AddExportDynamic = false;
673   for (auto RT : StaticRuntimes) {
674     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
675     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
676   }
677   for (auto RT : NonWholeStaticRuntimes) {
678     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
679     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
680   }
681   for (auto S : RequiredSymbols) {
682     CmdArgs.push_back("-u");
683     CmdArgs.push_back(Args.MakeArgString(S));
684   }
685   // If there is a static runtime with no dynamic list, force all the symbols
686   // to be dynamic to be sure we export sanitizer interface functions.
687   if (AddExportDynamic)
688     CmdArgs.push_back("-export-dynamic");
689 
690   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
691   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
692     CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
693 
694   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
695 }
696 
697 bool tools::areOptimizationsEnabled(const ArgList &Args) {
698   // Find the last -O arg and see if it is non-zero.
699   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
700     return !A->getOption().matches(options::OPT_O0);
701   // Defaults to -O0.
702   return false;
703 }
704 
705 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
706   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
707   if (FinalOutput && Args.hasArg(options::OPT_c)) {
708     SmallString<128> T(FinalOutput->getValue());
709     llvm::sys::path::replace_extension(T, "dwo");
710     return Args.MakeArgString(T);
711   } else {
712     // Use the compilation dir.
713     SmallString<128> T(
714         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
715     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
716     llvm::sys::path::replace_extension(F, "dwo");
717     T += F;
718     return Args.MakeArgString(F);
719   }
720 }
721 
722 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
723                            const JobAction &JA, const ArgList &Args,
724                            const InputInfo &Output, const char *OutFile) {
725   ArgStringList ExtractArgs;
726   ExtractArgs.push_back("--extract-dwo");
727 
728   ArgStringList StripArgs;
729   StripArgs.push_back("--strip-dwo");
730 
731   // Grabbing the output of the earlier compile step.
732   StripArgs.push_back(Output.getFilename());
733   ExtractArgs.push_back(Output.getFilename());
734   ExtractArgs.push_back(OutFile);
735 
736   const char *Exec =
737       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
738   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
739 
740   // First extract the dwo sections.
741   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
742 
743   // Then remove them from the original .o file.
744   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
745 }
746 
747 // Claim options we don't want to warn if they are unused. We do this for
748 // options that build systems might add but are unused when assembling or only
749 // running the preprocessor for example.
750 void tools::claimNoWarnArgs(const ArgList &Args) {
751   // Don't warn about unused -f(no-)?lto.  This can happen when we're
752   // preprocessing, precompiling or assembling.
753   Args.ClaimAllArgs(options::OPT_flto_EQ);
754   Args.ClaimAllArgs(options::OPT_flto);
755   Args.ClaimAllArgs(options::OPT_fno_lto);
756 }
757 
758 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
759   auto *ProfileUseArg = Args.getLastArg(
760       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
761       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
762       options::OPT_fno_profile_instr_use);
763 
764   if (ProfileUseArg &&
765       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
766     ProfileUseArg = nullptr;
767 
768   return ProfileUseArg;
769 }
770 
771 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
772   auto *ProfileSampleUseArg = Args.getLastArg(
773       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
774       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
775       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
776 
777   if (ProfileSampleUseArg &&
778       (ProfileSampleUseArg->getOption().matches(
779            options::OPT_fno_profile_sample_use) ||
780        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
781     return nullptr;
782 
783   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
784                          options::OPT_fauto_profile_EQ);
785 }
786 
787 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
788 /// smooshes them together with platform defaults, to decide whether
789 /// this compile should be using PIC mode or not. Returns a tuple of
790 /// (RelocationModel, PICLevel, IsPIE).
791 std::tuple<llvm::Reloc::Model, unsigned, bool>
792 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
793   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
794   const llvm::Triple &Triple = ToolChain.getTriple();
795 
796   bool PIE = ToolChain.isPIEDefault();
797   bool PIC = PIE || ToolChain.isPICDefault();
798   // The Darwin/MachO default to use PIC does not apply when using -static.
799   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
800     PIE = PIC = false;
801   bool IsPICLevelTwo = PIC;
802 
803   bool KernelOrKext =
804       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
805 
806   // Android-specific defaults for PIC/PIE
807   if (Triple.isAndroid()) {
808     switch (Triple.getArch()) {
809     case llvm::Triple::arm:
810     case llvm::Triple::armeb:
811     case llvm::Triple::thumb:
812     case llvm::Triple::thumbeb:
813     case llvm::Triple::aarch64:
814     case llvm::Triple::mips:
815     case llvm::Triple::mipsel:
816     case llvm::Triple::mips64:
817     case llvm::Triple::mips64el:
818       PIC = true; // "-fpic"
819       break;
820 
821     case llvm::Triple::x86:
822     case llvm::Triple::x86_64:
823       PIC = true; // "-fPIC"
824       IsPICLevelTwo = true;
825       break;
826 
827     default:
828       break;
829     }
830   }
831 
832   // OpenBSD-specific defaults for PIE
833   if (Triple.getOS() == llvm::Triple::OpenBSD) {
834     switch (ToolChain.getArch()) {
835     case llvm::Triple::arm:
836     case llvm::Triple::aarch64:
837     case llvm::Triple::mips64:
838     case llvm::Triple::mips64el:
839     case llvm::Triple::x86:
840     case llvm::Triple::x86_64:
841       IsPICLevelTwo = false; // "-fpie"
842       break;
843 
844     case llvm::Triple::ppc:
845     case llvm::Triple::sparc:
846     case llvm::Triple::sparcel:
847     case llvm::Triple::sparcv9:
848       IsPICLevelTwo = true; // "-fPIE"
849       break;
850 
851     default:
852       break;
853     }
854   }
855 
856   // The last argument relating to either PIC or PIE wins, and no
857   // other argument is used. If the last argument is any flavor of the
858   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
859   // option implicitly enables PIC at the same level.
860   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
861                                     options::OPT_fpic, options::OPT_fno_pic,
862                                     options::OPT_fPIE, options::OPT_fno_PIE,
863                                     options::OPT_fpie, options::OPT_fno_pie);
864   if (Triple.isOSWindows() && LastPICArg &&
865       LastPICArg ==
866           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
867                           options::OPT_fPIE, options::OPT_fpie)) {
868     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
869         << LastPICArg->getSpelling() << Triple.str();
870     if (Triple.getArch() == llvm::Triple::x86_64)
871       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
872     return std::make_tuple(llvm::Reloc::Static, 0U, false);
873   }
874 
875   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
876   // is forced, then neither PIC nor PIE flags will have no effect.
877   if (!ToolChain.isPICDefaultForced()) {
878     if (LastPICArg) {
879       Option O = LastPICArg->getOption();
880       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
881           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
882         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
883         PIC =
884             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
885         IsPICLevelTwo =
886             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
887       } else {
888         PIE = PIC = false;
889         if (EffectiveTriple.isPS4CPU()) {
890           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
891           StringRef Model = ModelArg ? ModelArg->getValue() : "";
892           if (Model != "kernel") {
893             PIC = true;
894             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
895                 << LastPICArg->getSpelling();
896           }
897         }
898       }
899     }
900   }
901 
902   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
903   // PIC level would've been set to level 1, force it back to level 2 PIC
904   // instead.
905   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
906     IsPICLevelTwo |= ToolChain.isPICDefault();
907 
908   // This kernel flags are a trump-card: they will disable PIC/PIE
909   // generation, independent of the argument order.
910   if (KernelOrKext &&
911       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
912        !EffectiveTriple.isWatchOS()))
913     PIC = PIE = false;
914 
915   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
916     // This is a very special mode. It trumps the other modes, almost no one
917     // uses it, and it isn't even valid on any OS but Darwin.
918     if (!Triple.isOSDarwin())
919       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
920           << A->getSpelling() << Triple.str();
921 
922     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
923 
924     // Only a forced PIC mode can cause the actual compile to have PIC defines
925     // etc., no flags are sufficient. This behavior was selected to closely
926     // match that of llvm-gcc and Apple GCC before that.
927     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
928 
929     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
930   }
931 
932   bool EmbeddedPISupported;
933   switch (Triple.getArch()) {
934     case llvm::Triple::arm:
935     case llvm::Triple::armeb:
936     case llvm::Triple::thumb:
937     case llvm::Triple::thumbeb:
938       EmbeddedPISupported = true;
939       break;
940     default:
941       EmbeddedPISupported = false;
942       break;
943   }
944 
945   bool ROPI = false, RWPI = false;
946   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
947   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
948     if (!EmbeddedPISupported)
949       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
950           << LastROPIArg->getSpelling() << Triple.str();
951     ROPI = true;
952   }
953   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
954   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
955     if (!EmbeddedPISupported)
956       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
957           << LastRWPIArg->getSpelling() << Triple.str();
958     RWPI = true;
959   }
960 
961   // ROPI and RWPI are not comaptible with PIC or PIE.
962   if ((ROPI || RWPI) && (PIC || PIE))
963     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
964 
965   // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
966   // used.
967   if ((Triple.getArch() == llvm::Triple::mips64 ||
968        Triple.getArch() == llvm::Triple::mips64el) &&
969       Args.hasArg(options::OPT_mno_abicalls))
970     return std::make_tuple(llvm::Reloc::Static, 0U, false);
971 
972   if (PIC)
973     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
974 
975   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
976   if (ROPI && RWPI)
977     RelocM = llvm::Reloc::ROPI_RWPI;
978   else if (ROPI)
979     RelocM = llvm::Reloc::ROPI;
980   else if (RWPI)
981     RelocM = llvm::Reloc::RWPI;
982 
983   return std::make_tuple(RelocM, 0U, false);
984 }
985 
986 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
987                              ArgStringList &CmdArgs) {
988   llvm::Reloc::Model RelocationModel;
989   unsigned PICLevel;
990   bool IsPIE;
991   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
992 
993   if (RelocationModel != llvm::Reloc::Static)
994     CmdArgs.push_back("-KPIC");
995 }
996 
997 /// \brief Determine whether Objective-C automated reference counting is
998 /// enabled.
999 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1000   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1001 }
1002 
1003 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1004                       ArgStringList &CmdArgs, const ArgList &Args) {
1005   bool isAndroid = Triple.isAndroid();
1006   bool isCygMing = Triple.isOSCygMing();
1007   bool IsIAMCU = Triple.isOSIAMCU();
1008   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1009                       Args.hasArg(options::OPT_static);
1010   if (!D.CCCIsCXX())
1011     CmdArgs.push_back("-lgcc");
1012 
1013   if (StaticLibgcc || isAndroid) {
1014     if (D.CCCIsCXX())
1015       CmdArgs.push_back("-lgcc");
1016   } else {
1017     if (!D.CCCIsCXX() && !isCygMing)
1018       CmdArgs.push_back("--as-needed");
1019     CmdArgs.push_back("-lgcc_s");
1020     if (!D.CCCIsCXX() && !isCygMing)
1021       CmdArgs.push_back("--no-as-needed");
1022   }
1023 
1024   if (StaticLibgcc && !isAndroid && !IsIAMCU)
1025     CmdArgs.push_back("-lgcc_eh");
1026   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
1027     CmdArgs.push_back("-lgcc");
1028 
1029   // According to Android ABI, we have to link with libdl if we are
1030   // linking with non-static libgcc.
1031   //
1032   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
1033   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1034   if (isAndroid && !StaticLibgcc)
1035     CmdArgs.push_back("-ldl");
1036 }
1037 
1038 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1039                            ArgStringList &CmdArgs, const ArgList &Args) {
1040   // Make use of compiler-rt if --rtlib option is used
1041   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1042 
1043   switch (RLT) {
1044   case ToolChain::RLT_CompilerRT:
1045     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1046     break;
1047   case ToolChain::RLT_Libgcc:
1048     // Make sure libgcc is not used under MSVC environment by default
1049     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1050       // Issue error diagnostic if libgcc is explicitly specified
1051       // through command line as --rtlib option argument.
1052       if (Args.hasArg(options::OPT_rtlib_EQ)) {
1053         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1054             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1055       }
1056     } else
1057       AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1058     break;
1059   }
1060 }
1061 
1062 /// Add OpenMP linker script arguments at the end of the argument list so that
1063 /// the fat binary is built by embedding each of the device images into the
1064 /// host. The linker script also defines a few symbols required by the code
1065 /// generation so that the images can be easily retrieved at runtime by the
1066 /// offloading library. This should be used only in tool chains that support
1067 /// linker scripts.
1068 void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1069                                   const InputInfo &Output,
1070                                   const InputInfoList &Inputs,
1071                                   const ArgList &Args, ArgStringList &CmdArgs,
1072                                   const JobAction &JA) {
1073 
1074   // If this is not an OpenMP host toolchain, we don't need to do anything.
1075   if (!JA.isHostOffloading(Action::OFK_OpenMP))
1076     return;
1077 
1078   // Create temporary linker script. Keep it if save-temps is enabled.
1079   const char *LKS;
1080   SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1081   if (C.getDriver().isSaveTempsEnabled()) {
1082     llvm::sys::path::replace_extension(Name, "lk");
1083     LKS = C.getArgs().MakeArgString(Name.c_str());
1084   } else {
1085     llvm::sys::path::replace_extension(Name, "");
1086     Name = C.getDriver().GetTemporaryPath(Name, "lk");
1087     LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1088   }
1089 
1090   // Add linker script option to the command.
1091   CmdArgs.push_back("-T");
1092   CmdArgs.push_back(LKS);
1093 
1094   // Create a buffer to write the contents of the linker script.
1095   std::string LksBuffer;
1096   llvm::raw_string_ostream LksStream(LksBuffer);
1097 
1098   // Get the OpenMP offload tool chains so that we can extract the triple
1099   // associated with each device input.
1100   auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1101   assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1102          "No OpenMP toolchains??");
1103 
1104   // Track the input file name and device triple in order to build the script,
1105   // inserting binaries in the designated sections.
1106   SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1107 
1108   // Add commands to embed target binaries. We ensure that each section and
1109   // image is 16-byte aligned. This is not mandatory, but increases the
1110   // likelihood of data to be aligned with a cache block in several main host
1111   // machines.
1112   LksStream << "/*\n";
1113   LksStream << "       OpenMP Offload Linker Script\n";
1114   LksStream << " *** Automatically generated by Clang ***\n";
1115   LksStream << "*/\n";
1116   LksStream << "TARGET(binary)\n";
1117   auto DTC = OpenMPToolChains.first;
1118   for (auto &II : Inputs) {
1119     const Action *A = II.getAction();
1120     // Is this a device linking action?
1121     if (A && isa<LinkJobAction>(A) &&
1122         A->isDeviceOffloading(Action::OFK_OpenMP)) {
1123       assert(DTC != OpenMPToolChains.second &&
1124              "More device inputs than device toolchains??");
1125       InputBinaryInfo.push_back(std::make_pair(
1126           DTC->second->getTriple().normalize(), II.getFilename()));
1127       ++DTC;
1128       LksStream << "INPUT(" << II.getFilename() << ")\n";
1129     }
1130   }
1131 
1132   assert(DTC == OpenMPToolChains.second &&
1133          "Less device inputs than device toolchains??");
1134 
1135   LksStream << "SECTIONS\n";
1136   LksStream << "{\n";
1137 
1138   // Put each target binary into a separate section.
1139   for (const auto &BI : InputBinaryInfo) {
1140     LksStream << "  .omp_offloading." << BI.first << " :\n";
1141     LksStream << "  ALIGN(0x10)\n";
1142     LksStream << "  {\n";
1143     LksStream << "    PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1144               << " = .);\n";
1145     LksStream << "    " << BI.second << "\n";
1146     LksStream << "    PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1147               << " = .);\n";
1148     LksStream << "  }\n";
1149   }
1150 
1151   // Add commands to define host entries begin and end. We use 1-byte subalign
1152   // so that the linker does not add any padding and the elements in this
1153   // section form an array.
1154   LksStream << "  .omp_offloading.entries :\n";
1155   LksStream << "  ALIGN(0x10)\n";
1156   LksStream << "  SUBALIGN(0x01)\n";
1157   LksStream << "  {\n";
1158   LksStream << "    PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1159   LksStream << "    *(.omp_offloading.entries)\n";
1160   LksStream << "    PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1161   LksStream << "  }\n";
1162   LksStream << "}\n";
1163   LksStream << "INSERT BEFORE .data\n";
1164   LksStream.flush();
1165 
1166   // Dump the contents of the linker script if the user requested that. We
1167   // support this option to enable testing of behavior with -###.
1168   if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1169     llvm::errs() << LksBuffer;
1170 
1171   // If this is a dry run, do not create the linker script file.
1172   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1173     return;
1174 
1175   // Open script file and write the contents.
1176   std::error_code EC;
1177   llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1178 
1179   if (EC) {
1180     C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1181     return;
1182   }
1183 
1184   Lksf << LksBuffer;
1185 }
1186