1218893Sdim//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed
10193326Sed#include "clang/Driver/Driver.h"
11249423Sdim#include "InputInfo.h"
12249423Sdim#include "ToolChains.h"
13249423Sdim#include "clang/Basic/Version.h"
14193326Sed#include "clang/Driver/Action.h"
15193326Sed#include "clang/Driver/Arg.h"
16193326Sed#include "clang/Driver/ArgList.h"
17193326Sed#include "clang/Driver/Compilation.h"
18193326Sed#include "clang/Driver/DriverDiagnostic.h"
19193326Sed#include "clang/Driver/Job.h"
20199512Srdivacky#include "clang/Driver/OptTable.h"
21193326Sed#include "clang/Driver/Option.h"
22193326Sed#include "clang/Driver/Options.h"
23193326Sed#include "clang/Driver/Tool.h"
24193326Sed#include "clang/Driver/ToolChain.h"
25221345Sdim#include "llvm/ADT/ArrayRef.h"
26249423Sdim#include "llvm/ADT/OwningPtr.h"
27193326Sed#include "llvm/ADT/StringSet.h"
28249423Sdim#include "llvm/Support/Debug.h"
29226633Sdim#include "llvm/Support/ErrorHandling.h"
30218893Sdim#include "llvm/Support/FileSystem.h"
31218893Sdim#include "llvm/Support/Path.h"
32249423Sdim#include "llvm/Support/PrettyStackTrace.h"
33218893Sdim#include "llvm/Support/Program.h"
34249423Sdim#include "llvm/Support/raw_ostream.h"
35193326Sed#include <map>
36193326Sed
37249423Sdim// FIXME: It would prevent us from including llvm-config.h
38249423Sdim// if config.h were included before system_error.h.
39234353Sdim#include "clang/Config/config.h"
40234353Sdim
41193326Sedusing namespace clang::driver;
42193326Sedusing namespace clang;
43193326Sed
44226633SdimDriver::Driver(StringRef ClangExecutable,
45234353Sdim               StringRef DefaultTargetTriple,
46226633Sdim               StringRef DefaultImageName,
47226633Sdim               DiagnosticsEngine &Diags)
48223017Sdim  : Opts(createDriverOptTable()), Diags(Diags),
49234982Sdim    ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
50234982Sdim    UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
51234353Sdim    DefaultImageName(DefaultImageName),
52243830Sdim    DriverTitle("clang LLVM compiler"),
53221345Sdim    CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
54221345Sdim    CCLogDiagnosticsFilename(0), CCCIsCXX(false),
55221345Sdim    CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
56221345Sdim    CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
57226633Sdim    CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
58243830Sdim    CCCUsePCH(true), SuppressMissingInputWarning(false) {
59202879Srdivacky
60218893Sdim  Name = llvm::sys::path::stem(ClangExecutable);
61218893Sdim  Dir  = llvm::sys::path::parent_path(ClangExecutable);
62212904Sdim
63202879Srdivacky  // Compute the path to the resource directory.
64226633Sdim  StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
65234353Sdim  SmallString<128> P(Dir);
66218893Sdim  if (ClangResourceDir != "")
67218893Sdim    llvm::sys::path::append(P, ClangResourceDir);
68218893Sdim  else
69218893Sdim    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
70202879Srdivacky  ResourceDir = P.str();
71193326Sed}
72193326Sed
73193326SedDriver::~Driver() {
74193326Sed  delete Opts;
75234353Sdim
76234353Sdim  for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(),
77234353Sdim                                              E = ToolChains.end();
78234353Sdim       I != E; ++I)
79234353Sdim    delete I->second;
80193326Sed}
81193326Sed
82226633SdimInputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
83193326Sed  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
84199512Srdivacky  unsigned MissingArgIndex, MissingArgCount;
85221345Sdim  InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
86199512Srdivacky                                           MissingArgIndex, MissingArgCount);
87198092Srdivacky
88199512Srdivacky  // Check for missing argument error.
89199512Srdivacky  if (MissingArgCount)
90199512Srdivacky    Diag(clang::diag::err_drv_missing_argument)
91199512Srdivacky      << Args->getArgString(MissingArgIndex) << MissingArgCount;
92193326Sed
93199512Srdivacky  // Check for unsupported options.
94199512Srdivacky  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
95199512Srdivacky       it != ie; ++it) {
96199512Srdivacky    Arg *A = *it;
97243830Sdim    if (A->getOption().hasFlag(options::Unsupported)) {
98193326Sed      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
99193326Sed      continue;
100193326Sed    }
101234353Sdim
102234353Sdim    // Warn about -mcpu= without an argument.
103239462Sdim    if (A->getOption().matches(options::OPT_mcpu_EQ) &&
104234353Sdim        A->containsValue("")) {
105239462Sdim      Diag(clang::diag::warn_drv_empty_joined_argument) <<
106239462Sdim        A->getAsString(*Args);
107234353Sdim    }
108193326Sed  }
109193326Sed
110193326Sed  return Args;
111193326Sed}
112193326Sed
113226633Sdim// Determine which compilation mode we are in. We look for options which
114226633Sdim// affect the phase, starting with the earliest phases, and record which
115226633Sdim// option we used to determine the final phase.
116226633Sdimphases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
117226633Sdimconst {
118226633Sdim  Arg *PhaseArg = 0;
119226633Sdim  phases::ID FinalPhase;
120226633Sdim
121226633Sdim  // -{E,M,MM} only run the preprocessor.
122226633Sdim  if (CCCIsCPP ||
123226633Sdim      (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
124226633Sdim      (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
125226633Sdim    FinalPhase = phases::Preprocess;
126226633Sdim
127226633Sdim    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
128226633Sdim  } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
129249423Sdim             (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
130226633Sdim             (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
131234353Sdim             (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
132234353Sdim             (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
133226633Sdim             (PhaseArg = DAL.getLastArg(options::OPT__analyze,
134234353Sdim                                        options::OPT__analyze_auto)) ||
135226633Sdim             (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
136226633Sdim             (PhaseArg = DAL.getLastArg(options::OPT_S))) {
137226633Sdim    FinalPhase = phases::Compile;
138226633Sdim
139226633Sdim    // -c only runs up to the assembler.
140226633Sdim  } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
141226633Sdim    FinalPhase = phases::Assemble;
142226633Sdim
143226633Sdim    // Otherwise do everything.
144226633Sdim  } else
145226633Sdim    FinalPhase = phases::Link;
146226633Sdim
147226633Sdim  if (FinalPhaseArg)
148226633Sdim    *FinalPhaseArg = PhaseArg;
149226633Sdim
150226633Sdim  return FinalPhase;
151226633Sdim}
152226633Sdim
153210299SedDerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
154210299Sed  DerivedArgList *DAL = new DerivedArgList(Args);
155210299Sed
156218893Sdim  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
157210299Sed  for (ArgList::const_iterator it = Args.begin(),
158210299Sed         ie = Args.end(); it != ie; ++it) {
159210299Sed    const Arg *A = *it;
160210299Sed
161210299Sed    // Unfortunately, we have to parse some forwarding options (-Xassembler,
162210299Sed    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
163210299Sed    // (assembler and preprocessor), or bypass a previous driver ('collect2').
164210299Sed
165210299Sed    // Rewrite linker options, to replace --no-demangle with a custom internal
166210299Sed    // option.
167210299Sed    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
168210299Sed         A->getOption().matches(options::OPT_Xlinker)) &&
169210299Sed        A->containsValue("--no-demangle")) {
170210299Sed      // Add the rewritten no-demangle argument.
171210299Sed      DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
172210299Sed
173210299Sed      // Add the remaining values as Xlinker arguments.
174210299Sed      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
175243830Sdim        if (StringRef(A->getValue(i)) != "--no-demangle")
176210299Sed          DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
177243830Sdim                              A->getValue(i));
178210299Sed
179210299Sed      continue;
180210299Sed    }
181210299Sed
182210299Sed    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
183210299Sed    // some build systems. We don't try to be complete here because we don't
184210299Sed    // care to encourage this usage model.
185210299Sed    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
186243830Sdim        (A->getValue(0) == StringRef("-MD") ||
187243830Sdim         A->getValue(0) == StringRef("-MMD"))) {
188210299Sed      // Rewrite to -MD/-MMD along with -MF.
189243830Sdim      if (A->getValue(0) == StringRef("-MD"))
190210299Sed        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
191210299Sed      else
192210299Sed        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
193243830Sdim      if (A->getNumValues() == 2)
194243830Sdim        DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
195243830Sdim                            A->getValue(1));
196210299Sed      continue;
197210299Sed    }
198210299Sed
199218893Sdim    // Rewrite reserved library names.
200218893Sdim    if (A->getOption().matches(options::OPT_l)) {
201243830Sdim      StringRef Value = A->getValue();
202218893Sdim
203218893Sdim      // Rewrite unless -nostdlib is present.
204218893Sdim      if (!HasNostdlib && Value == "stdc++") {
205218893Sdim        DAL->AddFlagArg(A, Opts->getOption(
206218893Sdim                              options::OPT_Z_reserved_lib_stdcxx));
207218893Sdim        continue;
208218893Sdim      }
209218893Sdim
210218893Sdim      // Rewrite unconditionally.
211218893Sdim      if (Value == "cc_kext") {
212218893Sdim        DAL->AddFlagArg(A, Opts->getOption(
213218893Sdim                              options::OPT_Z_reserved_lib_cckext));
214218893Sdim        continue;
215218893Sdim      }
216218893Sdim    }
217218893Sdim
218210299Sed    DAL->append(*it);
219210299Sed  }
220210299Sed
221212904Sdim  // Add a default value of -mlinker-version=, if one was given and the user
222212904Sdim  // didn't specify one.
223212904Sdim#if defined(HOST_LINK_VERSION)
224212904Sdim  if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
225212904Sdim    DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
226212904Sdim                      HOST_LINK_VERSION);
227212904Sdim    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
228212904Sdim  }
229212904Sdim#endif
230212904Sdim
231210299Sed  return DAL;
232210299Sed}
233210299Sed
234226633SdimCompilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
235193326Sed  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
236193326Sed
237226633Sdim  // FIXME: Handle environment options which affect driver behavior, somewhere
238234353Sdim  // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
239193326Sed
240226633Sdim  if (char *env = ::getenv("COMPILER_PATH")) {
241226633Sdim    StringRef CompilerPath = env;
242226633Sdim    while (!CompilerPath.empty()) {
243249423Sdim      std::pair<StringRef, StringRef> Split
244249423Sdim        = CompilerPath.split(llvm::sys::PathSeparator);
245226633Sdim      PrefixDirs.push_back(Split.first);
246226633Sdim      CompilerPath = Split.second;
247226633Sdim    }
248226633Sdim  }
249226633Sdim
250193326Sed  // FIXME: What are we going to do with -V and -b?
251193326Sed
252198092Srdivacky  // FIXME: This stuff needs to go into the Compilation, not the driver.
253249423Sdim  bool CCCPrintOptions, CCCPrintActions;
254193326Sed
255221345Sdim  InputArgList *Args = ParseArgStrings(ArgList.slice(1));
256193326Sed
257200583Srdivacky  // -no-canonical-prefixes is used very early in main.
258200583Srdivacky  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
259200583Srdivacky
260212904Sdim  // Ignore -pipe.
261212904Sdim  Args->ClaimAllArgs(options::OPT_pipe);
262212904Sdim
263200583Srdivacky  // Extract -ccc args.
264193326Sed  //
265198092Srdivacky  // FIXME: We need to figure out where this behavior should live. Most of it
266198092Srdivacky  // should be outside in the client; the parts that aren't should have proper
267198092Srdivacky  // options, either by introducing new ones or by overloading gcc ones like -V
268198092Srdivacky  // or -b.
269200583Srdivacky  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
270200583Srdivacky  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
271200583Srdivacky  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
272200583Srdivacky  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
273200583Srdivacky  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
274200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
275243830Sdim    CCCGenericGCCName = A->getValue();
276200583Srdivacky  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
277200583Srdivacky                            options::OPT_ccc_pch_is_pth);
278234353Sdim  // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
279234353Sdim  // and getToolChain is const.
280234353Sdim  if (const Arg *A = Args->getLastArg(options::OPT_target))
281243830Sdim    DefaultTargetTriple = A->getValue();
282200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
283243830Sdim    Dir = InstalledDir = A->getValue();
284218893Sdim  for (arg_iterator it = Args->filtered_begin(options::OPT_B),
285218893Sdim         ie = Args->filtered_end(); it != ie; ++it) {
286218893Sdim    const Arg *A = *it;
287218893Sdim    A->claim();
288243830Sdim    PrefixDirs.push_back(A->getValue(0));
289218893Sdim  }
290221345Sdim  if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
291243830Sdim    SysRoot = A->getValue();
292221345Sdim  if (Args->hasArg(options::OPT_nostdlib))
293221345Sdim    UseStdLib = false;
294193326Sed
295249423Sdim  if (const Arg *A = Args->getLastArg(options::OPT_resource_dir))
296249423Sdim    ResourceDir = A->getValue();
297249423Sdim
298210299Sed  // Perform the default argument translations.
299210299Sed  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
300210299Sed
301234353Sdim  // Owned by the host.
302234353Sdim  const ToolChain &TC = getToolChain(*Args);
303234353Sdim
304193326Sed  // The compilation takes ownership of Args.
305234353Sdim  Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
306193326Sed
307193326Sed  // FIXME: This behavior shouldn't be here.
308193326Sed  if (CCCPrintOptions) {
309210299Sed    PrintOptions(C->getInputArgs());
310193326Sed    return C;
311193326Sed  }
312193326Sed
313193326Sed  if (!HandleImmediateArgs(*C))
314193326Sed    return C;
315193326Sed
316226633Sdim  // Construct the list of inputs.
317226633Sdim  InputList Inputs;
318226633Sdim  BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
319226633Sdim
320234353Sdim  // Construct the list of abstract actions to perform for this compilation. On
321234353Sdim  // Darwin target OSes this uses the driver-driver and universal actions.
322234353Sdim  if (TC.getTriple().isOSDarwin())
323212904Sdim    BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
324226633Sdim                          Inputs, C->getActions());
325193326Sed  else
326226633Sdim    BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
327226633Sdim                 C->getActions());
328193326Sed
329193326Sed  if (CCCPrintActions) {
330193326Sed    PrintActions(*C);
331193326Sed    return C;
332193326Sed  }
333193326Sed
334193326Sed  BuildJobs(*C);
335193326Sed
336193326Sed  return C;
337193326Sed}
338193326Sed
339226633Sdim// When clang crashes, produce diagnostic information including the fully
340226633Sdim// preprocessed source file(s).  Request that the developer attach the
341226633Sdim// diagnostic information to a bug report.
342226633Sdimvoid Driver::generateCompilationDiagnostics(Compilation &C,
343226633Sdim                                            const Command *FailingCommand) {
344234353Sdim  if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
345239462Sdim    return;
346234353Sdim
347249423Sdim  // Don't try to generate diagnostics for link or dsymutil jobs.
348249423Sdim  if (FailingCommand && (FailingCommand->getCreator().isLinkJob() ||
349249423Sdim                         FailingCommand->getCreator().isDsymutilJob()))
350234353Sdim    return;
351234353Sdim
352239462Sdim  // Print the version of the compiler.
353239462Sdim  PrintVersion(C, llvm::errs());
354239462Sdim
355226633Sdim  Diag(clang::diag::note_drv_command_failed_diag_msg)
356239462Sdim    << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
357239462Sdim    "crash backtrace, preprocessed source, and associated run script.";
358226633Sdim
359226633Sdim  // Suppress driver output and emit preprocessor output to temp file.
360226633Sdim  CCCIsCPP = true;
361226633Sdim  CCGenDiagnostics = true;
362239462Sdim  C.getArgs().AddFlagArg(0, Opts->getOption(options::OPT_frewrite_includes));
363226633Sdim
364234353Sdim  // Save the original job command(s).
365234353Sdim  std::string Cmd;
366234353Sdim  llvm::raw_string_ostream OS(Cmd);
367239462Sdim  if (FailingCommand)
368243830Sdim    C.PrintDiagnosticJob(OS, *FailingCommand);
369239462Sdim  else
370239462Sdim    // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an
371239462Sdim    // associated FailingCommand, so just pass all jobs.
372243830Sdim    C.PrintDiagnosticJob(OS, C.getJobs());
373234353Sdim  OS.flush();
374234353Sdim
375249423Sdim  // Keep track of whether we produce any errors while trying to produce
376249423Sdim  // preprocessed sources.
377249423Sdim  DiagnosticErrorTrap Trap(Diags);
378249423Sdim
379249423Sdim  // Suppress tool output.
380226633Sdim  C.initCompilationForDiagnostics();
381226633Sdim
382226633Sdim  // Construct the list of inputs.
383226633Sdim  InputList Inputs;
384226633Sdim  BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
385226633Sdim
386226633Sdim  for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
387226633Sdim    bool IgnoreInput = false;
388226633Sdim
389226633Sdim    // Ignore input from stdin or any inputs that cannot be preprocessed.
390243830Sdim    if (!strcmp(it->second->getValue(), "-")) {
391226633Sdim      Diag(clang::diag::note_drv_command_failed_diag_msg)
392226633Sdim        << "Error generating preprocessed source(s) - ignoring input from stdin"
393226633Sdim        ".";
394226633Sdim      IgnoreInput = true;
395226633Sdim    } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
396226633Sdim      IgnoreInput = true;
397226633Sdim    }
398226633Sdim
399226633Sdim    if (IgnoreInput) {
400226633Sdim      it = Inputs.erase(it);
401226633Sdim      ie = Inputs.end();
402226633Sdim    } else {
403226633Sdim      ++it;
404226633Sdim    }
405226633Sdim  }
406226633Sdim
407249423Sdim  if (Inputs.empty()) {
408249423Sdim    Diag(clang::diag::note_drv_command_failed_diag_msg)
409249423Sdim      << "Error generating preprocessed source(s) - no preprocessable inputs.";
410249423Sdim    return;
411249423Sdim  }
412249423Sdim
413226633Sdim  // Don't attempt to generate preprocessed files if multiple -arch options are
414234353Sdim  // used, unless they're all duplicates.
415234353Sdim  llvm::StringSet<> ArchNames;
416226633Sdim  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
417226633Sdim       it != ie; ++it) {
418226633Sdim    Arg *A = *it;
419226633Sdim    if (A->getOption().matches(options::OPT_arch)) {
420243830Sdim      StringRef ArchName = A->getValue();
421234353Sdim      ArchNames.insert(ArchName);
422226633Sdim    }
423226633Sdim  }
424234353Sdim  if (ArchNames.size() > 1) {
425234353Sdim    Diag(clang::diag::note_drv_command_failed_diag_msg)
426234353Sdim      << "Error generating preprocessed source(s) - cannot generate "
427234353Sdim      "preprocessed source with multiple -arch options.";
428234353Sdim    return;
429234353Sdim  }
430226633Sdim
431234353Sdim  // Construct the list of abstract actions to perform for this compilation. On
432234353Sdim  // Darwin OSes this uses the driver-driver and builds universal actions.
433234353Sdim  const ToolChain &TC = C.getDefaultToolChain();
434234353Sdim  if (TC.getTriple().isOSDarwin())
435234353Sdim    BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
436226633Sdim  else
437234353Sdim    BuildActions(TC, C.getArgs(), Inputs, C.getActions());
438226633Sdim
439226633Sdim  BuildJobs(C);
440226633Sdim
441226633Sdim  // If there were errors building the compilation, quit now.
442249423Sdim  if (Trap.hasErrorOccurred()) {
443226633Sdim    Diag(clang::diag::note_drv_command_failed_diag_msg)
444226633Sdim      << "Error generating preprocessed source(s).";
445226633Sdim    return;
446226633Sdim  }
447226633Sdim
448226633Sdim  // Generate preprocessed output.
449249423Sdim  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
450249423Sdim  C.ExecuteJob(C.getJobs(), FailingCommands);
451226633Sdim
452226633Sdim  // If the command succeeded, we are done.
453249423Sdim  if (FailingCommands.empty()) {
454226633Sdim    Diag(clang::diag::note_drv_command_failed_diag_msg)
455239462Sdim      << "\n********************\n\n"
456239462Sdim      "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
457239462Sdim      "Preprocessed source(s) and associated run script(s) are located at:";
458226633Sdim    ArgStringList Files = C.getTempFiles();
459226633Sdim    for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
460234353Sdim         it != ie; ++it) {
461226633Sdim      Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
462234353Sdim
463234353Sdim      std::string Err;
464234353Sdim      std::string Script = StringRef(*it).rsplit('.').first;
465234353Sdim      Script += ".sh";
466234353Sdim      llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
467234353Sdim                                    llvm::raw_fd_ostream::F_Excl |
468234353Sdim                                    llvm::raw_fd_ostream::F_Binary);
469234353Sdim      if (!Err.empty()) {
470234353Sdim        Diag(clang::diag::note_drv_command_failed_diag_msg)
471234353Sdim          << "Error generating run script: " + Script + " " + Err;
472234353Sdim      } else {
473239462Sdim        // Append the new filename with correct preprocessed suffix.
474239462Sdim        size_t I, E;
475239462Sdim        I = Cmd.find("-main-file-name ");
476239462Sdim        assert (I != std::string::npos && "Expected to find -main-file-name");
477239462Sdim        I += 16;
478239462Sdim        E = Cmd.find(" ", I);
479239462Sdim        assert (E != std::string::npos && "-main-file-name missing argument?");
480239462Sdim        StringRef OldFilename = StringRef(Cmd).slice(I, E);
481239462Sdim        StringRef NewFilename = llvm::sys::path::filename(*it);
482239462Sdim        I = StringRef(Cmd).rfind(OldFilename);
483239462Sdim        E = I + OldFilename.size();
484239462Sdim        I = Cmd.rfind(" ", I) + 1;
485239462Sdim        Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size());
486234353Sdim        ScriptOS << Cmd;
487234353Sdim        Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
488234353Sdim      }
489234353Sdim    }
490239462Sdim    Diag(clang::diag::note_drv_command_failed_diag_msg)
491239462Sdim      << "\n\n********************";
492226633Sdim  } else {
493226633Sdim    // Failure, remove preprocessed files.
494251662Sdim    if (!C.getArgs().hasArg(options::OPT_save_temps))
495226633Sdim      C.CleanupFileList(C.getTempFiles(), true);
496226633Sdim
497226633Sdim    Diag(clang::diag::note_drv_command_failed_diag_msg)
498226633Sdim      << "Error generating preprocessed source(s).";
499226633Sdim  }
500226633Sdim}
501226633Sdim
502226633Sdimint Driver::ExecuteCompilation(const Compilation &C,
503249423Sdim    SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands) const {
504195341Sed  // Just print if -### was present.
505195341Sed  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
506195341Sed    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
507195341Sed    return 0;
508195341Sed  }
509195341Sed
510195341Sed  // If there were errors building the compilation, quit now.
511226633Sdim  if (Diags.hasErrorOccurred())
512195341Sed    return 1;
513195341Sed
514249423Sdim  C.ExecuteJob(C.getJobs(), FailingCommands);
515198092Srdivacky
516195341Sed  // Remove temp files.
517195341Sed  C.CleanupFileList(C.getTempFiles());
518195341Sed
519208600Srdivacky  // If the command succeeded, we are done.
520249423Sdim  if (FailingCommands.empty())
521249423Sdim    return 0;
522208600Srdivacky
523249423Sdim  // Otherwise, remove result files and print extra information about abnormal
524249423Sdim  // failures.
525249423Sdim  for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it =
526249423Sdim         FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) {
527249423Sdim    int Res = it->first;
528249423Sdim    const Command *FailingCommand = it->second;
529195341Sed
530249423Sdim    // Remove result files if we're not saving temps.
531249423Sdim    if (!C.getArgs().hasArg(options::OPT_save_temps)) {
532249423Sdim      const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
533249423Sdim      C.CleanupFileMap(C.getResultFiles(), JA, true);
534234353Sdim
535249423Sdim      // Failure result files are valid unless we crashed.
536249423Sdim      if (Res < 0)
537249423Sdim        C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
538249423Sdim    }
539195341Sed
540249423Sdim    // Print extra information about abnormal failures, if possible.
541249423Sdim    //
542249423Sdim    // This is ad-hoc, but we don't want to be excessively noisy. If the result
543249423Sdim    // status was 1, assume the command failed normally. In particular, if it
544249423Sdim    // was the compiler then assume it gave a reasonable error code. Failures
545249423Sdim    // in other tools are less common, and they generally have worse
546249423Sdim    // diagnostics, so always print the diagnostic there.
547249423Sdim    const Tool &FailingTool = FailingCommand->getCreator();
548249423Sdim
549249423Sdim    if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
550249423Sdim      // FIXME: See FIXME above regarding result code interpretation.
551249423Sdim      if (Res < 0)
552249423Sdim        Diag(clang::diag::err_drv_command_signalled)
553249423Sdim          << FailingTool.getShortName();
554249423Sdim      else
555249423Sdim        Diag(clang::diag::err_drv_command_failed)
556249423Sdim          << FailingTool.getShortName() << Res;
557249423Sdim    }
558195341Sed  }
559249423Sdim  return 0;
560195341Sed}
561195341Sed
562193326Sedvoid Driver::PrintOptions(const ArgList &Args) const {
563193326Sed  unsigned i = 0;
564198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
565193326Sed       it != ie; ++it, ++i) {
566193326Sed    Arg *A = *it;
567193326Sed    llvm::errs() << "Option " << i << " - "
568243830Sdim                 << "Name: \"" << A->getOption().getPrefixedName() << "\", "
569193326Sed                 << "Values: {";
570193326Sed    for (unsigned j = 0; j < A->getNumValues(); ++j) {
571193326Sed      if (j)
572193326Sed        llvm::errs() << ", ";
573243830Sdim      llvm::errs() << '"' << A->getValue(j) << '"';
574193326Sed    }
575193326Sed    llvm::errs() << "}\n";
576193326Sed  }
577193326Sed}
578193326Sed
579193326Sedvoid Driver::PrintHelp(bool ShowHidden) const {
580204643Srdivacky  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
581243830Sdim                      /*Include*/0,
582243830Sdim                      /*Exclude*/options::NoDriverOption |
583243830Sdim                      (ShowHidden ? 0 : options::HelpHidden));
584193326Sed}
585193326Sed
586226633Sdimvoid Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
587198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
588198092Srdivacky  // know what the client would like to do.
589202879Srdivacky  OS << getClangFullVersion() << '\n';
590193326Sed  const ToolChain &TC = C.getDefaultToolChain();
591198092Srdivacky  OS << "Target: " << TC.getTripleString() << '\n';
592194613Sed
593194613Sed  // Print the threading model.
594194613Sed  //
595194613Sed  // FIXME: Implement correctly.
596198092Srdivacky  OS << "Thread model: " << "posix" << '\n';
597193326Sed}
598193326Sed
599208600Srdivacky/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
600208600Srdivacky/// option.
601226633Sdimstatic void PrintDiagnosticCategories(raw_ostream &OS) {
602223017Sdim  // Skip the empty category.
603223017Sdim  for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
604223017Sdim       i != max; ++i)
605223017Sdim    OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
606208600Srdivacky}
607208600Srdivacky
608193326Sedbool Driver::HandleImmediateArgs(const Compilation &C) {
609210299Sed  // The order these options are handled in gcc is all over the place, but we
610198092Srdivacky  // don't expect inconsistencies w.r.t. that to matter in practice.
611193326Sed
612218893Sdim  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
613218893Sdim    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
614218893Sdim    return false;
615218893Sdim  }
616218893Sdim
617193326Sed  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
618218893Sdim    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
619218893Sdim    // return an answer which matches our definition of __VERSION__.
620218893Sdim    //
621218893Sdim    // If we want to return a more correct answer some day, then we should
622218893Sdim    // introduce a non-pedantically GCC compatible mode to Clang in which we
623218893Sdim    // provide sensible definitions for -dumpversion, __VERSION__, etc.
624218893Sdim    llvm::outs() << "4.2.1\n";
625193326Sed    return false;
626193326Sed  }
627210299Sed
628208600Srdivacky  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
629208600Srdivacky    PrintDiagnosticCategories(llvm::outs());
630208600Srdivacky    return false;
631208600Srdivacky  }
632193326Sed
633239462Sdim  if (C.getArgs().hasArg(options::OPT_help) ||
634193326Sed      C.getArgs().hasArg(options::OPT__help_hidden)) {
635193326Sed    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
636193326Sed    return false;
637193326Sed  }
638193326Sed
639193326Sed  if (C.getArgs().hasArg(options::OPT__version)) {
640198092Srdivacky    // Follow gcc behavior and use stdout for --version and stderr for -v.
641198092Srdivacky    PrintVersion(C, llvm::outs());
642193326Sed    return false;
643193326Sed  }
644193326Sed
645198092Srdivacky  if (C.getArgs().hasArg(options::OPT_v) ||
646193326Sed      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
647198092Srdivacky    PrintVersion(C, llvm::errs());
648193326Sed    SuppressMissingInputWarning = true;
649193326Sed  }
650193326Sed
651193326Sed  const ToolChain &TC = C.getDefaultToolChain();
652193326Sed  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
653193326Sed    llvm::outs() << "programs: =";
654193326Sed    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
655193326Sed           ie = TC.getProgramPaths().end(); it != ie; ++it) {
656193326Sed      if (it != TC.getProgramPaths().begin())
657193326Sed        llvm::outs() << ':';
658193326Sed      llvm::outs() << *it;
659193326Sed    }
660193326Sed    llvm::outs() << "\n";
661226633Sdim    llvm::outs() << "libraries: =" << ResourceDir;
662224145Sdim
663234982Sdim    StringRef sysroot = C.getSysRoot();
664224145Sdim
665198092Srdivacky    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
666193326Sed           ie = TC.getFilePaths().end(); it != ie; ++it) {
667226633Sdim      llvm::outs() << ':';
668224145Sdim      const char *path = it->c_str();
669224145Sdim      if (path[0] == '=')
670224145Sdim        llvm::outs() << sysroot << path + 1;
671224145Sdim      else
672224145Sdim        llvm::outs() << path;
673193326Sed    }
674193326Sed    llvm::outs() << "\n";
675193326Sed    return false;
676193326Sed  }
677193326Sed
678198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
679198092Srdivacky  // know what the client would like to do.
680193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
681243830Sdim    llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
682193326Sed    return false;
683193326Sed  }
684193326Sed
685193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
686243830Sdim    llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
687193326Sed    return false;
688193326Sed  }
689193326Sed
690193326Sed  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
691198092Srdivacky    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
692193326Sed    return false;
693193326Sed  }
694193326Sed
695194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
696194613Sed    // FIXME: We need tool chain support for this.
697194613Sed    llvm::outs() << ".;\n";
698194613Sed
699194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
700194613Sed    default:
701194613Sed      break;
702198092Srdivacky
703194613Sed    case llvm::Triple::x86_64:
704194613Sed      llvm::outs() << "x86_64;@m64" << "\n";
705194613Sed      break;
706194613Sed
707194613Sed    case llvm::Triple::ppc64:
708194613Sed      llvm::outs() << "ppc64;@m64" << "\n";
709194613Sed      break;
710194613Sed    }
711194613Sed    return false;
712194613Sed  }
713194613Sed
714194613Sed  // FIXME: What is the difference between print-multi-directory and
715194613Sed  // print-multi-os-directory?
716194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
717194613Sed      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
718194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
719194613Sed    default:
720194613Sed    case llvm::Triple::x86:
721194613Sed    case llvm::Triple::ppc:
722194613Sed      llvm::outs() << "." << "\n";
723194613Sed      break;
724198092Srdivacky
725194613Sed    case llvm::Triple::x86_64:
726213492Sdim      llvm::outs() << "." << "\n";
727194613Sed      break;
728194613Sed
729194613Sed    case llvm::Triple::ppc64:
730194613Sed      llvm::outs() << "ppc64" << "\n";
731194613Sed      break;
732194613Sed    }
733194613Sed    return false;
734194613Sed  }
735194613Sed
736193326Sed  return true;
737193326Sed}
738193326Sed
739198092Srdivackystatic unsigned PrintActions1(const Compilation &C, Action *A,
740193326Sed                              std::map<Action*, unsigned> &Ids) {
741193326Sed  if (Ids.count(A))
742193326Sed    return Ids[A];
743198092Srdivacky
744193326Sed  std::string str;
745193326Sed  llvm::raw_string_ostream os(str);
746198092Srdivacky
747193326Sed  os << Action::getClassName(A->getKind()) << ", ";
748198092Srdivacky  if (InputAction *IA = dyn_cast<InputAction>(A)) {
749243830Sdim    os << "\"" << IA->getInputArg().getValue() << "\"";
750193326Sed  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
751239462Sdim    os << '"' << BIA->getArchName() << '"'
752193326Sed       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
753193326Sed  } else {
754193326Sed    os << "{";
755193326Sed    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
756193326Sed      os << PrintActions1(C, *it, Ids);
757193326Sed      ++it;
758193326Sed      if (it != ie)
759193326Sed        os << ", ";
760193326Sed    }
761193326Sed    os << "}";
762193326Sed  }
763193326Sed
764193326Sed  unsigned Id = Ids.size();
765193326Sed  Ids[A] = Id;
766198092Srdivacky  llvm::errs() << Id << ": " << os.str() << ", "
767193326Sed               << types::getTypeName(A->getType()) << "\n";
768193326Sed
769193326Sed  return Id;
770193326Sed}
771193326Sed
772193326Sedvoid Driver::PrintActions(const Compilation &C) const {
773193326Sed  std::map<Action*, unsigned> Ids;
774198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
775193326Sed         ie = C.getActions().end(); it != ie; ++it)
776193326Sed    PrintActions1(C, *it, Ids);
777193326Sed}
778193326Sed
779223017Sdim/// \brief Check whether the given input tree contains any compilation or
780223017Sdim/// assembly actions.
781223017Sdimstatic bool ContainsCompileOrAssembleAction(const Action *A) {
782210299Sed  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
783210299Sed    return true;
784210299Sed
785210299Sed  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
786223017Sdim    if (ContainsCompileOrAssembleAction(*it))
787210299Sed      return true;
788210299Sed
789210299Sed  return false;
790210299Sed}
791210299Sed
792212904Sdimvoid Driver::BuildUniversalActions(const ToolChain &TC,
793221345Sdim                                   const DerivedArgList &Args,
794226633Sdim                                   const InputList &BAInputs,
795193326Sed                                   ActionList &Actions) const {
796198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
797198092Srdivacky  // Collect the list of architectures. Duplicates are allowed, but should only
798198092Srdivacky  // be handled once (in the order seen).
799193326Sed  llvm::StringSet<> ArchNames;
800226633Sdim  SmallVector<const char *, 4> Archs;
801198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
802193326Sed       it != ie; ++it) {
803193326Sed    Arg *A = *it;
804193326Sed
805199512Srdivacky    if (A->getOption().matches(options::OPT_arch)) {
806198092Srdivacky      // Validate the option here; we don't save the type here because its
807198092Srdivacky      // particular spelling may participate in other driver choices.
808198092Srdivacky      llvm::Triple::ArchType Arch =
809243830Sdim        tools::darwin::getArchTypeForDarwinArchName(A->getValue());
810198092Srdivacky      if (Arch == llvm::Triple::UnknownArch) {
811198092Srdivacky        Diag(clang::diag::err_drv_invalid_arch_name)
812198092Srdivacky          << A->getAsString(Args);
813198092Srdivacky        continue;
814198092Srdivacky      }
815193326Sed
816193326Sed      A->claim();
817243830Sdim      if (ArchNames.insert(A->getValue()))
818243830Sdim        Archs.push_back(A->getValue());
819193326Sed    }
820193326Sed  }
821193326Sed
822198092Srdivacky  // When there is no explicit arch for this platform, make sure we still bind
823198092Srdivacky  // the architecture (to the default) so that -Xarch_ is handled correctly.
824193326Sed  if (!Archs.size())
825243830Sdim    Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
826193326Sed
827193326Sed  ActionList SingleActions;
828226633Sdim  BuildActions(TC, Args, BAInputs, SingleActions);
829193326Sed
830210299Sed  // Add in arch bindings for every top level action, as well as lipo and
831210299Sed  // dsymutil steps if needed.
832193326Sed  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
833193326Sed    Action *Act = SingleActions[i];
834193326Sed
835198092Srdivacky    // Make sure we can lipo this kind of output. If not (and it is an actual
836198092Srdivacky    // output) then we disallow, since we can't create an output file with the
837198092Srdivacky    // right name without overwriting it. We could remove this oddity by just
838198092Srdivacky    // changing the output names to include the arch, which would also fix
839193326Sed    // -save-temps. Compatibility wins for now.
840193326Sed
841193326Sed    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
842193326Sed      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
843193326Sed        << types::getTypeName(Act->getType());
844193326Sed
845193326Sed    ActionList Inputs;
846205219Srdivacky    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
847193326Sed      Inputs.push_back(new BindArchAction(Act, Archs[i]));
848205219Srdivacky      if (i != 0)
849205219Srdivacky        Inputs.back()->setOwnsInputs(false);
850205219Srdivacky    }
851193326Sed
852198092Srdivacky    // Lipo if necessary, we do it this way because we need to set the arch flag
853198092Srdivacky    // so that -Xarch_ gets overwritten.
854193326Sed    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
855193326Sed      Actions.append(Inputs.begin(), Inputs.end());
856193326Sed    else
857193326Sed      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
858210299Sed
859234353Sdim    // Handle debug info queries.
860234353Sdim    Arg *A = Args.getLastArg(options::OPT_g_Group);
861234982Sdim    if (A && !A->getOption().matches(options::OPT_g0) &&
862234982Sdim        !A->getOption().matches(options::OPT_gstabs) &&
863234982Sdim        ContainsCompileOrAssembleAction(Actions.back())) {
864239462Sdim
865234982Sdim      // Add a 'dsymutil' step if necessary, when debug info is enabled and we
866234982Sdim      // have a compile input. We need to run 'dsymutil' ourselves in such cases
867249423Sdim      // because the debug info will refer to a temporary object file which
868234982Sdim      // will be removed at the end of the compilation process.
869234982Sdim      if (Act->getType() == types::TY_Image) {
870234982Sdim        ActionList Inputs;
871234982Sdim        Inputs.push_back(Actions.back());
872234982Sdim        Actions.pop_back();
873234982Sdim        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
874234982Sdim      }
875210299Sed
876234982Sdim      // Verify the output (debug information only) if we passed '-verify'.
877234982Sdim      if (Args.hasArg(options::OPT_verify)) {
878234982Sdim        ActionList VerifyInputs;
879234982Sdim        VerifyInputs.push_back(Actions.back());
880234982Sdim        Actions.pop_back();
881234982Sdim        Actions.push_back(new VerifyJobAction(VerifyInputs,
882234982Sdim                                              types::TY_Nothing));
883210299Sed      }
884234982Sdim    }
885193326Sed  }
886193326Sed}
887193326Sed
888226633Sdim// Construct a the list of inputs and their types.
889226633Sdimvoid Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
890226633Sdim                         InputList &Inputs) const {
891198092Srdivacky  // Track the current user specified (-x) input. We also explicitly track the
892198092Srdivacky  // argument used to set the type; we only want to claim the type when we
893198092Srdivacky  // actually use it, so we warn about unused -x arguments.
894193326Sed  types::ID InputType = types::TY_Nothing;
895193326Sed  Arg *InputTypeArg = 0;
896193326Sed
897198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
898193326Sed       it != ie; ++it) {
899193326Sed    Arg *A = *it;
900193326Sed
901243830Sdim    if (A->getOption().getKind() == Option::InputClass) {
902243830Sdim      const char *Value = A->getValue();
903193326Sed      types::ID Ty = types::TY_INVALID;
904193326Sed
905193326Sed      // Infer the input type if necessary.
906193326Sed      if (InputType == types::TY_Nothing) {
907193326Sed        // If there was an explicit arg for this, claim it.
908193326Sed        if (InputTypeArg)
909193326Sed          InputTypeArg->claim();
910193326Sed
911193326Sed        // stdin must be handled specially.
912193326Sed        if (memcmp(Value, "-", 2) == 0) {
913198092Srdivacky          // If running with -E, treat as a C input (this changes the builtin
914198092Srdivacky          // macros, for example). This may be overridden by -ObjC below.
915193326Sed          //
916198092Srdivacky          // Otherwise emit an error but still use a valid type to avoid
917198092Srdivacky          // spurious errors (e.g., no inputs).
918221345Sdim          if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
919193326Sed            Diag(clang::diag::err_drv_unknown_stdin_type);
920193326Sed          Ty = types::TY_C;
921193326Sed        } else {
922221345Sdim          // Otherwise lookup by extension.
923221345Sdim          // Fallback is C if invoked as C preprocessor or Object otherwise.
924221345Sdim          // We use a host hook here because Darwin at least has its own
925198092Srdivacky          // idea of what .s is.
926193326Sed          if (const char *Ext = strrchr(Value, '.'))
927212904Sdim            Ty = TC.LookupTypeForExtension(Ext + 1);
928193326Sed
929221345Sdim          if (Ty == types::TY_INVALID) {
930221345Sdim            if (CCCIsCPP)
931221345Sdim              Ty = types::TY_C;
932221345Sdim            else
933221345Sdim              Ty = types::TY_Object;
934221345Sdim          }
935204643Srdivacky
936204643Srdivacky          // If the driver is invoked as C++ compiler (like clang++ or c++) it
937204643Srdivacky          // should autodetect some input files as C++ for g++ compatibility.
938204643Srdivacky          if (CCCIsCXX) {
939204643Srdivacky            types::ID OldTy = Ty;
940204643Srdivacky            Ty = types::lookupCXXTypeForCType(Ty);
941204643Srdivacky
942204643Srdivacky            if (Ty != OldTy)
943204643Srdivacky              Diag(clang::diag::warn_drv_treating_input_as_cxx)
944204643Srdivacky                << getTypeName(OldTy) << getTypeName(Ty);
945204643Srdivacky          }
946193326Sed        }
947193326Sed
948193326Sed        // -ObjC and -ObjC++ override the default language, but only for "source
949193326Sed        // files". We just treat everything that isn't a linker input as a
950193326Sed        // source file.
951198092Srdivacky        //
952193326Sed        // FIXME: Clean this up if we move the phase sequence into the type.
953193326Sed        if (Ty != types::TY_Object) {
954193326Sed          if (Args.hasArg(options::OPT_ObjC))
955193326Sed            Ty = types::TY_ObjC;
956193326Sed          else if (Args.hasArg(options::OPT_ObjCXX))
957193326Sed            Ty = types::TY_ObjCXX;
958193326Sed        }
959193326Sed      } else {
960193326Sed        assert(InputTypeArg && "InputType set w/o InputTypeArg");
961193326Sed        InputTypeArg->claim();
962193326Sed        Ty = InputType;
963193326Sed      }
964193326Sed
965203955Srdivacky      // Check that the file exists, if enabled.
966218893Sdim      if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
967234353Sdim        SmallString<64> Path(Value);
968234353Sdim        if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
969243830Sdim          if (!llvm::sys::path::is_absolute(Path.str())) {
970243830Sdim            SmallString<64> Directory(WorkDir->getValue());
971234353Sdim            llvm::sys::path::append(Directory, Value);
972234353Sdim            Path.assign(Directory);
973218893Sdim          }
974234353Sdim        }
975218893Sdim
976218893Sdim        bool exists = false;
977234353Sdim        if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
978218893Sdim          Diag(clang::diag::err_drv_no_such_file) << Path.str();
979218893Sdim        else
980218893Sdim          Inputs.push_back(std::make_pair(Ty, A));
981218893Sdim      } else
982193326Sed        Inputs.push_back(std::make_pair(Ty, A));
983193326Sed
984243830Sdim    } else if (A->getOption().hasFlag(options::LinkerInput)) {
985198092Srdivacky      // Just treat as object type, we could make a special type for this if
986198092Srdivacky      // necessary.
987193326Sed      Inputs.push_back(std::make_pair(types::TY_Object, A));
988193326Sed
989199512Srdivacky    } else if (A->getOption().matches(options::OPT_x)) {
990198092Srdivacky      InputTypeArg = A;
991243830Sdim      InputType = types::lookupTypeForTypeSpecifier(A->getValue());
992234353Sdim      A->claim();
993193326Sed
994193326Sed      // Follow gcc behavior and treat as linker input for invalid -x
995198092Srdivacky      // options. Its not clear why we shouldn't just revert to unknown; but
996218893Sdim      // this isn't very important, we might as well be bug compatible.
997193326Sed      if (!InputType) {
998243830Sdim        Diag(clang::diag::err_drv_unknown_language) << A->getValue();
999193326Sed        InputType = types::TY_Object;
1000193326Sed      }
1001193326Sed    }
1002193326Sed  }
1003221345Sdim  if (CCCIsCPP && Inputs.empty()) {
1004221345Sdim    // If called as standalone preprocessor, stdin is processed
1005221345Sdim    // if no other input is present.
1006221345Sdim    unsigned Index = Args.getBaseArgs().MakeIndex("-");
1007221345Sdim    Arg *A = Opts->ParseOneArg(Args, Index);
1008221345Sdim    A->claim();
1009221345Sdim    Inputs.push_back(std::make_pair(types::TY_C, A));
1010221345Sdim  }
1011226633Sdim}
1012221345Sdim
1013226633Sdimvoid Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
1014226633Sdim                          const InputList &Inputs, ActionList &Actions) const {
1015226633Sdim  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1016226633Sdim
1017193326Sed  if (!SuppressMissingInputWarning && Inputs.empty()) {
1018193326Sed    Diag(clang::diag::err_drv_no_input_files);
1019193326Sed    return;
1020193326Sed  }
1021193326Sed
1022226633Sdim  Arg *FinalPhaseArg;
1023226633Sdim  phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1024193326Sed
1025198092Srdivacky  // Reject -Z* at the top level, these options should never have been exposed
1026198092Srdivacky  // by gcc.
1027193326Sed  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1028193326Sed    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1029193326Sed
1030193326Sed  // Construct the actions to perform.
1031193326Sed  ActionList LinkerInputs;
1032249423Sdim  ActionList SplitInputs;
1033249423Sdim  llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
1034193326Sed  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1035193326Sed    types::ID InputType = Inputs[i].first;
1036193326Sed    const Arg *InputArg = Inputs[i].second;
1037193326Sed
1038249423Sdim    PL.clear();
1039249423Sdim    types::getCompilationPhases(InputType, PL);
1040193326Sed
1041198092Srdivacky    // If the first step comes after the final phase we are doing as part of
1042198092Srdivacky    // this compilation, warn the user about it.
1043249423Sdim    phases::ID InitialPhase = PL[0];
1044193326Sed    if (InitialPhase > FinalPhase) {
1045193326Sed      // Claim here to avoid the more general unused warning.
1046193326Sed      InputArg->claim();
1047198092Srdivacky
1048221345Sdim      // Suppress all unused style warnings with -Qunused-arguments
1049221345Sdim      if (Args.hasArg(options::OPT_Qunused_arguments))
1050221345Sdim        continue;
1051221345Sdim
1052239462Sdim      // Special case when final phase determined by binary name, rather than
1053239462Sdim      // by a command-line argument with a corresponding Arg.
1054239462Sdim      if (CCCIsCPP)
1055239462Sdim        Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1056239462Sdim          << InputArg->getAsString(Args)
1057239462Sdim          << getPhaseName(InitialPhase);
1058198092Srdivacky      // Special case '-E' warning on a previously preprocessed file to make
1059198092Srdivacky      // more sense.
1060239462Sdim      else if (InitialPhase == phases::Compile &&
1061239462Sdim               FinalPhase == phases::Preprocess &&
1062239462Sdim               getPreprocessedType(InputType) == types::TY_INVALID)
1063198092Srdivacky        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1064198092Srdivacky          << InputArg->getAsString(Args)
1065239462Sdim          << !!FinalPhaseArg
1066239462Sdim          << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "";
1067198092Srdivacky      else
1068198092Srdivacky        Diag(clang::diag::warn_drv_input_file_unused)
1069198092Srdivacky          << InputArg->getAsString(Args)
1070198092Srdivacky          << getPhaseName(InitialPhase)
1071239462Sdim          << !!FinalPhaseArg
1072239462Sdim          << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "";
1073193326Sed      continue;
1074193326Sed    }
1075198092Srdivacky
1076193326Sed    // Build the pipeline for this file.
1077234353Sdim    OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
1078249423Sdim    for (llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases>::iterator
1079249423Sdim           i = PL.begin(), e = PL.end(); i != e; ++i) {
1080249423Sdim      phases::ID Phase = *i;
1081193326Sed
1082193326Sed      // We are done if this step is past what the user requested.
1083193326Sed      if (Phase > FinalPhase)
1084193326Sed        break;
1085193326Sed
1086193326Sed      // Queue linker inputs.
1087193326Sed      if (Phase == phases::Link) {
1088249423Sdim        assert((i + 1) == e && "linking must be final compilation step.");
1089202879Srdivacky        LinkerInputs.push_back(Current.take());
1090193326Sed        break;
1091193326Sed      }
1092193326Sed
1093198092Srdivacky      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1094198092Srdivacky      // encode this in the steps because the intermediate type depends on
1095198092Srdivacky      // arguments. Just special case here.
1096193326Sed      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1097193326Sed        continue;
1098193326Sed
1099193326Sed      // Otherwise construct the appropriate action.
1100202879Srdivacky      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
1101193326Sed      if (Current->getType() == types::TY_Nothing)
1102193326Sed        break;
1103193326Sed    }
1104193326Sed
1105193326Sed    // If we ended with something, add to the output list.
1106193326Sed    if (Current)
1107202879Srdivacky      Actions.push_back(Current.take());
1108193326Sed  }
1109193326Sed
1110193326Sed  // Add a link action if necessary.
1111193326Sed  if (!LinkerInputs.empty())
1112193326Sed    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1113201361Srdivacky
1114201361Srdivacky  // If we are linking, claim any options which are obviously only used for
1115201361Srdivacky  // compilation.
1116249423Sdim  if (FinalPhase == phases::Link && PL.size() == 1)
1117201361Srdivacky    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1118193326Sed}
1119193326Sed
1120193326SedAction *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
1121193326Sed                                     Action *Input) const {
1122193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1123193326Sed  // Build the appropriate action.
1124193326Sed  switch (Phase) {
1125226633Sdim  case phases::Link: llvm_unreachable("link action invalid here.");
1126193326Sed  case phases::Preprocess: {
1127193326Sed    types::ID OutputTy;
1128193326Sed    // -{M, MM} alter the output type.
1129218893Sdim    if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1130193326Sed      OutputTy = types::TY_Dependencies;
1131193326Sed    } else {
1132239462Sdim      OutputTy = Input->getType();
1133239462Sdim      if (!Args.hasFlag(options::OPT_frewrite_includes,
1134239462Sdim                        options::OPT_fno_rewrite_includes, false))
1135239462Sdim        OutputTy = types::getPreprocessedType(OutputTy);
1136193326Sed      assert(OutputTy != types::TY_INVALID &&
1137193326Sed             "Cannot preprocess this input type!");
1138193326Sed    }
1139193326Sed    return new PreprocessJobAction(Input, OutputTy);
1140193326Sed  }
1141239462Sdim  case phases::Precompile: {
1142239462Sdim    types::ID OutputTy = types::TY_PCH;
1143239462Sdim    if (Args.hasArg(options::OPT_fsyntax_only)) {
1144239462Sdim      // Syntax checks should not emit a PCH file
1145239462Sdim      OutputTy = types::TY_Nothing;
1146239462Sdim    }
1147239462Sdim    return new PrecompileJobAction(Input, OutputTy);
1148239462Sdim  }
1149193326Sed  case phases::Compile: {
1150193326Sed    if (Args.hasArg(options::OPT_fsyntax_only)) {
1151193326Sed      return new CompileJobAction(Input, types::TY_Nothing);
1152203955Srdivacky    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
1153203955Srdivacky      return new CompileJobAction(Input, types::TY_RewrittenObjC);
1154234353Sdim    } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
1155234353Sdim      return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
1156193326Sed    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
1157193326Sed      return new AnalyzeJobAction(Input, types::TY_Plist);
1158234353Sdim    } else if (Args.hasArg(options::OPT__migrate)) {
1159234353Sdim      return new MigrateJobAction(Input, types::TY_Remap);
1160198092Srdivacky    } else if (Args.hasArg(options::OPT_emit_ast)) {
1161198092Srdivacky      return new CompileJobAction(Input, types::TY_AST);
1162249423Sdim    } else if (Args.hasArg(options::OPT_module_file_info)) {
1163249423Sdim      return new CompileJobAction(Input, types::TY_ModuleFile);
1164224145Sdim    } else if (IsUsingLTO(Args)) {
1165198092Srdivacky      types::ID Output =
1166210299Sed        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1167193326Sed      return new CompileJobAction(Input, Output);
1168193326Sed    } else {
1169193326Sed      return new CompileJobAction(Input, types::TY_PP_Asm);
1170193326Sed    }
1171193326Sed  }
1172193326Sed  case phases::Assemble:
1173193326Sed    return new AssembleJobAction(Input, types::TY_Object);
1174193326Sed  }
1175193326Sed
1176226633Sdim  llvm_unreachable("invalid phase in ConstructPhaseAction");
1177193326Sed}
1178193326Sed
1179224145Sdimbool Driver::IsUsingLTO(const ArgList &Args) const {
1180224145Sdim  // Check for -emit-llvm or -flto.
1181224145Sdim  if (Args.hasArg(options::OPT_emit_llvm) ||
1182224145Sdim      Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
1183224145Sdim    return true;
1184224145Sdim
1185224145Sdim  // Check for -O4.
1186224145Sdim  if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
1187224145Sdim      return A->getOption().matches(options::OPT_O4);
1188224145Sdim
1189224145Sdim  return false;
1190224145Sdim}
1191224145Sdim
1192193326Sedvoid Driver::BuildJobs(Compilation &C) const {
1193193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1194193326Sed
1195193326Sed  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1196193326Sed
1197198092Srdivacky  // It is an error to provide a -o option if we are making multiple output
1198198092Srdivacky  // files.
1199193326Sed  if (FinalOutput) {
1200193326Sed    unsigned NumOutputs = 0;
1201198092Srdivacky    for (ActionList::const_iterator it = C.getActions().begin(),
1202193326Sed           ie = C.getActions().end(); it != ie; ++it)
1203193326Sed      if ((*it)->getType() != types::TY_Nothing)
1204193326Sed        ++NumOutputs;
1205198092Srdivacky
1206193326Sed    if (NumOutputs > 1) {
1207193326Sed      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1208193326Sed      FinalOutput = 0;
1209193326Sed    }
1210193326Sed  }
1211193326Sed
1212251662Sdim  // Collect the list of architectures.
1213251662Sdim  llvm::StringSet<> ArchNames;
1214251662Sdim  if (C.getDefaultToolChain().getTriple().isOSDarwin()) {
1215251662Sdim    for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1216251662Sdim         it != ie; ++it) {
1217251662Sdim      Arg *A = *it;
1218251662Sdim      if (A->getOption().matches(options::OPT_arch))
1219251662Sdim        ArchNames.insert(A->getValue());
1220251662Sdim    }
1221251662Sdim  }
1222251662Sdim
1223198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
1224193326Sed         ie = C.getActions().end(); it != ie; ++it) {
1225193326Sed    Action *A = *it;
1226193326Sed
1227198092Srdivacky    // If we are linking an image for multiple archs then the linker wants
1228198092Srdivacky    // -arch_multiple and -final_output <final image name>. Unfortunately, this
1229198092Srdivacky    // doesn't fit in cleanly because we have to pass this information down.
1230193326Sed    //
1231198092Srdivacky    // FIXME: This is a hack; find a cleaner way to integrate this into the
1232198092Srdivacky    // process.
1233193326Sed    const char *LinkingOutput = 0;
1234193326Sed    if (isa<LipoJobAction>(A)) {
1235193326Sed      if (FinalOutput)
1236243830Sdim        LinkingOutput = FinalOutput->getValue();
1237193326Sed      else
1238193326Sed        LinkingOutput = DefaultImageName.c_str();
1239193326Sed    }
1240193326Sed
1241193326Sed    InputInfo II;
1242198092Srdivacky    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1243198092Srdivacky                       /*BoundArch*/0,
1244193326Sed                       /*AtTopLevel*/ true,
1245251662Sdim                       /*MultipleArchs*/ ArchNames.size() > 1,
1246193326Sed                       /*LinkingOutput*/ LinkingOutput,
1247193326Sed                       II);
1248193326Sed  }
1249193326Sed
1250198092Srdivacky  // If the user passed -Qunused-arguments or there were errors, don't warn
1251198092Srdivacky  // about any unused arguments.
1252218893Sdim  if (Diags.hasErrorOccurred() ||
1253193326Sed      C.getArgs().hasArg(options::OPT_Qunused_arguments))
1254193326Sed    return;
1255193326Sed
1256193326Sed  // Claim -### here.
1257193326Sed  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1258198092Srdivacky
1259193326Sed  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1260193326Sed       it != ie; ++it) {
1261193326Sed    Arg *A = *it;
1262198092Srdivacky
1263193326Sed    // FIXME: It would be nice to be able to send the argument to the
1264226633Sdim    // DiagnosticsEngine, so that extra values, position, and so on could be
1265226633Sdim    // printed.
1266193326Sed    if (!A->isClaimed()) {
1267243830Sdim      if (A->getOption().hasFlag(options::NoArgumentUnused))
1268193326Sed        continue;
1269193326Sed
1270198092Srdivacky      // Suppress the warning automatically if this is just a flag, and it is an
1271198092Srdivacky      // instance of an argument we already claimed.
1272193326Sed      const Option &Opt = A->getOption();
1273243830Sdim      if (Opt.getKind() == Option::FlagClass) {
1274193326Sed        bool DuplicateClaimed = false;
1275193326Sed
1276199990Srdivacky        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1277199990Srdivacky               ie = C.getArgs().filtered_end(); it != ie; ++it) {
1278199990Srdivacky          if ((*it)->isClaimed()) {
1279193326Sed            DuplicateClaimed = true;
1280193326Sed            break;
1281193326Sed          }
1282193326Sed        }
1283193326Sed
1284193326Sed        if (DuplicateClaimed)
1285193326Sed          continue;
1286193326Sed      }
1287193326Sed
1288198092Srdivacky      Diag(clang::diag::warn_drv_unused_argument)
1289193326Sed        << A->getAsString(C.getArgs());
1290193326Sed    }
1291193326Sed  }
1292193326Sed}
1293193326Sed
1294249423Sdimstatic const Tool *SelectToolForJob(Compilation &C, const ToolChain *TC,
1295203955Srdivacky                                    const JobAction *JA,
1296203955Srdivacky                                    const ActionList *&Inputs) {
1297203955Srdivacky  const Tool *ToolForJob = 0;
1298203955Srdivacky
1299203955Srdivacky  // See if we should look for a compiler with an integrated assembler. We match
1300203955Srdivacky  // bottom up, so what we are actually looking for is an assembler job with a
1301203955Srdivacky  // compiler input.
1302208600Srdivacky
1303249423Sdim  if (TC->useIntegratedAs() &&
1304203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1305203955Srdivacky      isa<AssembleJobAction>(JA) &&
1306203955Srdivacky      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1307249423Sdim    const Tool *Compiler =
1308249423Sdim      TC->SelectTool(cast<JobAction>(**Inputs->begin()));
1309249423Sdim    if (!Compiler)
1310249423Sdim      return NULL;
1311249423Sdim    if (Compiler->hasIntegratedAssembler()) {
1312203955Srdivacky      Inputs = &(*Inputs)[0]->getInputs();
1313249423Sdim      ToolForJob = Compiler;
1314203955Srdivacky    }
1315203955Srdivacky  }
1316203955Srdivacky
1317203955Srdivacky  // Otherwise use the tool for the current job.
1318203955Srdivacky  if (!ToolForJob)
1319249423Sdim    ToolForJob = TC->SelectTool(*JA);
1320203955Srdivacky
1321203955Srdivacky  // See if we should use an integrated preprocessor. We do so when we have
1322203955Srdivacky  // exactly one input, since this is the only use case we care about
1323203955Srdivacky  // (irrelevant since we don't support combine yet).
1324203955Srdivacky  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1325203955Srdivacky      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1326203955Srdivacky      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1327203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1328243830Sdim      !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
1329203955Srdivacky      ToolForJob->hasIntegratedCPP())
1330203955Srdivacky    Inputs = &(*Inputs)[0]->getInputs();
1331203955Srdivacky
1332249423Sdim  return ToolForJob;
1333203955Srdivacky}
1334203955Srdivacky
1335193326Sedvoid Driver::BuildJobsForAction(Compilation &C,
1336193326Sed                                const Action *A,
1337193326Sed                                const ToolChain *TC,
1338198092Srdivacky                                const char *BoundArch,
1339193326Sed                                bool AtTopLevel,
1340251662Sdim                                bool MultipleArchs,
1341193326Sed                                const char *LinkingOutput,
1342193326Sed                                InputInfo &Result) const {
1343198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1344193326Sed
1345193326Sed  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1346198092Srdivacky    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1347198092Srdivacky    // just using Args was better?
1348193326Sed    const Arg &Input = IA->getInputArg();
1349193326Sed    Input.claim();
1350210299Sed    if (Input.getOption().matches(options::OPT_INPUT)) {
1351243830Sdim      const char *Name = Input.getValue();
1352193326Sed      Result = InputInfo(Name, A->getType(), Name);
1353193326Sed    } else
1354193326Sed      Result = InputInfo(&Input, A->getType(), "");
1355193326Sed    return;
1356193326Sed  }
1357193326Sed
1358193326Sed  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1359239462Sdim    const ToolChain *TC;
1360239462Sdim    const char *ArchName = BAA->getArchName();
1361198092Srdivacky
1362239462Sdim    if (ArchName)
1363239462Sdim      TC = &getToolChain(C.getArgs(), ArchName);
1364239462Sdim    else
1365239462Sdim      TC = &C.getDefaultToolChain();
1366198092Srdivacky
1367198092Srdivacky    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1368251662Sdim                       AtTopLevel, MultipleArchs, LinkingOutput, Result);
1369193326Sed    return;
1370193326Sed  }
1371193326Sed
1372203955Srdivacky  const ActionList *Inputs = &A->getInputs();
1373203955Srdivacky
1374193326Sed  const JobAction *JA = cast<JobAction>(A);
1375249423Sdim  const Tool *T = SelectToolForJob(C, TC, JA, Inputs);
1376249423Sdim  if (!T)
1377249423Sdim    return;
1378198092Srdivacky
1379193326Sed  // Only use pipes when there is exactly one input.
1380193326Sed  InputInfoList InputInfos;
1381193326Sed  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1382193326Sed       it != ie; ++it) {
1383249423Sdim    // Treat dsymutil and verify sub-jobs as being at the top-level too, they
1384249423Sdim    // shouldn't get temporary output names.
1385210299Sed    // FIXME: Clean this up.
1386210299Sed    bool SubJobAtTopLevel = false;
1387249423Sdim    if (AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)))
1388210299Sed      SubJobAtTopLevel = true;
1389210299Sed
1390193326Sed    InputInfo II;
1391251662Sdim    BuildJobsForAction(C, *it, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
1392251662Sdim                       LinkingOutput, II);
1393193326Sed    InputInfos.push_back(II);
1394193326Sed  }
1395193326Sed
1396193326Sed  // Always use the first input as the base input.
1397193326Sed  const char *BaseInput = InputInfos[0].getBaseInput();
1398193326Sed
1399210299Sed  // ... except dsymutil actions, which use their actual input as the base
1400210299Sed  // input.
1401210299Sed  if (JA->getType() == types::TY_dSYM)
1402210299Sed    BaseInput = InputInfos[0].getFilename();
1403210299Sed
1404212904Sdim  // Determine the place to write output to, if any.
1405249423Sdim  if (JA->getType() == types::TY_Nothing)
1406193326Sed    Result = InputInfo(A->getType(), BaseInput);
1407249423Sdim  else
1408251662Sdim    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
1409251662Sdim                                          AtTopLevel, MultipleArchs),
1410193326Sed                       A->getType(), BaseInput);
1411193326Sed
1412226633Sdim  if (CCCPrintBindings && !CCGenDiagnostics) {
1413249423Sdim    llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
1414249423Sdim                 << " - \"" << T->getName() << "\", inputs: [";
1415193326Sed    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1416193326Sed      llvm::errs() << InputInfos[i].getAsString();
1417193326Sed      if (i + 1 != e)
1418193326Sed        llvm::errs() << ", ";
1419193326Sed    }
1420193326Sed    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1421193326Sed  } else {
1422249423Sdim    T->ConstructJob(C, *JA, Result, InputInfos,
1423249423Sdim                    C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1424193326Sed  }
1425193326Sed}
1426193326Sed
1427198092Srdivackyconst char *Driver::GetNamedOutputPath(Compilation &C,
1428193326Sed                                       const JobAction &JA,
1429193326Sed                                       const char *BaseInput,
1430251662Sdim                                       const char *BoundArch,
1431251662Sdim                                       bool AtTopLevel,
1432251662Sdim                                       bool MultipleArchs) const {
1433193326Sed  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1434193326Sed  // Output to a user requested destination?
1435226633Sdim  if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
1436226633Sdim      !isa<VerifyJobAction>(JA)) {
1437193326Sed    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1438249423Sdim      return C.addResultFile(FinalOutput->getValue(), &JA);
1439193326Sed  }
1440193326Sed
1441212904Sdim  // Default to writing to stdout?
1442249423Sdim  if (AtTopLevel && !CCGenDiagnostics &&
1443249423Sdim      (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
1444212904Sdim    return "-";
1445212904Sdim
1446193326Sed  // Output to a temporary file?
1447226633Sdim  if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
1448226633Sdim      CCGenDiagnostics) {
1449226633Sdim    StringRef Name = llvm::sys::path::filename(BaseInput);
1450226633Sdim    std::pair<StringRef, StringRef> Split = Name.split('.');
1451198092Srdivacky    std::string TmpName =
1452226633Sdim      GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
1453193326Sed    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1454193326Sed  }
1455193326Sed
1456234353Sdim  SmallString<128> BasePath(BaseInput);
1457226633Sdim  StringRef BaseName;
1458193326Sed
1459221345Sdim  // Dsymutil actions should use the full path.
1460226633Sdim  if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
1461221345Sdim    BaseName = BasePath;
1462221345Sdim  else
1463221345Sdim    BaseName = llvm::sys::path::filename(BasePath);
1464221345Sdim
1465193326Sed  // Determine what the derived output name should be.
1466193326Sed  const char *NamedOutput;
1467251662Sdim  if (JA.getType() == types::TY_Image) {
1468251662Sdim    if (MultipleArchs && BoundArch) {
1469251662Sdim      SmallString<128> Output(DefaultImageName.c_str());
1470251662Sdim      Output += "-";
1471251662Sdim      Output.append(BoundArch);
1472251662Sdim      NamedOutput = C.getArgs().MakeArgString(Output.c_str());
1473251662Sdim    } else
1474251662Sdim      NamedOutput = DefaultImageName.c_str();
1475193326Sed  } else {
1476193326Sed    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1477193326Sed    assert(Suffix && "All types used for output should have a suffix.");
1478193326Sed
1479193326Sed    std::string::size_type End = std::string::npos;
1480193326Sed    if (!types::appendSuffixForType(JA.getType()))
1481193326Sed      End = BaseName.rfind('.');
1482251662Sdim    SmallString<128> Suffixed(BaseName.substr(0, End));
1483251662Sdim    if (MultipleArchs && BoundArch) {
1484251662Sdim      Suffixed += "-";
1485251662Sdim      Suffixed.append(BoundArch);
1486251662Sdim    }
1487193326Sed    Suffixed += '.';
1488193326Sed    Suffixed += Suffix;
1489193326Sed    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1490193326Sed  }
1491193326Sed
1492239462Sdim  // If we're saving temps and the temp file conflicts with the input file,
1493239462Sdim  // then avoid overwriting input file.
1494224145Sdim  if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
1495226633Sdim      NamedOutput == BaseName) {
1496239462Sdim
1497239462Sdim    bool SameFile = false;
1498239462Sdim    SmallString<256> Result;
1499239462Sdim    llvm::sys::fs::current_path(Result);
1500239462Sdim    llvm::sys::path::append(Result, BaseName);
1501239462Sdim    llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
1502239462Sdim    // Must share the same path to conflict.
1503239462Sdim    if (SameFile) {
1504239462Sdim      StringRef Name = llvm::sys::path::filename(BaseInput);
1505239462Sdim      std::pair<StringRef, StringRef> Split = Name.split('.');
1506239462Sdim      std::string TmpName =
1507239462Sdim        GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
1508239462Sdim      return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1509239462Sdim    }
1510224145Sdim  }
1511224145Sdim
1512198092Srdivacky  // As an annoying special case, PCH generation doesn't strip the pathname.
1513193326Sed  if (JA.getType() == types::TY_PCH) {
1514218893Sdim    llvm::sys::path::remove_filename(BasePath);
1515218893Sdim    if (BasePath.empty())
1516193326Sed      BasePath = NamedOutput;
1517193326Sed    else
1518218893Sdim      llvm::sys::path::append(BasePath, NamedOutput);
1519249423Sdim    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
1520193326Sed  } else {
1521249423Sdim    return C.addResultFile(NamedOutput, &JA);
1522193326Sed  }
1523193326Sed}
1524193326Sed
1525198092Srdivackystd::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1526206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1527243830Sdim  // attempting to use this prefix when looking for file paths.
1528218893Sdim  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1529218893Sdim       ie = PrefixDirs.end(); it != ie; ++it) {
1530221345Sdim    std::string Dir(*it);
1531221345Sdim    if (Dir.empty())
1532221345Sdim      continue;
1533221345Sdim    if (Dir[0] == '=')
1534221345Sdim      Dir = SysRoot + Dir.substr(1);
1535221345Sdim    llvm::sys::Path P(Dir);
1536206084Srdivacky    P.appendComponent(Name);
1537218893Sdim    bool Exists;
1538218893Sdim    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1539206084Srdivacky      return P.str();
1540206084Srdivacky  }
1541206084Srdivacky
1542226633Sdim  llvm::sys::Path P(ResourceDir);
1543226633Sdim  P.appendComponent(Name);
1544226633Sdim  bool Exists;
1545226633Sdim  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1546226633Sdim    return P.str();
1547226633Sdim
1548193326Sed  const ToolChain::path_list &List = TC.getFilePaths();
1549198092Srdivacky  for (ToolChain::path_list::const_iterator
1550193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1551221345Sdim    std::string Dir(*it);
1552221345Sdim    if (Dir.empty())
1553221345Sdim      continue;
1554221345Sdim    if (Dir[0] == '=')
1555221345Sdim      Dir = SysRoot + Dir.substr(1);
1556221345Sdim    llvm::sys::Path P(Dir);
1557193326Sed    P.appendComponent(Name);
1558218893Sdim    bool Exists;
1559218893Sdim    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1560198092Srdivacky      return P.str();
1561193326Sed  }
1562193326Sed
1563198092Srdivacky  return Name;
1564193326Sed}
1565193326Sed
1566243830Sdimstd::string Driver::GetProgramPath(const char *Name,
1567243830Sdim                                   const ToolChain &TC) const {
1568234353Sdim  // FIXME: Needs a better variable than DefaultTargetTriple
1569234353Sdim  std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
1570206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1571243830Sdim  // attempting to use this prefix when looking for program paths.
1572218893Sdim  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1573218893Sdim       ie = PrefixDirs.end(); it != ie; ++it) {
1574243830Sdim    bool IsDirectory;
1575243830Sdim    if (!llvm::sys::fs::is_directory(*it, IsDirectory) && IsDirectory) {
1576243830Sdim      llvm::sys::Path P(*it);
1577243830Sdim      P.appendComponent(TargetSpecificExecutable);
1578243830Sdim      if (P.canExecute()) return P.str();
1579243830Sdim      P.eraseComponent();
1580243830Sdim      P.appendComponent(Name);
1581243830Sdim      if (P.canExecute()) return P.str();
1582243830Sdim    } else {
1583243830Sdim      llvm::sys::Path P(*it + Name);
1584243830Sdim      if (P.canExecute()) return P.str();
1585243830Sdim    }
1586206084Srdivacky  }
1587206084Srdivacky
1588193326Sed  const ToolChain::path_list &List = TC.getProgramPaths();
1589198092Srdivacky  for (ToolChain::path_list::const_iterator
1590193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1591193326Sed    llvm::sys::Path P(*it);
1592226633Sdim    P.appendComponent(TargetSpecificExecutable);
1593243830Sdim    if (P.canExecute()) return P.str();
1594226633Sdim    P.eraseComponent();
1595193326Sed    P.appendComponent(Name);
1596243830Sdim    if (P.canExecute()) return P.str();
1597193326Sed  }
1598193326Sed
1599193326Sed  // If all else failed, search the path.
1600226633Sdim  llvm::sys::Path
1601226633Sdim      P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
1602193326Sed  if (!P.empty())
1603198092Srdivacky    return P.str();
1604193326Sed
1605226633Sdim  P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
1606226633Sdim  if (!P.empty())
1607226633Sdim    return P.str();
1608226633Sdim
1609198092Srdivacky  return Name;
1610193326Sed}
1611193326Sed
1612239462Sdimstd::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
1613226633Sdim  const {
1614198092Srdivacky  // FIXME: This is lame; sys::Path should provide this function (in particular,
1615198092Srdivacky  // it should know how to find the temporary files dir).
1616193326Sed  std::string Error;
1617193326Sed  const char *TmpDir = ::getenv("TMPDIR");
1618193326Sed  if (!TmpDir)
1619193326Sed    TmpDir = ::getenv("TEMP");
1620193326Sed  if (!TmpDir)
1621193326Sed    TmpDir = ::getenv("TMP");
1622193326Sed  if (!TmpDir)
1623193326Sed    TmpDir = "/tmp";
1624193326Sed  llvm::sys::Path P(TmpDir);
1625226633Sdim  P.appendComponent(Prefix);
1626193326Sed  if (P.makeUnique(false, &Error)) {
1627239462Sdim    Diag(clang::diag::err_unable_to_make_temp) << Error;
1628193326Sed    return "";
1629193326Sed  }
1630193326Sed
1631198092Srdivacky  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1632193326Sed  P.eraseFromDisk(false, 0);
1633193326Sed
1634239462Sdim  if (Suffix)
1635239462Sdim    P.appendSuffix(Suffix);
1636198092Srdivacky  return P.str();
1637193326Sed}
1638193326Sed
1639234353Sdim/// \brief Compute target triple from args.
1640234353Sdim///
1641234353Sdim/// This routine provides the logic to compute a target triple from various
1642234353Sdim/// args passed to the driver and the default triple string.
1643234353Sdimstatic llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
1644234353Sdim                                        const ArgList &Args,
1645234353Sdim                                        StringRef DarwinArchName) {
1646234353Sdim  // FIXME: Already done in Compilation *Driver::BuildCompilation
1647234353Sdim  if (const Arg *A = Args.getLastArg(options::OPT_target))
1648243830Sdim    DefaultTargetTriple = A->getValue();
1649193326Sed
1650234353Sdim  llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1651204793Srdivacky
1652234353Sdim  // Handle Darwin-specific options available here.
1653234353Sdim  if (Target.isOSDarwin()) {
1654234353Sdim    // If an explict Darwin arch name is given, that trumps all.
1655234353Sdim    if (!DarwinArchName.empty()) {
1656234353Sdim      Target.setArch(
1657243830Sdim        tools::darwin::getArchTypeForDarwinArchName(DarwinArchName));
1658234353Sdim      return Target;
1659234353Sdim    }
1660234353Sdim
1661234353Sdim    // Handle the Darwin '-arch' flag.
1662234353Sdim    if (Arg *A = Args.getLastArg(options::OPT_arch)) {
1663234353Sdim      llvm::Triple::ArchType DarwinArch
1664243830Sdim        = tools::darwin::getArchTypeForDarwinArchName(A->getValue());
1665234353Sdim      if (DarwinArch != llvm::Triple::UnknownArch)
1666234353Sdim        Target.setArch(DarwinArch);
1667234353Sdim    }
1668193326Sed  }
1669234353Sdim
1670249423Sdim  // Handle pseudo-target flags '-EL' and '-EB'.
1671249423Sdim  if (Arg *A = Args.getLastArg(options::OPT_EL, options::OPT_EB)) {
1672249423Sdim    if (A->getOption().matches(options::OPT_EL)) {
1673249423Sdim      if (Target.getArch() == llvm::Triple::mips)
1674249423Sdim        Target.setArch(llvm::Triple::mipsel);
1675249423Sdim      else if (Target.getArch() == llvm::Triple::mips64)
1676249423Sdim        Target.setArch(llvm::Triple::mips64el);
1677249423Sdim    } else {
1678249423Sdim      if (Target.getArch() == llvm::Triple::mipsel)
1679249423Sdim        Target.setArch(llvm::Triple::mips);
1680249423Sdim      else if (Target.getArch() == llvm::Triple::mips64el)
1681249423Sdim        Target.setArch(llvm::Triple::mips64);
1682249423Sdim    }
1683249423Sdim  }
1684249423Sdim
1685234353Sdim  // Skip further flag support on OSes which don't support '-m32' or '-m64'.
1686234353Sdim  if (Target.getArchName() == "tce" ||
1687234353Sdim      Target.getOS() == llvm::Triple::AuroraUX ||
1688234353Sdim      Target.getOS() == llvm::Triple::Minix)
1689234353Sdim    return Target;
1690234353Sdim
1691234353Sdim  // Handle pseudo-target flags '-m32' and '-m64'.
1692234353Sdim  // FIXME: Should this information be in llvm::Triple?
1693234353Sdim  if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
1694234353Sdim    if (A->getOption().matches(options::OPT_m32)) {
1695234353Sdim      if (Target.getArch() == llvm::Triple::x86_64)
1696234353Sdim        Target.setArch(llvm::Triple::x86);
1697234353Sdim      if (Target.getArch() == llvm::Triple::ppc64)
1698234353Sdim        Target.setArch(llvm::Triple::ppc);
1699234353Sdim    } else {
1700234353Sdim      if (Target.getArch() == llvm::Triple::x86)
1701234353Sdim        Target.setArch(llvm::Triple::x86_64);
1702234353Sdim      if (Target.getArch() == llvm::Triple::ppc)
1703234353Sdim        Target.setArch(llvm::Triple::ppc64);
1704234353Sdim    }
1705234353Sdim  }
1706234353Sdim
1707234353Sdim  return Target;
1708193326Sed}
1709193326Sed
1710234353Sdimconst ToolChain &Driver::getToolChain(const ArgList &Args,
1711234353Sdim                                      StringRef DarwinArchName) const {
1712234353Sdim  llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
1713234353Sdim                                            DarwinArchName);
1714234353Sdim
1715234353Sdim  ToolChain *&TC = ToolChains[Target.str()];
1716234353Sdim  if (!TC) {
1717234353Sdim    switch (Target.getOS()) {
1718234353Sdim    case llvm::Triple::AuroraUX:
1719234353Sdim      TC = new toolchains::AuroraUX(*this, Target, Args);
1720234353Sdim      break;
1721234353Sdim    case llvm::Triple::Darwin:
1722234353Sdim    case llvm::Triple::MacOSX:
1723234353Sdim    case llvm::Triple::IOS:
1724234353Sdim      if (Target.getArch() == llvm::Triple::x86 ||
1725234353Sdim          Target.getArch() == llvm::Triple::x86_64 ||
1726234353Sdim          Target.getArch() == llvm::Triple::arm ||
1727234353Sdim          Target.getArch() == llvm::Triple::thumb)
1728249423Sdim        TC = new toolchains::DarwinClang(*this, Target, Args);
1729234353Sdim      else
1730234353Sdim        TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args);
1731234353Sdim      break;
1732234353Sdim    case llvm::Triple::DragonFly:
1733234353Sdim      TC = new toolchains::DragonFly(*this, Target, Args);
1734234353Sdim      break;
1735234353Sdim    case llvm::Triple::OpenBSD:
1736234353Sdim      TC = new toolchains::OpenBSD(*this, Target, Args);
1737234353Sdim      break;
1738239462Sdim    case llvm::Triple::Bitrig:
1739239462Sdim      TC = new toolchains::Bitrig(*this, Target, Args);
1740239462Sdim      break;
1741234353Sdim    case llvm::Triple::NetBSD:
1742234353Sdim      TC = new toolchains::NetBSD(*this, Target, Args);
1743234353Sdim      break;
1744234353Sdim    case llvm::Triple::FreeBSD:
1745234353Sdim      TC = new toolchains::FreeBSD(*this, Target, Args);
1746234353Sdim      break;
1747234353Sdim    case llvm::Triple::Minix:
1748234353Sdim      TC = new toolchains::Minix(*this, Target, Args);
1749234353Sdim      break;
1750234353Sdim    case llvm::Triple::Linux:
1751234353Sdim      if (Target.getArch() == llvm::Triple::hexagon)
1752249423Sdim        TC = new toolchains::Hexagon_TC(*this, Target, Args);
1753234353Sdim      else
1754234353Sdim        TC = new toolchains::Linux(*this, Target, Args);
1755234353Sdim      break;
1756234353Sdim    case llvm::Triple::Solaris:
1757234353Sdim      TC = new toolchains::Solaris(*this, Target, Args);
1758234353Sdim      break;
1759234353Sdim    case llvm::Triple::Win32:
1760249423Sdim      TC = new toolchains::Windows(*this, Target, Args);
1761234353Sdim      break;
1762234353Sdim    case llvm::Triple::MinGW32:
1763234353Sdim      // FIXME: We need a MinGW toolchain. Fallthrough for now.
1764234353Sdim    default:
1765234353Sdim      // TCE is an OSless target
1766234353Sdim      if (Target.getArchName() == "tce") {
1767249423Sdim        TC = new toolchains::TCEToolChain(*this, Target, Args);
1768234353Sdim        break;
1769234353Sdim      }
1770249423Sdim      // If Hexagon is configured as an OSless target
1771249423Sdim      if (Target.getArch() == llvm::Triple::hexagon) {
1772249423Sdim        TC = new toolchains::Hexagon_TC(*this, Target, Args);
1773249423Sdim        break;
1774249423Sdim      }
1775234353Sdim      TC = new toolchains::Generic_GCC(*this, Target, Args);
1776234353Sdim      break;
1777234353Sdim    }
1778234353Sdim  }
1779234353Sdim  return *TC;
1780234353Sdim}
1781234353Sdim
1782249423Sdimbool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
1783198092Srdivacky  // Check if user requested no clang, or clang doesn't understand this type (we
1784198092Srdivacky  // only handle single inputs for now).
1785243830Sdim  if (JA.size() != 1 ||
1786193326Sed      !types::isAcceptedByClang((*JA.begin())->getType()))
1787193326Sed    return false;
1788193326Sed
1789193326Sed  // Otherwise make sure this is an action clang understands.
1790243830Sdim  if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
1791243830Sdim      !isa<CompileJobAction>(JA))
1792193326Sed    return false;
1793193326Sed
1794193326Sed  return true;
1795193326Sed}
1796193326Sed
1797198092Srdivacky/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1798198092Srdivacky/// grouped values as integers. Numbers which are not provided are set to 0.
1799193326Sed///
1800198092Srdivacky/// \return True if the entire string was parsed (9.2), or all groups were
1801198092Srdivacky/// parsed (10.3.5extrastuff).
1802198092Srdivackybool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1803193326Sed                               unsigned &Minor, unsigned &Micro,
1804193326Sed                               bool &HadExtra) {
1805193326Sed  HadExtra = false;
1806193326Sed
1807193326Sed  Major = Minor = Micro = 0;
1808198092Srdivacky  if (*Str == '\0')
1809193326Sed    return true;
1810193326Sed
1811193326Sed  char *End;
1812193326Sed  Major = (unsigned) strtol(Str, &End, 10);
1813193326Sed  if (*Str != '\0' && *End == '\0')
1814193326Sed    return true;
1815193326Sed  if (*End != '.')
1816193326Sed    return false;
1817198092Srdivacky
1818193326Sed  Str = End+1;
1819193326Sed  Minor = (unsigned) strtol(Str, &End, 10);
1820193326Sed  if (*Str != '\0' && *End == '\0')
1821193326Sed    return true;
1822193326Sed  if (*End != '.')
1823193326Sed    return false;
1824193326Sed
1825193326Sed  Str = End+1;
1826193326Sed  Micro = (unsigned) strtol(Str, &End, 10);
1827193326Sed  if (*Str != '\0' && *End == '\0')
1828193326Sed    return true;
1829193326Sed  if (Str == End)
1830193326Sed    return false;
1831193326Sed  HadExtra = true;
1832193326Sed  return true;
1833193326Sed}
1834