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