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