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