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