1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
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 "clang/Driver/Driver.h"
10 #include "InputInfo.h"
11 #include "ToolChains/AMDGPU.h"
12 #include "ToolChains/AVR.h"
13 #include "ToolChains/Ananas.h"
14 #include "ToolChains/BareMetal.h"
15 #include "ToolChains/Clang.h"
16 #include "ToolChains/CloudABI.h"
17 #include "ToolChains/Contiki.h"
18 #include "ToolChains/CrossWindows.h"
19 #include "ToolChains/Cuda.h"
20 #include "ToolChains/Darwin.h"
21 #include "ToolChains/DragonFly.h"
22 #include "ToolChains/FreeBSD.h"
23 #include "ToolChains/Fuchsia.h"
24 #include "ToolChains/Gnu.h"
25 #include "ToolChains/HIP.h"
26 #include "ToolChains/Haiku.h"
27 #include "ToolChains/Hexagon.h"
28 #include "ToolChains/Hurd.h"
29 #include "ToolChains/Lanai.h"
30 #include "ToolChains/Linux.h"
31 #include "ToolChains/MSP430.h"
32 #include "ToolChains/MSVC.h"
33 #include "ToolChains/MinGW.h"
34 #include "ToolChains/Minix.h"
35 #include "ToolChains/MipsLinux.h"
36 #include "ToolChains/Myriad.h"
37 #include "ToolChains/NaCl.h"
38 #include "ToolChains/NetBSD.h"
39 #include "ToolChains/OpenBSD.h"
40 #include "ToolChains/PS4CPU.h"
41 #include "ToolChains/PPCLinux.h"
42 #include "ToolChains/RISCVToolchain.h"
43 #include "ToolChains/Solaris.h"
44 #include "ToolChains/TCE.h"
45 #include "ToolChains/WebAssembly.h"
46 #include "ToolChains/XCore.h"
47 #include "clang/Basic/Version.h"
48 #include "clang/Config/config.h"
49 #include "clang/Driver/Action.h"
50 #include "clang/Driver/Compilation.h"
51 #include "clang/Driver/DriverDiagnostic.h"
52 #include "clang/Driver/Job.h"
53 #include "clang/Driver/Options.h"
54 #include "clang/Driver/SanitizerArgs.h"
55 #include "clang/Driver/Tool.h"
56 #include "clang/Driver/ToolChain.h"
57 #include "llvm/ADT/ArrayRef.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include "llvm/ADT/SmallSet.h"
60 #include "llvm/ADT/StringExtras.h"
61 #include "llvm/ADT/StringSet.h"
62 #include "llvm/ADT/StringSwitch.h"
63 #include "llvm/Config/llvm-config.h"
64 #include "llvm/Option/Arg.h"
65 #include "llvm/Option/ArgList.h"
66 #include "llvm/Option/OptSpecifier.h"
67 #include "llvm/Option/OptTable.h"
68 #include "llvm/Option/Option.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/FileSystem.h"
72 #include "llvm/Support/FormatVariadic.h"
73 #include "llvm/Support/Path.h"
74 #include "llvm/Support/PrettyStackTrace.h"
75 #include "llvm/Support/Process.h"
76 #include "llvm/Support/Program.h"
77 #include "llvm/Support/StringSaver.h"
78 #include "llvm/Support/TargetRegistry.h"
79 #include "llvm/Support/VirtualFileSystem.h"
80 #include "llvm/Support/raw_ostream.h"
81 #include <map>
82 #include <memory>
83 #include <utility>
84 #if LLVM_ON_UNIX
85 #include <unistd.h> // getpid
86 #include <sysexits.h> // EX_IOERR
87 #endif
88 
89 using namespace clang::driver;
90 using namespace clang;
91 using namespace llvm::opt;
92 
93 // static
94 std::string Driver::GetResourcesPath(StringRef BinaryPath,
95                                      StringRef CustomResourceDir) {
96   // Since the resource directory is embedded in the module hash, it's important
97   // that all places that need it call this function, so that they get the
98   // exact same string ("a/../b/" and "b/" get different hashes, for example).
99 
100   // Dir is bin/ or lib/, depending on where BinaryPath is.
101   std::string Dir = llvm::sys::path::parent_path(BinaryPath);
102 
103   SmallString<128> P(Dir);
104   if (CustomResourceDir != "") {
105     llvm::sys::path::append(P, CustomResourceDir);
106   } else {
107     // On Windows, libclang.dll is in bin/.
108     // On non-Windows, libclang.so/.dylib is in lib/.
109     // With a static-library build of libclang, LibClangPath will contain the
110     // path of the embedding binary, which for LLVM binaries will be in bin/.
111     // ../lib gets us to lib/ in both cases.
112     P = llvm::sys::path::parent_path(Dir);
113     llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
114                             CLANG_VERSION_STRING);
115   }
116 
117   return P.str();
118 }
119 
120 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
121                DiagnosticsEngine &Diags,
122                IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
123     : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
124       Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
125       LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
126       SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
127       CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
128       CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
129       CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
130       CCGenDiagnostics(false), TargetTriple(TargetTriple),
131       CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
132       GenReproducer(false), SuppressMissingInputWarning(false) {
133 
134   // Provide a sane fallback if no VFS is specified.
135   if (!this->VFS)
136     this->VFS = llvm::vfs::getRealFileSystem();
137 
138   Name = llvm::sys::path::filename(ClangExecutable);
139   Dir = llvm::sys::path::parent_path(ClangExecutable);
140   InstalledDir = Dir; // Provide a sensible default installed dir.
141 
142 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
143   SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
144 #endif
145 #if defined(CLANG_CONFIG_FILE_USER_DIR)
146   UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
147 #endif
148 
149   // Compute the path to the resource directory.
150   ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
151 }
152 
153 void Driver::ParseDriverMode(StringRef ProgramName,
154                              ArrayRef<const char *> Args) {
155   if (ClangNameParts.isEmpty())
156     ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
157   setDriverModeFromOption(ClangNameParts.DriverMode);
158 
159   for (const char *ArgPtr : Args) {
160     // Ignore nullptrs, they are the response file's EOL markers.
161     if (ArgPtr == nullptr)
162       continue;
163     const StringRef Arg = ArgPtr;
164     setDriverModeFromOption(Arg);
165   }
166 }
167 
168 void Driver::setDriverModeFromOption(StringRef Opt) {
169   const std::string OptName =
170       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
171   if (!Opt.startswith(OptName))
172     return;
173   StringRef Value = Opt.drop_front(OptName.size());
174 
175   if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
176                    .Case("gcc", GCCMode)
177                    .Case("g++", GXXMode)
178                    .Case("cpp", CPPMode)
179                    .Case("cl", CLMode)
180                    .Default(None))
181     Mode = *M;
182   else
183     Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
184 }
185 
186 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
187                                      bool IsClCompatMode,
188                                      bool &ContainsError) {
189   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
190   ContainsError = false;
191 
192   unsigned IncludedFlagsBitmask;
193   unsigned ExcludedFlagsBitmask;
194   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
195       getIncludeExcludeOptionFlagMasks(IsClCompatMode);
196 
197   unsigned MissingArgIndex, MissingArgCount;
198   InputArgList Args =
199       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
200                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
201 
202   // Check for missing argument error.
203   if (MissingArgCount) {
204     Diag(diag::err_drv_missing_argument)
205         << Args.getArgString(MissingArgIndex) << MissingArgCount;
206     ContainsError |=
207         Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
208                                  SourceLocation()) > DiagnosticsEngine::Warning;
209   }
210 
211   // Check for unsupported options.
212   for (const Arg *A : Args) {
213     if (A->getOption().hasFlag(options::Unsupported)) {
214       unsigned DiagID;
215       auto ArgString = A->getAsString(Args);
216       std::string Nearest;
217       if (getOpts().findNearest(
218             ArgString, Nearest, IncludedFlagsBitmask,
219             ExcludedFlagsBitmask | options::Unsupported) > 1) {
220         DiagID = diag::err_drv_unsupported_opt;
221         Diag(DiagID) << ArgString;
222       } else {
223         DiagID = diag::err_drv_unsupported_opt_with_suggestion;
224         Diag(DiagID) << ArgString << Nearest;
225       }
226       ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
227                        DiagnosticsEngine::Warning;
228       continue;
229     }
230 
231     // Warn about -mcpu= without an argument.
232     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
233       Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
234       ContainsError |= Diags.getDiagnosticLevel(
235                            diag::warn_drv_empty_joined_argument,
236                            SourceLocation()) > DiagnosticsEngine::Warning;
237     }
238   }
239 
240   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
241     unsigned DiagID;
242     auto ArgString = A->getAsString(Args);
243     std::string Nearest;
244     if (getOpts().findNearest(
245           ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
246       DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
247                           : diag::err_drv_unknown_argument;
248       Diags.Report(DiagID) << ArgString;
249     } else {
250       DiagID = IsCLMode()
251                    ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
252                    : diag::err_drv_unknown_argument_with_suggestion;
253       Diags.Report(DiagID) << ArgString << Nearest;
254     }
255     ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
256                      DiagnosticsEngine::Warning;
257   }
258 
259   return Args;
260 }
261 
262 // Determine which compilation mode we are in. We look for options which
263 // affect the phase, starting with the earliest phases, and record which
264 // option we used to determine the final phase.
265 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
266                                  Arg **FinalPhaseArg) const {
267   Arg *PhaseArg = nullptr;
268   phases::ID FinalPhase;
269 
270   // -{E,EP,P,M,MM} only run the preprocessor.
271   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
272       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
273       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
274       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
275     FinalPhase = phases::Preprocess;
276 
277     // --precompile only runs up to precompilation.
278   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
279     FinalPhase = phases::Precompile;
280 
281     // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
282   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
283              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
284              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
285              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
286              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
287              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
288              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
289                                         options::OPT__analyze_auto)) ||
290              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
291     FinalPhase = phases::Compile;
292 
293     // -S only runs up to the backend.
294   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
295     FinalPhase = phases::Backend;
296 
297     // -c compilation only runs up to the assembler.
298   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
299     FinalPhase = phases::Assemble;
300 
301     // Otherwise do everything.
302   } else
303     FinalPhase = phases::Link;
304 
305   if (FinalPhaseArg)
306     *FinalPhaseArg = PhaseArg;
307 
308   return FinalPhase;
309 }
310 
311 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
312                          StringRef Value, bool Claim = true) {
313   Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
314                    Args.getBaseArgs().MakeIndex(Value), Value.data());
315   Args.AddSynthesizedArg(A);
316   if (Claim)
317     A->claim();
318   return A;
319 }
320 
321 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
322   DerivedArgList *DAL = new DerivedArgList(Args);
323 
324   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
325   bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
326   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
327   for (Arg *A : Args) {
328     // Unfortunately, we have to parse some forwarding options (-Xassembler,
329     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
330     // (assembler and preprocessor), or bypass a previous driver ('collect2').
331 
332     // Rewrite linker options, to replace --no-demangle with a custom internal
333     // option.
334     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
335          A->getOption().matches(options::OPT_Xlinker)) &&
336         A->containsValue("--no-demangle")) {
337       // Add the rewritten no-demangle argument.
338       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
339 
340       // Add the remaining values as Xlinker arguments.
341       for (StringRef Val : A->getValues())
342         if (Val != "--no-demangle")
343           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
344 
345       continue;
346     }
347 
348     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
349     // some build systems. We don't try to be complete here because we don't
350     // care to encourage this usage model.
351     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
352         (A->getValue(0) == StringRef("-MD") ||
353          A->getValue(0) == StringRef("-MMD"))) {
354       // Rewrite to -MD/-MMD along with -MF.
355       if (A->getValue(0) == StringRef("-MD"))
356         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
357       else
358         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
359       if (A->getNumValues() == 2)
360         DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
361                             A->getValue(1));
362       continue;
363     }
364 
365     // Rewrite reserved library names.
366     if (A->getOption().matches(options::OPT_l)) {
367       StringRef Value = A->getValue();
368 
369       // Rewrite unless -nostdlib is present.
370       if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
371           Value == "stdc++") {
372         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
373         continue;
374       }
375 
376       // Rewrite unconditionally.
377       if (Value == "cc_kext") {
378         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
379         continue;
380       }
381     }
382 
383     // Pick up inputs via the -- option.
384     if (A->getOption().matches(options::OPT__DASH_DASH)) {
385       A->claim();
386       for (StringRef Val : A->getValues())
387         DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
388       continue;
389     }
390 
391     DAL->append(A);
392   }
393 
394   // Enforce -static if -miamcu is present.
395   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
396     DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
397 
398 // Add a default value of -mlinker-version=, if one was given and the user
399 // didn't specify one.
400 #if defined(HOST_LINK_VERSION)
401   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
402       strlen(HOST_LINK_VERSION) > 0) {
403     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
404                       HOST_LINK_VERSION);
405     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
406   }
407 #endif
408 
409   return DAL;
410 }
411 
412 /// Compute target triple from args.
413 ///
414 /// This routine provides the logic to compute a target triple from various
415 /// args passed to the driver and the default triple string.
416 static llvm::Triple computeTargetTriple(const Driver &D,
417                                         StringRef TargetTriple,
418                                         const ArgList &Args,
419                                         StringRef DarwinArchName = "") {
420   // FIXME: Already done in Compilation *Driver::BuildCompilation
421   if (const Arg *A = Args.getLastArg(options::OPT_target))
422     TargetTriple = A->getValue();
423 
424   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
425 
426   // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
427   // -gnu* only, and we can not change this, so we have to detect that case as
428   // being the Hurd OS.
429   if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
430       TargetTriple.find("-pc-gnu") != StringRef::npos)
431     Target.setOSName("hurd");
432 
433   // Handle Apple-specific options available here.
434   if (Target.isOSBinFormatMachO()) {
435     // If an explicit Darwin arch name is given, that trumps all.
436     if (!DarwinArchName.empty()) {
437       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
438       return Target;
439     }
440 
441     // Handle the Darwin '-arch' flag.
442     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
443       StringRef ArchName = A->getValue();
444       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
445     }
446   }
447 
448   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
449   // '-mbig-endian'/'-EB'.
450   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
451                                options::OPT_mbig_endian)) {
452     if (A->getOption().matches(options::OPT_mlittle_endian)) {
453       llvm::Triple LE = Target.getLittleEndianArchVariant();
454       if (LE.getArch() != llvm::Triple::UnknownArch)
455         Target = std::move(LE);
456     } else {
457       llvm::Triple BE = Target.getBigEndianArchVariant();
458       if (BE.getArch() != llvm::Triple::UnknownArch)
459         Target = std::move(BE);
460     }
461   }
462 
463   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
464   if (Target.getArch() == llvm::Triple::tce ||
465       Target.getOS() == llvm::Triple::Minix)
466     return Target;
467 
468   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
469   Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
470                            options::OPT_m32, options::OPT_m16);
471   if (A) {
472     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
473 
474     if (A->getOption().matches(options::OPT_m64)) {
475       AT = Target.get64BitArchVariant().getArch();
476       if (Target.getEnvironment() == llvm::Triple::GNUX32)
477         Target.setEnvironment(llvm::Triple::GNU);
478     } else if (A->getOption().matches(options::OPT_mx32) &&
479                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
480       AT = llvm::Triple::x86_64;
481       Target.setEnvironment(llvm::Triple::GNUX32);
482     } else if (A->getOption().matches(options::OPT_m32)) {
483       AT = Target.get32BitArchVariant().getArch();
484       if (Target.getEnvironment() == llvm::Triple::GNUX32)
485         Target.setEnvironment(llvm::Triple::GNU);
486     } else if (A->getOption().matches(options::OPT_m16) &&
487                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
488       AT = llvm::Triple::x86;
489       Target.setEnvironment(llvm::Triple::CODE16);
490     }
491 
492     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
493       Target.setArch(AT);
494   }
495 
496   // Handle -miamcu flag.
497   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
498     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
499       D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
500                                                        << Target.str();
501 
502     if (A && !A->getOption().matches(options::OPT_m32))
503       D.Diag(diag::err_drv_argument_not_allowed_with)
504           << "-miamcu" << A->getBaseArg().getAsString(Args);
505 
506     Target.setArch(llvm::Triple::x86);
507     Target.setArchName("i586");
508     Target.setEnvironment(llvm::Triple::UnknownEnvironment);
509     Target.setEnvironmentName("");
510     Target.setOS(llvm::Triple::ELFIAMCU);
511     Target.setVendor(llvm::Triple::UnknownVendor);
512     Target.setVendorName("intel");
513   }
514 
515   // If target is MIPS adjust the target triple
516   // accordingly to provided ABI name.
517   A = Args.getLastArg(options::OPT_mabi_EQ);
518   if (A && Target.isMIPS()) {
519     StringRef ABIName = A->getValue();
520     if (ABIName == "32") {
521       Target = Target.get32BitArchVariant();
522       if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
523           Target.getEnvironment() == llvm::Triple::GNUABIN32)
524         Target.setEnvironment(llvm::Triple::GNU);
525     } else if (ABIName == "n32") {
526       Target = Target.get64BitArchVariant();
527       if (Target.getEnvironment() == llvm::Triple::GNU ||
528           Target.getEnvironment() == llvm::Triple::GNUABI64)
529         Target.setEnvironment(llvm::Triple::GNUABIN32);
530     } else if (ABIName == "64") {
531       Target = Target.get64BitArchVariant();
532       if (Target.getEnvironment() == llvm::Triple::GNU ||
533           Target.getEnvironment() == llvm::Triple::GNUABIN32)
534         Target.setEnvironment(llvm::Triple::GNUABI64);
535     }
536   }
537 
538   return Target;
539 }
540 
541 // Parse the LTO options and record the type of LTO compilation
542 // based on which -f(no-)?lto(=.*)? option occurs last.
543 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
544   LTOMode = LTOK_None;
545   if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
546                     options::OPT_fno_lto, false))
547     return;
548 
549   StringRef LTOName("full");
550 
551   const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
552   if (A)
553     LTOName = A->getValue();
554 
555   LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
556                 .Case("full", LTOK_Full)
557                 .Case("thin", LTOK_Thin)
558                 .Default(LTOK_Unknown);
559 
560   if (LTOMode == LTOK_Unknown) {
561     assert(A);
562     Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
563                                                     << A->getValue();
564   }
565 }
566 
567 /// Compute the desired OpenMP runtime from the flags provided.
568 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
569   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
570 
571   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
572   if (A)
573     RuntimeName = A->getValue();
574 
575   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
576                 .Case("libomp", OMPRT_OMP)
577                 .Case("libgomp", OMPRT_GOMP)
578                 .Case("libiomp5", OMPRT_IOMP5)
579                 .Default(OMPRT_Unknown);
580 
581   if (RT == OMPRT_Unknown) {
582     if (A)
583       Diag(diag::err_drv_unsupported_option_argument)
584           << A->getOption().getName() << A->getValue();
585     else
586       // FIXME: We could use a nicer diagnostic here.
587       Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
588   }
589 
590   return RT;
591 }
592 
593 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
594                                               InputList &Inputs) {
595 
596   //
597   // CUDA/HIP
598   //
599   // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
600   // or HIP type. However, mixed CUDA/HIP compilation is not supported.
601   bool IsCuda =
602       llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
603         return types::isCuda(I.first);
604       });
605   bool IsHIP =
606       llvm::any_of(Inputs,
607                    [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
608                      return types::isHIP(I.first);
609                    }) ||
610       C.getInputArgs().hasArg(options::OPT_hip_link);
611   if (IsCuda && IsHIP) {
612     Diag(clang::diag::err_drv_mix_cuda_hip);
613     return;
614   }
615   if (IsCuda) {
616     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
617     const llvm::Triple &HostTriple = HostTC->getTriple();
618     StringRef DeviceTripleStr;
619     auto OFK = Action::OFK_Cuda;
620     DeviceTripleStr =
621         HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
622     llvm::Triple CudaTriple(DeviceTripleStr);
623     // Use the CUDA and host triples as the key into the ToolChains map,
624     // because the device toolchain we create depends on both.
625     auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
626     if (!CudaTC) {
627       CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
628           *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
629     }
630     C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
631   } else if (IsHIP) {
632     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
633     const llvm::Triple &HostTriple = HostTC->getTriple();
634     StringRef DeviceTripleStr;
635     auto OFK = Action::OFK_HIP;
636     DeviceTripleStr = "amdgcn-amd-amdhsa";
637     llvm::Triple HIPTriple(DeviceTripleStr);
638     // Use the HIP and host triples as the key into the ToolChains map,
639     // because the device toolchain we create depends on both.
640     auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
641     if (!HIPTC) {
642       HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
643           *this, HIPTriple, *HostTC, C.getInputArgs());
644     }
645     C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
646   }
647 
648   //
649   // OpenMP
650   //
651   // We need to generate an OpenMP toolchain if the user specified targets with
652   // the -fopenmp-targets option.
653   if (Arg *OpenMPTargets =
654           C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
655     if (OpenMPTargets->getNumValues()) {
656       // We expect that -fopenmp-targets is always used in conjunction with the
657       // option -fopenmp specifying a valid runtime with offloading support,
658       // i.e. libomp or libiomp.
659       bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
660           options::OPT_fopenmp, options::OPT_fopenmp_EQ,
661           options::OPT_fno_openmp, false);
662       if (HasValidOpenMPRuntime) {
663         OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
664         HasValidOpenMPRuntime =
665             OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
666       }
667 
668       if (HasValidOpenMPRuntime) {
669         llvm::StringMap<const char *> FoundNormalizedTriples;
670         for (const char *Val : OpenMPTargets->getValues()) {
671           llvm::Triple TT(Val);
672           std::string NormalizedName = TT.normalize();
673 
674           // Make sure we don't have a duplicate triple.
675           auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
676           if (Duplicate != FoundNormalizedTriples.end()) {
677             Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
678                 << Val << Duplicate->second;
679             continue;
680           }
681 
682           // Store the current triple so that we can check for duplicates in the
683           // following iterations.
684           FoundNormalizedTriples[NormalizedName] = Val;
685 
686           // If the specified target is invalid, emit a diagnostic.
687           if (TT.getArch() == llvm::Triple::UnknownArch)
688             Diag(clang::diag::err_drv_invalid_omp_target) << Val;
689           else {
690             const ToolChain *TC;
691             // CUDA toolchains have to be selected differently. They pair host
692             // and device in their implementation.
693             if (TT.isNVPTX()) {
694               const ToolChain *HostTC =
695                   C.getSingleOffloadToolChain<Action::OFK_Host>();
696               assert(HostTC && "Host toolchain should be always defined.");
697               auto &CudaTC =
698                   ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
699               if (!CudaTC)
700                 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
701                     *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
702               TC = CudaTC.get();
703             } else
704               TC = &getToolChain(C.getInputArgs(), TT);
705             C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
706           }
707         }
708       } else
709         Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
710     } else
711       Diag(clang::diag::warn_drv_empty_joined_argument)
712           << OpenMPTargets->getAsString(C.getInputArgs());
713   }
714 
715   //
716   // TODO: Add support for other offloading programming models here.
717   //
718 }
719 
720 /// Looks the given directories for the specified file.
721 ///
722 /// \param[out] FilePath File path, if the file was found.
723 /// \param[in]  Dirs Directories used for the search.
724 /// \param[in]  FileName Name of the file to search for.
725 /// \return True if file was found.
726 ///
727 /// Looks for file specified by FileName sequentially in directories specified
728 /// by Dirs.
729 ///
730 static bool searchForFile(SmallVectorImpl<char> &FilePath,
731                           ArrayRef<std::string> Dirs,
732                           StringRef FileName) {
733   SmallString<128> WPath;
734   for (const StringRef &Dir : Dirs) {
735     if (Dir.empty())
736       continue;
737     WPath.clear();
738     llvm::sys::path::append(WPath, Dir, FileName);
739     llvm::sys::path::native(WPath);
740     if (llvm::sys::fs::is_regular_file(WPath)) {
741       FilePath = std::move(WPath);
742       return true;
743     }
744   }
745   return false;
746 }
747 
748 bool Driver::readConfigFile(StringRef FileName) {
749   // Try reading the given file.
750   SmallVector<const char *, 32> NewCfgArgs;
751   if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
752     Diag(diag::err_drv_cannot_read_config_file) << FileName;
753     return true;
754   }
755 
756   // Read options from config file.
757   llvm::SmallString<128> CfgFileName(FileName);
758   llvm::sys::path::native(CfgFileName);
759   ConfigFile = CfgFileName.str();
760   bool ContainErrors;
761   CfgOptions = llvm::make_unique<InputArgList>(
762       ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
763   if (ContainErrors) {
764     CfgOptions.reset();
765     return true;
766   }
767 
768   if (CfgOptions->hasArg(options::OPT_config)) {
769     CfgOptions.reset();
770     Diag(diag::err_drv_nested_config_file);
771     return true;
772   }
773 
774   // Claim all arguments that come from a configuration file so that the driver
775   // does not warn on any that is unused.
776   for (Arg *A : *CfgOptions)
777     A->claim();
778   return false;
779 }
780 
781 bool Driver::loadConfigFile() {
782   std::string CfgFileName;
783   bool FileSpecifiedExplicitly = false;
784 
785   // Process options that change search path for config files.
786   if (CLOptions) {
787     if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
788       SmallString<128> CfgDir;
789       CfgDir.append(
790           CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
791       if (!CfgDir.empty()) {
792         if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
793           SystemConfigDir.clear();
794         else
795           SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
796       }
797     }
798     if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
799       SmallString<128> CfgDir;
800       CfgDir.append(
801           CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
802       if (!CfgDir.empty()) {
803         if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
804           UserConfigDir.clear();
805         else
806           UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
807       }
808     }
809   }
810 
811   // First try to find config file specified in command line.
812   if (CLOptions) {
813     std::vector<std::string> ConfigFiles =
814         CLOptions->getAllArgValues(options::OPT_config);
815     if (ConfigFiles.size() > 1) {
816       Diag(diag::err_drv_duplicate_config);
817       return true;
818     }
819 
820     if (!ConfigFiles.empty()) {
821       CfgFileName = ConfigFiles.front();
822       assert(!CfgFileName.empty());
823 
824       // If argument contains directory separator, treat it as a path to
825       // configuration file.
826       if (llvm::sys::path::has_parent_path(CfgFileName)) {
827         SmallString<128> CfgFilePath;
828         if (llvm::sys::path::is_relative(CfgFileName))
829           llvm::sys::fs::current_path(CfgFilePath);
830         llvm::sys::path::append(CfgFilePath, CfgFileName);
831         if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
832           Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
833           return true;
834         }
835         return readConfigFile(CfgFilePath);
836       }
837 
838       FileSpecifiedExplicitly = true;
839     }
840   }
841 
842   // If config file is not specified explicitly, try to deduce configuration
843   // from executable name. For instance, an executable 'armv7l-clang' will
844   // search for config file 'armv7l-clang.cfg'.
845   if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
846     CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
847 
848   if (CfgFileName.empty())
849     return false;
850 
851   // Determine architecture part of the file name, if it is present.
852   StringRef CfgFileArch = CfgFileName;
853   size_t ArchPrefixLen = CfgFileArch.find('-');
854   if (ArchPrefixLen == StringRef::npos)
855     ArchPrefixLen = CfgFileArch.size();
856   llvm::Triple CfgTriple;
857   CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
858   CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
859   if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
860     ArchPrefixLen = 0;
861 
862   if (!StringRef(CfgFileName).endswith(".cfg"))
863     CfgFileName += ".cfg";
864 
865   // If config file starts with architecture name and command line options
866   // redefine architecture (with options like -m32 -LE etc), try finding new
867   // config file with that architecture.
868   SmallString<128> FixedConfigFile;
869   size_t FixedArchPrefixLen = 0;
870   if (ArchPrefixLen) {
871     // Get architecture name from config file name like 'i386.cfg' or
872     // 'armv7l-clang.cfg'.
873     // Check if command line options changes effective triple.
874     llvm::Triple EffectiveTriple = computeTargetTriple(*this,
875                                              CfgTriple.getTriple(), *CLOptions);
876     if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
877       FixedConfigFile = EffectiveTriple.getArchName();
878       FixedArchPrefixLen = FixedConfigFile.size();
879       // Append the rest of original file name so that file name transforms
880       // like: i386-clang.cfg -> x86_64-clang.cfg.
881       if (ArchPrefixLen < CfgFileName.size())
882         FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
883     }
884   }
885 
886   // Prepare list of directories where config file is searched for.
887   SmallVector<std::string, 3> CfgFileSearchDirs;
888   CfgFileSearchDirs.push_back(UserConfigDir);
889   CfgFileSearchDirs.push_back(SystemConfigDir);
890   CfgFileSearchDirs.push_back(Dir);
891 
892   // Try to find config file. First try file with corrected architecture.
893   llvm::SmallString<128> CfgFilePath;
894   if (!FixedConfigFile.empty()) {
895     if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
896       return readConfigFile(CfgFilePath);
897     // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
898     FixedConfigFile.resize(FixedArchPrefixLen);
899     FixedConfigFile.append(".cfg");
900     if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
901       return readConfigFile(CfgFilePath);
902   }
903 
904   // Then try original file name.
905   if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
906     return readConfigFile(CfgFilePath);
907 
908   // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
909   if (!ClangNameParts.ModeSuffix.empty() &&
910       !ClangNameParts.TargetPrefix.empty()) {
911     CfgFileName.assign(ClangNameParts.TargetPrefix);
912     CfgFileName.append(".cfg");
913     if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
914       return readConfigFile(CfgFilePath);
915   }
916 
917   // Report error but only if config file was specified explicitly, by option
918   // --config. If it was deduced from executable name, it is not an error.
919   if (FileSpecifiedExplicitly) {
920     Diag(diag::err_drv_config_file_not_found) << CfgFileName;
921     for (const std::string &SearchDir : CfgFileSearchDirs)
922       if (!SearchDir.empty())
923         Diag(diag::note_drv_config_file_searched_in) << SearchDir;
924     return true;
925   }
926 
927   return false;
928 }
929 
930 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
931   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
932 
933   // FIXME: Handle environment options which affect driver behavior, somewhere
934   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
935 
936   if (Optional<std::string> CompilerPathValue =
937           llvm::sys::Process::GetEnv("COMPILER_PATH")) {
938     StringRef CompilerPath = *CompilerPathValue;
939     while (!CompilerPath.empty()) {
940       std::pair<StringRef, StringRef> Split =
941           CompilerPath.split(llvm::sys::EnvPathSeparator);
942       PrefixDirs.push_back(Split.first);
943       CompilerPath = Split.second;
944     }
945   }
946 
947   // We look for the driver mode option early, because the mode can affect
948   // how other options are parsed.
949   ParseDriverMode(ClangExecutable, ArgList.slice(1));
950 
951   // FIXME: What are we going to do with -V and -b?
952 
953   // Arguments specified in command line.
954   bool ContainsError;
955   CLOptions = llvm::make_unique<InputArgList>(
956       ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
957 
958   // Try parsing configuration file.
959   if (!ContainsError)
960     ContainsError = loadConfigFile();
961   bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
962 
963   // All arguments, from both config file and command line.
964   InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
965                                               : std::move(*CLOptions));
966 
967   auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
968       unsigned Index = Args.MakeIndex(Opt->getSpelling());
969       Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
970                                      Index, BaseArg);
971       Copy->getValues() = Opt->getValues();
972       if (Opt->isClaimed())
973         Copy->claim();
974       Args.append(Copy);
975   };
976 
977   if (HasConfigFile)
978     for (auto *Opt : *CLOptions) {
979       if (Opt->getOption().matches(options::OPT_config))
980         continue;
981       const Arg *BaseArg = &Opt->getBaseArg();
982       if (BaseArg == Opt)
983         BaseArg = nullptr;
984       appendOneArg(Opt, BaseArg);
985     }
986 
987   // In CL mode, look for any pass-through arguments
988   if (IsCLMode() && !ContainsError) {
989     SmallVector<const char *, 16> CLModePassThroughArgList;
990     for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
991       A->claim();
992       CLModePassThroughArgList.push_back(A->getValue());
993     }
994 
995     if (!CLModePassThroughArgList.empty()) {
996       // Parse any pass through args using default clang processing rather
997       // than clang-cl processing.
998       auto CLModePassThroughOptions = llvm::make_unique<InputArgList>(
999           ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1000 
1001       if (!ContainsError)
1002         for (auto *Opt : *CLModePassThroughOptions) {
1003           appendOneArg(Opt, nullptr);
1004         }
1005     }
1006   }
1007 
1008   // FIXME: This stuff needs to go into the Compilation, not the driver.
1009   bool CCCPrintPhases;
1010 
1011   // Silence driver warnings if requested
1012   Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1013 
1014   // -no-canonical-prefixes is used very early in main.
1015   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1016 
1017   // Ignore -pipe.
1018   Args.ClaimAllArgs(options::OPT_pipe);
1019 
1020   // Extract -ccc args.
1021   //
1022   // FIXME: We need to figure out where this behavior should live. Most of it
1023   // should be outside in the client; the parts that aren't should have proper
1024   // options, either by introducing new ones or by overloading gcc ones like -V
1025   // or -b.
1026   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1027   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1028   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1029     CCCGenericGCCName = A->getValue();
1030   GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1031                                options::OPT_fno_crash_diagnostics,
1032                                !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
1033   // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1034   // and getToolChain is const.
1035   if (IsCLMode()) {
1036     // clang-cl targets MSVC-style Win32.
1037     llvm::Triple T(TargetTriple);
1038     T.setOS(llvm::Triple::Win32);
1039     T.setVendor(llvm::Triple::PC);
1040     T.setEnvironment(llvm::Triple::MSVC);
1041     T.setObjectFormat(llvm::Triple::COFF);
1042     TargetTriple = T.str();
1043   }
1044   if (const Arg *A = Args.getLastArg(options::OPT_target))
1045     TargetTriple = A->getValue();
1046   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1047     Dir = InstalledDir = A->getValue();
1048   for (const Arg *A : Args.filtered(options::OPT_B)) {
1049     A->claim();
1050     PrefixDirs.push_back(A->getValue(0));
1051   }
1052   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1053     SysRoot = A->getValue();
1054   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1055     DyldPrefix = A->getValue();
1056 
1057   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1058     ResourceDir = A->getValue();
1059 
1060   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1061     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1062                     .Case("cwd", SaveTempsCwd)
1063                     .Case("obj", SaveTempsObj)
1064                     .Default(SaveTempsCwd);
1065   }
1066 
1067   setLTOMode(Args);
1068 
1069   // Process -fembed-bitcode= flags.
1070   if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1071     StringRef Name = A->getValue();
1072     unsigned Model = llvm::StringSwitch<unsigned>(Name)
1073         .Case("off", EmbedNone)
1074         .Case("all", EmbedBitcode)
1075         .Case("bitcode", EmbedBitcode)
1076         .Case("marker", EmbedMarker)
1077         .Default(~0U);
1078     if (Model == ~0U) {
1079       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1080                                                 << Name;
1081     } else
1082       BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1083   }
1084 
1085   std::unique_ptr<llvm::opt::InputArgList> UArgs =
1086       llvm::make_unique<InputArgList>(std::move(Args));
1087 
1088   // Perform the default argument translations.
1089   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1090 
1091   // Owned by the host.
1092   const ToolChain &TC = getToolChain(
1093       *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1094 
1095   // The compilation takes ownership of Args.
1096   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1097                                    ContainsError);
1098 
1099   if (!HandleImmediateArgs(*C))
1100     return C;
1101 
1102   // Construct the list of inputs.
1103   InputList Inputs;
1104   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1105 
1106   // Populate the tool chains for the offloading devices, if any.
1107   CreateOffloadingDeviceToolChains(*C, Inputs);
1108 
1109   // Construct the list of abstract actions to perform for this compilation. On
1110   // MachO targets this uses the driver-driver and universal actions.
1111   if (TC.getTriple().isOSBinFormatMachO())
1112     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1113   else
1114     BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1115 
1116   if (CCCPrintPhases) {
1117     PrintActions(*C);
1118     return C;
1119   }
1120 
1121   BuildJobs(*C);
1122 
1123   return C;
1124 }
1125 
1126 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1127   llvm::opt::ArgStringList ASL;
1128   for (const auto *A : Args)
1129     A->render(Args, ASL);
1130 
1131   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1132     if (I != ASL.begin())
1133       OS << ' ';
1134     Command::printArg(OS, *I, true);
1135   }
1136   OS << '\n';
1137 }
1138 
1139 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1140                                     SmallString<128> &CrashDiagDir) {
1141   using namespace llvm::sys;
1142   assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1143          "Only knows about .crash files on Darwin");
1144 
1145   // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1146   // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1147   // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1148   path::home_directory(CrashDiagDir);
1149   if (CrashDiagDir.startswith("/var/root"))
1150     CrashDiagDir = "/";
1151   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1152   int PID =
1153 #if LLVM_ON_UNIX
1154       getpid();
1155 #else
1156       0;
1157 #endif
1158   std::error_code EC;
1159   fs::file_status FileStatus;
1160   TimePoint<> LastAccessTime;
1161   SmallString<128> CrashFilePath;
1162   // Lookup the .crash files and get the one generated by a subprocess spawned
1163   // by this driver invocation.
1164   for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1165        File != FileEnd && !EC; File.increment(EC)) {
1166     StringRef FileName = path::filename(File->path());
1167     if (!FileName.startswith(Name))
1168       continue;
1169     if (fs::status(File->path(), FileStatus))
1170       continue;
1171     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1172         llvm::MemoryBuffer::getFile(File->path());
1173     if (!CrashFile)
1174       continue;
1175     // The first line should start with "Process:", otherwise this isn't a real
1176     // .crash file.
1177     StringRef Data = CrashFile.get()->getBuffer();
1178     if (!Data.startswith("Process:"))
1179       continue;
1180     // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1181     size_t ParentProcPos = Data.find("Parent Process:");
1182     if (ParentProcPos == StringRef::npos)
1183       continue;
1184     size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1185     if (LineEnd == StringRef::npos)
1186       continue;
1187     StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1188     int OpenBracket = -1, CloseBracket = -1;
1189     for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1190       if (ParentProcess[i] == '[')
1191         OpenBracket = i;
1192       if (ParentProcess[i] == ']')
1193         CloseBracket = i;
1194     }
1195     // Extract the parent process PID from the .crash file and check whether
1196     // it matches this driver invocation pid.
1197     int CrashPID;
1198     if (OpenBracket < 0 || CloseBracket < 0 ||
1199         ParentProcess.slice(OpenBracket + 1, CloseBracket)
1200             .getAsInteger(10, CrashPID) || CrashPID != PID) {
1201       continue;
1202     }
1203 
1204     // Found a .crash file matching the driver pid. To avoid getting an older
1205     // and misleading crash file, continue looking for the most recent.
1206     // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1207     // multiple crashes poiting to the same parent process. Since the driver
1208     // does not collect pid information for the dispatched invocation there's
1209     // currently no way to distinguish among them.
1210     const auto FileAccessTime = FileStatus.getLastModificationTime();
1211     if (FileAccessTime > LastAccessTime) {
1212       CrashFilePath.assign(File->path());
1213       LastAccessTime = FileAccessTime;
1214     }
1215   }
1216 
1217   // If found, copy it over to the location of other reproducer files.
1218   if (!CrashFilePath.empty()) {
1219     EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1220     if (EC)
1221       return false;
1222     return true;
1223   }
1224 
1225   return false;
1226 }
1227 
1228 // When clang crashes, produce diagnostic information including the fully
1229 // preprocessed source file(s).  Request that the developer attach the
1230 // diagnostic information to a bug report.
1231 void Driver::generateCompilationDiagnostics(
1232     Compilation &C, const Command &FailingCommand,
1233     StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1234   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1235     return;
1236 
1237   // Don't try to generate diagnostics for link or dsymutil jobs.
1238   if (FailingCommand.getCreator().isLinkJob() ||
1239       FailingCommand.getCreator().isDsymutilJob())
1240     return;
1241 
1242   // Print the version of the compiler.
1243   PrintVersion(C, llvm::errs());
1244 
1245   Diag(clang::diag::note_drv_command_failed_diag_msg)
1246       << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1247          "crash backtrace, preprocessed source, and associated run script.";
1248 
1249   // Suppress driver output and emit preprocessor output to temp file.
1250   Mode = CPPMode;
1251   CCGenDiagnostics = true;
1252 
1253   // Save the original job command(s).
1254   Command Cmd = FailingCommand;
1255 
1256   // Keep track of whether we produce any errors while trying to produce
1257   // preprocessed sources.
1258   DiagnosticErrorTrap Trap(Diags);
1259 
1260   // Suppress tool output.
1261   C.initCompilationForDiagnostics();
1262 
1263   // Construct the list of inputs.
1264   InputList Inputs;
1265   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1266 
1267   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1268     bool IgnoreInput = false;
1269 
1270     // Ignore input from stdin or any inputs that cannot be preprocessed.
1271     // Check type first as not all linker inputs have a value.
1272     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1273       IgnoreInput = true;
1274     } else if (!strcmp(it->second->getValue(), "-")) {
1275       Diag(clang::diag::note_drv_command_failed_diag_msg)
1276           << "Error generating preprocessed source(s) - "
1277              "ignoring input from stdin.";
1278       IgnoreInput = true;
1279     }
1280 
1281     if (IgnoreInput) {
1282       it = Inputs.erase(it);
1283       ie = Inputs.end();
1284     } else {
1285       ++it;
1286     }
1287   }
1288 
1289   if (Inputs.empty()) {
1290     Diag(clang::diag::note_drv_command_failed_diag_msg)
1291         << "Error generating preprocessed source(s) - "
1292            "no preprocessable inputs.";
1293     return;
1294   }
1295 
1296   // Don't attempt to generate preprocessed files if multiple -arch options are
1297   // used, unless they're all duplicates.
1298   llvm::StringSet<> ArchNames;
1299   for (const Arg *A : C.getArgs()) {
1300     if (A->getOption().matches(options::OPT_arch)) {
1301       StringRef ArchName = A->getValue();
1302       ArchNames.insert(ArchName);
1303     }
1304   }
1305   if (ArchNames.size() > 1) {
1306     Diag(clang::diag::note_drv_command_failed_diag_msg)
1307         << "Error generating preprocessed source(s) - cannot generate "
1308            "preprocessed source with multiple -arch options.";
1309     return;
1310   }
1311 
1312   // Construct the list of abstract actions to perform for this compilation. On
1313   // Darwin OSes this uses the driver-driver and builds universal actions.
1314   const ToolChain &TC = C.getDefaultToolChain();
1315   if (TC.getTriple().isOSBinFormatMachO())
1316     BuildUniversalActions(C, TC, Inputs);
1317   else
1318     BuildActions(C, C.getArgs(), Inputs, C.getActions());
1319 
1320   BuildJobs(C);
1321 
1322   // If there were errors building the compilation, quit now.
1323   if (Trap.hasErrorOccurred()) {
1324     Diag(clang::diag::note_drv_command_failed_diag_msg)
1325         << "Error generating preprocessed source(s).";
1326     return;
1327   }
1328 
1329   // Generate preprocessed output.
1330   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1331   C.ExecuteJobs(C.getJobs(), FailingCommands);
1332 
1333   // If any of the preprocessing commands failed, clean up and exit.
1334   if (!FailingCommands.empty()) {
1335     Diag(clang::diag::note_drv_command_failed_diag_msg)
1336         << "Error generating preprocessed source(s).";
1337     return;
1338   }
1339 
1340   const ArgStringList &TempFiles = C.getTempFiles();
1341   if (TempFiles.empty()) {
1342     Diag(clang::diag::note_drv_command_failed_diag_msg)
1343         << "Error generating preprocessed source(s).";
1344     return;
1345   }
1346 
1347   Diag(clang::diag::note_drv_command_failed_diag_msg)
1348       << "\n********************\n\n"
1349          "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1350          "Preprocessed source(s) and associated run script(s) are located at:";
1351 
1352   SmallString<128> VFS;
1353   SmallString<128> ReproCrashFilename;
1354   for (const char *TempFile : TempFiles) {
1355     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1356     if (Report)
1357       Report->TemporaryFiles.push_back(TempFile);
1358     if (ReproCrashFilename.empty()) {
1359       ReproCrashFilename = TempFile;
1360       llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1361     }
1362     if (StringRef(TempFile).endswith(".cache")) {
1363       // In some cases (modules) we'll dump extra data to help with reproducing
1364       // the crash into a directory next to the output.
1365       VFS = llvm::sys::path::filename(TempFile);
1366       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1367     }
1368   }
1369 
1370   // Assume associated files are based off of the first temporary file.
1371   CrashReportInfo CrashInfo(TempFiles[0], VFS);
1372 
1373   llvm::SmallString<128> Script(CrashInfo.Filename);
1374   llvm::sys::path::replace_extension(Script, "sh");
1375   std::error_code EC;
1376   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1377   if (EC) {
1378     Diag(clang::diag::note_drv_command_failed_diag_msg)
1379         << "Error generating run script: " << Script << " " << EC.message();
1380   } else {
1381     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1382              << "# Driver args: ";
1383     printArgList(ScriptOS, C.getInputArgs());
1384     ScriptOS << "# Original command: ";
1385     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1386     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1387     if (!AdditionalInformation.empty())
1388       ScriptOS << "\n# Additional information: " << AdditionalInformation
1389                << "\n";
1390     if (Report)
1391       Report->TemporaryFiles.push_back(Script.str());
1392     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1393   }
1394 
1395   // On darwin, provide information about the .crash diagnostic report.
1396   if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1397     SmallString<128> CrashDiagDir;
1398     if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1399       Diag(clang::diag::note_drv_command_failed_diag_msg)
1400           << ReproCrashFilename.str();
1401     } else { // Suggest a directory for the user to look for .crash files.
1402       llvm::sys::path::append(CrashDiagDir, Name);
1403       CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1404       Diag(clang::diag::note_drv_command_failed_diag_msg)
1405           << "Crash backtrace is located in";
1406       Diag(clang::diag::note_drv_command_failed_diag_msg)
1407           << CrashDiagDir.str();
1408       Diag(clang::diag::note_drv_command_failed_diag_msg)
1409           << "(choose the .crash file that corresponds to your crash)";
1410     }
1411   }
1412 
1413   for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1414                                             options::OPT_frewrite_map_file_EQ))
1415     Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1416 
1417   Diag(clang::diag::note_drv_command_failed_diag_msg)
1418       << "\n\n********************";
1419 }
1420 
1421 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1422   // Since commandLineFitsWithinSystemLimits() may underestimate system's
1423   // capacity if the tool does not support response files, there is a chance/
1424   // that things will just work without a response file, so we silently just
1425   // skip it.
1426   if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1427       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1428                                                    Cmd.getArguments()))
1429     return;
1430 
1431   std::string TmpName = GetTemporaryPath("response", "txt");
1432   Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1433 }
1434 
1435 int Driver::ExecuteCompilation(
1436     Compilation &C,
1437     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1438   // Just print if -### was present.
1439   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1440     C.getJobs().Print(llvm::errs(), "\n", true);
1441     return 0;
1442   }
1443 
1444   // If there were errors building the compilation, quit now.
1445   if (Diags.hasErrorOccurred())
1446     return 1;
1447 
1448   // Set up response file names for each command, if necessary
1449   for (auto &Job : C.getJobs())
1450     setUpResponseFiles(C, Job);
1451 
1452   C.ExecuteJobs(C.getJobs(), FailingCommands);
1453 
1454   // If the command succeeded, we are done.
1455   if (FailingCommands.empty())
1456     return 0;
1457 
1458   // Otherwise, remove result files and print extra information about abnormal
1459   // failures.
1460   int Res = 0;
1461   for (const auto &CmdPair : FailingCommands) {
1462     int CommandRes = CmdPair.first;
1463     const Command *FailingCommand = CmdPair.second;
1464 
1465     // Remove result files if we're not saving temps.
1466     if (!isSaveTempsEnabled()) {
1467       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1468       C.CleanupFileMap(C.getResultFiles(), JA, true);
1469 
1470       // Failure result files are valid unless we crashed.
1471       if (CommandRes < 0)
1472         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1473     }
1474 
1475 #if LLVM_ON_UNIX
1476     // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1477     // for SIGPIPE. Do not print diagnostics for this case.
1478     if (CommandRes == EX_IOERR) {
1479       Res = CommandRes;
1480       continue;
1481     }
1482 #endif
1483 
1484     // Print extra information about abnormal failures, if possible.
1485     //
1486     // This is ad-hoc, but we don't want to be excessively noisy. If the result
1487     // status was 1, assume the command failed normally. In particular, if it
1488     // was the compiler then assume it gave a reasonable error code. Failures
1489     // in other tools are less common, and they generally have worse
1490     // diagnostics, so always print the diagnostic there.
1491     const Tool &FailingTool = FailingCommand->getCreator();
1492 
1493     if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1494       // FIXME: See FIXME above regarding result code interpretation.
1495       if (CommandRes < 0)
1496         Diag(clang::diag::err_drv_command_signalled)
1497             << FailingTool.getShortName();
1498       else
1499         Diag(clang::diag::err_drv_command_failed)
1500             << FailingTool.getShortName() << CommandRes;
1501     }
1502   }
1503   return Res;
1504 }
1505 
1506 void Driver::PrintHelp(bool ShowHidden) const {
1507   unsigned IncludedFlagsBitmask;
1508   unsigned ExcludedFlagsBitmask;
1509   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1510       getIncludeExcludeOptionFlagMasks(IsCLMode());
1511 
1512   ExcludedFlagsBitmask |= options::NoDriverOption;
1513   if (!ShowHidden)
1514     ExcludedFlagsBitmask |= HelpHidden;
1515 
1516   std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1517   getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1518                       IncludedFlagsBitmask, ExcludedFlagsBitmask,
1519                       /*ShowAllAliases=*/false);
1520 }
1521 
1522 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1523   // FIXME: The following handlers should use a callback mechanism, we don't
1524   // know what the client would like to do.
1525   OS << getClangFullVersion() << '\n';
1526   const ToolChain &TC = C.getDefaultToolChain();
1527   OS << "Target: " << TC.getTripleString() << '\n';
1528 
1529   // Print the threading model.
1530   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1531     // Don't print if the ToolChain would have barfed on it already
1532     if (TC.isThreadModelSupported(A->getValue()))
1533       OS << "Thread model: " << A->getValue();
1534   } else
1535     OS << "Thread model: " << TC.getThreadModel();
1536   OS << '\n';
1537 
1538   // Print out the install directory.
1539   OS << "InstalledDir: " << InstalledDir << '\n';
1540 
1541   // If configuration file was used, print its path.
1542   if (!ConfigFile.empty())
1543     OS << "Configuration file: " << ConfigFile << '\n';
1544 }
1545 
1546 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1547 /// option.
1548 static void PrintDiagnosticCategories(raw_ostream &OS) {
1549   // Skip the empty category.
1550   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1551        ++i)
1552     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1553 }
1554 
1555 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1556   if (PassedFlags == "")
1557     return;
1558   // Print out all options that start with a given argument. This is used for
1559   // shell autocompletion.
1560   std::vector<std::string> SuggestedCompletions;
1561   std::vector<std::string> Flags;
1562 
1563   unsigned short DisableFlags =
1564       options::NoDriverOption | options::Unsupported | options::Ignored;
1565 
1566   // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1567   // because the latter indicates that the user put space before pushing tab
1568   // which should end up in a file completion.
1569   const bool HasSpace = PassedFlags.endswith(",");
1570 
1571   // Parse PassedFlags by "," as all the command-line flags are passed to this
1572   // function separated by ","
1573   StringRef TargetFlags = PassedFlags;
1574   while (TargetFlags != "") {
1575     StringRef CurFlag;
1576     std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1577     Flags.push_back(std::string(CurFlag));
1578   }
1579 
1580   // We want to show cc1-only options only when clang is invoked with -cc1 or
1581   // -Xclang.
1582   if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1583     DisableFlags &= ~options::NoDriverOption;
1584 
1585   StringRef Cur;
1586   Cur = Flags.at(Flags.size() - 1);
1587   StringRef Prev;
1588   if (Flags.size() >= 2) {
1589     Prev = Flags.at(Flags.size() - 2);
1590     SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1591   }
1592 
1593   if (SuggestedCompletions.empty())
1594     SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1595 
1596   // If Flags were empty, it means the user typed `clang [tab]` where we should
1597   // list all possible flags. If there was no value completion and the user
1598   // pressed tab after a space, we should fall back to a file completion.
1599   // We're printing a newline to be consistent with what we print at the end of
1600   // this function.
1601   if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1602     llvm::outs() << '\n';
1603     return;
1604   }
1605 
1606   // When flag ends with '=' and there was no value completion, return empty
1607   // string and fall back to the file autocompletion.
1608   if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1609     // If the flag is in the form of "--autocomplete=-foo",
1610     // we were requested to print out all option names that start with "-foo".
1611     // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1612     SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
1613 
1614     // We have to query the -W flags manually as they're not in the OptTable.
1615     // TODO: Find a good way to add them to OptTable instead and them remove
1616     // this code.
1617     for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1618       if (S.startswith(Cur))
1619         SuggestedCompletions.push_back(S);
1620   }
1621 
1622   // Sort the autocomplete candidates so that shells print them out in a
1623   // deterministic order. We could sort in any way, but we chose
1624   // case-insensitive sorting for consistency with the -help option
1625   // which prints out options in the case-insensitive alphabetical order.
1626   llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1627     if (int X = A.compare_lower(B))
1628       return X < 0;
1629     return A.compare(B) > 0;
1630   });
1631 
1632   llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1633 }
1634 
1635 bool Driver::HandleImmediateArgs(const Compilation &C) {
1636   // The order these options are handled in gcc is all over the place, but we
1637   // don't expect inconsistencies w.r.t. that to matter in practice.
1638 
1639   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1640     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1641     return false;
1642   }
1643 
1644   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1645     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1646     // return an answer which matches our definition of __VERSION__.
1647     llvm::outs() << CLANG_VERSION_STRING << "\n";
1648     return false;
1649   }
1650 
1651   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1652     PrintDiagnosticCategories(llvm::outs());
1653     return false;
1654   }
1655 
1656   if (C.getArgs().hasArg(options::OPT_help) ||
1657       C.getArgs().hasArg(options::OPT__help_hidden)) {
1658     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1659     return false;
1660   }
1661 
1662   if (C.getArgs().hasArg(options::OPT__version)) {
1663     // Follow gcc behavior and use stdout for --version and stderr for -v.
1664     PrintVersion(C, llvm::outs());
1665     return false;
1666   }
1667 
1668   if (C.getArgs().hasArg(options::OPT_v) ||
1669       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1670     PrintVersion(C, llvm::errs());
1671     SuppressMissingInputWarning = true;
1672   }
1673 
1674   if (C.getArgs().hasArg(options::OPT_v)) {
1675     if (!SystemConfigDir.empty())
1676       llvm::errs() << "System configuration file directory: "
1677                    << SystemConfigDir << "\n";
1678     if (!UserConfigDir.empty())
1679       llvm::errs() << "User configuration file directory: "
1680                    << UserConfigDir << "\n";
1681   }
1682 
1683   const ToolChain &TC = C.getDefaultToolChain();
1684 
1685   if (C.getArgs().hasArg(options::OPT_v))
1686     TC.printVerboseInfo(llvm::errs());
1687 
1688   if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1689     llvm::outs() << ResourceDir << '\n';
1690     return false;
1691   }
1692 
1693   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1694     llvm::outs() << "programs: =";
1695     bool separator = false;
1696     for (const std::string &Path : TC.getProgramPaths()) {
1697       if (separator)
1698         llvm::outs() << llvm::sys::EnvPathSeparator;
1699       llvm::outs() << Path;
1700       separator = true;
1701     }
1702     llvm::outs() << "\n";
1703     llvm::outs() << "libraries: =" << ResourceDir;
1704 
1705     StringRef sysroot = C.getSysRoot();
1706 
1707     for (const std::string &Path : TC.getFilePaths()) {
1708       // Always print a separator. ResourceDir was the first item shown.
1709       llvm::outs() << llvm::sys::EnvPathSeparator;
1710       // Interpretation of leading '=' is needed only for NetBSD.
1711       if (Path[0] == '=')
1712         llvm::outs() << sysroot << Path.substr(1);
1713       else
1714         llvm::outs() << Path;
1715     }
1716     llvm::outs() << "\n";
1717     return false;
1718   }
1719 
1720   // FIXME: The following handlers should use a callback mechanism, we don't
1721   // know what the client would like to do.
1722   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1723     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1724     return false;
1725   }
1726 
1727   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1728     StringRef ProgName = A->getValue();
1729 
1730     // Null program name cannot have a path.
1731     if (! ProgName.empty())
1732       llvm::outs() << GetProgramPath(ProgName, TC);
1733 
1734     llvm::outs() << "\n";
1735     return false;
1736   }
1737 
1738   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1739     StringRef PassedFlags = A->getValue();
1740     HandleAutocompletions(PassedFlags);
1741     return false;
1742   }
1743 
1744   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1745     ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1746     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1747     RegisterEffectiveTriple TripleRAII(TC, Triple);
1748     switch (RLT) {
1749     case ToolChain::RLT_CompilerRT:
1750       llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1751       break;
1752     case ToolChain::RLT_Libgcc:
1753       llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1754       break;
1755     }
1756     return false;
1757   }
1758 
1759   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1760     for (const Multilib &Multilib : TC.getMultilibs())
1761       llvm::outs() << Multilib << "\n";
1762     return false;
1763   }
1764 
1765   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1766     const Multilib &Multilib = TC.getMultilib();
1767     if (Multilib.gccSuffix().empty())
1768       llvm::outs() << ".\n";
1769     else {
1770       StringRef Suffix(Multilib.gccSuffix());
1771       assert(Suffix.front() == '/');
1772       llvm::outs() << Suffix.substr(1) << "\n";
1773     }
1774     return false;
1775   }
1776 
1777   if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1778     llvm::outs() << TC.getTripleString() << "\n";
1779     return false;
1780   }
1781 
1782   if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1783     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1784     llvm::outs() << Triple.getTriple() << "\n";
1785     return false;
1786   }
1787 
1788   return true;
1789 }
1790 
1791 // Display an action graph human-readably.  Action A is the "sink" node
1792 // and latest-occuring action. Traversal is in pre-order, visiting the
1793 // inputs to each action before printing the action itself.
1794 static unsigned PrintActions1(const Compilation &C, Action *A,
1795                               std::map<Action *, unsigned> &Ids) {
1796   if (Ids.count(A)) // A was already visited.
1797     return Ids[A];
1798 
1799   std::string str;
1800   llvm::raw_string_ostream os(str);
1801 
1802   os << Action::getClassName(A->getKind()) << ", ";
1803   if (InputAction *IA = dyn_cast<InputAction>(A)) {
1804     os << "\"" << IA->getInputArg().getValue() << "\"";
1805   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1806     os << '"' << BIA->getArchName() << '"' << ", {"
1807        << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1808   } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1809     bool IsFirst = true;
1810     OA->doOnEachDependence(
1811         [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1812           // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1813           // sm_35 this will generate:
1814           // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1815           // (nvptx64-nvidia-cuda:sm_35) {#ID}
1816           if (!IsFirst)
1817             os << ", ";
1818           os << '"';
1819           if (TC)
1820             os << A->getOffloadingKindPrefix();
1821           else
1822             os << "host";
1823           os << " (";
1824           os << TC->getTriple().normalize();
1825 
1826           if (BoundArch)
1827             os << ":" << BoundArch;
1828           os << ")";
1829           os << '"';
1830           os << " {" << PrintActions1(C, A, Ids) << "}";
1831           IsFirst = false;
1832         });
1833   } else {
1834     const ActionList *AL = &A->getInputs();
1835 
1836     if (AL->size()) {
1837       const char *Prefix = "{";
1838       for (Action *PreRequisite : *AL) {
1839         os << Prefix << PrintActions1(C, PreRequisite, Ids);
1840         Prefix = ", ";
1841       }
1842       os << "}";
1843     } else
1844       os << "{}";
1845   }
1846 
1847   // Append offload info for all options other than the offloading action
1848   // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1849   std::string offload_str;
1850   llvm::raw_string_ostream offload_os(offload_str);
1851   if (!isa<OffloadAction>(A)) {
1852     auto S = A->getOffloadingKindPrefix();
1853     if (!S.empty()) {
1854       offload_os << ", (" << S;
1855       if (A->getOffloadingArch())
1856         offload_os << ", " << A->getOffloadingArch();
1857       offload_os << ")";
1858     }
1859   }
1860 
1861   unsigned Id = Ids.size();
1862   Ids[A] = Id;
1863   llvm::errs() << Id << ": " << os.str() << ", "
1864                << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1865 
1866   return Id;
1867 }
1868 
1869 // Print the action graphs in a compilation C.
1870 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1871 void Driver::PrintActions(const Compilation &C) const {
1872   std::map<Action *, unsigned> Ids;
1873   for (Action *A : C.getActions())
1874     PrintActions1(C, A, Ids);
1875 }
1876 
1877 /// Check whether the given input tree contains any compilation or
1878 /// assembly actions.
1879 static bool ContainsCompileOrAssembleAction(const Action *A) {
1880   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1881       isa<AssembleJobAction>(A))
1882     return true;
1883 
1884   for (const Action *Input : A->inputs())
1885     if (ContainsCompileOrAssembleAction(Input))
1886       return true;
1887 
1888   return false;
1889 }
1890 
1891 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1892                                    const InputList &BAInputs) const {
1893   DerivedArgList &Args = C.getArgs();
1894   ActionList &Actions = C.getActions();
1895   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1896   // Collect the list of architectures. Duplicates are allowed, but should only
1897   // be handled once (in the order seen).
1898   llvm::StringSet<> ArchNames;
1899   SmallVector<const char *, 4> Archs;
1900   for (Arg *A : Args) {
1901     if (A->getOption().matches(options::OPT_arch)) {
1902       // Validate the option here; we don't save the type here because its
1903       // particular spelling may participate in other driver choices.
1904       llvm::Triple::ArchType Arch =
1905           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1906       if (Arch == llvm::Triple::UnknownArch) {
1907         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1908         continue;
1909       }
1910 
1911       A->claim();
1912       if (ArchNames.insert(A->getValue()).second)
1913         Archs.push_back(A->getValue());
1914     }
1915   }
1916 
1917   // When there is no explicit arch for this platform, make sure we still bind
1918   // the architecture (to the default) so that -Xarch_ is handled correctly.
1919   if (!Archs.size())
1920     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1921 
1922   ActionList SingleActions;
1923   BuildActions(C, Args, BAInputs, SingleActions);
1924 
1925   // Add in arch bindings for every top level action, as well as lipo and
1926   // dsymutil steps if needed.
1927   for (Action* Act : SingleActions) {
1928     // Make sure we can lipo this kind of output. If not (and it is an actual
1929     // output) then we disallow, since we can't create an output file with the
1930     // right name without overwriting it. We could remove this oddity by just
1931     // changing the output names to include the arch, which would also fix
1932     // -save-temps. Compatibility wins for now.
1933 
1934     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1935       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1936           << types::getTypeName(Act->getType());
1937 
1938     ActionList Inputs;
1939     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1940       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1941 
1942     // Lipo if necessary, we do it this way because we need to set the arch flag
1943     // so that -Xarch_ gets overwritten.
1944     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1945       Actions.append(Inputs.begin(), Inputs.end());
1946     else
1947       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1948 
1949     // Handle debug info queries.
1950     Arg *A = Args.getLastArg(options::OPT_g_Group);
1951     if (A && !A->getOption().matches(options::OPT_g0) &&
1952         !A->getOption().matches(options::OPT_gstabs) &&
1953         ContainsCompileOrAssembleAction(Actions.back())) {
1954 
1955       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1956       // have a compile input. We need to run 'dsymutil' ourselves in such cases
1957       // because the debug info will refer to a temporary object file which
1958       // will be removed at the end of the compilation process.
1959       if (Act->getType() == types::TY_Image) {
1960         ActionList Inputs;
1961         Inputs.push_back(Actions.back());
1962         Actions.pop_back();
1963         Actions.push_back(
1964             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1965       }
1966 
1967       // Verify the debug info output.
1968       if (Args.hasArg(options::OPT_verify_debug_info)) {
1969         Action* LastAction = Actions.back();
1970         Actions.pop_back();
1971         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1972             LastAction, types::TY_Nothing));
1973       }
1974     }
1975   }
1976 }
1977 
1978 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
1979                                     types::ID Ty, bool TypoCorrect) const {
1980   if (!getCheckInputsExist())
1981     return true;
1982 
1983   // stdin always exists.
1984   if (Value == "-")
1985     return true;
1986 
1987   SmallString<64> Path(Value);
1988   if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1989     if (!llvm::sys::path::is_absolute(Path)) {
1990       SmallString<64> Directory(WorkDir->getValue());
1991       llvm::sys::path::append(Directory, Value);
1992       Path.assign(Directory);
1993     }
1994   }
1995 
1996   if (getVFS().exists(Path))
1997     return true;
1998 
1999   if (IsCLMode()) {
2000     if (!llvm::sys::path::is_absolute(Twine(Path)) &&
2001         llvm::sys::Process::FindInEnvPath("LIB", Value))
2002       return true;
2003 
2004     if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2005       // Arguments to the /link flag might cause the linker to search for object
2006       // and library files in paths we don't know about. Don't error in such
2007       // cases.
2008       return true;
2009     }
2010   }
2011 
2012   if (TypoCorrect) {
2013     // Check if the filename is a typo for an option flag. OptTable thinks
2014     // that all args that are not known options and that start with / are
2015     // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2016     // the option `/diagnostics:caret` than a reference to a file in the root
2017     // directory.
2018     unsigned IncludedFlagsBitmask;
2019     unsigned ExcludedFlagsBitmask;
2020     std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2021         getIncludeExcludeOptionFlagMasks(IsCLMode());
2022     std::string Nearest;
2023     if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2024                               ExcludedFlagsBitmask) <= 1) {
2025       Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2026           << Path << Nearest;
2027       return false;
2028     }
2029   }
2030 
2031   Diag(clang::diag::err_drv_no_such_file) << Path;
2032   return false;
2033 }
2034 
2035 // Construct a the list of inputs and their types.
2036 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2037                          InputList &Inputs) const {
2038   // Track the current user specified (-x) input. We also explicitly track the
2039   // argument used to set the type; we only want to claim the type when we
2040   // actually use it, so we warn about unused -x arguments.
2041   types::ID InputType = types::TY_Nothing;
2042   Arg *InputTypeArg = nullptr;
2043 
2044   // The last /TC or /TP option sets the input type to C or C++ globally.
2045   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2046                                          options::OPT__SLASH_TP)) {
2047     InputTypeArg = TCTP;
2048     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2049                     ? types::TY_C
2050                     : types::TY_CXX;
2051 
2052     Arg *Previous = nullptr;
2053     bool ShowNote = false;
2054     for (Arg *A :
2055          Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2056       if (Previous) {
2057         Diag(clang::diag::warn_drv_overriding_flag_option)
2058           << Previous->getSpelling() << A->getSpelling();
2059         ShowNote = true;
2060       }
2061       Previous = A;
2062     }
2063     if (ShowNote)
2064       Diag(clang::diag::note_drv_t_option_is_global);
2065 
2066     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2067     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2068   }
2069 
2070   for (Arg *A : Args) {
2071     if (A->getOption().getKind() == Option::InputClass) {
2072       const char *Value = A->getValue();
2073       types::ID Ty = types::TY_INVALID;
2074 
2075       // Infer the input type if necessary.
2076       if (InputType == types::TY_Nothing) {
2077         // If there was an explicit arg for this, claim it.
2078         if (InputTypeArg)
2079           InputTypeArg->claim();
2080 
2081         // stdin must be handled specially.
2082         if (memcmp(Value, "-", 2) == 0) {
2083           // If running with -E, treat as a C input (this changes the builtin
2084           // macros, for example). This may be overridden by -ObjC below.
2085           //
2086           // Otherwise emit an error but still use a valid type to avoid
2087           // spurious errors (e.g., no inputs).
2088           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2089             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2090                             : clang::diag::err_drv_unknown_stdin_type);
2091           Ty = types::TY_C;
2092         } else {
2093           // Otherwise lookup by extension.
2094           // Fallback is C if invoked as C preprocessor, C++ if invoked with
2095           // clang-cl /E, or Object otherwise.
2096           // We use a host hook here because Darwin at least has its own
2097           // idea of what .s is.
2098           if (const char *Ext = strrchr(Value, '.'))
2099             Ty = TC.LookupTypeForExtension(Ext + 1);
2100 
2101           if (Ty == types::TY_INVALID) {
2102             if (CCCIsCPP())
2103               Ty = types::TY_C;
2104             else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2105               Ty = types::TY_CXX;
2106             else
2107               Ty = types::TY_Object;
2108           }
2109 
2110           // If the driver is invoked as C++ compiler (like clang++ or c++) it
2111           // should autodetect some input files as C++ for g++ compatibility.
2112           if (CCCIsCXX()) {
2113             types::ID OldTy = Ty;
2114             Ty = types::lookupCXXTypeForCType(Ty);
2115 
2116             if (Ty != OldTy)
2117               Diag(clang::diag::warn_drv_treating_input_as_cxx)
2118                   << getTypeName(OldTy) << getTypeName(Ty);
2119           }
2120         }
2121 
2122         // -ObjC and -ObjC++ override the default language, but only for "source
2123         // files". We just treat everything that isn't a linker input as a
2124         // source file.
2125         //
2126         // FIXME: Clean this up if we move the phase sequence into the type.
2127         if (Ty != types::TY_Object) {
2128           if (Args.hasArg(options::OPT_ObjC))
2129             Ty = types::TY_ObjC;
2130           else if (Args.hasArg(options::OPT_ObjCXX))
2131             Ty = types::TY_ObjCXX;
2132         }
2133       } else {
2134         assert(InputTypeArg && "InputType set w/o InputTypeArg");
2135         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2136           // If emulating cl.exe, make sure that /TC and /TP don't affect input
2137           // object files.
2138           const char *Ext = strrchr(Value, '.');
2139           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2140             Ty = types::TY_Object;
2141         }
2142         if (Ty == types::TY_INVALID) {
2143           Ty = InputType;
2144           InputTypeArg->claim();
2145         }
2146       }
2147 
2148       if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2149         Inputs.push_back(std::make_pair(Ty, A));
2150 
2151     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2152       StringRef Value = A->getValue();
2153       if (DiagnoseInputExistence(Args, Value, types::TY_C,
2154                                  /*TypoCorrect=*/false)) {
2155         Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
2156         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2157       }
2158       A->claim();
2159     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2160       StringRef Value = A->getValue();
2161       if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2162                                  /*TypoCorrect=*/false)) {
2163         Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
2164         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2165       }
2166       A->claim();
2167     } else if (A->getOption().hasFlag(options::LinkerInput)) {
2168       // Just treat as object type, we could make a special type for this if
2169       // necessary.
2170       Inputs.push_back(std::make_pair(types::TY_Object, A));
2171 
2172     } else if (A->getOption().matches(options::OPT_x)) {
2173       InputTypeArg = A;
2174       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2175       A->claim();
2176 
2177       // Follow gcc behavior and treat as linker input for invalid -x
2178       // options. Its not clear why we shouldn't just revert to unknown; but
2179       // this isn't very important, we might as well be bug compatible.
2180       if (!InputType) {
2181         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2182         InputType = types::TY_Object;
2183       }
2184     } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2185       assert(A->getNumValues() == 1 && "The /U option has one value.");
2186       StringRef Val = A->getValue(0);
2187       if (Val.find_first_of("/\\") != StringRef::npos) {
2188         // Warn about e.g. "/Users/me/myfile.c".
2189         Diag(diag::warn_slash_u_filename) << Val;
2190         Diag(diag::note_use_dashdash);
2191       }
2192     }
2193   }
2194   if (CCCIsCPP() && Inputs.empty()) {
2195     // If called as standalone preprocessor, stdin is processed
2196     // if no other input is present.
2197     Arg *A = MakeInputArg(Args, *Opts, "-");
2198     Inputs.push_back(std::make_pair(types::TY_C, A));
2199   }
2200 }
2201 
2202 namespace {
2203 /// Provides a convenient interface for different programming models to generate
2204 /// the required device actions.
2205 class OffloadingActionBuilder final {
2206   /// Flag used to trace errors in the builder.
2207   bool IsValid = false;
2208 
2209   /// The compilation that is using this builder.
2210   Compilation &C;
2211 
2212   /// Map between an input argument and the offload kinds used to process it.
2213   std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2214 
2215   /// Builder interface. It doesn't build anything or keep any state.
2216   class DeviceActionBuilder {
2217   public:
2218     typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2219 
2220     enum ActionBuilderReturnCode {
2221       // The builder acted successfully on the current action.
2222       ABRT_Success,
2223       // The builder didn't have to act on the current action.
2224       ABRT_Inactive,
2225       // The builder was successful and requested the host action to not be
2226       // generated.
2227       ABRT_Ignore_Host,
2228     };
2229 
2230   protected:
2231     /// Compilation associated with this builder.
2232     Compilation &C;
2233 
2234     /// Tool chains associated with this builder. The same programming
2235     /// model may have associated one or more tool chains.
2236     SmallVector<const ToolChain *, 2> ToolChains;
2237 
2238     /// The derived arguments associated with this builder.
2239     DerivedArgList &Args;
2240 
2241     /// The inputs associated with this builder.
2242     const Driver::InputList &Inputs;
2243 
2244     /// The associated offload kind.
2245     Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2246 
2247   public:
2248     DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2249                         const Driver::InputList &Inputs,
2250                         Action::OffloadKind AssociatedOffloadKind)
2251         : C(C), Args(Args), Inputs(Inputs),
2252           AssociatedOffloadKind(AssociatedOffloadKind) {}
2253     virtual ~DeviceActionBuilder() {}
2254 
2255     /// Fill up the array \a DA with all the device dependences that should be
2256     /// added to the provided host action \a HostAction. By default it is
2257     /// inactive.
2258     virtual ActionBuilderReturnCode
2259     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2260                          phases::ID CurPhase, phases::ID FinalPhase,
2261                          PhasesTy &Phases) {
2262       return ABRT_Inactive;
2263     }
2264 
2265     /// Update the state to include the provided host action \a HostAction as a
2266     /// dependency of the current device action. By default it is inactive.
2267     virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2268       return ABRT_Inactive;
2269     }
2270 
2271     /// Append top level actions generated by the builder. Return true if errors
2272     /// were found.
2273     virtual void appendTopLevelActions(ActionList &AL) {}
2274 
2275     /// Append linker actions generated by the builder. Return true if errors
2276     /// were found.
2277     virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2278 
2279     /// Initialize the builder. Return true if any initialization errors are
2280     /// found.
2281     virtual bool initialize() { return false; }
2282 
2283     /// Return true if the builder can use bundling/unbundling.
2284     virtual bool canUseBundlerUnbundler() const { return false; }
2285 
2286     /// Return true if this builder is valid. We have a valid builder if we have
2287     /// associated device tool chains.
2288     bool isValid() { return !ToolChains.empty(); }
2289 
2290     /// Return the associated offload kind.
2291     Action::OffloadKind getAssociatedOffloadKind() {
2292       return AssociatedOffloadKind;
2293     }
2294   };
2295 
2296   /// Base class for CUDA/HIP action builder. It injects device code in
2297   /// the host backend action.
2298   class CudaActionBuilderBase : public DeviceActionBuilder {
2299   protected:
2300     /// Flags to signal if the user requested host-only or device-only
2301     /// compilation.
2302     bool CompileHostOnly = false;
2303     bool CompileDeviceOnly = false;
2304 
2305     /// List of GPU architectures to use in this compilation.
2306     SmallVector<CudaArch, 4> GpuArchList;
2307 
2308     /// The CUDA actions for the current input.
2309     ActionList CudaDeviceActions;
2310 
2311     /// The CUDA fat binary if it was generated for the current input.
2312     Action *CudaFatBinary = nullptr;
2313 
2314     /// Flag that is set to true if this builder acted on the current input.
2315     bool IsActive = false;
2316 
2317     /// Flag for -fgpu-rdc.
2318     bool Relocatable = false;
2319   public:
2320     CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2321                           const Driver::InputList &Inputs,
2322                           Action::OffloadKind OFKind)
2323         : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2324 
2325     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2326       // While generating code for CUDA, we only depend on the host input action
2327       // to trigger the creation of all the CUDA device actions.
2328 
2329       // If we are dealing with an input action, replicate it for each GPU
2330       // architecture. If we are in host-only mode we return 'success' so that
2331       // the host uses the CUDA offload kind.
2332       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2333         assert(!GpuArchList.empty() &&
2334                "We should have at least one GPU architecture.");
2335 
2336         // If the host input is not CUDA or HIP, we don't need to bother about
2337         // this input.
2338         if (IA->getType() != types::TY_CUDA &&
2339             IA->getType() != types::TY_HIP) {
2340           // The builder will ignore this input.
2341           IsActive = false;
2342           return ABRT_Inactive;
2343         }
2344 
2345         // Set the flag to true, so that the builder acts on the current input.
2346         IsActive = true;
2347 
2348         if (CompileHostOnly)
2349           return ABRT_Success;
2350 
2351         // Replicate inputs for each GPU architecture.
2352         auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2353                                                  : types::TY_CUDA_DEVICE;
2354         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2355           CudaDeviceActions.push_back(
2356               C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2357         }
2358 
2359         return ABRT_Success;
2360       }
2361 
2362       // If this is an unbundling action use it as is for each CUDA toolchain.
2363       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2364 
2365         // If -fgpu-rdc is disabled, should not unbundle since there is no
2366         // device code to link.
2367         if (!Relocatable)
2368           return ABRT_Inactive;
2369 
2370         CudaDeviceActions.clear();
2371         auto *IA = cast<InputAction>(UA->getInputs().back());
2372         std::string FileName = IA->getInputArg().getAsString(Args);
2373         // Check if the type of the file is the same as the action. Do not
2374         // unbundle it if it is not. Do not unbundle .so files, for example,
2375         // which are not object files.
2376         if (IA->getType() == types::TY_Object &&
2377             (!llvm::sys::path::has_extension(FileName) ||
2378              types::lookupTypeForExtension(
2379                  llvm::sys::path::extension(FileName).drop_front()) !=
2380                  types::TY_Object))
2381           return ABRT_Inactive;
2382 
2383         for (auto Arch : GpuArchList) {
2384           CudaDeviceActions.push_back(UA);
2385           UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2386                                           AssociatedOffloadKind);
2387         }
2388         return ABRT_Success;
2389       }
2390 
2391       return IsActive ? ABRT_Success : ABRT_Inactive;
2392     }
2393 
2394     void appendTopLevelActions(ActionList &AL) override {
2395       // Utility to append actions to the top level list.
2396       auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2397         OffloadAction::DeviceDependences Dep;
2398         Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2399                 AssociatedOffloadKind);
2400         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2401       };
2402 
2403       // If we have a fat binary, add it to the list.
2404       if (CudaFatBinary) {
2405         AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2406         CudaDeviceActions.clear();
2407         CudaFatBinary = nullptr;
2408         return;
2409       }
2410 
2411       if (CudaDeviceActions.empty())
2412         return;
2413 
2414       // If we have CUDA actions at this point, that's because we have a have
2415       // partial compilation, so we should have an action for each GPU
2416       // architecture.
2417       assert(CudaDeviceActions.size() == GpuArchList.size() &&
2418              "Expecting one action per GPU architecture.");
2419       assert(ToolChains.size() == 1 &&
2420              "Expecting to have a sing CUDA toolchain.");
2421       for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2422         AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2423 
2424       CudaDeviceActions.clear();
2425     }
2426 
2427     bool initialize() override {
2428       assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2429              AssociatedOffloadKind == Action::OFK_HIP);
2430 
2431       // We don't need to support CUDA.
2432       if (AssociatedOffloadKind == Action::OFK_Cuda &&
2433           !C.hasOffloadToolChain<Action::OFK_Cuda>())
2434         return false;
2435 
2436       // We don't need to support HIP.
2437       if (AssociatedOffloadKind == Action::OFK_HIP &&
2438           !C.hasOffloadToolChain<Action::OFK_HIP>())
2439         return false;
2440 
2441       Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2442           options::OPT_fno_gpu_rdc, /*Default=*/false);
2443 
2444       const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2445       assert(HostTC && "No toolchain for host compilation.");
2446       if (HostTC->getTriple().isNVPTX() ||
2447           HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2448         // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2449         // an error and abort pipeline construction early so we don't trip
2450         // asserts that assume device-side compilation.
2451         C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2452             << HostTC->getTriple().getArchName();
2453         return true;
2454       }
2455 
2456       ToolChains.push_back(
2457           AssociatedOffloadKind == Action::OFK_Cuda
2458               ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2459               : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2460 
2461       Arg *PartialCompilationArg = Args.getLastArg(
2462           options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2463           options::OPT_cuda_compile_host_device);
2464       CompileHostOnly = PartialCompilationArg &&
2465                         PartialCompilationArg->getOption().matches(
2466                             options::OPT_cuda_host_only);
2467       CompileDeviceOnly = PartialCompilationArg &&
2468                           PartialCompilationArg->getOption().matches(
2469                               options::OPT_cuda_device_only);
2470 
2471       // Collect all cuda_gpu_arch parameters, removing duplicates.
2472       std::set<CudaArch> GpuArchs;
2473       bool Error = false;
2474       for (Arg *A : Args) {
2475         if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2476               A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2477           continue;
2478         A->claim();
2479 
2480         const StringRef ArchStr = A->getValue();
2481         if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2482             ArchStr == "all") {
2483           GpuArchs.clear();
2484           continue;
2485         }
2486         CudaArch Arch = StringToCudaArch(ArchStr);
2487         if (Arch == CudaArch::UNKNOWN) {
2488           C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2489           Error = true;
2490         } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2491           GpuArchs.insert(Arch);
2492         else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2493           GpuArchs.erase(Arch);
2494         else
2495           llvm_unreachable("Unexpected option.");
2496       }
2497 
2498       // Collect list of GPUs remaining in the set.
2499       for (CudaArch Arch : GpuArchs)
2500         GpuArchList.push_back(Arch);
2501 
2502       // Default to sm_20 which is the lowest common denominator for
2503       // supported GPUs.  sm_20 code should work correctly, if
2504       // suboptimally, on all newer GPUs.
2505       if (GpuArchList.empty())
2506         GpuArchList.push_back(CudaArch::SM_20);
2507 
2508       return Error;
2509     }
2510   };
2511 
2512   /// \brief CUDA action builder. It injects device code in the host backend
2513   /// action.
2514   class CudaActionBuilder final : public CudaActionBuilderBase {
2515   public:
2516     CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2517                       const Driver::InputList &Inputs)
2518         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
2519 
2520     ActionBuilderReturnCode
2521     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2522                          phases::ID CurPhase, phases::ID FinalPhase,
2523                          PhasesTy &Phases) override {
2524       if (!IsActive)
2525         return ABRT_Inactive;
2526 
2527       // If we don't have more CUDA actions, we don't have any dependences to
2528       // create for the host.
2529       if (CudaDeviceActions.empty())
2530         return ABRT_Success;
2531 
2532       assert(CudaDeviceActions.size() == GpuArchList.size() &&
2533              "Expecting one action per GPU architecture.");
2534       assert(!CompileHostOnly &&
2535              "Not expecting CUDA actions in host-only compilation.");
2536 
2537       // If we are generating code for the device or we are in a backend phase,
2538       // we attempt to generate the fat binary. We compile each arch to ptx and
2539       // assemble to cubin, then feed the cubin *and* the ptx into a device
2540       // "link" action, which uses fatbinary to combine these cubins into one
2541       // fatbin.  The fatbin is then an input to the host action if not in
2542       // device-only mode.
2543       if (CompileDeviceOnly || CurPhase == phases::Backend) {
2544         ActionList DeviceActions;
2545         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2546           // Produce the device action from the current phase up to the assemble
2547           // phase.
2548           for (auto Ph : Phases) {
2549             // Skip the phases that were already dealt with.
2550             if (Ph < CurPhase)
2551               continue;
2552             // We have to be consistent with the host final phase.
2553             if (Ph > FinalPhase)
2554               break;
2555 
2556             CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2557                 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2558 
2559             if (Ph == phases::Assemble)
2560               break;
2561           }
2562 
2563           // If we didn't reach the assemble phase, we can't generate the fat
2564           // binary. We don't need to generate the fat binary if we are not in
2565           // device-only mode.
2566           if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2567               CompileDeviceOnly)
2568             continue;
2569 
2570           Action *AssembleAction = CudaDeviceActions[I];
2571           assert(AssembleAction->getType() == types::TY_Object);
2572           assert(AssembleAction->getInputs().size() == 1);
2573 
2574           Action *BackendAction = AssembleAction->getInputs()[0];
2575           assert(BackendAction->getType() == types::TY_PP_Asm);
2576 
2577           for (auto &A : {AssembleAction, BackendAction}) {
2578             OffloadAction::DeviceDependences DDep;
2579             DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2580                      Action::OFK_Cuda);
2581             DeviceActions.push_back(
2582                 C.MakeAction<OffloadAction>(DDep, A->getType()));
2583           }
2584         }
2585 
2586         // We generate the fat binary if we have device input actions.
2587         if (!DeviceActions.empty()) {
2588           CudaFatBinary =
2589               C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2590 
2591           if (!CompileDeviceOnly) {
2592             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2593                    Action::OFK_Cuda);
2594             // Clear the fat binary, it is already a dependence to an host
2595             // action.
2596             CudaFatBinary = nullptr;
2597           }
2598 
2599           // Remove the CUDA actions as they are already connected to an host
2600           // action or fat binary.
2601           CudaDeviceActions.clear();
2602         }
2603 
2604         // We avoid creating host action in device-only mode.
2605         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2606       } else if (CurPhase > phases::Backend) {
2607         // If we are past the backend phase and still have a device action, we
2608         // don't have to do anything as this action is already a device
2609         // top-level action.
2610         return ABRT_Success;
2611       }
2612 
2613       assert(CurPhase < phases::Backend && "Generating single CUDA "
2614                                            "instructions should only occur "
2615                                            "before the backend phase!");
2616 
2617       // By default, we produce an action for each device arch.
2618       for (Action *&A : CudaDeviceActions)
2619         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2620 
2621       return ABRT_Success;
2622     }
2623   };
2624   /// \brief HIP action builder. It injects device code in the host backend
2625   /// action.
2626   class HIPActionBuilder final : public CudaActionBuilderBase {
2627     /// The linker inputs obtained for each device arch.
2628     SmallVector<ActionList, 8> DeviceLinkerInputs;
2629 
2630   public:
2631     HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2632                      const Driver::InputList &Inputs)
2633         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {}
2634 
2635     bool canUseBundlerUnbundler() const override { return true; }
2636 
2637     ActionBuilderReturnCode
2638     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2639                          phases::ID CurPhase, phases::ID FinalPhase,
2640                          PhasesTy &Phases) override {
2641       // amdgcn does not support linking of object files, therefore we skip
2642       // backend and assemble phases to output LLVM IR. Except for generating
2643       // non-relocatable device coee, where we generate fat binary for device
2644       // code and pass to host in Backend phase.
2645       if (CudaDeviceActions.empty() ||
2646           (CurPhase == phases::Backend && Relocatable) ||
2647           CurPhase == phases::Assemble)
2648         return ABRT_Success;
2649 
2650       assert(((CurPhase == phases::Link && Relocatable) ||
2651               CudaDeviceActions.size() == GpuArchList.size()) &&
2652              "Expecting one action per GPU architecture.");
2653       assert(!CompileHostOnly &&
2654              "Not expecting CUDA actions in host-only compilation.");
2655 
2656       if (!Relocatable && CurPhase == phases::Backend) {
2657         // If we are in backend phase, we attempt to generate the fat binary.
2658         // We compile each arch to IR and use a link action to generate code
2659         // object containing ISA. Then we use a special "link" action to create
2660         // a fat binary containing all the code objects for different GPU's.
2661         // The fat binary is then an input to the host action.
2662         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2663           // Create a link action to link device IR with device library
2664           // and generate ISA.
2665           ActionList AL;
2666           AL.push_back(CudaDeviceActions[I]);
2667           CudaDeviceActions[I] =
2668               C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2669 
2670           // OffloadingActionBuilder propagates device arch until an offload
2671           // action. Since the next action for creating fatbin does
2672           // not have device arch, whereas the above link action and its input
2673           // have device arch, an offload action is needed to stop the null
2674           // device arch of the next action being propagated to the above link
2675           // action.
2676           OffloadAction::DeviceDependences DDep;
2677           DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2678                    CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2679           CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2680               DDep, CudaDeviceActions[I]->getType());
2681         }
2682         // Create HIP fat binary with a special "link" action.
2683         CudaFatBinary =
2684             C.MakeAction<LinkJobAction>(CudaDeviceActions,
2685                 types::TY_HIP_FATBIN);
2686 
2687         if (!CompileDeviceOnly) {
2688           DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2689                  AssociatedOffloadKind);
2690           // Clear the fat binary, it is already a dependence to an host
2691           // action.
2692           CudaFatBinary = nullptr;
2693         }
2694 
2695         // Remove the CUDA actions as they are already connected to an host
2696         // action or fat binary.
2697         CudaDeviceActions.clear();
2698 
2699         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2700       } else if (CurPhase == phases::Link) {
2701         // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2702         // This happens to each device action originated from each input file.
2703         // Later on, device actions in DeviceLinkerInputs are used to create
2704         // device link actions in appendLinkDependences and the created device
2705         // link actions are passed to the offload action as device dependence.
2706         DeviceLinkerInputs.resize(CudaDeviceActions.size());
2707         auto LI = DeviceLinkerInputs.begin();
2708         for (auto *A : CudaDeviceActions) {
2709           LI->push_back(A);
2710           ++LI;
2711         }
2712 
2713         // We will pass the device action as a host dependence, so we don't
2714         // need to do anything else with them.
2715         CudaDeviceActions.clear();
2716         return ABRT_Success;
2717       }
2718 
2719       // By default, we produce an action for each device arch.
2720       for (Action *&A : CudaDeviceActions)
2721         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2722                                                AssociatedOffloadKind);
2723 
2724       return ABRT_Success;
2725     }
2726 
2727     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2728       // Append a new link action for each device.
2729       unsigned I = 0;
2730       for (auto &LI : DeviceLinkerInputs) {
2731         auto *DeviceLinkAction =
2732             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2733         DA.add(*DeviceLinkAction, *ToolChains[0],
2734                CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2735         ++I;
2736       }
2737     }
2738   };
2739 
2740   /// OpenMP action builder. The host bitcode is passed to the device frontend
2741   /// and all the device linked images are passed to the host link phase.
2742   class OpenMPActionBuilder final : public DeviceActionBuilder {
2743     /// The OpenMP actions for the current input.
2744     ActionList OpenMPDeviceActions;
2745 
2746     /// The linker inputs obtained for each toolchain.
2747     SmallVector<ActionList, 8> DeviceLinkerInputs;
2748 
2749   public:
2750     OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2751                         const Driver::InputList &Inputs)
2752         : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2753 
2754     ActionBuilderReturnCode
2755     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2756                          phases::ID CurPhase, phases::ID FinalPhase,
2757                          PhasesTy &Phases) override {
2758       if (OpenMPDeviceActions.empty())
2759         return ABRT_Inactive;
2760 
2761       // We should always have an action for each input.
2762       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2763              "Number of OpenMP actions and toolchains do not match.");
2764 
2765       // The host only depends on device action in the linking phase, when all
2766       // the device images have to be embedded in the host image.
2767       if (CurPhase == phases::Link) {
2768         assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2769                "Toolchains and linker inputs sizes do not match.");
2770         auto LI = DeviceLinkerInputs.begin();
2771         for (auto *A : OpenMPDeviceActions) {
2772           LI->push_back(A);
2773           ++LI;
2774         }
2775 
2776         // We passed the device action as a host dependence, so we don't need to
2777         // do anything else with them.
2778         OpenMPDeviceActions.clear();
2779         return ABRT_Success;
2780       }
2781 
2782       // By default, we produce an action for each device arch.
2783       for (Action *&A : OpenMPDeviceActions)
2784         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2785 
2786       return ABRT_Success;
2787     }
2788 
2789     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2790 
2791       // If this is an input action replicate it for each OpenMP toolchain.
2792       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2793         OpenMPDeviceActions.clear();
2794         for (unsigned I = 0; I < ToolChains.size(); ++I)
2795           OpenMPDeviceActions.push_back(
2796               C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2797         return ABRT_Success;
2798       }
2799 
2800       // If this is an unbundling action use it as is for each OpenMP toolchain.
2801       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2802         OpenMPDeviceActions.clear();
2803         auto *IA = cast<InputAction>(UA->getInputs().back());
2804         std::string FileName = IA->getInputArg().getAsString(Args);
2805         // Check if the type of the file is the same as the action. Do not
2806         // unbundle it if it is not. Do not unbundle .so files, for example,
2807         // which are not object files.
2808         if (IA->getType() == types::TY_Object &&
2809             (!llvm::sys::path::has_extension(FileName) ||
2810              types::lookupTypeForExtension(
2811                  llvm::sys::path::extension(FileName).drop_front()) !=
2812                  types::TY_Object))
2813           return ABRT_Inactive;
2814         for (unsigned I = 0; I < ToolChains.size(); ++I) {
2815           OpenMPDeviceActions.push_back(UA);
2816           UA->registerDependentActionInfo(
2817               ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2818         }
2819         return ABRT_Success;
2820       }
2821 
2822       // When generating code for OpenMP we use the host compile phase result as
2823       // a dependence to the device compile phase so that it can learn what
2824       // declarations should be emitted. However, this is not the only use for
2825       // the host action, so we prevent it from being collapsed.
2826       if (isa<CompileJobAction>(HostAction)) {
2827         HostAction->setCannotBeCollapsedWithNextDependentAction();
2828         assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2829                "Toolchains and device action sizes do not match.");
2830         OffloadAction::HostDependence HDep(
2831             *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2832             /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2833         auto TC = ToolChains.begin();
2834         for (Action *&A : OpenMPDeviceActions) {
2835           assert(isa<CompileJobAction>(A));
2836           OffloadAction::DeviceDependences DDep;
2837           DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2838           A = C.MakeAction<OffloadAction>(HDep, DDep);
2839           ++TC;
2840         }
2841       }
2842       return ABRT_Success;
2843     }
2844 
2845     void appendTopLevelActions(ActionList &AL) override {
2846       if (OpenMPDeviceActions.empty())
2847         return;
2848 
2849       // We should always have an action for each input.
2850       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2851              "Number of OpenMP actions and toolchains do not match.");
2852 
2853       // Append all device actions followed by the proper offload action.
2854       auto TI = ToolChains.begin();
2855       for (auto *A : OpenMPDeviceActions) {
2856         OffloadAction::DeviceDependences Dep;
2857         Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2858         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2859         ++TI;
2860       }
2861       // We no longer need the action stored in this builder.
2862       OpenMPDeviceActions.clear();
2863     }
2864 
2865     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2866       assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2867              "Toolchains and linker inputs sizes do not match.");
2868 
2869       // Append a new link action for each device.
2870       auto TC = ToolChains.begin();
2871       for (auto &LI : DeviceLinkerInputs) {
2872         auto *DeviceLinkAction =
2873             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2874         DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2875                Action::OFK_OpenMP);
2876         ++TC;
2877       }
2878     }
2879 
2880     bool initialize() override {
2881       // Get the OpenMP toolchains. If we don't get any, the action builder will
2882       // know there is nothing to do related to OpenMP offloading.
2883       auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2884       for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2885            ++TI)
2886         ToolChains.push_back(TI->second);
2887 
2888       DeviceLinkerInputs.resize(ToolChains.size());
2889       return false;
2890     }
2891 
2892     bool canUseBundlerUnbundler() const override {
2893       // OpenMP should use bundled files whenever possible.
2894       return true;
2895     }
2896   };
2897 
2898   ///
2899   /// TODO: Add the implementation for other specialized builders here.
2900   ///
2901 
2902   /// Specialized builders being used by this offloading action builder.
2903   SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2904 
2905   /// Flag set to true if all valid builders allow file bundling/unbundling.
2906   bool CanUseBundler;
2907 
2908 public:
2909   OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2910                           const Driver::InputList &Inputs)
2911       : C(C) {
2912     // Create a specialized builder for each device toolchain.
2913 
2914     IsValid = true;
2915 
2916     // Create a specialized builder for CUDA.
2917     SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2918 
2919     // Create a specialized builder for HIP.
2920     SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2921 
2922     // Create a specialized builder for OpenMP.
2923     SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2924 
2925     //
2926     // TODO: Build other specialized builders here.
2927     //
2928 
2929     // Initialize all the builders, keeping track of errors. If all valid
2930     // builders agree that we can use bundling, set the flag to true.
2931     unsigned ValidBuilders = 0u;
2932     unsigned ValidBuildersSupportingBundling = 0u;
2933     for (auto *SB : SpecializedBuilders) {
2934       IsValid = IsValid && !SB->initialize();
2935 
2936       // Update the counters if the builder is valid.
2937       if (SB->isValid()) {
2938         ++ValidBuilders;
2939         if (SB->canUseBundlerUnbundler())
2940           ++ValidBuildersSupportingBundling;
2941       }
2942     }
2943     CanUseBundler =
2944         ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2945   }
2946 
2947   ~OffloadingActionBuilder() {
2948     for (auto *SB : SpecializedBuilders)
2949       delete SB;
2950   }
2951 
2952   /// Generate an action that adds device dependences (if any) to a host action.
2953   /// If no device dependence actions exist, just return the host action \a
2954   /// HostAction. If an error is found or if no builder requires the host action
2955   /// to be generated, return nullptr.
2956   Action *
2957   addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2958                                    phases::ID CurPhase, phases::ID FinalPhase,
2959                                    DeviceActionBuilder::PhasesTy &Phases) {
2960     if (!IsValid)
2961       return nullptr;
2962 
2963     if (SpecializedBuilders.empty())
2964       return HostAction;
2965 
2966     assert(HostAction && "Invalid host action!");
2967 
2968     OffloadAction::DeviceDependences DDeps;
2969     // Check if all the programming models agree we should not emit the host
2970     // action. Also, keep track of the offloading kinds employed.
2971     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2972     unsigned InactiveBuilders = 0u;
2973     unsigned IgnoringBuilders = 0u;
2974     for (auto *SB : SpecializedBuilders) {
2975       if (!SB->isValid()) {
2976         ++InactiveBuilders;
2977         continue;
2978       }
2979 
2980       auto RetCode =
2981           SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2982 
2983       // If the builder explicitly says the host action should be ignored,
2984       // we need to increment the variable that tracks the builders that request
2985       // the host object to be ignored.
2986       if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2987         ++IgnoringBuilders;
2988 
2989       // Unless the builder was inactive for this action, we have to record the
2990       // offload kind because the host will have to use it.
2991       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2992         OffloadKind |= SB->getAssociatedOffloadKind();
2993     }
2994 
2995     // If all builders agree that the host object should be ignored, just return
2996     // nullptr.
2997     if (IgnoringBuilders &&
2998         SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2999       return nullptr;
3000 
3001     if (DDeps.getActions().empty())
3002       return HostAction;
3003 
3004     // We have dependences we need to bundle together. We use an offload action
3005     // for that.
3006     OffloadAction::HostDependence HDep(
3007         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3008         /*BoundArch=*/nullptr, DDeps);
3009     return C.MakeAction<OffloadAction>(HDep, DDeps);
3010   }
3011 
3012   /// Generate an action that adds a host dependence to a device action. The
3013   /// results will be kept in this action builder. Return true if an error was
3014   /// found.
3015   bool addHostDependenceToDeviceActions(Action *&HostAction,
3016                                         const Arg *InputArg) {
3017     if (!IsValid)
3018       return true;
3019 
3020     // If we are supporting bundling/unbundling and the current action is an
3021     // input action of non-source file, we replace the host action by the
3022     // unbundling action. The bundler tool has the logic to detect if an input
3023     // is a bundle or not and if the input is not a bundle it assumes it is a
3024     // host file. Therefore it is safe to create an unbundling action even if
3025     // the input is not a bundle.
3026     if (CanUseBundler && isa<InputAction>(HostAction) &&
3027         InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3028         !types::isSrcFile(HostAction->getType())) {
3029       auto UnbundlingHostAction =
3030           C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3031       UnbundlingHostAction->registerDependentActionInfo(
3032           C.getSingleOffloadToolChain<Action::OFK_Host>(),
3033           /*BoundArch=*/StringRef(), Action::OFK_Host);
3034       HostAction = UnbundlingHostAction;
3035     }
3036 
3037     assert(HostAction && "Invalid host action!");
3038 
3039     // Register the offload kinds that are used.
3040     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3041     for (auto *SB : SpecializedBuilders) {
3042       if (!SB->isValid())
3043         continue;
3044 
3045       auto RetCode = SB->addDeviceDepences(HostAction);
3046 
3047       // Host dependences for device actions are not compatible with that same
3048       // action being ignored.
3049       assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3050              "Host dependence not expected to be ignored.!");
3051 
3052       // Unless the builder was inactive for this action, we have to record the
3053       // offload kind because the host will have to use it.
3054       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3055         OffloadKind |= SB->getAssociatedOffloadKind();
3056     }
3057 
3058     // Do not use unbundler if the Host does not depend on device action.
3059     if (OffloadKind == Action::OFK_None && CanUseBundler)
3060       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3061         HostAction = UA->getInputs().back();
3062 
3063     return false;
3064   }
3065 
3066   /// Add the offloading top level actions to the provided action list. This
3067   /// function can replace the host action by a bundling action if the
3068   /// programming models allow it.
3069   bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3070                              const Arg *InputArg) {
3071     // Get the device actions to be appended.
3072     ActionList OffloadAL;
3073     for (auto *SB : SpecializedBuilders) {
3074       if (!SB->isValid())
3075         continue;
3076       SB->appendTopLevelActions(OffloadAL);
3077     }
3078 
3079     // If we can use the bundler, replace the host action by the bundling one in
3080     // the resulting list. Otherwise, just append the device actions. For
3081     // device only compilation, HostAction is a null pointer, therefore only do
3082     // this when HostAction is not a null pointer.
3083     if (CanUseBundler && HostAction && !OffloadAL.empty()) {
3084       // Add the host action to the list in order to create the bundling action.
3085       OffloadAL.push_back(HostAction);
3086 
3087       // We expect that the host action was just appended to the action list
3088       // before this method was called.
3089       assert(HostAction == AL.back() && "Host action not in the list??");
3090       HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3091       AL.back() = HostAction;
3092     } else
3093       AL.append(OffloadAL.begin(), OffloadAL.end());
3094 
3095     // Propagate to the current host action (if any) the offload information
3096     // associated with the current input.
3097     if (HostAction)
3098       HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3099                                            /*BoundArch=*/nullptr);
3100     return false;
3101   }
3102 
3103   /// Processes the host linker action. This currently consists of replacing it
3104   /// with an offload action if there are device link objects and propagate to
3105   /// the host action all the offload kinds used in the current compilation. The
3106   /// resulting action is returned.
3107   Action *processHostLinkAction(Action *HostAction) {
3108     // Add all the dependences from the device linking actions.
3109     OffloadAction::DeviceDependences DDeps;
3110     for (auto *SB : SpecializedBuilders) {
3111       if (!SB->isValid())
3112         continue;
3113 
3114       SB->appendLinkDependences(DDeps);
3115     }
3116 
3117     // Calculate all the offload kinds used in the current compilation.
3118     unsigned ActiveOffloadKinds = 0u;
3119     for (auto &I : InputArgToOffloadKindMap)
3120       ActiveOffloadKinds |= I.second;
3121 
3122     // If we don't have device dependencies, we don't have to create an offload
3123     // action.
3124     if (DDeps.getActions().empty()) {
3125       // Propagate all the active kinds to host action. Given that it is a link
3126       // action it is assumed to depend on all actions generated so far.
3127       HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3128                                            /*BoundArch=*/nullptr);
3129       return HostAction;
3130     }
3131 
3132     // Create the offload action with all dependences. When an offload action
3133     // is created the kinds are propagated to the host action, so we don't have
3134     // to do that explicitly here.
3135     OffloadAction::HostDependence HDep(
3136         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3137         /*BoundArch*/ nullptr, ActiveOffloadKinds);
3138     return C.MakeAction<OffloadAction>(HDep, DDeps);
3139   }
3140 };
3141 } // anonymous namespace.
3142 
3143 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3144                           const InputList &Inputs, ActionList &Actions) const {
3145   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3146 
3147   if (!SuppressMissingInputWarning && Inputs.empty()) {
3148     Diag(clang::diag::err_drv_no_input_files);
3149     return;
3150   }
3151 
3152   Arg *FinalPhaseArg;
3153   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3154 
3155   if (FinalPhase == phases::Link) {
3156     if (Args.hasArg(options::OPT_emit_llvm))
3157       Diag(clang::diag::err_drv_emit_llvm_link);
3158     if (IsCLMode() && LTOMode != LTOK_None &&
3159         !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3160       Diag(clang::diag::err_drv_lto_without_lld);
3161   }
3162 
3163   // Reject -Z* at the top level, these options should never have been exposed
3164   // by gcc.
3165   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3166     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3167 
3168   // Diagnose misuse of /Fo.
3169   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3170     StringRef V = A->getValue();
3171     if (Inputs.size() > 1 && !V.empty() &&
3172         !llvm::sys::path::is_separator(V.back())) {
3173       // Check whether /Fo tries to name an output file for multiple inputs.
3174       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3175           << A->getSpelling() << V;
3176       Args.eraseArg(options::OPT__SLASH_Fo);
3177     }
3178   }
3179 
3180   // Diagnose misuse of /Fa.
3181   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3182     StringRef V = A->getValue();
3183     if (Inputs.size() > 1 && !V.empty() &&
3184         !llvm::sys::path::is_separator(V.back())) {
3185       // Check whether /Fa tries to name an asm file for multiple inputs.
3186       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3187           << A->getSpelling() << V;
3188       Args.eraseArg(options::OPT__SLASH_Fa);
3189     }
3190   }
3191 
3192   // Diagnose misuse of /o.
3193   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3194     if (A->getValue()[0] == '\0') {
3195       // It has to have a value.
3196       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3197       Args.eraseArg(options::OPT__SLASH_o);
3198     }
3199   }
3200 
3201   // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3202   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3203   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3204   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3205     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3206     Args.eraseArg(options::OPT__SLASH_Yc);
3207     Args.eraseArg(options::OPT__SLASH_Yu);
3208     YcArg = YuArg = nullptr;
3209   }
3210   if (YcArg && Inputs.size() > 1) {
3211     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3212     Args.eraseArg(options::OPT__SLASH_Yc);
3213     YcArg = nullptr;
3214   }
3215   if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3216     // If only preprocessing or /Y- is used, all pch handling is disabled.
3217     // Rather than check for it everywhere, just remove clang-cl pch-related
3218     // flags here.
3219     Args.eraseArg(options::OPT__SLASH_Fp);
3220     Args.eraseArg(options::OPT__SLASH_Yc);
3221     Args.eraseArg(options::OPT__SLASH_Yu);
3222     YcArg = YuArg = nullptr;
3223   }
3224 
3225   // Builder to be used to build offloading actions.
3226   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3227 
3228   // Construct the actions to perform.
3229   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3230   ActionList LinkerInputs;
3231 
3232   llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
3233   for (auto &I : Inputs) {
3234     types::ID InputType = I.first;
3235     const Arg *InputArg = I.second;
3236 
3237     PL.clear();
3238     types::getCompilationPhases(InputType, PL);
3239 
3240     // If the first step comes after the final phase we are doing as part of
3241     // this compilation, warn the user about it.
3242     phases::ID InitialPhase = PL[0];
3243     if (InitialPhase > FinalPhase) {
3244       if (InputArg->isClaimed())
3245         continue;
3246 
3247       // Claim here to avoid the more general unused warning.
3248       InputArg->claim();
3249 
3250       // Suppress all unused style warnings with -Qunused-arguments
3251       if (Args.hasArg(options::OPT_Qunused_arguments))
3252         continue;
3253 
3254       // Special case when final phase determined by binary name, rather than
3255       // by a command-line argument with a corresponding Arg.
3256       if (CCCIsCPP())
3257         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3258             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3259       // Special case '-E' warning on a previously preprocessed file to make
3260       // more sense.
3261       else if (InitialPhase == phases::Compile &&
3262                FinalPhase == phases::Preprocess &&
3263                getPreprocessedType(InputType) == types::TY_INVALID)
3264         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3265             << InputArg->getAsString(Args) << !!FinalPhaseArg
3266             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3267       else
3268         Diag(clang::diag::warn_drv_input_file_unused)
3269             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3270             << !!FinalPhaseArg
3271             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3272       continue;
3273     }
3274 
3275     if (YcArg) {
3276       // Add a separate precompile phase for the compile phase.
3277       if (FinalPhase >= phases::Compile) {
3278         const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3279         llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
3280         types::getCompilationPhases(HeaderType, PCHPL);
3281         // Build the pipeline for the pch file.
3282         Action *ClangClPch =
3283             C.MakeAction<InputAction>(*InputArg, HeaderType);
3284         for (phases::ID Phase : PCHPL)
3285           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3286         assert(ClangClPch);
3287         Actions.push_back(ClangClPch);
3288         // The driver currently exits after the first failed command.  This
3289         // relies on that behavior, to make sure if the pch generation fails,
3290         // the main compilation won't run.
3291         // FIXME: If the main compilation fails, the PCH generation should
3292         // probably not be considered successful either.
3293       }
3294     }
3295 
3296     // Build the pipeline for this file.
3297     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3298 
3299     // Use the current host action in any of the offloading actions, if
3300     // required.
3301     if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3302       break;
3303 
3304     for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3305          i != e; ++i) {
3306       phases::ID Phase = *i;
3307 
3308       // We are done if this step is past what the user requested.
3309       if (Phase > FinalPhase)
3310         break;
3311 
3312       // Add any offload action the host action depends on.
3313       Current = OffloadBuilder.addDeviceDependencesToHostAction(
3314           Current, InputArg, Phase, FinalPhase, PL);
3315       if (!Current)
3316         break;
3317 
3318       // Queue linker inputs.
3319       if (Phase == phases::Link) {
3320         assert((i + 1) == e && "linking must be final compilation step.");
3321         LinkerInputs.push_back(Current);
3322         Current = nullptr;
3323         break;
3324       }
3325 
3326       // Each precompiled header file after a module file action is a module
3327       // header of that same module file, rather than being compiled to a
3328       // separate PCH.
3329       if (Phase == phases::Precompile && HeaderModuleAction &&
3330           getPrecompiledType(InputType) == types::TY_PCH) {
3331         HeaderModuleAction->addModuleHeaderInput(Current);
3332         Current = nullptr;
3333         break;
3334       }
3335 
3336       // FIXME: Should we include any prior module file outputs as inputs of
3337       // later actions in the same command line?
3338 
3339       // Otherwise construct the appropriate action.
3340       Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3341 
3342       // We didn't create a new action, so we will just move to the next phase.
3343       if (NewCurrent == Current)
3344         continue;
3345 
3346       if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3347         HeaderModuleAction = HMA;
3348 
3349       Current = NewCurrent;
3350 
3351       // Use the current host action in any of the offloading actions, if
3352       // required.
3353       if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3354         break;
3355 
3356       if (Current->getType() == types::TY_Nothing)
3357         break;
3358     }
3359 
3360     // If we ended with something, add to the output list.
3361     if (Current)
3362       Actions.push_back(Current);
3363 
3364     // Add any top level actions generated for offloading.
3365     OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3366   }
3367 
3368   // Add a link action if necessary.
3369   if (!LinkerInputs.empty()) {
3370     Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3371     LA = OffloadBuilder.processHostLinkAction(LA);
3372     Actions.push_back(LA);
3373   }
3374 
3375   // If we are linking, claim any options which are obviously only used for
3376   // compilation.
3377   if (FinalPhase == phases::Link && PL.size() == 1) {
3378     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3379     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3380   }
3381 
3382   // Claim ignored clang-cl options.
3383   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3384 
3385   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3386   // to non-CUDA compilations and should not trigger warnings there.
3387   Args.ClaimAllArgs(options::OPT_cuda_host_only);
3388   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3389 }
3390 
3391 Action *Driver::ConstructPhaseAction(
3392     Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3393     Action::OffloadKind TargetDeviceOffloadKind) const {
3394   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3395 
3396   // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3397   // encode this in the steps because the intermediate type depends on
3398   // arguments. Just special case here.
3399   if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3400     return Input;
3401 
3402   // Build the appropriate action.
3403   switch (Phase) {
3404   case phases::Link:
3405     llvm_unreachable("link action invalid here.");
3406   case phases::Preprocess: {
3407     types::ID OutputTy;
3408     // -{M, MM} alter the output type.
3409     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
3410       OutputTy = types::TY_Dependencies;
3411     } else {
3412       OutputTy = Input->getType();
3413       if (!Args.hasFlag(options::OPT_frewrite_includes,
3414                         options::OPT_fno_rewrite_includes, false) &&
3415           !Args.hasFlag(options::OPT_frewrite_imports,
3416                         options::OPT_fno_rewrite_imports, false) &&
3417           !CCGenDiagnostics)
3418         OutputTy = types::getPreprocessedType(OutputTy);
3419       assert(OutputTy != types::TY_INVALID &&
3420              "Cannot preprocess this input type!");
3421     }
3422     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3423   }
3424   case phases::Precompile: {
3425     types::ID OutputTy = getPrecompiledType(Input->getType());
3426     assert(OutputTy != types::TY_INVALID &&
3427            "Cannot precompile this input type!");
3428 
3429     // If we're given a module name, precompile header file inputs as a
3430     // module, not as a precompiled header.
3431     const char *ModName = nullptr;
3432     if (OutputTy == types::TY_PCH) {
3433       if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3434         ModName = A->getValue();
3435       if (ModName)
3436         OutputTy = types::TY_ModuleFile;
3437     }
3438 
3439     if (Args.hasArg(options::OPT_fsyntax_only)) {
3440       // Syntax checks should not emit a PCH file
3441       OutputTy = types::TY_Nothing;
3442     }
3443 
3444     if (ModName)
3445       return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3446                                                            ModName);
3447     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3448   }
3449   case phases::Compile: {
3450     if (Args.hasArg(options::OPT_fsyntax_only))
3451       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3452     if (Args.hasArg(options::OPT_rewrite_objc))
3453       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3454     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3455       return C.MakeAction<CompileJobAction>(Input,
3456                                             types::TY_RewrittenLegacyObjC);
3457     if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
3458       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3459     if (Args.hasArg(options::OPT__migrate))
3460       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3461     if (Args.hasArg(options::OPT_emit_ast))
3462       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3463     if (Args.hasArg(options::OPT_module_file_info))
3464       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3465     if (Args.hasArg(options::OPT_verify_pch))
3466       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3467     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3468   }
3469   case phases::Backend: {
3470     if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3471       types::ID Output =
3472           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3473       return C.MakeAction<BackendJobAction>(Input, Output);
3474     }
3475     if (Args.hasArg(options::OPT_emit_llvm)) {
3476       types::ID Output =
3477           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3478       return C.MakeAction<BackendJobAction>(Input, Output);
3479     }
3480     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3481   }
3482   case phases::Assemble:
3483     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3484   }
3485 
3486   llvm_unreachable("invalid phase in ConstructPhaseAction");
3487 }
3488 
3489 void Driver::BuildJobs(Compilation &C) const {
3490   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3491 
3492   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3493 
3494   // It is an error to provide a -o option if we are making multiple output
3495   // files.
3496   if (FinalOutput) {
3497     unsigned NumOutputs = 0;
3498     for (const Action *A : C.getActions())
3499       if (A->getType() != types::TY_Nothing)
3500         ++NumOutputs;
3501 
3502     if (NumOutputs > 1) {
3503       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3504       FinalOutput = nullptr;
3505     }
3506   }
3507 
3508   // Collect the list of architectures.
3509   llvm::StringSet<> ArchNames;
3510   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3511     for (const Arg *A : C.getArgs())
3512       if (A->getOption().matches(options::OPT_arch))
3513         ArchNames.insert(A->getValue());
3514 
3515   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3516   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3517   for (Action *A : C.getActions()) {
3518     // If we are linking an image for multiple archs then the linker wants
3519     // -arch_multiple and -final_output <final image name>. Unfortunately, this
3520     // doesn't fit in cleanly because we have to pass this information down.
3521     //
3522     // FIXME: This is a hack; find a cleaner way to integrate this into the
3523     // process.
3524     const char *LinkingOutput = nullptr;
3525     if (isa<LipoJobAction>(A)) {
3526       if (FinalOutput)
3527         LinkingOutput = FinalOutput->getValue();
3528       else
3529         LinkingOutput = getDefaultImageName();
3530     }
3531 
3532     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3533                        /*BoundArch*/ StringRef(),
3534                        /*AtTopLevel*/ true,
3535                        /*MultipleArchs*/ ArchNames.size() > 1,
3536                        /*LinkingOutput*/ LinkingOutput, CachedResults,
3537                        /*TargetDeviceOffloadKind*/ Action::OFK_None);
3538   }
3539 
3540   // If the user passed -Qunused-arguments or there were errors, don't warn
3541   // about any unused arguments.
3542   if (Diags.hasErrorOccurred() ||
3543       C.getArgs().hasArg(options::OPT_Qunused_arguments))
3544     return;
3545 
3546   // Claim -### here.
3547   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
3548 
3549   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
3550   (void)C.getArgs().hasArg(options::OPT_driver_mode);
3551   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
3552 
3553   for (Arg *A : C.getArgs()) {
3554     // FIXME: It would be nice to be able to send the argument to the
3555     // DiagnosticsEngine, so that extra values, position, and so on could be
3556     // printed.
3557     if (!A->isClaimed()) {
3558       if (A->getOption().hasFlag(options::NoArgumentUnused))
3559         continue;
3560 
3561       // Suppress the warning automatically if this is just a flag, and it is an
3562       // instance of an argument we already claimed.
3563       const Option &Opt = A->getOption();
3564       if (Opt.getKind() == Option::FlagClass) {
3565         bool DuplicateClaimed = false;
3566 
3567         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3568           if (AA->isClaimed()) {
3569             DuplicateClaimed = true;
3570             break;
3571           }
3572         }
3573 
3574         if (DuplicateClaimed)
3575           continue;
3576       }
3577 
3578       // In clang-cl, don't mention unknown arguments here since they have
3579       // already been warned about.
3580       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3581         Diag(clang::diag::warn_drv_unused_argument)
3582             << A->getAsString(C.getArgs());
3583     }
3584   }
3585 }
3586 
3587 namespace {
3588 /// Utility class to control the collapse of dependent actions and select the
3589 /// tools accordingly.
3590 class ToolSelector final {
3591   /// The tool chain this selector refers to.
3592   const ToolChain &TC;
3593 
3594   /// The compilation this selector refers to.
3595   const Compilation &C;
3596 
3597   /// The base action this selector refers to.
3598   const JobAction *BaseAction;
3599 
3600   /// Set to true if the current toolchain refers to host actions.
3601   bool IsHostSelector;
3602 
3603   /// Set to true if save-temps and embed-bitcode functionalities are active.
3604   bool SaveTemps;
3605   bool EmbedBitcode;
3606 
3607   /// Get previous dependent action or null if that does not exist. If
3608   /// \a CanBeCollapsed is false, that action must be legal to collapse or
3609   /// null will be returned.
3610   const JobAction *getPrevDependentAction(const ActionList &Inputs,
3611                                           ActionList &SavedOffloadAction,
3612                                           bool CanBeCollapsed = true) {
3613     // An option can be collapsed only if it has a single input.
3614     if (Inputs.size() != 1)
3615       return nullptr;
3616 
3617     Action *CurAction = *Inputs.begin();
3618     if (CanBeCollapsed &&
3619         !CurAction->isCollapsingWithNextDependentActionLegal())
3620       return nullptr;
3621 
3622     // If the input action is an offload action. Look through it and save any
3623     // offload action that can be dropped in the event of a collapse.
3624     if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3625       // If the dependent action is a device action, we will attempt to collapse
3626       // only with other device actions. Otherwise, we would do the same but
3627       // with host actions only.
3628       if (!IsHostSelector) {
3629         if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3630           CurAction =
3631               OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3632           if (CanBeCollapsed &&
3633               !CurAction->isCollapsingWithNextDependentActionLegal())
3634             return nullptr;
3635           SavedOffloadAction.push_back(OA);
3636           return dyn_cast<JobAction>(CurAction);
3637         }
3638       } else if (OA->hasHostDependence()) {
3639         CurAction = OA->getHostDependence();
3640         if (CanBeCollapsed &&
3641             !CurAction->isCollapsingWithNextDependentActionLegal())
3642           return nullptr;
3643         SavedOffloadAction.push_back(OA);
3644         return dyn_cast<JobAction>(CurAction);
3645       }
3646       return nullptr;
3647     }
3648 
3649     return dyn_cast<JobAction>(CurAction);
3650   }
3651 
3652   /// Return true if an assemble action can be collapsed.
3653   bool canCollapseAssembleAction() const {
3654     return TC.useIntegratedAs() && !SaveTemps &&
3655            !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3656            !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3657            !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3658   }
3659 
3660   /// Return true if a preprocessor action can be collapsed.
3661   bool canCollapsePreprocessorAction() const {
3662     return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3663            !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3664            !C.getArgs().hasArg(options::OPT_rewrite_objc);
3665   }
3666 
3667   /// Struct that relates an action with the offload actions that would be
3668   /// collapsed with it.
3669   struct JobActionInfo final {
3670     /// The action this info refers to.
3671     const JobAction *JA = nullptr;
3672     /// The offload actions we need to take care off if this action is
3673     /// collapsed.
3674     ActionList SavedOffloadAction;
3675   };
3676 
3677   /// Append collapsed offload actions from the give nnumber of elements in the
3678   /// action info array.
3679   static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3680                                            ArrayRef<JobActionInfo> &ActionInfo,
3681                                            unsigned ElementNum) {
3682     assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3683     for (unsigned I = 0; I < ElementNum; ++I)
3684       CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3685                                     ActionInfo[I].SavedOffloadAction.end());
3686   }
3687 
3688   /// Functions that attempt to perform the combining. They detect if that is
3689   /// legal, and if so they update the inputs \a Inputs and the offload action
3690   /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3691   /// the combined action is returned. If the combining is not legal or if the
3692   /// tool does not exist, null is returned.
3693   /// Currently three kinds of collapsing are supported:
3694   ///  - Assemble + Backend + Compile;
3695   ///  - Assemble + Backend ;
3696   ///  - Backend + Compile.
3697   const Tool *
3698   combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3699                                 ActionList &Inputs,
3700                                 ActionList &CollapsedOffloadAction) {
3701     if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3702       return nullptr;
3703     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3704     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3705     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3706     if (!AJ || !BJ || !CJ)
3707       return nullptr;
3708 
3709     // Get compiler tool.
3710     const Tool *T = TC.SelectTool(*CJ);
3711     if (!T)
3712       return nullptr;
3713 
3714     // When using -fembed-bitcode, it is required to have the same tool (clang)
3715     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3716     if (EmbedBitcode) {
3717       const Tool *BT = TC.SelectTool(*BJ);
3718       if (BT == T)
3719         return nullptr;
3720     }
3721 
3722     if (!T->hasIntegratedAssembler())
3723       return nullptr;
3724 
3725     Inputs = CJ->getInputs();
3726     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3727                                  /*NumElements=*/3);
3728     return T;
3729   }
3730   const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3731                                      ActionList &Inputs,
3732                                      ActionList &CollapsedOffloadAction) {
3733     if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3734       return nullptr;
3735     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3736     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3737     if (!AJ || !BJ)
3738       return nullptr;
3739 
3740     // Retrieve the compile job, backend action must always be preceded by one.
3741     ActionList CompileJobOffloadActions;
3742     auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3743                                       /*CanBeCollapsed=*/false);
3744     if (!AJ || !BJ || !CJ)
3745       return nullptr;
3746 
3747     assert(isa<CompileJobAction>(CJ) &&
3748            "Expecting compile job preceding backend job.");
3749 
3750     // Get compiler tool.
3751     const Tool *T = TC.SelectTool(*CJ);
3752     if (!T)
3753       return nullptr;
3754 
3755     if (!T->hasIntegratedAssembler())
3756       return nullptr;
3757 
3758     Inputs = BJ->getInputs();
3759     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3760                                  /*NumElements=*/2);
3761     return T;
3762   }
3763   const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3764                                     ActionList &Inputs,
3765                                     ActionList &CollapsedOffloadAction) {
3766     if (ActionInfo.size() < 2)
3767       return nullptr;
3768     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3769     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3770     if (!BJ || !CJ)
3771       return nullptr;
3772 
3773     // Check if the initial input (to the compile job or its predessor if one
3774     // exists) is LLVM bitcode. In that case, no preprocessor step is required
3775     // and we can still collapse the compile and backend jobs when we have
3776     // -save-temps. I.e. there is no need for a separate compile job just to
3777     // emit unoptimized bitcode.
3778     bool InputIsBitcode = true;
3779     for (size_t i = 1; i < ActionInfo.size(); i++)
3780       if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3781           ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3782         InputIsBitcode = false;
3783         break;
3784       }
3785     if (!InputIsBitcode && !canCollapsePreprocessorAction())
3786       return nullptr;
3787 
3788     // Get compiler tool.
3789     const Tool *T = TC.SelectTool(*CJ);
3790     if (!T)
3791       return nullptr;
3792 
3793     if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
3794       return nullptr;
3795 
3796     Inputs = CJ->getInputs();
3797     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3798                                  /*NumElements=*/2);
3799     return T;
3800   }
3801 
3802   /// Updates the inputs if the obtained tool supports combining with
3803   /// preprocessor action, and the current input is indeed a preprocessor
3804   /// action. If combining results in the collapse of offloading actions, those
3805   /// are appended to \a CollapsedOffloadAction.
3806   void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
3807                                ActionList &CollapsedOffloadAction) {
3808     if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3809       return;
3810 
3811     // Attempt to get a preprocessor action dependence.
3812     ActionList PreprocessJobOffloadActions;
3813     ActionList NewInputs;
3814     for (Action *A : Inputs) {
3815       auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
3816       if (!PJ || !isa<PreprocessJobAction>(PJ)) {
3817         NewInputs.push_back(A);
3818         continue;
3819       }
3820 
3821       // This is legal to combine. Append any offload action we found and add the
3822       // current input to preprocessor inputs.
3823       CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3824                                     PreprocessJobOffloadActions.end());
3825       NewInputs.append(PJ->input_begin(), PJ->input_end());
3826     }
3827     Inputs = NewInputs;
3828   }
3829 
3830 public:
3831   ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3832                const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3833       : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3834         EmbedBitcode(EmbedBitcode) {
3835     assert(BaseAction && "Invalid base action.");
3836     IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3837   }
3838 
3839   /// Check if a chain of actions can be combined and return the tool that can
3840   /// handle the combination of actions. The pointer to the current inputs \a
3841   /// Inputs and the list of offload actions \a CollapsedOffloadActions
3842   /// connected to collapsed actions are updated accordingly. The latter enables
3843   /// the caller of the selector to process them afterwards instead of just
3844   /// dropping them. If no suitable tool is found, null will be returned.
3845   const Tool *getTool(ActionList &Inputs,
3846                       ActionList &CollapsedOffloadAction) {
3847     //
3848     // Get the largest chain of actions that we could combine.
3849     //
3850 
3851     SmallVector<JobActionInfo, 5> ActionChain(1);
3852     ActionChain.back().JA = BaseAction;
3853     while (ActionChain.back().JA) {
3854       const Action *CurAction = ActionChain.back().JA;
3855 
3856       // Grow the chain by one element.
3857       ActionChain.resize(ActionChain.size() + 1);
3858       JobActionInfo &AI = ActionChain.back();
3859 
3860       // Attempt to fill it with the
3861       AI.JA =
3862           getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3863     }
3864 
3865     // Pop the last action info as it could not be filled.
3866     ActionChain.pop_back();
3867 
3868     //
3869     // Attempt to combine actions. If all combining attempts failed, just return
3870     // the tool of the provided action. At the end we attempt to combine the
3871     // action with any preprocessor action it may depend on.
3872     //
3873 
3874     const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3875                                                   CollapsedOffloadAction);
3876     if (!T)
3877       T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3878     if (!T)
3879       T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3880     if (!T) {
3881       Inputs = BaseAction->getInputs();
3882       T = TC.SelectTool(*BaseAction);
3883     }
3884 
3885     combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3886     return T;
3887   }
3888 };
3889 }
3890 
3891 /// Return a string that uniquely identifies the result of a job. The bound arch
3892 /// is not necessarily represented in the toolchain's triple -- for example,
3893 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3894 /// Also, we need to add the offloading device kind, as the same tool chain can
3895 /// be used for host and device for some programming models, e.g. OpenMP.
3896 static std::string GetTriplePlusArchString(const ToolChain *TC,
3897                                            StringRef BoundArch,
3898                                            Action::OffloadKind OffloadKind) {
3899   std::string TriplePlusArch = TC->getTriple().normalize();
3900   if (!BoundArch.empty()) {
3901     TriplePlusArch += "-";
3902     TriplePlusArch += BoundArch;
3903   }
3904   TriplePlusArch += "-";
3905   TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3906   return TriplePlusArch;
3907 }
3908 
3909 InputInfo Driver::BuildJobsForAction(
3910     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3911     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3912     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3913     Action::OffloadKind TargetDeviceOffloadKind) const {
3914   std::pair<const Action *, std::string> ActionTC = {
3915       A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3916   auto CachedResult = CachedResults.find(ActionTC);
3917   if (CachedResult != CachedResults.end()) {
3918     return CachedResult->second;
3919   }
3920   InputInfo Result = BuildJobsForActionNoCache(
3921       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3922       CachedResults, TargetDeviceOffloadKind);
3923   CachedResults[ActionTC] = Result;
3924   return Result;
3925 }
3926 
3927 InputInfo Driver::BuildJobsForActionNoCache(
3928     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3929     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3930     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3931     Action::OffloadKind TargetDeviceOffloadKind) const {
3932   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3933 
3934   InputInfoList OffloadDependencesInputInfo;
3935   bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3936   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3937     // The 'Darwin' toolchain is initialized only when its arguments are
3938     // computed. Get the default arguments for OFK_None to ensure that
3939     // initialization is performed before processing the offload action.
3940     // FIXME: Remove when darwin's toolchain is initialized during construction.
3941     C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3942 
3943     // The offload action is expected to be used in four different situations.
3944     //
3945     // a) Set a toolchain/architecture/kind for a host action:
3946     //    Host Action 1 -> OffloadAction -> Host Action 2
3947     //
3948     // b) Set a toolchain/architecture/kind for a device action;
3949     //    Device Action 1 -> OffloadAction -> Device Action 2
3950     //
3951     // c) Specify a device dependence to a host action;
3952     //    Device Action 1  _
3953     //                      \
3954     //      Host Action 1  ---> OffloadAction -> Host Action 2
3955     //
3956     // d) Specify a host dependence to a device action.
3957     //      Host Action 1  _
3958     //                      \
3959     //    Device Action 1  ---> OffloadAction -> Device Action 2
3960     //
3961     // For a) and b), we just return the job generated for the dependence. For
3962     // c) and d) we override the current action with the host/device dependence
3963     // if the current toolchain is host/device and set the offload dependences
3964     // info with the jobs obtained from the device/host dependence(s).
3965 
3966     // If there is a single device option, just generate the job for it.
3967     if (OA->hasSingleDeviceDependence()) {
3968       InputInfo DevA;
3969       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3970                                        const char *DepBoundArch) {
3971         DevA =
3972             BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3973                                /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3974                                CachedResults, DepA->getOffloadingDeviceKind());
3975       });
3976       return DevA;
3977     }
3978 
3979     // If 'Action 2' is host, we generate jobs for the device dependences and
3980     // override the current action with the host dependence. Otherwise, we
3981     // generate the host dependences and override the action with the device
3982     // dependence. The dependences can't therefore be a top-level action.
3983     OA->doOnEachDependence(
3984         /*IsHostDependence=*/BuildingForOffloadDevice,
3985         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3986           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3987               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3988               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3989               DepA->getOffloadingDeviceKind()));
3990         });
3991 
3992     A = BuildingForOffloadDevice
3993             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3994             : OA->getHostDependence();
3995   }
3996 
3997   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3998     // FIXME: It would be nice to not claim this here; maybe the old scheme of
3999     // just using Args was better?
4000     const Arg &Input = IA->getInputArg();
4001     Input.claim();
4002     if (Input.getOption().matches(options::OPT_INPUT)) {
4003       const char *Name = Input.getValue();
4004       return InputInfo(A, Name, /* BaseInput = */ Name);
4005     }
4006     return InputInfo(A, &Input, /* BaseInput = */ "");
4007   }
4008 
4009   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4010     const ToolChain *TC;
4011     StringRef ArchName = BAA->getArchName();
4012 
4013     if (!ArchName.empty())
4014       TC = &getToolChain(C.getArgs(),
4015                          computeTargetTriple(*this, TargetTriple,
4016                                              C.getArgs(), ArchName));
4017     else
4018       TC = &C.getDefaultToolChain();
4019 
4020     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4021                               MultipleArchs, LinkingOutput, CachedResults,
4022                               TargetDeviceOffloadKind);
4023   }
4024 
4025 
4026   ActionList Inputs = A->getInputs();
4027 
4028   const JobAction *JA = cast<JobAction>(A);
4029   ActionList CollapsedOffloadActions;
4030 
4031   ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4032                   embedBitcodeInObject() && !isUsingLTO());
4033   const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4034 
4035   if (!T)
4036     return InputInfo();
4037 
4038   // If we've collapsed action list that contained OffloadAction we
4039   // need to build jobs for host/device-side inputs it may have held.
4040   for (const auto *OA : CollapsedOffloadActions)
4041     cast<OffloadAction>(OA)->doOnEachDependence(
4042         /*IsHostDependence=*/BuildingForOffloadDevice,
4043         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4044           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4045               C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4046               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4047               DepA->getOffloadingDeviceKind()));
4048         });
4049 
4050   // Only use pipes when there is exactly one input.
4051   InputInfoList InputInfos;
4052   for (const Action *Input : Inputs) {
4053     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4054     // shouldn't get temporary output names.
4055     // FIXME: Clean this up.
4056     bool SubJobAtTopLevel =
4057         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4058     InputInfos.push_back(BuildJobsForAction(
4059         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4060         CachedResults, A->getOffloadingDeviceKind()));
4061   }
4062 
4063   // Always use the first input as the base input.
4064   const char *BaseInput = InputInfos[0].getBaseInput();
4065 
4066   // ... except dsymutil actions, which use their actual input as the base
4067   // input.
4068   if (JA->getType() == types::TY_dSYM)
4069     BaseInput = InputInfos[0].getFilename();
4070 
4071   // ... and in header module compilations, which use the module name.
4072   if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4073     BaseInput = ModuleJA->getModuleName();
4074 
4075   // Append outputs of offload device jobs to the input list
4076   if (!OffloadDependencesInputInfo.empty())
4077     InputInfos.append(OffloadDependencesInputInfo.begin(),
4078                       OffloadDependencesInputInfo.end());
4079 
4080   // Set the effective triple of the toolchain for the duration of this job.
4081   llvm::Triple EffectiveTriple;
4082   const ToolChain &ToolTC = T->getToolChain();
4083   const ArgList &Args =
4084       C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4085   if (InputInfos.size() != 1) {
4086     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4087   } else {
4088     // Pass along the input type if it can be unambiguously determined.
4089     EffectiveTriple = llvm::Triple(
4090         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4091   }
4092   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4093 
4094   // Determine the place to write output to, if any.
4095   InputInfo Result;
4096   InputInfoList UnbundlingResults;
4097   if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4098     // If we have an unbundling job, we need to create results for all the
4099     // outputs. We also update the results cache so that other actions using
4100     // this unbundling action can get the right results.
4101     for (auto &UI : UA->getDependentActionsInfo()) {
4102       assert(UI.DependentOffloadKind != Action::OFK_None &&
4103              "Unbundling with no offloading??");
4104 
4105       // Unbundling actions are never at the top level. When we generate the
4106       // offloading prefix, we also do that for the host file because the
4107       // unbundling action does not change the type of the output which can
4108       // cause a overwrite.
4109       std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4110           UI.DependentOffloadKind,
4111           UI.DependentToolChain->getTriple().normalize(),
4112           /*CreatePrefixForHost=*/true);
4113       auto CurI = InputInfo(
4114           UA,
4115           GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4116                              /*AtTopLevel=*/false,
4117                              MultipleArchs ||
4118                                  UI.DependentOffloadKind == Action::OFK_HIP,
4119                              OffloadingPrefix),
4120           BaseInput);
4121       // Save the unbundling result.
4122       UnbundlingResults.push_back(CurI);
4123 
4124       // Get the unique string identifier for this dependence and cache the
4125       // result.
4126       StringRef Arch;
4127       if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4128         if (UI.DependentOffloadKind == Action::OFK_Host)
4129           Arch = StringRef();
4130         else
4131           Arch = UI.DependentBoundArch;
4132       } else
4133         Arch = BoundArch;
4134 
4135       CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4136                                                 UI.DependentOffloadKind)}] =
4137           CurI;
4138     }
4139 
4140     // Now that we have all the results generated, select the one that should be
4141     // returned for the current depending action.
4142     std::pair<const Action *, std::string> ActionTC = {
4143         A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4144     assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4145            "Result does not exist??");
4146     Result = CachedResults[ActionTC];
4147   } else if (JA->getType() == types::TY_Nothing)
4148     Result = InputInfo(A, BaseInput);
4149   else {
4150     // We only have to generate a prefix for the host if this is not a top-level
4151     // action.
4152     std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4153         A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4154         /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4155             !AtTopLevel);
4156     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4157                                              AtTopLevel, MultipleArchs,
4158                                              OffloadingPrefix),
4159                        BaseInput);
4160   }
4161 
4162   if (CCCPrintBindings && !CCGenDiagnostics) {
4163     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4164                  << " - \"" << T->getName() << "\", inputs: [";
4165     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4166       llvm::errs() << InputInfos[i].getAsString();
4167       if (i + 1 != e)
4168         llvm::errs() << ", ";
4169     }
4170     if (UnbundlingResults.empty())
4171       llvm::errs() << "], output: " << Result.getAsString() << "\n";
4172     else {
4173       llvm::errs() << "], outputs: [";
4174       for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4175         llvm::errs() << UnbundlingResults[i].getAsString();
4176         if (i + 1 != e)
4177           llvm::errs() << ", ";
4178       }
4179       llvm::errs() << "] \n";
4180     }
4181   } else {
4182     if (UnbundlingResults.empty())
4183       T->ConstructJob(
4184           C, *JA, Result, InputInfos,
4185           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4186           LinkingOutput);
4187     else
4188       T->ConstructJobMultipleOutputs(
4189           C, *JA, UnbundlingResults, InputInfos,
4190           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4191           LinkingOutput);
4192   }
4193   return Result;
4194 }
4195 
4196 const char *Driver::getDefaultImageName() const {
4197   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4198   return Target.isOSWindows() ? "a.exe" : "a.out";
4199 }
4200 
4201 /// Create output filename based on ArgValue, which could either be a
4202 /// full filename, filename without extension, or a directory. If ArgValue
4203 /// does not provide a filename, then use BaseName, and use the extension
4204 /// suitable for FileType.
4205 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4206                                         StringRef BaseName,
4207                                         types::ID FileType) {
4208   SmallString<128> Filename = ArgValue;
4209 
4210   if (ArgValue.empty()) {
4211     // If the argument is empty, output to BaseName in the current dir.
4212     Filename = BaseName;
4213   } else if (llvm::sys::path::is_separator(Filename.back())) {
4214     // If the argument is a directory, output to BaseName in that dir.
4215     llvm::sys::path::append(Filename, BaseName);
4216   }
4217 
4218   if (!llvm::sys::path::has_extension(ArgValue)) {
4219     // If the argument didn't provide an extension, then set it.
4220     const char *Extension = types::getTypeTempSuffix(FileType, true);
4221 
4222     if (FileType == types::TY_Image &&
4223         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4224       // The output file is a dll.
4225       Extension = "dll";
4226     }
4227 
4228     llvm::sys::path::replace_extension(Filename, Extension);
4229   }
4230 
4231   return Args.MakeArgString(Filename.c_str());
4232 }
4233 
4234 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4235                                        const char *BaseInput,
4236                                        StringRef BoundArch, bool AtTopLevel,
4237                                        bool MultipleArchs,
4238                                        StringRef OffloadingPrefix) const {
4239   llvm::PrettyStackTraceString CrashInfo("Computing output path");
4240   // Output to a user requested destination?
4241   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4242     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4243       return C.addResultFile(FinalOutput->getValue(), &JA);
4244   }
4245 
4246   // For /P, preprocess to file named after BaseInput.
4247   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4248     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4249     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4250     StringRef NameArg;
4251     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4252       NameArg = A->getValue();
4253     return C.addResultFile(
4254         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4255         &JA);
4256   }
4257 
4258   // Default to writing to stdout?
4259   if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
4260     return "-";
4261 
4262   // Is this the assembly listing for /FA?
4263   if (JA.getType() == types::TY_PP_Asm &&
4264       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4265        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4266     // Use /Fa and the input filename to determine the asm file name.
4267     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4268     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4269     return C.addResultFile(
4270         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4271         &JA);
4272   }
4273 
4274   // Output to a temporary file?
4275   if ((!AtTopLevel && !isSaveTempsEnabled() &&
4276        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4277       CCGenDiagnostics) {
4278     StringRef Name = llvm::sys::path::filename(BaseInput);
4279     std::pair<StringRef, StringRef> Split = Name.split('.');
4280     SmallString<128> TmpName;
4281     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4282     Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4283     if (CCGenDiagnostics && A) {
4284       SmallString<128> CrashDirectory(A->getValue());
4285       if (!getVFS().exists(CrashDirectory))
4286         llvm::sys::fs::create_directories(CrashDirectory);
4287       llvm::sys::path::append(CrashDirectory, Split.first);
4288       const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4289       std::error_code EC = llvm::sys::fs::createUniqueFile(
4290           CrashDirectory + Middle + Suffix, TmpName);
4291       if (EC) {
4292         Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4293         return "";
4294       }
4295     } else {
4296       TmpName = GetTemporaryPath(Split.first, Suffix);
4297     }
4298     return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4299   }
4300 
4301   SmallString<128> BasePath(BaseInput);
4302   StringRef BaseName;
4303 
4304   // Dsymutil actions should use the full path.
4305   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4306     BaseName = BasePath;
4307   else
4308     BaseName = llvm::sys::path::filename(BasePath);
4309 
4310   // Determine what the derived output name should be.
4311   const char *NamedOutput;
4312 
4313   if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4314       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4315     // The /Fo or /o flag decides the object filename.
4316     StringRef Val =
4317         C.getArgs()
4318             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4319             ->getValue();
4320     NamedOutput =
4321         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4322   } else if (JA.getType() == types::TY_Image &&
4323              C.getArgs().hasArg(options::OPT__SLASH_Fe,
4324                                 options::OPT__SLASH_o)) {
4325     // The /Fe or /o flag names the linked file.
4326     StringRef Val =
4327         C.getArgs()
4328             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4329             ->getValue();
4330     NamedOutput =
4331         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4332   } else if (JA.getType() == types::TY_Image) {
4333     if (IsCLMode()) {
4334       // clang-cl uses BaseName for the executable name.
4335       NamedOutput =
4336           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4337     } else {
4338       SmallString<128> Output(getDefaultImageName());
4339       Output += OffloadingPrefix;
4340       if (MultipleArchs && !BoundArch.empty()) {
4341         Output += "-";
4342         Output.append(BoundArch);
4343       }
4344       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4345     }
4346   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4347     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4348   } else {
4349     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4350     assert(Suffix && "All types used for output should have a suffix.");
4351 
4352     std::string::size_type End = std::string::npos;
4353     if (!types::appendSuffixForType(JA.getType()))
4354       End = BaseName.rfind('.');
4355     SmallString<128> Suffixed(BaseName.substr(0, End));
4356     Suffixed += OffloadingPrefix;
4357     if (MultipleArchs && !BoundArch.empty()) {
4358       Suffixed += "-";
4359       Suffixed.append(BoundArch);
4360     }
4361     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4362     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4363     // optimized bitcode output.
4364     if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4365         JA.getType() == types::TY_LLVM_BC)
4366       Suffixed += ".tmp";
4367     Suffixed += '.';
4368     Suffixed += Suffix;
4369     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4370   }
4371 
4372   // Prepend object file path if -save-temps=obj
4373   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4374       JA.getType() != types::TY_PCH) {
4375     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4376     SmallString<128> TempPath(FinalOutput->getValue());
4377     llvm::sys::path::remove_filename(TempPath);
4378     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4379     llvm::sys::path::append(TempPath, OutputFileName);
4380     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4381   }
4382 
4383   // If we're saving temps and the temp file conflicts with the input file,
4384   // then avoid overwriting input file.
4385   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4386     bool SameFile = false;
4387     SmallString<256> Result;
4388     llvm::sys::fs::current_path(Result);
4389     llvm::sys::path::append(Result, BaseName);
4390     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4391     // Must share the same path to conflict.
4392     if (SameFile) {
4393       StringRef Name = llvm::sys::path::filename(BaseInput);
4394       std::pair<StringRef, StringRef> Split = Name.split('.');
4395       std::string TmpName = GetTemporaryPath(
4396           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4397       return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4398     }
4399   }
4400 
4401   // As an annoying special case, PCH generation doesn't strip the pathname.
4402   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4403     llvm::sys::path::remove_filename(BasePath);
4404     if (BasePath.empty())
4405       BasePath = NamedOutput;
4406     else
4407       llvm::sys::path::append(BasePath, NamedOutput);
4408     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4409   } else {
4410     return C.addResultFile(NamedOutput, &JA);
4411   }
4412 }
4413 
4414 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4415   // Search for Name in a list of paths.
4416   auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4417       -> llvm::Optional<std::string> {
4418     // Respect a limited subset of the '-Bprefix' functionality in GCC by
4419     // attempting to use this prefix when looking for file paths.
4420     for (const auto &Dir : P) {
4421       if (Dir.empty())
4422         continue;
4423       SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4424       llvm::sys::path::append(P, Name);
4425       if (llvm::sys::fs::exists(Twine(P)))
4426         return P.str().str();
4427     }
4428     return None;
4429   };
4430 
4431   if (auto P = SearchPaths(PrefixDirs))
4432     return *P;
4433 
4434   SmallString<128> R(ResourceDir);
4435   llvm::sys::path::append(R, Name);
4436   if (llvm::sys::fs::exists(Twine(R)))
4437     return R.str();
4438 
4439   SmallString<128> P(TC.getCompilerRTPath());
4440   llvm::sys::path::append(P, Name);
4441   if (llvm::sys::fs::exists(Twine(P)))
4442     return P.str();
4443 
4444   if (auto P = SearchPaths(TC.getLibraryPaths()))
4445     return *P;
4446 
4447   if (auto P = SearchPaths(TC.getFilePaths()))
4448     return *P;
4449 
4450   return Name;
4451 }
4452 
4453 void Driver::generatePrefixedToolNames(
4454     StringRef Tool, const ToolChain &TC,
4455     SmallVectorImpl<std::string> &Names) const {
4456   // FIXME: Needs a better variable than TargetTriple
4457   Names.emplace_back((TargetTriple + "-" + Tool).str());
4458   Names.emplace_back(Tool);
4459 
4460   // Allow the discovery of tools prefixed with LLVM's default target triple.
4461   std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4462   if (DefaultTargetTriple != TargetTriple)
4463     Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4464 }
4465 
4466 static bool ScanDirForExecutable(SmallString<128> &Dir,
4467                                  ArrayRef<std::string> Names) {
4468   for (const auto &Name : Names) {
4469     llvm::sys::path::append(Dir, Name);
4470     if (llvm::sys::fs::can_execute(Twine(Dir)))
4471       return true;
4472     llvm::sys::path::remove_filename(Dir);
4473   }
4474   return false;
4475 }
4476 
4477 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4478   SmallVector<std::string, 2> TargetSpecificExecutables;
4479   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4480 
4481   // Respect a limited subset of the '-Bprefix' functionality in GCC by
4482   // attempting to use this prefix when looking for program paths.
4483   for (const auto &PrefixDir : PrefixDirs) {
4484     if (llvm::sys::fs::is_directory(PrefixDir)) {
4485       SmallString<128> P(PrefixDir);
4486       if (ScanDirForExecutable(P, TargetSpecificExecutables))
4487         return P.str();
4488     } else {
4489       SmallString<128> P((PrefixDir + Name).str());
4490       if (llvm::sys::fs::can_execute(Twine(P)))
4491         return P.str();
4492     }
4493   }
4494 
4495   const ToolChain::path_list &List = TC.getProgramPaths();
4496   for (const auto &Path : List) {
4497     SmallString<128> P(Path);
4498     if (ScanDirForExecutable(P, TargetSpecificExecutables))
4499       return P.str();
4500   }
4501 
4502   // If all else failed, search the path.
4503   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4504     if (llvm::ErrorOr<std::string> P =
4505             llvm::sys::findProgramByName(TargetSpecificExecutable))
4506       return *P;
4507 
4508   return Name;
4509 }
4510 
4511 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
4512   SmallString<128> Path;
4513   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
4514   if (EC) {
4515     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4516     return "";
4517   }
4518 
4519   return Path.str();
4520 }
4521 
4522 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4523   SmallString<128> Path;
4524   std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4525   if (EC) {
4526     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4527     return "";
4528   }
4529 
4530   return Path.str();
4531 }
4532 
4533 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4534   SmallString<128> Output;
4535   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4536     // FIXME: If anybody needs it, implement this obscure rule:
4537     // "If you specify a directory without a file name, the default file name
4538     // is VCx0.pch., where x is the major version of Visual C++ in use."
4539     Output = FpArg->getValue();
4540 
4541     // "If you do not specify an extension as part of the path name, an
4542     // extension of .pch is assumed. "
4543     if (!llvm::sys::path::has_extension(Output))
4544       Output += ".pch";
4545   } else {
4546     if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4547       Output = YcArg->getValue();
4548     if (Output.empty())
4549       Output = BaseName;
4550     llvm::sys::path::replace_extension(Output, ".pch");
4551   }
4552   return Output.str();
4553 }
4554 
4555 const ToolChain &Driver::getToolChain(const ArgList &Args,
4556                                       const llvm::Triple &Target) const {
4557 
4558   auto &TC = ToolChains[Target.str()];
4559   if (!TC) {
4560     switch (Target.getOS()) {
4561     case llvm::Triple::Haiku:
4562       TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
4563       break;
4564     case llvm::Triple::Ananas:
4565       TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4566       break;
4567     case llvm::Triple::CloudABI:
4568       TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
4569       break;
4570     case llvm::Triple::Darwin:
4571     case llvm::Triple::MacOSX:
4572     case llvm::Triple::IOS:
4573     case llvm::Triple::TvOS:
4574     case llvm::Triple::WatchOS:
4575       TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
4576       break;
4577     case llvm::Triple::DragonFly:
4578       TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
4579       break;
4580     case llvm::Triple::OpenBSD:
4581       TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
4582       break;
4583     case llvm::Triple::NetBSD:
4584       TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
4585       break;
4586     case llvm::Triple::FreeBSD:
4587       TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
4588       break;
4589     case llvm::Triple::Minix:
4590       TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
4591       break;
4592     case llvm::Triple::Linux:
4593     case llvm::Triple::ELFIAMCU:
4594       if (Target.getArch() == llvm::Triple::hexagon)
4595         TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4596                                                              Args);
4597       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4598                !Target.hasEnvironment())
4599         TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4600                                                               Args);
4601       else if (Target.getArch() == llvm::Triple::ppc ||
4602                Target.getArch() == llvm::Triple::ppc64 ||
4603                Target.getArch() == llvm::Triple::ppc64le)
4604         TC = llvm::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
4605                                                               Args);
4606       else
4607         TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
4608       break;
4609     case llvm::Triple::NaCl:
4610       TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
4611       break;
4612     case llvm::Triple::Fuchsia:
4613       TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
4614       break;
4615     case llvm::Triple::Solaris:
4616       TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
4617       break;
4618     case llvm::Triple::AMDHSA:
4619       TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
4620       break;
4621     case llvm::Triple::Win32:
4622       switch (Target.getEnvironment()) {
4623       default:
4624         if (Target.isOSBinFormatELF())
4625           TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4626         else if (Target.isOSBinFormatMachO())
4627           TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
4628         else
4629           TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4630         break;
4631       case llvm::Triple::GNU:
4632         TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
4633         break;
4634       case llvm::Triple::Itanium:
4635         TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4636                                                                   Args);
4637         break;
4638       case llvm::Triple::MSVC:
4639       case llvm::Triple::UnknownEnvironment:
4640         if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4641                 .startswith_lower("bfd"))
4642           TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4643               *this, Target, Args);
4644         else
4645           TC =
4646               llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
4647         break;
4648       }
4649       break;
4650     case llvm::Triple::PS4:
4651       TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
4652       break;
4653     case llvm::Triple::Contiki:
4654       TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
4655       break;
4656     case llvm::Triple::Hurd:
4657       TC = llvm::make_unique<toolchains::Hurd>(*this, Target, Args);
4658       break;
4659     default:
4660       // Of these targets, Hexagon is the only one that might have
4661       // an OS of Linux, in which case it got handled above already.
4662       switch (Target.getArch()) {
4663       case llvm::Triple::tce:
4664         TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
4665         break;
4666       case llvm::Triple::tcele:
4667         TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
4668         break;
4669       case llvm::Triple::hexagon:
4670         TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4671                                                              Args);
4672         break;
4673       case llvm::Triple::lanai:
4674         TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
4675         break;
4676       case llvm::Triple::xcore:
4677         TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
4678         break;
4679       case llvm::Triple::wasm32:
4680       case llvm::Triple::wasm64:
4681         TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
4682         break;
4683       case llvm::Triple::avr:
4684         TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
4685         break;
4686       case llvm::Triple::msp430:
4687         TC =
4688             llvm::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
4689         break;
4690       case llvm::Triple::riscv32:
4691       case llvm::Triple::riscv64:
4692         TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4693         break;
4694       default:
4695         if (Target.getVendor() == llvm::Triple::Myriad)
4696           TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4697                                                               Args);
4698         else if (toolchains::BareMetal::handlesTarget(Target))
4699           TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
4700         else if (Target.isOSBinFormatELF())
4701           TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4702         else if (Target.isOSBinFormatMachO())
4703           TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
4704         else
4705           TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4706       }
4707     }
4708   }
4709 
4710   // Intentionally omitted from the switch above: llvm::Triple::CUDA.  CUDA
4711   // compiles always need two toolchains, the CUDA toolchain and the host
4712   // toolchain.  So the only valid way to create a CUDA toolchain is via
4713   // CreateOffloadingDeviceToolChains.
4714 
4715   return *TC;
4716 }
4717 
4718 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
4719   // Say "no" if there is not exactly one input of a type clang understands.
4720   if (JA.size() != 1 ||
4721       !types::isAcceptedByClang((*JA.input_begin())->getType()))
4722     return false;
4723 
4724   // And say "no" if this is not a kind of action clang understands.
4725   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
4726       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4727     return false;
4728 
4729   return true;
4730 }
4731 
4732 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4733 /// grouped values as integers. Numbers which are not provided are set to 0.
4734 ///
4735 /// \return True if the entire string was parsed (9.2), or all groups were
4736 /// parsed (10.3.5extrastuff).
4737 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4738                                unsigned &Micro, bool &HadExtra) {
4739   HadExtra = false;
4740 
4741   Major = Minor = Micro = 0;
4742   if (Str.empty())
4743     return false;
4744 
4745   if (Str.consumeInteger(10, Major))
4746     return false;
4747   if (Str.empty())
4748     return true;
4749   if (Str[0] != '.')
4750     return false;
4751 
4752   Str = Str.drop_front(1);
4753 
4754   if (Str.consumeInteger(10, Minor))
4755     return false;
4756   if (Str.empty())
4757     return true;
4758   if (Str[0] != '.')
4759     return false;
4760   Str = Str.drop_front(1);
4761 
4762   if (Str.consumeInteger(10, Micro))
4763     return false;
4764   if (!Str.empty())
4765     HadExtra = true;
4766   return true;
4767 }
4768 
4769 /// Parse digits from a string \p Str and fulfill \p Digits with
4770 /// the parsed numbers. This method assumes that the max number of
4771 /// digits to look for is equal to Digits.size().
4772 ///
4773 /// \return True if the entire string was parsed and there are
4774 /// no extra characters remaining at the end.
4775 bool Driver::GetReleaseVersion(StringRef Str,
4776                                MutableArrayRef<unsigned> Digits) {
4777   if (Str.empty())
4778     return false;
4779 
4780   unsigned CurDigit = 0;
4781   while (CurDigit < Digits.size()) {
4782     unsigned Digit;
4783     if (Str.consumeInteger(10, Digit))
4784       return false;
4785     Digits[CurDigit] = Digit;
4786     if (Str.empty())
4787       return true;
4788     if (Str[0] != '.')
4789       return false;
4790     Str = Str.drop_front(1);
4791     CurDigit++;
4792   }
4793 
4794   // More digits than requested, bail out...
4795   return false;
4796 }
4797 
4798 std::pair<unsigned, unsigned>
4799 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
4800   unsigned IncludedFlagsBitmask = 0;
4801   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
4802 
4803   if (IsClCompatMode) {
4804     // Include CL and Core options.
4805     IncludedFlagsBitmask |= options::CLOption;
4806     IncludedFlagsBitmask |= options::CoreOption;
4807   } else {
4808     ExcludedFlagsBitmask |= options::CLOption;
4809   }
4810 
4811   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4812 }
4813 
4814 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
4815   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4816 }
4817