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