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