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