• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Basic/VirtualFileSystem.h"
15 #include "clang/Config/config.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Job.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "clang/Driver/Tool.h"
23 #include "clang/Driver/ToolChain.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/Option/Arg.h"
31 #include "llvm/Option/ArgList.h"
32 #include "llvm/Option/OptSpecifier.h"
33 #include "llvm/Option/OptTable.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/Program.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <map>
44 #include <memory>
45 #include <utility>
46 
47 using namespace clang::driver;
48 using namespace clang;
49 using namespace llvm::opt;
50 
Driver(StringRef ClangExecutable,StringRef DefaultTargetTriple,DiagnosticsEngine & Diags,IntrusiveRefCntPtr<vfs::FileSystem> VFS)51 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
52                DiagnosticsEngine &Diags,
53                IntrusiveRefCntPtr<vfs::FileSystem> VFS)
54     : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
55       Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
56       LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
57       SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
58       DefaultTargetTriple(DefaultTargetTriple),
59       DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
60       CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
61       CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
62       CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
63       CCCUsePCH(true), SuppressMissingInputWarning(false) {
64 
65   // Provide a sane fallback if no VFS is specified.
66   if (!this->VFS)
67     this->VFS = vfs::getRealFileSystem();
68 
69   Name = llvm::sys::path::filename(ClangExecutable);
70   Dir = llvm::sys::path::parent_path(ClangExecutable);
71   InstalledDir = Dir; // Provide a sensible default installed dir.
72 
73   // Compute the path to the resource directory.
74   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
75   SmallString<128> P(Dir);
76   if (ClangResourceDir != "") {
77     llvm::sys::path::append(P, ClangResourceDir);
78   } else {
79     StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
80     llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
81                             CLANG_VERSION_STRING);
82   }
83   ResourceDir = P.str();
84 }
85 
~Driver()86 Driver::~Driver() {
87   delete Opts;
88 
89   llvm::DeleteContainerSeconds(ToolChains);
90 }
91 
ParseDriverMode(ArrayRef<const char * > Args)92 void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
93   const std::string OptName =
94       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
95 
96   for (const char *ArgPtr : Args) {
97     // Ingore nullptrs, they are response file's EOL markers
98     if (ArgPtr == nullptr)
99       continue;
100     const StringRef Arg = ArgPtr;
101     if (!Arg.startswith(OptName))
102       continue;
103 
104     const StringRef Value = Arg.drop_front(OptName.size());
105     const unsigned M = llvm::StringSwitch<unsigned>(Value)
106                            .Case("gcc", GCCMode)
107                            .Case("g++", GXXMode)
108                            .Case("cpp", CPPMode)
109                            .Case("cl", CLMode)
110                            .Default(~0U);
111 
112     if (M != ~0U)
113       Mode = static_cast<DriverMode>(M);
114     else
115       Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
116   }
117 }
118 
ParseArgStrings(ArrayRef<const char * > ArgStrings)119 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
120   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
121 
122   unsigned IncludedFlagsBitmask;
123   unsigned ExcludedFlagsBitmask;
124   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
125       getIncludeExcludeOptionFlagMasks();
126 
127   unsigned MissingArgIndex, MissingArgCount;
128   InputArgList Args =
129       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
130                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
131 
132   // Check for missing argument error.
133   if (MissingArgCount)
134     Diag(clang::diag::err_drv_missing_argument)
135         << Args.getArgString(MissingArgIndex) << MissingArgCount;
136 
137   // Check for unsupported options.
138   for (const Arg *A : Args) {
139     if (A->getOption().hasFlag(options::Unsupported)) {
140       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
141       continue;
142     }
143 
144     // Warn about -mcpu= without an argument.
145     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
146       Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
147     }
148   }
149 
150   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
151     Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
152                               diag::err_drv_unknown_argument)
153       << A->getAsString(Args);
154 
155   return Args;
156 }
157 
158 // Determine which compilation mode we are in. We look for options which
159 // affect the phase, starting with the earliest phases, and record which
160 // option we used to determine the final phase.
getFinalPhase(const DerivedArgList & DAL,Arg ** FinalPhaseArg) const161 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
162                                  Arg **FinalPhaseArg) const {
163   Arg *PhaseArg = nullptr;
164   phases::ID FinalPhase;
165 
166   // -{E,EP,P,M,MM} only run the preprocessor.
167   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
168       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
169       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
170       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
171     FinalPhase = phases::Preprocess;
172 
173     // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
174   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
175              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
176              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
177              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
178              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
179              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
180              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
181                                         options::OPT__analyze_auto)) ||
182              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
183     FinalPhase = phases::Compile;
184 
185     // -S only runs up to the backend.
186   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
187     FinalPhase = phases::Backend;
188 
189     // -c compilation only runs up to the assembler.
190   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
191     FinalPhase = phases::Assemble;
192 
193     // Otherwise do everything.
194   } else
195     FinalPhase = phases::Link;
196 
197   if (FinalPhaseArg)
198     *FinalPhaseArg = PhaseArg;
199 
200   return FinalPhase;
201 }
202 
MakeInputArg(DerivedArgList & Args,OptTable * Opts,StringRef Value)203 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
204                          StringRef Value) {
205   Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
206                    Args.getBaseArgs().MakeIndex(Value), Value.data());
207   Args.AddSynthesizedArg(A);
208   A->claim();
209   return A;
210 }
211 
TranslateInputArgs(const InputArgList & Args) const212 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
213   DerivedArgList *DAL = new DerivedArgList(Args);
214 
215   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
216   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
217   for (Arg *A : Args) {
218     // Unfortunately, we have to parse some forwarding options (-Xassembler,
219     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
220     // (assembler and preprocessor), or bypass a previous driver ('collect2').
221 
222     // Rewrite linker options, to replace --no-demangle with a custom internal
223     // option.
224     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
225          A->getOption().matches(options::OPT_Xlinker)) &&
226         A->containsValue("--no-demangle")) {
227       // Add the rewritten no-demangle argument.
228       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
229 
230       // Add the remaining values as Xlinker arguments.
231       for (StringRef Val : A->getValues())
232         if (Val != "--no-demangle")
233           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
234 
235       continue;
236     }
237 
238     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
239     // some build systems. We don't try to be complete here because we don't
240     // care to encourage this usage model.
241     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
242         (A->getValue(0) == StringRef("-MD") ||
243          A->getValue(0) == StringRef("-MMD"))) {
244       // Rewrite to -MD/-MMD along with -MF.
245       if (A->getValue(0) == StringRef("-MD"))
246         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
247       else
248         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
249       if (A->getNumValues() == 2)
250         DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
251                             A->getValue(1));
252       continue;
253     }
254 
255     // Rewrite reserved library names.
256     if (A->getOption().matches(options::OPT_l)) {
257       StringRef Value = A->getValue();
258 
259       // Rewrite unless -nostdlib is present.
260       if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
261         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
262         continue;
263       }
264 
265       // Rewrite unconditionally.
266       if (Value == "cc_kext") {
267         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
268         continue;
269       }
270     }
271 
272     // Pick up inputs via the -- option.
273     if (A->getOption().matches(options::OPT__DASH_DASH)) {
274       A->claim();
275       for (StringRef Val : A->getValues())
276         DAL->append(MakeInputArg(*DAL, Opts, Val));
277       continue;
278     }
279 
280     DAL->append(A);
281   }
282 
283   // Enforce -static if -miamcu is present.
284   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
285     DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
286 
287 // Add a default value of -mlinker-version=, if one was given and the user
288 // didn't specify one.
289 #if defined(HOST_LINK_VERSION)
290   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
291       strlen(HOST_LINK_VERSION) > 0) {
292     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
293                       HOST_LINK_VERSION);
294     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
295   }
296 #endif
297 
298   return DAL;
299 }
300 
301 /// \brief Compute target triple from args.
302 ///
303 /// This routine provides the logic to compute a target triple from various
304 /// args passed to the driver and the default triple string.
computeTargetTriple(const Driver & D,StringRef DefaultTargetTriple,const ArgList & Args,StringRef DarwinArchName="")305 static llvm::Triple computeTargetTriple(const Driver &D,
306                                         StringRef DefaultTargetTriple,
307                                         const ArgList &Args,
308                                         StringRef DarwinArchName = "") {
309   // FIXME: Already done in Compilation *Driver::BuildCompilation
310   if (const Arg *A = Args.getLastArg(options::OPT_target))
311     DefaultTargetTriple = A->getValue();
312 
313   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
314 
315   // Handle Apple-specific options available here.
316   if (Target.isOSBinFormatMachO()) {
317     // If an explict Darwin arch name is given, that trumps all.
318     if (!DarwinArchName.empty()) {
319       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
320       return Target;
321     }
322 
323     // Handle the Darwin '-arch' flag.
324     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
325       StringRef ArchName = A->getValue();
326       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
327     }
328   }
329 
330   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
331   // '-mbig-endian'/'-EB'.
332   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
333                                options::OPT_mbig_endian)) {
334     if (A->getOption().matches(options::OPT_mlittle_endian)) {
335       llvm::Triple LE = Target.getLittleEndianArchVariant();
336       if (LE.getArch() != llvm::Triple::UnknownArch)
337         Target = std::move(LE);
338     } else {
339       llvm::Triple BE = Target.getBigEndianArchVariant();
340       if (BE.getArch() != llvm::Triple::UnknownArch)
341         Target = std::move(BE);
342     }
343   }
344 
345   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
346   if (Target.getArch() == llvm::Triple::tce ||
347       Target.getOS() == llvm::Triple::Minix)
348     return Target;
349 
350   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
351   Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
352                            options::OPT_m32, options::OPT_m16);
353   if (A) {
354     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
355 
356     if (A->getOption().matches(options::OPT_m64)) {
357       AT = Target.get64BitArchVariant().getArch();
358       if (Target.getEnvironment() == llvm::Triple::GNUX32)
359         Target.setEnvironment(llvm::Triple::GNU);
360     } else if (A->getOption().matches(options::OPT_mx32) &&
361                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
362       AT = llvm::Triple::x86_64;
363       Target.setEnvironment(llvm::Triple::GNUX32);
364     } else if (A->getOption().matches(options::OPT_m32)) {
365       AT = Target.get32BitArchVariant().getArch();
366       if (Target.getEnvironment() == llvm::Triple::GNUX32)
367         Target.setEnvironment(llvm::Triple::GNU);
368     } else if (A->getOption().matches(options::OPT_m16) &&
369                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
370       AT = llvm::Triple::x86;
371       Target.setEnvironment(llvm::Triple::CODE16);
372     }
373 
374     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
375       Target.setArch(AT);
376   }
377 
378   // Handle -miamcu flag.
379   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
380     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
381       D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
382                                                        << Target.str();
383 
384     if (A && !A->getOption().matches(options::OPT_m32))
385       D.Diag(diag::err_drv_argument_not_allowed_with)
386           << "-miamcu" << A->getBaseArg().getAsString(Args);
387 
388     Target.setArch(llvm::Triple::x86);
389     Target.setArchName("i586");
390     Target.setEnvironment(llvm::Triple::UnknownEnvironment);
391     Target.setEnvironmentName("");
392     Target.setOS(llvm::Triple::ELFIAMCU);
393     Target.setVendor(llvm::Triple::UnknownVendor);
394     Target.setVendorName("intel");
395   }
396 
397   return Target;
398 }
399 
400 // \brief Parse the LTO options and record the type of LTO compilation
401 // based on which -f(no-)?lto(=.*)? option occurs last.
setLTOMode(const llvm::opt::ArgList & Args)402 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
403   LTOMode = LTOK_None;
404   if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
405                     options::OPT_fno_lto, false))
406     return;
407 
408   StringRef LTOName("full");
409 
410   const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
411   if (A)
412     LTOName = A->getValue();
413 
414   LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
415                 .Case("full", LTOK_Full)
416                 .Case("thin", LTOK_Thin)
417                 .Default(LTOK_Unknown);
418 
419   if (LTOMode == LTOK_Unknown) {
420     assert(A);
421     Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
422                                                     << A->getValue();
423   }
424 }
425 
CreateOffloadingDeviceToolChains(Compilation & C,InputList & Inputs)426 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
427                                               InputList &Inputs) {
428 
429   //
430   // CUDA
431   //
432   // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
433   if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
434         return types::isCuda(I.first);
435       })) {
436     const ToolChain &TC = getToolChain(
437         C.getInputArgs(),
438         llvm::Triple(C.getOffloadingHostToolChain()->getTriple().isArch64Bit()
439                          ? "nvptx64-nvidia-cuda"
440                          : "nvptx-nvidia-cuda"));
441     C.addOffloadDeviceToolChain(&TC, Action::OFK_Cuda);
442   }
443 
444   //
445   // TODO: Add support for other offloading programming models here.
446   //
447 
448   return;
449 }
450 
BuildCompilation(ArrayRef<const char * > ArgList)451 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
452   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
453 
454   // FIXME: Handle environment options which affect driver behavior, somewhere
455   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
456 
457   if (char *env = ::getenv("COMPILER_PATH")) {
458     StringRef CompilerPath = env;
459     while (!CompilerPath.empty()) {
460       std::pair<StringRef, StringRef> Split =
461           CompilerPath.split(llvm::sys::EnvPathSeparator);
462       PrefixDirs.push_back(Split.first);
463       CompilerPath = Split.second;
464     }
465   }
466 
467   // We look for the driver mode option early, because the mode can affect
468   // how other options are parsed.
469   ParseDriverMode(ArgList.slice(1));
470 
471   // FIXME: What are we going to do with -V and -b?
472 
473   // FIXME: This stuff needs to go into the Compilation, not the driver.
474   bool CCCPrintPhases;
475 
476   InputArgList Args = ParseArgStrings(ArgList.slice(1));
477 
478   // Silence driver warnings if requested
479   Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
480 
481   // -no-canonical-prefixes is used very early in main.
482   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
483 
484   // Ignore -pipe.
485   Args.ClaimAllArgs(options::OPT_pipe);
486 
487   // Extract -ccc args.
488   //
489   // FIXME: We need to figure out where this behavior should live. Most of it
490   // should be outside in the client; the parts that aren't should have proper
491   // options, either by introducing new ones or by overloading gcc ones like -V
492   // or -b.
493   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
494   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
495   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
496     CCCGenericGCCName = A->getValue();
497   CCCUsePCH =
498       Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
499   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
500   // and getToolChain is const.
501   if (IsCLMode()) {
502     // clang-cl targets MSVC-style Win32.
503     llvm::Triple T(DefaultTargetTriple);
504     T.setOS(llvm::Triple::Win32);
505     T.setVendor(llvm::Triple::PC);
506     T.setEnvironment(llvm::Triple::MSVC);
507     DefaultTargetTriple = T.str();
508   }
509   if (const Arg *A = Args.getLastArg(options::OPT_target))
510     DefaultTargetTriple = A->getValue();
511   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
512     Dir = InstalledDir = A->getValue();
513   for (const Arg *A : Args.filtered(options::OPT_B)) {
514     A->claim();
515     PrefixDirs.push_back(A->getValue(0));
516   }
517   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
518     SysRoot = A->getValue();
519   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
520     DyldPrefix = A->getValue();
521   if (Args.hasArg(options::OPT_nostdlib))
522     UseStdLib = false;
523 
524   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
525     ResourceDir = A->getValue();
526 
527   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
528     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
529                     .Case("cwd", SaveTempsCwd)
530                     .Case("obj", SaveTempsObj)
531                     .Default(SaveTempsCwd);
532   }
533 
534   setLTOMode(Args);
535 
536   // Ignore -fembed-bitcode options with LTO
537   // since the output will be bitcode anyway.
538   if (getLTOMode() == LTOK_None) {
539     if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
540       StringRef Name = A->getValue();
541       unsigned Model = llvm::StringSwitch<unsigned>(Name)
542           .Case("off", EmbedNone)
543           .Case("all", EmbedBitcode)
544           .Case("bitcode", EmbedBitcode)
545           .Case("marker", EmbedMarker)
546           .Default(~0U);
547       if (Model == ~0U) {
548         Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
549                                                   << Name;
550       } else
551         BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
552     }
553   } else {
554     // claim the bitcode option under LTO so no warning is issued.
555     Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ);
556   }
557 
558   std::unique_ptr<llvm::opt::InputArgList> UArgs =
559       llvm::make_unique<InputArgList>(std::move(Args));
560 
561   // Perform the default argument translations.
562   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
563 
564   // Owned by the host.
565   const ToolChain &TC = getToolChain(
566       *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
567 
568   // The compilation takes ownership of Args.
569   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
570 
571   if (!HandleImmediateArgs(*C))
572     return C;
573 
574   // Construct the list of inputs.
575   InputList Inputs;
576   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
577 
578   // Populate the tool chains for the offloading devices, if any.
579   CreateOffloadingDeviceToolChains(*C, Inputs);
580 
581   // Construct the list of abstract actions to perform for this compilation. On
582   // MachO targets this uses the driver-driver and universal actions.
583   if (TC.getTriple().isOSBinFormatMachO())
584     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
585   else
586     BuildActions(*C, C->getArgs(), Inputs, C->getActions());
587 
588   if (CCCPrintPhases) {
589     PrintActions(*C);
590     return C;
591   }
592 
593   BuildJobs(*C);
594 
595   return C;
596 }
597 
printArgList(raw_ostream & OS,const llvm::opt::ArgList & Args)598 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
599   llvm::opt::ArgStringList ASL;
600   for (const auto *A : Args)
601     A->render(Args, ASL);
602 
603   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
604     if (I != ASL.begin())
605       OS << ' ';
606     Command::printArg(OS, *I, true);
607   }
608   OS << '\n';
609 }
610 
611 // When clang crashes, produce diagnostic information including the fully
612 // preprocessed source file(s).  Request that the developer attach the
613 // diagnostic information to a bug report.
generateCompilationDiagnostics(Compilation & C,const Command & FailingCommand)614 void Driver::generateCompilationDiagnostics(Compilation &C,
615                                             const Command &FailingCommand) {
616   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
617     return;
618 
619   // Don't try to generate diagnostics for link or dsymutil jobs.
620   if (FailingCommand.getCreator().isLinkJob() ||
621       FailingCommand.getCreator().isDsymutilJob())
622     return;
623 
624   // Print the version of the compiler.
625   PrintVersion(C, llvm::errs());
626 
627   Diag(clang::diag::note_drv_command_failed_diag_msg)
628       << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
629          "crash backtrace, preprocessed source, and associated run script.";
630 
631   // Suppress driver output and emit preprocessor output to temp file.
632   Mode = CPPMode;
633   CCGenDiagnostics = true;
634 
635   // Save the original job command(s).
636   Command Cmd = FailingCommand;
637 
638   // Keep track of whether we produce any errors while trying to produce
639   // preprocessed sources.
640   DiagnosticErrorTrap Trap(Diags);
641 
642   // Suppress tool output.
643   C.initCompilationForDiagnostics();
644 
645   // Construct the list of inputs.
646   InputList Inputs;
647   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
648 
649   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
650     bool IgnoreInput = false;
651 
652     // Ignore input from stdin or any inputs that cannot be preprocessed.
653     // Check type first as not all linker inputs have a value.
654     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
655       IgnoreInput = true;
656     } else if (!strcmp(it->second->getValue(), "-")) {
657       Diag(clang::diag::note_drv_command_failed_diag_msg)
658           << "Error generating preprocessed source(s) - "
659              "ignoring input from stdin.";
660       IgnoreInput = true;
661     }
662 
663     if (IgnoreInput) {
664       it = Inputs.erase(it);
665       ie = Inputs.end();
666     } else {
667       ++it;
668     }
669   }
670 
671   if (Inputs.empty()) {
672     Diag(clang::diag::note_drv_command_failed_diag_msg)
673         << "Error generating preprocessed source(s) - "
674            "no preprocessable inputs.";
675     return;
676   }
677 
678   // Don't attempt to generate preprocessed files if multiple -arch options are
679   // used, unless they're all duplicates.
680   llvm::StringSet<> ArchNames;
681   for (const Arg *A : C.getArgs()) {
682     if (A->getOption().matches(options::OPT_arch)) {
683       StringRef ArchName = A->getValue();
684       ArchNames.insert(ArchName);
685     }
686   }
687   if (ArchNames.size() > 1) {
688     Diag(clang::diag::note_drv_command_failed_diag_msg)
689         << "Error generating preprocessed source(s) - cannot generate "
690            "preprocessed source with multiple -arch options.";
691     return;
692   }
693 
694   // Construct the list of abstract actions to perform for this compilation. On
695   // Darwin OSes this uses the driver-driver and builds universal actions.
696   const ToolChain &TC = C.getDefaultToolChain();
697   if (TC.getTriple().isOSBinFormatMachO())
698     BuildUniversalActions(C, TC, Inputs);
699   else
700     BuildActions(C, C.getArgs(), Inputs, C.getActions());
701 
702   BuildJobs(C);
703 
704   // If there were errors building the compilation, quit now.
705   if (Trap.hasErrorOccurred()) {
706     Diag(clang::diag::note_drv_command_failed_diag_msg)
707         << "Error generating preprocessed source(s).";
708     return;
709   }
710 
711   // Generate preprocessed output.
712   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
713   C.ExecuteJobs(C.getJobs(), FailingCommands);
714 
715   // If any of the preprocessing commands failed, clean up and exit.
716   if (!FailingCommands.empty()) {
717     if (!isSaveTempsEnabled())
718       C.CleanupFileList(C.getTempFiles(), true);
719 
720     Diag(clang::diag::note_drv_command_failed_diag_msg)
721         << "Error generating preprocessed source(s).";
722     return;
723   }
724 
725   const ArgStringList &TempFiles = C.getTempFiles();
726   if (TempFiles.empty()) {
727     Diag(clang::diag::note_drv_command_failed_diag_msg)
728         << "Error generating preprocessed source(s).";
729     return;
730   }
731 
732   Diag(clang::diag::note_drv_command_failed_diag_msg)
733       << "\n********************\n\n"
734          "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
735          "Preprocessed source(s) and associated run script(s) are located at:";
736 
737   SmallString<128> VFS;
738   for (const char *TempFile : TempFiles) {
739     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
740     if (StringRef(TempFile).endswith(".cache")) {
741       // In some cases (modules) we'll dump extra data to help with reproducing
742       // the crash into a directory next to the output.
743       VFS = llvm::sys::path::filename(TempFile);
744       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
745     }
746   }
747 
748   // Assume associated files are based off of the first temporary file.
749   CrashReportInfo CrashInfo(TempFiles[0], VFS);
750 
751   std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
752   std::error_code EC;
753   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
754   if (EC) {
755     Diag(clang::diag::note_drv_command_failed_diag_msg)
756         << "Error generating run script: " + Script + " " + EC.message();
757   } else {
758     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
759              << "# Driver args: ";
760     printArgList(ScriptOS, C.getInputArgs());
761     ScriptOS << "# Original command: ";
762     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
763     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
764     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
765   }
766 
767   for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
768                                             options::OPT_frewrite_map_file_EQ))
769     Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
770 
771   Diag(clang::diag::note_drv_command_failed_diag_msg)
772       << "\n\n********************";
773 }
774 
setUpResponseFiles(Compilation & C,Command & Cmd)775 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
776   // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
777   // if the tool does not support response files, there is a chance/ that things
778   // will just work without a response file, so we silently just skip it.
779   if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
780       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
781     return;
782 
783   std::string TmpName = GetTemporaryPath("response", "txt");
784   Cmd.setResponseFile(
785       C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
786 }
787 
ExecuteCompilation(Compilation & C,SmallVectorImpl<std::pair<int,const Command * >> & FailingCommands)788 int Driver::ExecuteCompilation(
789     Compilation &C,
790     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
791   // Just print if -### was present.
792   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
793     C.getJobs().Print(llvm::errs(), "\n", true);
794     return 0;
795   }
796 
797   // If there were errors building the compilation, quit now.
798   if (Diags.hasErrorOccurred())
799     return 1;
800 
801   // Set up response file names for each command, if necessary
802   for (auto &Job : C.getJobs())
803     setUpResponseFiles(C, Job);
804 
805   C.ExecuteJobs(C.getJobs(), FailingCommands);
806 
807   // Remove temp files.
808   C.CleanupFileList(C.getTempFiles());
809 
810   // If the command succeeded, we are done.
811   if (FailingCommands.empty())
812     return 0;
813 
814   // Otherwise, remove result files and print extra information about abnormal
815   // failures.
816   for (const auto &CmdPair : FailingCommands) {
817     int Res = CmdPair.first;
818     const Command *FailingCommand = CmdPair.second;
819 
820     // Remove result files if we're not saving temps.
821     if (!isSaveTempsEnabled()) {
822       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
823       C.CleanupFileMap(C.getResultFiles(), JA, true);
824 
825       // Failure result files are valid unless we crashed.
826       if (Res < 0)
827         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
828     }
829 
830     // Print extra information about abnormal failures, if possible.
831     //
832     // This is ad-hoc, but we don't want to be excessively noisy. If the result
833     // status was 1, assume the command failed normally. In particular, if it
834     // was the compiler then assume it gave a reasonable error code. Failures
835     // in other tools are less common, and they generally have worse
836     // diagnostics, so always print the diagnostic there.
837     const Tool &FailingTool = FailingCommand->getCreator();
838 
839     if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
840       // FIXME: See FIXME above regarding result code interpretation.
841       if (Res < 0)
842         Diag(clang::diag::err_drv_command_signalled)
843             << FailingTool.getShortName();
844       else
845         Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
846                                                   << Res;
847     }
848   }
849   return 0;
850 }
851 
PrintHelp(bool ShowHidden) const852 void Driver::PrintHelp(bool ShowHidden) const {
853   unsigned IncludedFlagsBitmask;
854   unsigned ExcludedFlagsBitmask;
855   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
856       getIncludeExcludeOptionFlagMasks();
857 
858   ExcludedFlagsBitmask |= options::NoDriverOption;
859   if (!ShowHidden)
860     ExcludedFlagsBitmask |= HelpHidden;
861 
862   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
863                       IncludedFlagsBitmask, ExcludedFlagsBitmask);
864 }
865 
PrintVersion(const Compilation & C,raw_ostream & OS) const866 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
867   // FIXME: The following handlers should use a callback mechanism, we don't
868   // know what the client would like to do.
869   OS << getClangFullVersion() << '\n';
870   const ToolChain &TC = C.getDefaultToolChain();
871   OS << "Target: " << TC.getTripleString() << '\n';
872 
873   // Print the threading model.
874   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
875     // Don't print if the ToolChain would have barfed on it already
876     if (TC.isThreadModelSupported(A->getValue()))
877       OS << "Thread model: " << A->getValue();
878   } else
879     OS << "Thread model: " << TC.getThreadModel();
880   OS << '\n';
881 
882   // Print out the install directory.
883   OS << "InstalledDir: " << InstalledDir << '\n';
884 }
885 
886 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
887 /// option.
PrintDiagnosticCategories(raw_ostream & OS)888 static void PrintDiagnosticCategories(raw_ostream &OS) {
889   // Skip the empty category.
890   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
891        ++i)
892     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
893 }
894 
HandleImmediateArgs(const Compilation & C)895 bool Driver::HandleImmediateArgs(const Compilation &C) {
896   // The order these options are handled in gcc is all over the place, but we
897   // don't expect inconsistencies w.r.t. that to matter in practice.
898 
899   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
900     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
901     return false;
902   }
903 
904   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
905     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
906     // return an answer which matches our definition of __VERSION__.
907     //
908     // If we want to return a more correct answer some day, then we should
909     // introduce a non-pedantically GCC compatible mode to Clang in which we
910     // provide sensible definitions for -dumpversion, __VERSION__, etc.
911     llvm::outs() << "4.2.1\n";
912     return false;
913   }
914 
915   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
916     PrintDiagnosticCategories(llvm::outs());
917     return false;
918   }
919 
920   if (C.getArgs().hasArg(options::OPT_help) ||
921       C.getArgs().hasArg(options::OPT__help_hidden)) {
922     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
923     return false;
924   }
925 
926   if (C.getArgs().hasArg(options::OPT__version)) {
927     // Follow gcc behavior and use stdout for --version and stderr for -v.
928     PrintVersion(C, llvm::outs());
929     return false;
930   }
931 
932   if (C.getArgs().hasArg(options::OPT_v) ||
933       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
934     PrintVersion(C, llvm::errs());
935     SuppressMissingInputWarning = true;
936   }
937 
938   const ToolChain &TC = C.getDefaultToolChain();
939 
940   if (C.getArgs().hasArg(options::OPT_v))
941     TC.printVerboseInfo(llvm::errs());
942 
943   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
944     llvm::outs() << "programs: =";
945     bool separator = false;
946     for (const std::string &Path : TC.getProgramPaths()) {
947       if (separator)
948         llvm::outs() << ':';
949       llvm::outs() << Path;
950       separator = true;
951     }
952     llvm::outs() << "\n";
953     llvm::outs() << "libraries: =" << ResourceDir;
954 
955     StringRef sysroot = C.getSysRoot();
956 
957     for (const std::string &Path : TC.getFilePaths()) {
958       // Always print a separator. ResourceDir was the first item shown.
959       llvm::outs() << ':';
960       // Interpretation of leading '=' is needed only for NetBSD.
961       if (Path[0] == '=')
962         llvm::outs() << sysroot << Path.substr(1);
963       else
964         llvm::outs() << Path;
965     }
966     llvm::outs() << "\n";
967     return false;
968   }
969 
970   // FIXME: The following handlers should use a callback mechanism, we don't
971   // know what the client would like to do.
972   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
973     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
974     return false;
975   }
976 
977   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
978     llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
979     return false;
980   }
981 
982   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
983     llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
984     return false;
985   }
986 
987   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
988     for (const Multilib &Multilib : TC.getMultilibs())
989       llvm::outs() << Multilib << "\n";
990     return false;
991   }
992 
993   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
994     for (const Multilib &Multilib : TC.getMultilibs()) {
995       if (Multilib.gccSuffix().empty())
996         llvm::outs() << ".\n";
997       else {
998         StringRef Suffix(Multilib.gccSuffix());
999         assert(Suffix.front() == '/');
1000         llvm::outs() << Suffix.substr(1) << "\n";
1001       }
1002     }
1003     return false;
1004   }
1005   return true;
1006 }
1007 
1008 // Display an action graph human-readably.  Action A is the "sink" node
1009 // and latest-occuring action. Traversal is in pre-order, visiting the
1010 // inputs to each action before printing the action itself.
PrintActions1(const Compilation & C,Action * A,std::map<Action *,unsigned> & Ids)1011 static unsigned PrintActions1(const Compilation &C, Action *A,
1012                               std::map<Action *, unsigned> &Ids) {
1013   if (Ids.count(A)) // A was already visited.
1014     return Ids[A];
1015 
1016   std::string str;
1017   llvm::raw_string_ostream os(str);
1018 
1019   os << Action::getClassName(A->getKind()) << ", ";
1020   if (InputAction *IA = dyn_cast<InputAction>(A)) {
1021     os << "\"" << IA->getInputArg().getValue() << "\"";
1022   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1023     os << '"' << BIA->getArchName() << '"' << ", {"
1024        << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1025   } else if (CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
1026     CudaArch Arch = CDA->getGpuArch();
1027     if (Arch != CudaArch::UNKNOWN)
1028       os << "'" << CudaArchToString(Arch) << "', ";
1029     os << "{" << PrintActions1(C, *CDA->input_begin(), Ids) << "}";
1030   } else {
1031     const ActionList *AL;
1032     if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
1033       os << "{" << PrintActions1(C, *CHA->input_begin(), Ids) << "}"
1034          << ", gpu binaries ";
1035       AL = &CHA->getDeviceActions();
1036     } else
1037       AL = &A->getInputs();
1038 
1039     if (AL->size()) {
1040       const char *Prefix = "{";
1041       for (Action *PreRequisite : *AL) {
1042         os << Prefix << PrintActions1(C, PreRequisite, Ids);
1043         Prefix = ", ";
1044       }
1045       os << "}";
1046     } else
1047       os << "{}";
1048   }
1049 
1050   unsigned Id = Ids.size();
1051   Ids[A] = Id;
1052   llvm::errs() << Id << ": " << os.str() << ", "
1053                << types::getTypeName(A->getType()) << "\n";
1054 
1055   return Id;
1056 }
1057 
1058 // Print the action graphs in a compilation C.
1059 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
PrintActions(const Compilation & C) const1060 void Driver::PrintActions(const Compilation &C) const {
1061   std::map<Action *, unsigned> Ids;
1062   for (Action *A : C.getActions())
1063     PrintActions1(C, A, Ids);
1064 }
1065 
1066 /// \brief Check whether the given input tree contains any compilation or
1067 /// assembly actions.
ContainsCompileOrAssembleAction(const Action * A)1068 static bool ContainsCompileOrAssembleAction(const Action *A) {
1069   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1070       isa<AssembleJobAction>(A))
1071     return true;
1072 
1073   for (const Action *Input : A->inputs())
1074     if (ContainsCompileOrAssembleAction(Input))
1075       return true;
1076 
1077   return false;
1078 }
1079 
BuildUniversalActions(Compilation & C,const ToolChain & TC,const InputList & BAInputs) const1080 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1081                                    const InputList &BAInputs) const {
1082   DerivedArgList &Args = C.getArgs();
1083   ActionList &Actions = C.getActions();
1084   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1085   // Collect the list of architectures. Duplicates are allowed, but should only
1086   // be handled once (in the order seen).
1087   llvm::StringSet<> ArchNames;
1088   SmallVector<const char *, 4> Archs;
1089   for (Arg *A : Args) {
1090     if (A->getOption().matches(options::OPT_arch)) {
1091       // Validate the option here; we don't save the type here because its
1092       // particular spelling may participate in other driver choices.
1093       llvm::Triple::ArchType Arch =
1094           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1095       if (Arch == llvm::Triple::UnknownArch) {
1096         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1097         continue;
1098       }
1099 
1100       A->claim();
1101       if (ArchNames.insert(A->getValue()).second)
1102         Archs.push_back(A->getValue());
1103     }
1104   }
1105 
1106   // When there is no explicit arch for this platform, make sure we still bind
1107   // the architecture (to the default) so that -Xarch_ is handled correctly.
1108   if (!Archs.size())
1109     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1110 
1111   ActionList SingleActions;
1112   BuildActions(C, Args, BAInputs, SingleActions);
1113 
1114   // Add in arch bindings for every top level action, as well as lipo and
1115   // dsymutil steps if needed.
1116   for (Action* Act : SingleActions) {
1117     // Make sure we can lipo this kind of output. If not (and it is an actual
1118     // output) then we disallow, since we can't create an output file with the
1119     // right name without overwriting it. We could remove this oddity by just
1120     // changing the output names to include the arch, which would also fix
1121     // -save-temps. Compatibility wins for now.
1122 
1123     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1124       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1125           << types::getTypeName(Act->getType());
1126 
1127     ActionList Inputs;
1128     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1129       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1130 
1131     // Lipo if necessary, we do it this way because we need to set the arch flag
1132     // so that -Xarch_ gets overwritten.
1133     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1134       Actions.append(Inputs.begin(), Inputs.end());
1135     else
1136       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1137 
1138     // Handle debug info queries.
1139     Arg *A = Args.getLastArg(options::OPT_g_Group);
1140     if (A && !A->getOption().matches(options::OPT_g0) &&
1141         !A->getOption().matches(options::OPT_gstabs) &&
1142         ContainsCompileOrAssembleAction(Actions.back())) {
1143 
1144       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1145       // have a compile input. We need to run 'dsymutil' ourselves in such cases
1146       // because the debug info will refer to a temporary object file which
1147       // will be removed at the end of the compilation process.
1148       if (Act->getType() == types::TY_Image) {
1149         ActionList Inputs;
1150         Inputs.push_back(Actions.back());
1151         Actions.pop_back();
1152         Actions.push_back(
1153             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1154       }
1155 
1156       // Verify the debug info output.
1157       if (Args.hasArg(options::OPT_verify_debug_info)) {
1158         Action* LastAction = Actions.back();
1159         Actions.pop_back();
1160         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1161             LastAction, types::TY_Nothing));
1162       }
1163     }
1164   }
1165 }
1166 
1167 /// \brief Check that the file referenced by Value exists. If it doesn't,
1168 /// issue a diagnostic and return false.
DiagnoseInputExistence(const Driver & D,const DerivedArgList & Args,StringRef Value,types::ID Ty)1169 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1170                                    StringRef Value, types::ID Ty) {
1171   if (!D.getCheckInputsExist())
1172     return true;
1173 
1174   // stdin always exists.
1175   if (Value == "-")
1176     return true;
1177 
1178   SmallString<64> Path(Value);
1179   if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1180     if (!llvm::sys::path::is_absolute(Path)) {
1181       SmallString<64> Directory(WorkDir->getValue());
1182       llvm::sys::path::append(Directory, Value);
1183       Path.assign(Directory);
1184     }
1185   }
1186 
1187   if (llvm::sys::fs::exists(Twine(Path)))
1188     return true;
1189 
1190   if (D.IsCLMode()) {
1191     if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1192         llvm::sys::Process::FindInEnvPath("LIB", Value))
1193       return true;
1194 
1195     if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1196       // Arguments to the /link flag might cause the linker to search for object
1197       // and library files in paths we don't know about. Don't error in such
1198       // cases.
1199       return true;
1200     }
1201   }
1202 
1203   D.Diag(clang::diag::err_drv_no_such_file) << Path;
1204   return false;
1205 }
1206 
1207 // Construct a the list of inputs and their types.
BuildInputs(const ToolChain & TC,DerivedArgList & Args,InputList & Inputs) const1208 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1209                          InputList &Inputs) const {
1210   // Track the current user specified (-x) input. We also explicitly track the
1211   // argument used to set the type; we only want to claim the type when we
1212   // actually use it, so we warn about unused -x arguments.
1213   types::ID InputType = types::TY_Nothing;
1214   Arg *InputTypeArg = nullptr;
1215 
1216   // The last /TC or /TP option sets the input type to C or C++ globally.
1217   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1218                                          options::OPT__SLASH_TP)) {
1219     InputTypeArg = TCTP;
1220     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1221                     ? types::TY_C
1222                     : types::TY_CXX;
1223 
1224     arg_iterator it =
1225         Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
1226     const arg_iterator ie = Args.filtered_end();
1227     Arg *Previous = *it++;
1228     bool ShowNote = false;
1229     while (it != ie) {
1230       Diag(clang::diag::warn_drv_overriding_flag_option)
1231           << Previous->getSpelling() << (*it)->getSpelling();
1232       Previous = *it++;
1233       ShowNote = true;
1234     }
1235     if (ShowNote)
1236       Diag(clang::diag::note_drv_t_option_is_global);
1237 
1238     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1239     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1240   }
1241 
1242   for (Arg *A : Args) {
1243     if (A->getOption().getKind() == Option::InputClass) {
1244       const char *Value = A->getValue();
1245       types::ID Ty = types::TY_INVALID;
1246 
1247       // Infer the input type if necessary.
1248       if (InputType == types::TY_Nothing) {
1249         // If there was an explicit arg for this, claim it.
1250         if (InputTypeArg)
1251           InputTypeArg->claim();
1252 
1253         // stdin must be handled specially.
1254         if (memcmp(Value, "-", 2) == 0) {
1255           // If running with -E, treat as a C input (this changes the builtin
1256           // macros, for example). This may be overridden by -ObjC below.
1257           //
1258           // Otherwise emit an error but still use a valid type to avoid
1259           // spurious errors (e.g., no inputs).
1260           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1261             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1262                             : clang::diag::err_drv_unknown_stdin_type);
1263           Ty = types::TY_C;
1264         } else {
1265           // Otherwise lookup by extension.
1266           // Fallback is C if invoked as C preprocessor or Object otherwise.
1267           // We use a host hook here because Darwin at least has its own
1268           // idea of what .s is.
1269           if (const char *Ext = strrchr(Value, '.'))
1270             Ty = TC.LookupTypeForExtension(Ext + 1);
1271 
1272           if (Ty == types::TY_INVALID) {
1273             if (CCCIsCPP())
1274               Ty = types::TY_C;
1275             else
1276               Ty = types::TY_Object;
1277           }
1278 
1279           // If the driver is invoked as C++ compiler (like clang++ or c++) it
1280           // should autodetect some input files as C++ for g++ compatibility.
1281           if (CCCIsCXX()) {
1282             types::ID OldTy = Ty;
1283             Ty = types::lookupCXXTypeForCType(Ty);
1284 
1285             if (Ty != OldTy)
1286               Diag(clang::diag::warn_drv_treating_input_as_cxx)
1287                   << getTypeName(OldTy) << getTypeName(Ty);
1288           }
1289         }
1290 
1291         // -ObjC and -ObjC++ override the default language, but only for "source
1292         // files". We just treat everything that isn't a linker input as a
1293         // source file.
1294         //
1295         // FIXME: Clean this up if we move the phase sequence into the type.
1296         if (Ty != types::TY_Object) {
1297           if (Args.hasArg(options::OPT_ObjC))
1298             Ty = types::TY_ObjC;
1299           else if (Args.hasArg(options::OPT_ObjCXX))
1300             Ty = types::TY_ObjCXX;
1301         }
1302       } else {
1303         assert(InputTypeArg && "InputType set w/o InputTypeArg");
1304         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1305           // If emulating cl.exe, make sure that /TC and /TP don't affect input
1306           // object files.
1307           const char *Ext = strrchr(Value, '.');
1308           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1309             Ty = types::TY_Object;
1310         }
1311         if (Ty == types::TY_INVALID) {
1312           Ty = InputType;
1313           InputTypeArg->claim();
1314         }
1315       }
1316 
1317       if (DiagnoseInputExistence(*this, Args, Value, Ty))
1318         Inputs.push_back(std::make_pair(Ty, A));
1319 
1320     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1321       StringRef Value = A->getValue();
1322       if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1323         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1324         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1325       }
1326       A->claim();
1327     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1328       StringRef Value = A->getValue();
1329       if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1330         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1331         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1332       }
1333       A->claim();
1334     } else if (A->getOption().hasFlag(options::LinkerInput)) {
1335       // Just treat as object type, we could make a special type for this if
1336       // necessary.
1337       Inputs.push_back(std::make_pair(types::TY_Object, A));
1338 
1339     } else if (A->getOption().matches(options::OPT_x)) {
1340       InputTypeArg = A;
1341       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1342       A->claim();
1343 
1344       // Follow gcc behavior and treat as linker input for invalid -x
1345       // options. Its not clear why we shouldn't just revert to unknown; but
1346       // this isn't very important, we might as well be bug compatible.
1347       if (!InputType) {
1348         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1349         InputType = types::TY_Object;
1350       }
1351     }
1352   }
1353   if (CCCIsCPP() && Inputs.empty()) {
1354     // If called as standalone preprocessor, stdin is processed
1355     // if no other input is present.
1356     Arg *A = MakeInputArg(Args, Opts, "-");
1357     Inputs.push_back(std::make_pair(types::TY_C, A));
1358   }
1359 }
1360 
1361 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE
1362 // input action and then wraps each in CudaDeviceAction paired with
1363 // appropriate GPU arch name. In case of partial (i.e preprocessing
1364 // only) or device-only compilation, each device action is added to /p
1365 // Actions and /p Current is released. Otherwise the function creates
1366 // and returns a new CudaHostAction which wraps /p Current and device
1367 // side actions.
buildCudaActions(Compilation & C,DerivedArgList & Args,const Arg * InputArg,Action * HostAction,ActionList & Actions)1368 static Action *buildCudaActions(Compilation &C, DerivedArgList &Args,
1369                                 const Arg *InputArg, Action *HostAction,
1370                                 ActionList &Actions) {
1371   Arg *PartialCompilationArg = Args.getLastArg(
1372       options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1373       options::OPT_cuda_compile_host_device);
1374   bool CompileHostOnly =
1375       PartialCompilationArg &&
1376       PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only);
1377   bool CompileDeviceOnly =
1378       PartialCompilationArg &&
1379       PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only);
1380 
1381   if (CompileHostOnly)
1382     return C.MakeAction<CudaHostAction>(HostAction, ActionList());
1383 
1384   // Collect all cuda_gpu_arch parameters, removing duplicates.
1385   SmallVector<CudaArch, 4> GpuArchList;
1386   llvm::SmallSet<CudaArch, 4> GpuArchs;
1387   for (Arg *A : Args) {
1388     if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1389       continue;
1390     A->claim();
1391 
1392     const auto &ArchStr = A->getValue();
1393     CudaArch Arch = StringToCudaArch(ArchStr);
1394     if (Arch == CudaArch::UNKNOWN)
1395       C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1396     else if (GpuArchs.insert(Arch).second)
1397       GpuArchList.push_back(Arch);
1398   }
1399 
1400   // Default to sm_20 which is the lowest common denominator for supported GPUs.
1401   // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1402   if (GpuArchList.empty())
1403     GpuArchList.push_back(CudaArch::SM_20);
1404 
1405   // Replicate inputs for each GPU architecture.
1406   Driver::InputList CudaDeviceInputs;
1407   for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1408     CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
1409 
1410   // Build actions for all device inputs.
1411   assert(C.getSingleOffloadToolChain<Action::OFK_Cuda>() &&
1412          "Missing toolchain for device-side compilation.");
1413   ActionList CudaDeviceActions;
1414   C.getDriver().BuildActions(C, Args, CudaDeviceInputs, CudaDeviceActions);
1415   assert(GpuArchList.size() == CudaDeviceActions.size() &&
1416          "Failed to create actions for all devices");
1417 
1418   // Check whether any of device actions stopped before they could generate PTX.
1419   bool PartialCompilation =
1420       llvm::any_of(CudaDeviceActions, [](const Action *a) {
1421         return a->getKind() != Action::AssembleJobClass;
1422       });
1423 
1424   // Figure out what to do with device actions -- pass them as inputs to the
1425   // host action or run each of them independently.
1426   if (PartialCompilation || CompileDeviceOnly) {
1427     // In case of partial or device-only compilation results of device actions
1428     // are not consumed by the host action device actions have to be added to
1429     // top-level actions list with AtTopLevel=true and run independently.
1430 
1431     // -o is ambiguous if we have more than one top-level action.
1432     if (Args.hasArg(options::OPT_o) &&
1433         (!CompileDeviceOnly || GpuArchList.size() > 1)) {
1434       C.getDriver().Diag(
1435           clang::diag::err_drv_output_argument_with_multiple_files);
1436       return nullptr;
1437     }
1438 
1439     for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1440       Actions.push_back(C.MakeAction<CudaDeviceAction>(CudaDeviceActions[I],
1441                                                        GpuArchList[I],
1442                                                        /* AtTopLevel */ true));
1443     // Kill host action in case of device-only compilation.
1444     if (CompileDeviceOnly)
1445       return nullptr;
1446     return HostAction;
1447   }
1448 
1449   // If we're not a partial or device-only compilation, we compile each arch to
1450   // ptx and assemble to cubin, then feed the cubin *and* the ptx into a device
1451   // "link" action, which uses fatbinary to combine these cubins into one
1452   // fatbin.  The fatbin is then an input to the host compilation.
1453   ActionList DeviceActions;
1454   for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1455     Action* AssembleAction = CudaDeviceActions[I];
1456     assert(AssembleAction->getType() == types::TY_Object);
1457     assert(AssembleAction->getInputs().size() == 1);
1458 
1459     Action* BackendAction = AssembleAction->getInputs()[0];
1460     assert(BackendAction->getType() == types::TY_PP_Asm);
1461 
1462     for (const auto& A : {AssembleAction, BackendAction}) {
1463       DeviceActions.push_back(C.MakeAction<CudaDeviceAction>(
1464           A, GpuArchList[I], /* AtTopLevel */ false));
1465     }
1466   }
1467   auto FatbinAction = C.MakeAction<CudaDeviceAction>(
1468       C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN),
1469       CudaArch::UNKNOWN,
1470       /* AtTopLevel = */ false);
1471   // Return a new host action that incorporates original host action and all
1472   // device actions.
1473   return C.MakeAction<CudaHostAction>(std::move(HostAction),
1474                                       ActionList({FatbinAction}));
1475 }
1476 
BuildActions(Compilation & C,DerivedArgList & Args,const InputList & Inputs,ActionList & Actions) const1477 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
1478                           const InputList &Inputs, ActionList &Actions) const {
1479   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1480 
1481   if (!SuppressMissingInputWarning && Inputs.empty()) {
1482     Diag(clang::diag::err_drv_no_input_files);
1483     return;
1484   }
1485 
1486   Arg *FinalPhaseArg;
1487   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1488 
1489   if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1490     Diag(clang::diag::err_drv_emit_llvm_link);
1491   }
1492 
1493   // Reject -Z* at the top level, these options should never have been exposed
1494   // by gcc.
1495   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1496     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1497 
1498   // Diagnose misuse of /Fo.
1499   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1500     StringRef V = A->getValue();
1501     if (Inputs.size() > 1 && !V.empty() &&
1502         !llvm::sys::path::is_separator(V.back())) {
1503       // Check whether /Fo tries to name an output file for multiple inputs.
1504       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1505           << A->getSpelling() << V;
1506       Args.eraseArg(options::OPT__SLASH_Fo);
1507     }
1508   }
1509 
1510   // Diagnose misuse of /Fa.
1511   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1512     StringRef V = A->getValue();
1513     if (Inputs.size() > 1 && !V.empty() &&
1514         !llvm::sys::path::is_separator(V.back())) {
1515       // Check whether /Fa tries to name an asm file for multiple inputs.
1516       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1517           << A->getSpelling() << V;
1518       Args.eraseArg(options::OPT__SLASH_Fa);
1519     }
1520   }
1521 
1522   // Diagnose misuse of /o.
1523   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1524     if (A->getValue()[0] == '\0') {
1525       // It has to have a value.
1526       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1527       Args.eraseArg(options::OPT__SLASH_o);
1528     }
1529   }
1530 
1531   // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
1532   // * no filename after it
1533   // * both /Yc and /Yu passed but with different filenames
1534   // * corresponding file not also passed as /FI
1535   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1536   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1537   if (YcArg && YcArg->getValue()[0] == '\0') {
1538     Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
1539     Args.eraseArg(options::OPT__SLASH_Yc);
1540     YcArg = nullptr;
1541   }
1542   if (YuArg && YuArg->getValue()[0] == '\0') {
1543     Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
1544     Args.eraseArg(options::OPT__SLASH_Yu);
1545     YuArg = nullptr;
1546   }
1547   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
1548     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
1549     Args.eraseArg(options::OPT__SLASH_Yc);
1550     Args.eraseArg(options::OPT__SLASH_Yu);
1551     YcArg = YuArg = nullptr;
1552   }
1553   if (YcArg || YuArg) {
1554     StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
1555     bool FoundMatchingInclude = false;
1556     for (const Arg *Inc : Args.filtered(options::OPT_include)) {
1557       // FIXME: Do case-insensitive matching and consider / and \ as equal.
1558       if (Inc->getValue() == Val)
1559         FoundMatchingInclude = true;
1560     }
1561     if (!FoundMatchingInclude) {
1562       Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
1563           << (YcArg ? YcArg : YuArg)->getSpelling();
1564       Args.eraseArg(options::OPT__SLASH_Yc);
1565       Args.eraseArg(options::OPT__SLASH_Yu);
1566       YcArg = YuArg = nullptr;
1567     }
1568   }
1569   if (YcArg && Inputs.size() > 1) {
1570     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
1571     Args.eraseArg(options::OPT__SLASH_Yc);
1572     YcArg = nullptr;
1573   }
1574   if (Args.hasArg(options::OPT__SLASH_Y_)) {
1575     // /Y- disables all pch handling.  Rather than check for it everywhere,
1576     // just remove clang-cl pch-related flags here.
1577     Args.eraseArg(options::OPT__SLASH_Fp);
1578     Args.eraseArg(options::OPT__SLASH_Yc);
1579     Args.eraseArg(options::OPT__SLASH_Yu);
1580     YcArg = YuArg = nullptr;
1581   }
1582 
1583   // Construct the actions to perform.
1584   ActionList LinkerInputs;
1585 
1586   llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
1587   for (auto &I : Inputs) {
1588     types::ID InputType = I.first;
1589     const Arg *InputArg = I.second;
1590 
1591     PL.clear();
1592     types::getCompilationPhases(InputType, PL);
1593 
1594     // If the first step comes after the final phase we are doing as part of
1595     // this compilation, warn the user about it.
1596     phases::ID InitialPhase = PL[0];
1597     if (InitialPhase > FinalPhase) {
1598       // Claim here to avoid the more general unused warning.
1599       InputArg->claim();
1600 
1601       // Suppress all unused style warnings with -Qunused-arguments
1602       if (Args.hasArg(options::OPT_Qunused_arguments))
1603         continue;
1604 
1605       // Special case when final phase determined by binary name, rather than
1606       // by a command-line argument with a corresponding Arg.
1607       if (CCCIsCPP())
1608         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1609             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
1610       // Special case '-E' warning on a previously preprocessed file to make
1611       // more sense.
1612       else if (InitialPhase == phases::Compile &&
1613                FinalPhase == phases::Preprocess &&
1614                getPreprocessedType(InputType) == types::TY_INVALID)
1615         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1616             << InputArg->getAsString(Args) << !!FinalPhaseArg
1617             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1618       else
1619         Diag(clang::diag::warn_drv_input_file_unused)
1620             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
1621             << !!FinalPhaseArg
1622             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1623       continue;
1624     }
1625 
1626     if (YcArg) {
1627       // Add a separate precompile phase for the compile phase.
1628       if (FinalPhase >= phases::Compile) {
1629         llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
1630         types::getCompilationPhases(types::TY_CXXHeader, PCHPL);
1631         Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue());
1632 
1633         // Build the pipeline for the pch file.
1634         Action *ClangClPch = C.MakeAction<InputAction>(*PchInputArg, InputType);
1635         for (phases::ID Phase : PCHPL)
1636           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
1637         assert(ClangClPch);
1638         Actions.push_back(ClangClPch);
1639         // The driver currently exits after the first failed command.  This
1640         // relies on that behavior, to make sure if the pch generation fails,
1641         // the main compilation won't run.
1642       }
1643     }
1644 
1645     phases::ID CudaInjectionPhase =
1646         (phases::Compile < FinalPhase &&
1647          llvm::find(PL, phases::Compile) != PL.end())
1648             ? phases::Compile
1649             : FinalPhase;
1650 
1651     // Build the pipeline for this file.
1652     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
1653     for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
1654          i != e; ++i) {
1655       phases::ID Phase = *i;
1656 
1657       // We are done if this step is past what the user requested.
1658       if (Phase > FinalPhase)
1659         break;
1660 
1661       // Queue linker inputs.
1662       if (Phase == phases::Link) {
1663         assert((i + 1) == e && "linking must be final compilation step.");
1664         LinkerInputs.push_back(Current);
1665         Current = nullptr;
1666         break;
1667       }
1668 
1669       // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1670       // encode this in the steps because the intermediate type depends on
1671       // arguments. Just special case here.
1672       if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1673         continue;
1674 
1675       // Otherwise construct the appropriate action.
1676       Current = ConstructPhaseAction(C, Args, Phase, Current);
1677 
1678       if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) {
1679         Current = buildCudaActions(C, Args, InputArg, Current, Actions);
1680         if (!Current)
1681           break;
1682       }
1683 
1684       if (Current->getType() == types::TY_Nothing)
1685         break;
1686     }
1687 
1688     // If we ended with something, add to the output list.
1689     if (Current)
1690       Actions.push_back(Current);
1691   }
1692 
1693   // Add a link action if necessary.
1694   if (!LinkerInputs.empty())
1695     Actions.push_back(
1696         C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image));
1697 
1698   // If we are linking, claim any options which are obviously only used for
1699   // compilation.
1700   if (FinalPhase == phases::Link && PL.size() == 1) {
1701     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1702     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1703   }
1704 
1705   // Claim ignored clang-cl options.
1706   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1707 
1708   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
1709   // to non-CUDA compilations and should not trigger warnings there.
1710   Args.ClaimAllArgs(options::OPT_cuda_host_only);
1711   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
1712 }
1713 
ConstructPhaseAction(Compilation & C,const ArgList & Args,phases::ID Phase,Action * Input) const1714 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
1715                                      phases::ID Phase, Action *Input) const {
1716   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1717   // Build the appropriate action.
1718   switch (Phase) {
1719   case phases::Link:
1720     llvm_unreachable("link action invalid here.");
1721   case phases::Preprocess: {
1722     types::ID OutputTy;
1723     // -{M, MM} alter the output type.
1724     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1725       OutputTy = types::TY_Dependencies;
1726     } else {
1727       OutputTy = Input->getType();
1728       if (!Args.hasFlag(options::OPT_frewrite_includes,
1729                         options::OPT_fno_rewrite_includes, false) &&
1730           !CCGenDiagnostics)
1731         OutputTy = types::getPreprocessedType(OutputTy);
1732       assert(OutputTy != types::TY_INVALID &&
1733              "Cannot preprocess this input type!");
1734     }
1735     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
1736   }
1737   case phases::Precompile: {
1738     types::ID OutputTy = types::TY_PCH;
1739     if (Args.hasArg(options::OPT_fsyntax_only)) {
1740       // Syntax checks should not emit a PCH file
1741       OutputTy = types::TY_Nothing;
1742     }
1743     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
1744   }
1745   case phases::Compile: {
1746     if (Args.hasArg(options::OPT_fsyntax_only))
1747       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
1748     if (Args.hasArg(options::OPT_rewrite_objc))
1749       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
1750     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
1751       return C.MakeAction<CompileJobAction>(Input,
1752                                             types::TY_RewrittenLegacyObjC);
1753     if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
1754       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
1755     if (Args.hasArg(options::OPT__migrate))
1756       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
1757     if (Args.hasArg(options::OPT_emit_ast))
1758       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
1759     if (Args.hasArg(options::OPT_module_file_info))
1760       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
1761     if (Args.hasArg(options::OPT_verify_pch))
1762       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
1763     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
1764   }
1765   case phases::Backend: {
1766     if (isUsingLTO()) {
1767       types::ID Output =
1768           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1769       return C.MakeAction<BackendJobAction>(Input, Output);
1770     }
1771     if (Args.hasArg(options::OPT_emit_llvm)) {
1772       types::ID Output =
1773           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1774       return C.MakeAction<BackendJobAction>(Input, Output);
1775     }
1776     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
1777   }
1778   case phases::Assemble:
1779     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
1780   }
1781 
1782   llvm_unreachable("invalid phase in ConstructPhaseAction");
1783 }
1784 
BuildJobs(Compilation & C) const1785 void Driver::BuildJobs(Compilation &C) const {
1786   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1787 
1788   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1789 
1790   // It is an error to provide a -o option if we are making multiple output
1791   // files.
1792   if (FinalOutput) {
1793     unsigned NumOutputs = 0;
1794     for (const Action *A : C.getActions())
1795       if (A->getType() != types::TY_Nothing)
1796         ++NumOutputs;
1797 
1798     if (NumOutputs > 1) {
1799       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1800       FinalOutput = nullptr;
1801     }
1802   }
1803 
1804   // Collect the list of architectures.
1805   llvm::StringSet<> ArchNames;
1806   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
1807     for (const Arg *A : C.getArgs())
1808       if (A->getOption().matches(options::OPT_arch))
1809         ArchNames.insert(A->getValue());
1810 
1811   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
1812   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
1813   for (Action *A : C.getActions()) {
1814     // If we are linking an image for multiple archs then the linker wants
1815     // -arch_multiple and -final_output <final image name>. Unfortunately, this
1816     // doesn't fit in cleanly because we have to pass this information down.
1817     //
1818     // FIXME: This is a hack; find a cleaner way to integrate this into the
1819     // process.
1820     const char *LinkingOutput = nullptr;
1821     if (isa<LipoJobAction>(A)) {
1822       if (FinalOutput)
1823         LinkingOutput = FinalOutput->getValue();
1824       else
1825         LinkingOutput = getDefaultImageName();
1826     }
1827 
1828     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1829                        /*BoundArch*/ nullptr,
1830                        /*AtTopLevel*/ true,
1831                        /*MultipleArchs*/ ArchNames.size() > 1,
1832                        /*LinkingOutput*/ LinkingOutput, CachedResults);
1833   }
1834 
1835   // If the user passed -Qunused-arguments or there were errors, don't warn
1836   // about any unused arguments.
1837   if (Diags.hasErrorOccurred() ||
1838       C.getArgs().hasArg(options::OPT_Qunused_arguments))
1839     return;
1840 
1841   // Claim -### here.
1842   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1843 
1844   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
1845   (void)C.getArgs().hasArg(options::OPT_driver_mode);
1846   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
1847 
1848   for (Arg *A : C.getArgs()) {
1849     // FIXME: It would be nice to be able to send the argument to the
1850     // DiagnosticsEngine, so that extra values, position, and so on could be
1851     // printed.
1852     if (!A->isClaimed()) {
1853       if (A->getOption().hasFlag(options::NoArgumentUnused))
1854         continue;
1855 
1856       // Suppress the warning automatically if this is just a flag, and it is an
1857       // instance of an argument we already claimed.
1858       const Option &Opt = A->getOption();
1859       if (Opt.getKind() == Option::FlagClass) {
1860         bool DuplicateClaimed = false;
1861 
1862         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
1863           if (AA->isClaimed()) {
1864             DuplicateClaimed = true;
1865             break;
1866           }
1867         }
1868 
1869         if (DuplicateClaimed)
1870           continue;
1871       }
1872 
1873       // In clang-cl, don't mention unknown arguments here since they have
1874       // already been warned about.
1875       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
1876         Diag(clang::diag::warn_drv_unused_argument)
1877             << A->getAsString(C.getArgs());
1878     }
1879   }
1880 }
1881 
1882 // Returns a Tool for a given JobAction.  In case the action and its
1883 // predecessors can be combined, updates Inputs with the inputs of the
1884 // first combined action. If one of the collapsed actions is a
1885 // CudaHostAction, updates CollapsedCHA with the pointer to it so the
1886 // caller can deal with extra handling such action requires.
selectToolForJob(Compilation & C,bool SaveTemps,bool EmbedBitcode,const ToolChain * TC,const JobAction * JA,const ActionList * & Inputs,const CudaHostAction * & CollapsedCHA)1887 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps,
1888                                     bool EmbedBitcode, const ToolChain *TC,
1889                                     const JobAction *JA,
1890                                     const ActionList *&Inputs,
1891                                     const CudaHostAction *&CollapsedCHA) {
1892   const Tool *ToolForJob = nullptr;
1893   CollapsedCHA = nullptr;
1894 
1895   // See if we should look for a compiler with an integrated assembler. We match
1896   // bottom up, so what we are actually looking for is an assembler job with a
1897   // compiler input.
1898 
1899   if (TC->useIntegratedAs() && !SaveTemps &&
1900       !C.getArgs().hasArg(options::OPT_via_file_asm) &&
1901       !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
1902       !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
1903       isa<AssembleJobAction>(JA) && Inputs->size() == 1 &&
1904       isa<BackendJobAction>(*Inputs->begin())) {
1905     // A BackendJob is always preceded by a CompileJob, and without -save-temps
1906     // or -fembed-bitcode, they will always get combined together, so instead of
1907     // checking the backend tool, check if the tool for the CompileJob has an
1908     // integrated assembler. For -fembed-bitcode, CompileJob is still used to
1909     // look up tools for BackendJob, but they need to match before we can split
1910     // them.
1911     const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
1912     // Compile job may be wrapped in CudaHostAction, extract it if
1913     // that's the case and update CollapsedCHA if we combine phases.
1914     CudaHostAction *CHA = dyn_cast<CudaHostAction>(*BackendInputs->begin());
1915     JobAction *CompileJA = cast<CompileJobAction>(
1916         CHA ? *CHA->input_begin() : *BackendInputs->begin());
1917     assert(CompileJA && "Backend job is not preceeded by compile job.");
1918     const Tool *Compiler = TC->SelectTool(*CompileJA);
1919     if (!Compiler)
1920       return nullptr;
1921     // When using -fembed-bitcode, it is required to have the same tool (clang)
1922     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
1923     if (EmbedBitcode) {
1924       JobAction *InputJA = cast<JobAction>(*Inputs->begin());
1925       const Tool *BackendTool = TC->SelectTool(*InputJA);
1926       if (BackendTool == Compiler)
1927         CompileJA = InputJA;
1928     }
1929     if (Compiler->hasIntegratedAssembler()) {
1930       Inputs = &CompileJA->getInputs();
1931       ToolForJob = Compiler;
1932       CollapsedCHA = CHA;
1933     }
1934   }
1935 
1936   // A backend job should always be combined with the preceding compile job
1937   // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is
1938   // capable of emitting LLVM IR as an intermediate output.
1939   if (isa<BackendJobAction>(JA)) {
1940     // Check if the compiler supports emitting LLVM IR.
1941     assert(Inputs->size() == 1);
1942     // Compile job may be wrapped in CudaHostAction, extract it if
1943     // that's the case and update CollapsedCHA if we combine phases.
1944     CudaHostAction *CHA = dyn_cast<CudaHostAction>(*Inputs->begin());
1945     JobAction *CompileJA =
1946         cast<CompileJobAction>(CHA ? *CHA->input_begin() : *Inputs->begin());
1947     assert(CompileJA && "Backend job is not preceeded by compile job.");
1948     const Tool *Compiler = TC->SelectTool(*CompileJA);
1949     if (!Compiler)
1950       return nullptr;
1951     if (!Compiler->canEmitIR() ||
1952         (!SaveTemps && !EmbedBitcode)) {
1953       Inputs = &CompileJA->getInputs();
1954       ToolForJob = Compiler;
1955       CollapsedCHA = CHA;
1956     }
1957   }
1958 
1959   // Otherwise use the tool for the current job.
1960   if (!ToolForJob)
1961     ToolForJob = TC->SelectTool(*JA);
1962 
1963   // See if we should use an integrated preprocessor. We do so when we have
1964   // exactly one input, since this is the only use case we care about
1965   // (irrelevant since we don't support combine yet).
1966   if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1967       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1968       !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
1969       !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
1970       ToolForJob->hasIntegratedCPP())
1971     Inputs = &(*Inputs)[0]->getInputs();
1972 
1973   return ToolForJob;
1974 }
1975 
BuildJobsForAction(Compilation & C,const Action * A,const ToolChain * TC,const char * BoundArch,bool AtTopLevel,bool MultipleArchs,const char * LinkingOutput,std::map<std::pair<const Action *,std::string>,InputInfo> & CachedResults) const1976 InputInfo Driver::BuildJobsForAction(
1977     Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
1978     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
1979     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults)
1980     const {
1981   // The bound arch is not necessarily represented in the toolchain's triple --
1982   // for example, armv7 and armv7s both map to the same triple -- so we need
1983   // both in our map.
1984   std::string TriplePlusArch = TC->getTriple().normalize();
1985   if (BoundArch) {
1986     TriplePlusArch += "-";
1987     TriplePlusArch += BoundArch;
1988   }
1989   std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch};
1990   auto CachedResult = CachedResults.find(ActionTC);
1991   if (CachedResult != CachedResults.end()) {
1992     return CachedResult->second;
1993   }
1994   InputInfo Result =
1995       BuildJobsForActionNoCache(C, A, TC, BoundArch, AtTopLevel, MultipleArchs,
1996                                 LinkingOutput, CachedResults);
1997   CachedResults[ActionTC] = Result;
1998   return Result;
1999 }
2000 
BuildJobsForActionNoCache(Compilation & C,const Action * A,const ToolChain * TC,const char * BoundArch,bool AtTopLevel,bool MultipleArchs,const char * LinkingOutput,std::map<std::pair<const Action *,std::string>,InputInfo> & CachedResults) const2001 InputInfo Driver::BuildJobsForActionNoCache(
2002     Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
2003     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2004     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults)
2005     const {
2006   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2007 
2008   InputInfoList CudaDeviceInputInfos;
2009   if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
2010     // Append outputs of device jobs to the input list.
2011     for (const Action *DA : CHA->getDeviceActions()) {
2012       CudaDeviceInputInfos.push_back(BuildJobsForAction(
2013           C, DA, TC, nullptr, AtTopLevel,
2014           /*MultipleArchs*/ false, LinkingOutput, CachedResults));
2015     }
2016     // Override current action with a real host compile action and continue
2017     // processing it.
2018     A = *CHA->input_begin();
2019   }
2020 
2021   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
2022     // FIXME: It would be nice to not claim this here; maybe the old scheme of
2023     // just using Args was better?
2024     const Arg &Input = IA->getInputArg();
2025     Input.claim();
2026     if (Input.getOption().matches(options::OPT_INPUT)) {
2027       const char *Name = Input.getValue();
2028       return InputInfo(A, Name, /* BaseInput = */ Name);
2029     }
2030     return InputInfo(A, &Input, /* BaseInput = */ "");
2031   }
2032 
2033   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
2034     const ToolChain *TC;
2035     const char *ArchName = BAA->getArchName();
2036 
2037     if (ArchName)
2038       TC = &getToolChain(C.getArgs(),
2039                          computeTargetTriple(*this, DefaultTargetTriple,
2040                                              C.getArgs(), ArchName));
2041     else
2042       TC = &C.getDefaultToolChain();
2043 
2044     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
2045                               MultipleArchs, LinkingOutput, CachedResults);
2046   }
2047 
2048   if (const CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
2049     // Initial processing of CudaDeviceAction carries host params.
2050     // Call BuildJobsForAction() again, now with correct device parameters.
2051     InputInfo II = BuildJobsForAction(
2052         C, *CDA->input_begin(), C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
2053         CudaArchToString(CDA->getGpuArch()), CDA->isAtTopLevel(),
2054         /*MultipleArchs=*/true, LinkingOutput, CachedResults);
2055     // Currently II's Action is *CDA->input_begin().  Set it to CDA instead, so
2056     // that one can retrieve II's GPU arch.
2057     II.setAction(A);
2058     return II;
2059   }
2060 
2061   const ActionList *Inputs = &A->getInputs();
2062 
2063   const JobAction *JA = cast<JobAction>(A);
2064   const CudaHostAction *CollapsedCHA = nullptr;
2065   const Tool *T =
2066       selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA,
2067                        Inputs, CollapsedCHA);
2068   if (!T)
2069     return InputInfo();
2070 
2071   // If we've collapsed action list that contained CudaHostAction we
2072   // need to build jobs for device-side inputs it may have held.
2073   if (CollapsedCHA) {
2074     for (const Action *DA : CollapsedCHA->getDeviceActions()) {
2075       CudaDeviceInputInfos.push_back(BuildJobsForAction(
2076           C, DA, TC, "", AtTopLevel,
2077           /*MultipleArchs*/ false, LinkingOutput, CachedResults));
2078     }
2079   }
2080 
2081   // Only use pipes when there is exactly one input.
2082   InputInfoList InputInfos;
2083   for (const Action *Input : *Inputs) {
2084     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
2085     // shouldn't get temporary output names.
2086     // FIXME: Clean this up.
2087     bool SubJobAtTopLevel =
2088         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
2089     InputInfos.push_back(BuildJobsForAction(C, Input, TC, BoundArch,
2090                                             SubJobAtTopLevel, MultipleArchs,
2091                                             LinkingOutput, CachedResults));
2092   }
2093 
2094   // Always use the first input as the base input.
2095   const char *BaseInput = InputInfos[0].getBaseInput();
2096 
2097   // ... except dsymutil actions, which use their actual input as the base
2098   // input.
2099   if (JA->getType() == types::TY_dSYM)
2100     BaseInput = InputInfos[0].getFilename();
2101 
2102   // Append outputs of cuda device jobs to the input list
2103   if (CudaDeviceInputInfos.size())
2104     InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end());
2105 
2106   // Determine the place to write output to, if any.
2107   InputInfo Result;
2108   if (JA->getType() == types::TY_Nothing)
2109     Result = InputInfo(A, BaseInput);
2110   else
2111     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
2112                                              AtTopLevel, MultipleArchs),
2113                        BaseInput);
2114 
2115   if (CCCPrintBindings && !CCGenDiagnostics) {
2116     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
2117                  << " - \"" << T->getName() << "\", inputs: [";
2118     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
2119       llvm::errs() << InputInfos[i].getAsString();
2120       if (i + 1 != e)
2121         llvm::errs() << ", ";
2122     }
2123     llvm::errs() << "], output: " << Result.getAsString() << "\n";
2124   } else {
2125     T->ConstructJob(C, *JA, Result, InputInfos,
2126                     C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
2127   }
2128   return Result;
2129 }
2130 
getDefaultImageName() const2131 const char *Driver::getDefaultImageName() const {
2132   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
2133   return Target.isOSWindows() ? "a.exe" : "a.out";
2134 }
2135 
2136 /// \brief Create output filename based on ArgValue, which could either be a
2137 /// full filename, filename without extension, or a directory. If ArgValue
2138 /// does not provide a filename, then use BaseName, and use the extension
2139 /// suitable for FileType.
MakeCLOutputFilename(const ArgList & Args,StringRef ArgValue,StringRef BaseName,types::ID FileType)2140 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
2141                                         StringRef BaseName,
2142                                         types::ID FileType) {
2143   SmallString<128> Filename = ArgValue;
2144 
2145   if (ArgValue.empty()) {
2146     // If the argument is empty, output to BaseName in the current dir.
2147     Filename = BaseName;
2148   } else if (llvm::sys::path::is_separator(Filename.back())) {
2149     // If the argument is a directory, output to BaseName in that dir.
2150     llvm::sys::path::append(Filename, BaseName);
2151   }
2152 
2153   if (!llvm::sys::path::has_extension(ArgValue)) {
2154     // If the argument didn't provide an extension, then set it.
2155     const char *Extension = types::getTypeTempSuffix(FileType, true);
2156 
2157     if (FileType == types::TY_Image &&
2158         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
2159       // The output file is a dll.
2160       Extension = "dll";
2161     }
2162 
2163     llvm::sys::path::replace_extension(Filename, Extension);
2164   }
2165 
2166   return Args.MakeArgString(Filename.c_str());
2167 }
2168 
GetNamedOutputPath(Compilation & C,const JobAction & JA,const char * BaseInput,const char * BoundArch,bool AtTopLevel,bool MultipleArchs) const2169 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
2170                                        const char *BaseInput,
2171                                        const char *BoundArch, bool AtTopLevel,
2172                                        bool MultipleArchs) const {
2173   llvm::PrettyStackTraceString CrashInfo("Computing output path");
2174   // Output to a user requested destination?
2175   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
2176     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
2177       return C.addResultFile(FinalOutput->getValue(), &JA);
2178   }
2179 
2180   // For /P, preprocess to file named after BaseInput.
2181   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
2182     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
2183     StringRef BaseName = llvm::sys::path::filename(BaseInput);
2184     StringRef NameArg;
2185     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
2186       NameArg = A->getValue();
2187     return C.addResultFile(
2188         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
2189         &JA);
2190   }
2191 
2192   // Default to writing to stdout?
2193   if (AtTopLevel && !CCGenDiagnostics &&
2194       (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
2195     return "-";
2196 
2197   // Is this the assembly listing for /FA?
2198   if (JA.getType() == types::TY_PP_Asm &&
2199       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
2200        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
2201     // Use /Fa and the input filename to determine the asm file name.
2202     StringRef BaseName = llvm::sys::path::filename(BaseInput);
2203     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
2204     return C.addResultFile(
2205         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
2206         &JA);
2207   }
2208 
2209   // Output to a temporary file?
2210   if ((!AtTopLevel && !isSaveTempsEnabled() &&
2211        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
2212       CCGenDiagnostics) {
2213     StringRef Name = llvm::sys::path::filename(BaseInput);
2214     std::pair<StringRef, StringRef> Split = Name.split('.');
2215     std::string TmpName = GetTemporaryPath(
2216         Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2217     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2218   }
2219 
2220   SmallString<128> BasePath(BaseInput);
2221   StringRef BaseName;
2222 
2223   // Dsymutil actions should use the full path.
2224   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
2225     BaseName = BasePath;
2226   else
2227     BaseName = llvm::sys::path::filename(BasePath);
2228 
2229   // Determine what the derived output name should be.
2230   const char *NamedOutput;
2231 
2232   if (JA.getType() == types::TY_Object &&
2233       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
2234     // The /Fo or /o flag decides the object filename.
2235     StringRef Val =
2236         C.getArgs()
2237             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
2238             ->getValue();
2239     NamedOutput =
2240         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
2241   } else if (JA.getType() == types::TY_Image &&
2242              C.getArgs().hasArg(options::OPT__SLASH_Fe,
2243                                 options::OPT__SLASH_o)) {
2244     // The /Fe or /o flag names the linked file.
2245     StringRef Val =
2246         C.getArgs()
2247             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
2248             ->getValue();
2249     NamedOutput =
2250         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
2251   } else if (JA.getType() == types::TY_Image) {
2252     if (IsCLMode()) {
2253       // clang-cl uses BaseName for the executable name.
2254       NamedOutput =
2255           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
2256     } else if (MultipleArchs && BoundArch) {
2257       SmallString<128> Output(getDefaultImageName());
2258       Output += "-";
2259       Output.append(BoundArch);
2260       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
2261     } else {
2262       NamedOutput = getDefaultImageName();
2263     }
2264   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
2265     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str());
2266   } else {
2267     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
2268     assert(Suffix && "All types used for output should have a suffix.");
2269 
2270     std::string::size_type End = std::string::npos;
2271     if (!types::appendSuffixForType(JA.getType()))
2272       End = BaseName.rfind('.');
2273     SmallString<128> Suffixed(BaseName.substr(0, End));
2274     if (MultipleArchs && BoundArch) {
2275       Suffixed += "-";
2276       Suffixed.append(BoundArch);
2277     }
2278     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
2279     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
2280     // optimized bitcode output.
2281     if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
2282         JA.getType() == types::TY_LLVM_BC)
2283       Suffixed += ".tmp";
2284     Suffixed += '.';
2285     Suffixed += Suffix;
2286     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2287   }
2288 
2289   // Prepend object file path if -save-temps=obj
2290   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
2291       JA.getType() != types::TY_PCH) {
2292     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2293     SmallString<128> TempPath(FinalOutput->getValue());
2294     llvm::sys::path::remove_filename(TempPath);
2295     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2296     llvm::sys::path::append(TempPath, OutputFileName);
2297     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
2298   }
2299 
2300   // If we're saving temps and the temp file conflicts with the input file,
2301   // then avoid overwriting input file.
2302   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
2303     bool SameFile = false;
2304     SmallString<256> Result;
2305     llvm::sys::fs::current_path(Result);
2306     llvm::sys::path::append(Result, BaseName);
2307     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2308     // Must share the same path to conflict.
2309     if (SameFile) {
2310       StringRef Name = llvm::sys::path::filename(BaseInput);
2311       std::pair<StringRef, StringRef> Split = Name.split('.');
2312       std::string TmpName = GetTemporaryPath(
2313           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2314       return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2315     }
2316   }
2317 
2318   // As an annoying special case, PCH generation doesn't strip the pathname.
2319   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
2320     llvm::sys::path::remove_filename(BasePath);
2321     if (BasePath.empty())
2322       BasePath = NamedOutput;
2323     else
2324       llvm::sys::path::append(BasePath, NamedOutput);
2325     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
2326   } else {
2327     return C.addResultFile(NamedOutput, &JA);
2328   }
2329 }
2330 
GetFilePath(const char * Name,const ToolChain & TC) const2331 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
2332   // Respect a limited subset of the '-Bprefix' functionality in GCC by
2333   // attempting to use this prefix when looking for file paths.
2334   for (const std::string &Dir : PrefixDirs) {
2335     if (Dir.empty())
2336       continue;
2337     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2338     llvm::sys::path::append(P, Name);
2339     if (llvm::sys::fs::exists(Twine(P)))
2340       return P.str();
2341   }
2342 
2343   SmallString<128> P(ResourceDir);
2344   llvm::sys::path::append(P, Name);
2345   if (llvm::sys::fs::exists(Twine(P)))
2346     return P.str();
2347 
2348   for (const std::string &Dir : TC.getFilePaths()) {
2349     if (Dir.empty())
2350       continue;
2351     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2352     llvm::sys::path::append(P, Name);
2353     if (llvm::sys::fs::exists(Twine(P)))
2354       return P.str();
2355   }
2356 
2357   return Name;
2358 }
2359 
generatePrefixedToolNames(const char * Tool,const ToolChain & TC,SmallVectorImpl<std::string> & Names) const2360 void Driver::generatePrefixedToolNames(
2361     const char *Tool, const ToolChain &TC,
2362     SmallVectorImpl<std::string> &Names) const {
2363   // FIXME: Needs a better variable than DefaultTargetTriple
2364   Names.emplace_back(DefaultTargetTriple + "-" + Tool);
2365   Names.emplace_back(Tool);
2366 
2367   // Allow the discovery of tools prefixed with LLVM's default target triple.
2368   std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
2369   if (LLVMDefaultTargetTriple != DefaultTargetTriple)
2370     Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool);
2371 }
2372 
ScanDirForExecutable(SmallString<128> & Dir,ArrayRef<std::string> Names)2373 static bool ScanDirForExecutable(SmallString<128> &Dir,
2374                                  ArrayRef<std::string> Names) {
2375   for (const auto &Name : Names) {
2376     llvm::sys::path::append(Dir, Name);
2377     if (llvm::sys::fs::can_execute(Twine(Dir)))
2378       return true;
2379     llvm::sys::path::remove_filename(Dir);
2380   }
2381   return false;
2382 }
2383 
GetProgramPath(const char * Name,const ToolChain & TC) const2384 std::string Driver::GetProgramPath(const char *Name,
2385                                    const ToolChain &TC) const {
2386   SmallVector<std::string, 2> TargetSpecificExecutables;
2387   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2388 
2389   // Respect a limited subset of the '-Bprefix' functionality in GCC by
2390   // attempting to use this prefix when looking for program paths.
2391   for (const auto &PrefixDir : PrefixDirs) {
2392     if (llvm::sys::fs::is_directory(PrefixDir)) {
2393       SmallString<128> P(PrefixDir);
2394       if (ScanDirForExecutable(P, TargetSpecificExecutables))
2395         return P.str();
2396     } else {
2397       SmallString<128> P(PrefixDir + Name);
2398       if (llvm::sys::fs::can_execute(Twine(P)))
2399         return P.str();
2400     }
2401   }
2402 
2403   const ToolChain::path_list &List = TC.getProgramPaths();
2404   for (const auto &Path : List) {
2405     SmallString<128> P(Path);
2406     if (ScanDirForExecutable(P, TargetSpecificExecutables))
2407       return P.str();
2408   }
2409 
2410   // If all else failed, search the path.
2411   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2412     if (llvm::ErrorOr<std::string> P =
2413             llvm::sys::findProgramByName(TargetSpecificExecutable))
2414       return *P;
2415 
2416   return Name;
2417 }
2418 
GetTemporaryPath(StringRef Prefix,const char * Suffix) const2419 std::string Driver::GetTemporaryPath(StringRef Prefix,
2420                                      const char *Suffix) const {
2421   SmallString<128> Path;
2422   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
2423   if (EC) {
2424     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
2425     return "";
2426   }
2427 
2428   return Path.str();
2429 }
2430 
GetClPchPath(Compilation & C,StringRef BaseName) const2431 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
2432   SmallString<128> Output;
2433   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
2434     // FIXME: If anybody needs it, implement this obscure rule:
2435     // "If you specify a directory without a file name, the default file name
2436     // is VCx0.pch., where x is the major version of Visual C++ in use."
2437     Output = FpArg->getValue();
2438 
2439     // "If you do not specify an extension as part of the path name, an
2440     // extension of .pch is assumed. "
2441     if (!llvm::sys::path::has_extension(Output))
2442       Output += ".pch";
2443   } else {
2444     Output = BaseName;
2445     llvm::sys::path::replace_extension(Output, ".pch");
2446   }
2447   return Output.str();
2448 }
2449 
getToolChain(const ArgList & Args,const llvm::Triple & Target) const2450 const ToolChain &Driver::getToolChain(const ArgList &Args,
2451                                       const llvm::Triple &Target) const {
2452 
2453   ToolChain *&TC = ToolChains[Target.str()];
2454   if (!TC) {
2455     switch (Target.getOS()) {
2456     case llvm::Triple::Haiku:
2457       TC = new toolchains::Haiku(*this, Target, Args);
2458       break;
2459     case llvm::Triple::CloudABI:
2460       TC = new toolchains::CloudABI(*this, Target, Args);
2461       break;
2462     case llvm::Triple::Darwin:
2463     case llvm::Triple::MacOSX:
2464     case llvm::Triple::IOS:
2465     case llvm::Triple::TvOS:
2466     case llvm::Triple::WatchOS:
2467       TC = new toolchains::DarwinClang(*this, Target, Args);
2468       break;
2469     case llvm::Triple::DragonFly:
2470       TC = new toolchains::DragonFly(*this, Target, Args);
2471       break;
2472     case llvm::Triple::OpenBSD:
2473       TC = new toolchains::OpenBSD(*this, Target, Args);
2474       break;
2475     case llvm::Triple::Bitrig:
2476       TC = new toolchains::Bitrig(*this, Target, Args);
2477       break;
2478     case llvm::Triple::NetBSD:
2479       TC = new toolchains::NetBSD(*this, Target, Args);
2480       break;
2481     case llvm::Triple::FreeBSD:
2482       TC = new toolchains::FreeBSD(*this, Target, Args);
2483       break;
2484     case llvm::Triple::Minix:
2485       TC = new toolchains::Minix(*this, Target, Args);
2486       break;
2487     case llvm::Triple::Linux:
2488     case llvm::Triple::ELFIAMCU:
2489       if (Target.getArch() == llvm::Triple::hexagon)
2490         TC = new toolchains::HexagonToolChain(*this, Target, Args);
2491       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
2492                !Target.hasEnvironment())
2493         TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
2494       else
2495         TC = new toolchains::Linux(*this, Target, Args);
2496       break;
2497     case llvm::Triple::NaCl:
2498       TC = new toolchains::NaClToolChain(*this, Target, Args);
2499       break;
2500     case llvm::Triple::Solaris:
2501       TC = new toolchains::Solaris(*this, Target, Args);
2502       break;
2503     case llvm::Triple::AMDHSA:
2504       TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
2505       break;
2506     case llvm::Triple::Win32:
2507       switch (Target.getEnvironment()) {
2508       default:
2509         if (Target.isOSBinFormatELF())
2510           TC = new toolchains::Generic_ELF(*this, Target, Args);
2511         else if (Target.isOSBinFormatMachO())
2512           TC = new toolchains::MachO(*this, Target, Args);
2513         else
2514           TC = new toolchains::Generic_GCC(*this, Target, Args);
2515         break;
2516       case llvm::Triple::GNU:
2517         TC = new toolchains::MinGW(*this, Target, Args);
2518         break;
2519       case llvm::Triple::Itanium:
2520         TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2521         break;
2522       case llvm::Triple::MSVC:
2523       case llvm::Triple::UnknownEnvironment:
2524         TC = new toolchains::MSVCToolChain(*this, Target, Args);
2525         break;
2526       }
2527       break;
2528     case llvm::Triple::CUDA:
2529       TC = new toolchains::CudaToolChain(*this, Target, Args);
2530       break;
2531     case llvm::Triple::PS4:
2532       TC = new toolchains::PS4CPU(*this, Target, Args);
2533       break;
2534     default:
2535       // Of these targets, Hexagon is the only one that might have
2536       // an OS of Linux, in which case it got handled above already.
2537       switch (Target.getArch()) {
2538       case llvm::Triple::tce:
2539         TC = new toolchains::TCEToolChain(*this, Target, Args);
2540         break;
2541       case llvm::Triple::hexagon:
2542         TC = new toolchains::HexagonToolChain(*this, Target, Args);
2543         break;
2544       case llvm::Triple::lanai:
2545         TC = new toolchains::LanaiToolChain(*this, Target, Args);
2546         break;
2547       case llvm::Triple::xcore:
2548         TC = new toolchains::XCoreToolChain(*this, Target, Args);
2549         break;
2550       case llvm::Triple::wasm32:
2551       case llvm::Triple::wasm64:
2552         TC = new toolchains::WebAssembly(*this, Target, Args);
2553         break;
2554       default:
2555         if (Target.getVendor() == llvm::Triple::Myriad)
2556           TC = new toolchains::MyriadToolChain(*this, Target, Args);
2557         else if (Target.isOSBinFormatELF())
2558           TC = new toolchains::Generic_ELF(*this, Target, Args);
2559         else if (Target.isOSBinFormatMachO())
2560           TC = new toolchains::MachO(*this, Target, Args);
2561         else
2562           TC = new toolchains::Generic_GCC(*this, Target, Args);
2563       }
2564     }
2565   }
2566   return *TC;
2567 }
2568 
ShouldUseClangCompiler(const JobAction & JA) const2569 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
2570   // Say "no" if there is not exactly one input of a type clang understands.
2571   if (JA.size() != 1 ||
2572       !types::isAcceptedByClang((*JA.input_begin())->getType()))
2573     return false;
2574 
2575   // And say "no" if this is not a kind of action clang understands.
2576   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
2577       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
2578     return false;
2579 
2580   return true;
2581 }
2582 
2583 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2584 /// grouped values as integers. Numbers which are not provided are set to 0.
2585 ///
2586 /// \return True if the entire string was parsed (9.2), or all groups were
2587 /// parsed (10.3.5extrastuff).
GetReleaseVersion(const char * Str,unsigned & Major,unsigned & Minor,unsigned & Micro,bool & HadExtra)2588 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
2589                                unsigned &Minor, unsigned &Micro,
2590                                bool &HadExtra) {
2591   HadExtra = false;
2592 
2593   Major = Minor = Micro = 0;
2594   if (*Str == '\0')
2595     return false;
2596 
2597   char *End;
2598   Major = (unsigned)strtol(Str, &End, 10);
2599   if (*Str != '\0' && *End == '\0')
2600     return true;
2601   if (*End != '.')
2602     return false;
2603 
2604   Str = End + 1;
2605   Minor = (unsigned)strtol(Str, &End, 10);
2606   if (*Str != '\0' && *End == '\0')
2607     return true;
2608   if (*End != '.')
2609     return false;
2610 
2611   Str = End + 1;
2612   Micro = (unsigned)strtol(Str, &End, 10);
2613   if (*Str != '\0' && *End == '\0')
2614     return true;
2615   if (Str == End)
2616     return false;
2617   HadExtra = true;
2618   return true;
2619 }
2620 
2621 /// Parse digits from a string \p Str and fulfill \p Digits with
2622 /// the parsed numbers. This method assumes that the max number of
2623 /// digits to look for is equal to Digits.size().
2624 ///
2625 /// \return True if the entire string was parsed and there are
2626 /// no extra characters remaining at the end.
GetReleaseVersion(const char * Str,MutableArrayRef<unsigned> Digits)2627 bool Driver::GetReleaseVersion(const char *Str,
2628                                MutableArrayRef<unsigned> Digits) {
2629   if (*Str == '\0')
2630     return false;
2631 
2632   char *End;
2633   unsigned CurDigit = 0;
2634   while (CurDigit < Digits.size()) {
2635     unsigned Digit = (unsigned)strtol(Str, &End, 10);
2636     Digits[CurDigit] = Digit;
2637     if (*Str != '\0' && *End == '\0')
2638       return true;
2639     if (*End != '.' || Str == End)
2640       return false;
2641     Str = End + 1;
2642     CurDigit++;
2643   }
2644 
2645   // More digits than requested, bail out...
2646   return false;
2647 }
2648 
getIncludeExcludeOptionFlagMasks() const2649 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2650   unsigned IncludedFlagsBitmask = 0;
2651   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
2652 
2653   if (Mode == CLMode) {
2654     // Include CL and Core options.
2655     IncludedFlagsBitmask |= options::CLOption;
2656     IncludedFlagsBitmask |= options::CoreOption;
2657   } else {
2658     ExcludedFlagsBitmask |= options::CLOption;
2659   }
2660 
2661   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2662 }
2663 
isOptimizationLevelFast(const ArgList & Args)2664 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
2665   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
2666 }
2667