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