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