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