Driver.cpp revision 210299
1193326Sed//===--- 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"
11193326Sed
12193326Sed#include "clang/Driver/Action.h"
13193326Sed#include "clang/Driver/Arg.h"
14193326Sed#include "clang/Driver/ArgList.h"
15193326Sed#include "clang/Driver/Compilation.h"
16193326Sed#include "clang/Driver/DriverDiagnostic.h"
17193326Sed#include "clang/Driver/HostInfo.h"
18193326Sed#include "clang/Driver/Job.h"
19199512Srdivacky#include "clang/Driver/OptTable.h"
20193326Sed#include "clang/Driver/Option.h"
21193326Sed#include "clang/Driver/Options.h"
22193326Sed#include "clang/Driver/Tool.h"
23193326Sed#include "clang/Driver/ToolChain.h"
24193326Sed#include "clang/Driver/Types.h"
25193326Sed
26193326Sed#include "clang/Basic/Version.h"
27193326Sed
28193326Sed#include "llvm/ADT/StringSet.h"
29202879Srdivacky#include "llvm/ADT/OwningPtr.h"
30193326Sed#include "llvm/Support/PrettyStackTrace.h"
31193326Sed#include "llvm/Support/raw_ostream.h"
32193326Sed#include "llvm/System/Path.h"
33193326Sed#include "llvm/System/Program.h"
34193326Sed
35193326Sed#include "InputInfo.h"
36193326Sed
37193326Sed#include <map>
38193326Sed
39193326Sedusing namespace clang::driver;
40193326Sedusing namespace clang;
41193326Sed
42200583SrdivackyDriver::Driver(llvm::StringRef _Name, llvm::StringRef _Dir,
43200583Srdivacky               llvm::StringRef _DefaultHostTriple,
44200583Srdivacky               llvm::StringRef _DefaultImageName,
45206084Srdivacky               bool IsProduction, bool CXXIsProduction,
46206084Srdivacky               Diagnostic &_Diags)
47199512Srdivacky  : Opts(createDriverOptTable()), Diags(_Diags),
48193326Sed    Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
49193326Sed    DefaultImageName(_DefaultImageName),
50204643Srdivacky    DriverTitle("clang \"gcc-compatible\" driver"),
51193326Sed    Host(0),
52205408Srdivacky    CCCGenericGCCName("gcc"), CCPrintOptionsFilename(0), CCCIsCXX(false),
53205408Srdivacky    CCCEcho(false), CCCPrintBindings(false), CCPrintOptions(false),
54205408Srdivacky    CheckInputsExist(true), CCCUseClang(true), CCCUseClangCXX(true),
55205408Srdivacky    CCCUseClangCPP(true), CCCUsePCH(true), SuppressMissingInputWarning(false) {
56198092Srdivacky  if (IsProduction) {
57198092Srdivacky    // In a "production" build, only use clang on architectures we expect to
58198092Srdivacky    // work, and don't use clang C++.
59198092Srdivacky    //
60198092Srdivacky    // During development its more convenient to always have the driver use
61198092Srdivacky    // clang, but we don't want users to be confused when things don't work, or
62198092Srdivacky    // to file bugs for things we don't support.
63198092Srdivacky    CCCClangArchs.insert(llvm::Triple::x86);
64198092Srdivacky    CCCClangArchs.insert(llvm::Triple::x86_64);
65198092Srdivacky    CCCClangArchs.insert(llvm::Triple::arm);
66198092Srdivacky
67206084Srdivacky    if (!CXXIsProduction)
68206084Srdivacky      CCCUseClangCXX = false;
69198092Srdivacky  }
70202879Srdivacky
71202879Srdivacky  // Compute the path to the resource directory.
72202879Srdivacky  llvm::sys::Path P(Dir);
73202879Srdivacky  P.eraseComponent(); // Remove /bin from foo/bin
74202879Srdivacky  P.appendComponent("lib");
75202879Srdivacky  P.appendComponent("clang");
76202879Srdivacky  P.appendComponent(CLANG_VERSION_STRING);
77202879Srdivacky  ResourceDir = P.str();
78210299Sed
79210299Sed  // Save the original clang executable path.
80210299Sed  P = Dir;
81210299Sed  P.appendComponent(Name);
82210299Sed  ClangExecutable = P.str();
83193326Sed}
84193326Sed
85193326SedDriver::~Driver() {
86193326Sed  delete Opts;
87193326Sed  delete Host;
88193326Sed}
89193326Sed
90198092SrdivackyInputArgList *Driver::ParseArgStrings(const char **ArgBegin,
91193326Sed                                      const char **ArgEnd) {
92193326Sed  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
93199512Srdivacky  unsigned MissingArgIndex, MissingArgCount;
94199512Srdivacky  InputArgList *Args = getOpts().ParseArgs(ArgBegin, ArgEnd,
95199512Srdivacky                                           MissingArgIndex, MissingArgCount);
96198092Srdivacky
97199512Srdivacky  // Check for missing argument error.
98199512Srdivacky  if (MissingArgCount)
99199512Srdivacky    Diag(clang::diag::err_drv_missing_argument)
100199512Srdivacky      << Args->getArgString(MissingArgIndex) << MissingArgCount;
101193326Sed
102199512Srdivacky  // Check for unsupported options.
103199512Srdivacky  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
104199512Srdivacky       it != ie; ++it) {
105199512Srdivacky    Arg *A = *it;
106193326Sed    if (A->getOption().isUnsupported()) {
107193326Sed      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
108193326Sed      continue;
109193326Sed    }
110193326Sed  }
111193326Sed
112193326Sed  return Args;
113193326Sed}
114193326Sed
115210299SedDerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
116210299Sed  DerivedArgList *DAL = new DerivedArgList(Args);
117210299Sed
118210299Sed  for (ArgList::const_iterator it = Args.begin(),
119210299Sed         ie = Args.end(); it != ie; ++it) {
120210299Sed    const Arg *A = *it;
121210299Sed
122210299Sed    // Unfortunately, we have to parse some forwarding options (-Xassembler,
123210299Sed    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
124210299Sed    // (assembler and preprocessor), or bypass a previous driver ('collect2').
125210299Sed
126210299Sed    // Rewrite linker options, to replace --no-demangle with a custom internal
127210299Sed    // option.
128210299Sed    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
129210299Sed         A->getOption().matches(options::OPT_Xlinker)) &&
130210299Sed        A->containsValue("--no-demangle")) {
131210299Sed      // Add the rewritten no-demangle argument.
132210299Sed      DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
133210299Sed
134210299Sed      // Add the remaining values as Xlinker arguments.
135210299Sed      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
136210299Sed        if (llvm::StringRef(A->getValue(Args, i)) != "--no-demangle")
137210299Sed          DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
138210299Sed                              A->getValue(Args, i));
139210299Sed
140210299Sed      continue;
141210299Sed    }
142210299Sed
143210299Sed    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
144210299Sed    // some build systems. We don't try to be complete here because we don't
145210299Sed    // care to encourage this usage model.
146210299Sed    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
147210299Sed        A->getNumValues() == 2 &&
148210299Sed        (A->getValue(Args, 0) == llvm::StringRef("-MD") ||
149210299Sed         A->getValue(Args, 0) == llvm::StringRef("-MMD"))) {
150210299Sed      // Rewrite to -MD/-MMD along with -MF.
151210299Sed      if (A->getValue(Args, 0) == llvm::StringRef("-MD"))
152210299Sed        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
153210299Sed      else
154210299Sed        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
155210299Sed      DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
156210299Sed                          A->getValue(Args, 1));
157210299Sed      continue;
158210299Sed    }
159210299Sed
160210299Sed    DAL->append(*it);
161210299Sed  }
162210299Sed
163210299Sed  return DAL;
164210299Sed}
165210299Sed
166193326SedCompilation *Driver::BuildCompilation(int argc, const char **argv) {
167193326Sed  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
168193326Sed
169198092Srdivacky  // FIXME: Handle environment options which effect driver behavior, somewhere
170198092Srdivacky  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
171198092Srdivacky  // CC_PRINT_OPTIONS.
172193326Sed
173193326Sed  // FIXME: What are we going to do with -V and -b?
174193326Sed
175198092Srdivacky  // FIXME: This stuff needs to go into the Compilation, not the driver.
176193326Sed  bool CCCPrintOptions = false, CCCPrintActions = false;
177193326Sed
178193326Sed  const char **Start = argv + 1, **End = argv + argc;
179193326Sed  const char *HostTriple = DefaultHostTriple.c_str();
180193326Sed
181200583Srdivacky  InputArgList *Args = ParseArgStrings(Start, End);
182200583Srdivacky
183200583Srdivacky  // -no-canonical-prefixes is used very early in main.
184200583Srdivacky  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
185200583Srdivacky
186200583Srdivacky  // Extract -ccc args.
187193326Sed  //
188198092Srdivacky  // FIXME: We need to figure out where this behavior should live. Most of it
189198092Srdivacky  // should be outside in the client; the parts that aren't should have proper
190198092Srdivacky  // options, either by introducing new ones or by overloading gcc ones like -V
191198092Srdivacky  // or -b.
192200583Srdivacky  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
193200583Srdivacky  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
194200583Srdivacky  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
195200583Srdivacky  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
196200583Srdivacky  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
197200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
198200583Srdivacky    CCCGenericGCCName = A->getValue(*Args);
199200583Srdivacky  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
200200583Srdivacky                                 options::OPT_ccc_no_clang_cxx,
201200583Srdivacky                                 CCCUseClangCXX);
202200583Srdivacky  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
203200583Srdivacky                            options::OPT_ccc_pch_is_pth);
204200583Srdivacky  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
205200583Srdivacky  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
206200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
207200583Srdivacky    llvm::StringRef Cur = A->getValue(*Args);
208198092Srdivacky
209200583Srdivacky    CCCClangArchs.clear();
210200583Srdivacky    while (!Cur.empty()) {
211200583Srdivacky      std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
212198092Srdivacky
213200583Srdivacky      if (!Split.first.empty()) {
214200583Srdivacky        llvm::Triple::ArchType Arch =
215200583Srdivacky          llvm::Triple(Split.first, "", "").getArch();
216193326Sed
217203955Srdivacky        if (Arch == llvm::Triple::UnknownArch)
218203955Srdivacky          Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
219198092Srdivacky
220200583Srdivacky        CCCClangArchs.insert(Arch);
221193326Sed      }
222193326Sed
223200583Srdivacky      Cur = Split.second;
224193326Sed    }
225193326Sed  }
226200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple))
227200583Srdivacky    HostTriple = A->getValue(*Args);
228200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
229200583Srdivacky    Dir = A->getValue(*Args);
230206084Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_B))
231206084Srdivacky    PrefixDir = A->getValue(*Args);
232193326Sed
233193326Sed  Host = GetHostInfo(HostTriple);
234193326Sed
235210299Sed  // Perform the default argument translations.
236210299Sed  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
237210299Sed
238193326Sed  // The compilation takes ownership of Args.
239210299Sed  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args,
240210299Sed                                   TranslatedArgs);
241193326Sed
242193326Sed  // FIXME: This behavior shouldn't be here.
243193326Sed  if (CCCPrintOptions) {
244210299Sed    PrintOptions(C->getInputArgs());
245193326Sed    return C;
246193326Sed  }
247193326Sed
248193326Sed  if (!HandleImmediateArgs(*C))
249193326Sed    return C;
250193326Sed
251198092Srdivacky  // Construct the list of abstract actions to perform for this compilation. We
252198092Srdivacky  // avoid passing a Compilation here simply to enforce the abstraction that
253198092Srdivacky  // pipelining is not host or toolchain dependent (other than the driver driver
254198092Srdivacky  // test).
255193326Sed  if (Host->useDriverDriver())
256193326Sed    BuildUniversalActions(C->getArgs(), C->getActions());
257193326Sed  else
258193326Sed    BuildActions(C->getArgs(), C->getActions());
259193326Sed
260193326Sed  if (CCCPrintActions) {
261193326Sed    PrintActions(*C);
262193326Sed    return C;
263193326Sed  }
264193326Sed
265193326Sed  BuildJobs(*C);
266193326Sed
267193326Sed  return C;
268193326Sed}
269193326Sed
270195341Sedint Driver::ExecuteCompilation(const Compilation &C) const {
271195341Sed  // Just print if -### was present.
272195341Sed  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
273195341Sed    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
274195341Sed    return 0;
275195341Sed  }
276195341Sed
277195341Sed  // If there were errors building the compilation, quit now.
278195341Sed  if (getDiags().getNumErrors())
279195341Sed    return 1;
280195341Sed
281195341Sed  const Command *FailingCommand = 0;
282195341Sed  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
283198092Srdivacky
284195341Sed  // Remove temp files.
285195341Sed  C.CleanupFileList(C.getTempFiles());
286195341Sed
287208600Srdivacky  // If the command succeeded, we are done.
288208600Srdivacky  if (Res == 0)
289208600Srdivacky    return Res;
290208600Srdivacky
291208600Srdivacky  // Otherwise, remove result files as well.
292208600Srdivacky  if (!C.getArgs().hasArg(options::OPT_save_temps))
293195341Sed    C.CleanupFileList(C.getResultFiles(), true);
294195341Sed
295195341Sed  // Print extra information about abnormal failures, if possible.
296208600Srdivacky  //
297208600Srdivacky  // This is ad-hoc, but we don't want to be excessively noisy. If the result
298208600Srdivacky  // status was 1, assume the command failed normally. In particular, if it was
299208600Srdivacky  // the compiler then assume it gave a reasonable error code. Failures in other
300208600Srdivacky  // tools are less common, and they generally have worse diagnostics, so always
301208600Srdivacky  // print the diagnostic there.
302208600Srdivacky  const Tool &FailingTool = FailingCommand->getCreator();
303195341Sed
304208600Srdivacky  if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
305208600Srdivacky    // FIXME: See FIXME above regarding result code interpretation.
306208600Srdivacky    if (Res < 0)
307208600Srdivacky      Diag(clang::diag::err_drv_command_signalled)
308208600Srdivacky        << FailingTool.getShortName() << -Res;
309208600Srdivacky    else
310208600Srdivacky      Diag(clang::diag::err_drv_command_failed)
311208600Srdivacky        << FailingTool.getShortName() << Res;
312195341Sed  }
313195341Sed
314195341Sed  return Res;
315195341Sed}
316195341Sed
317193326Sedvoid Driver::PrintOptions(const ArgList &Args) const {
318193326Sed  unsigned i = 0;
319198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
320193326Sed       it != ie; ++it, ++i) {
321193326Sed    Arg *A = *it;
322193326Sed    llvm::errs() << "Option " << i << " - "
323193326Sed                 << "Name: \"" << A->getOption().getName() << "\", "
324193326Sed                 << "Values: {";
325193326Sed    for (unsigned j = 0; j < A->getNumValues(); ++j) {
326193326Sed      if (j)
327193326Sed        llvm::errs() << ", ";
328193326Sed      llvm::errs() << '"' << A->getValue(Args, j) << '"';
329193326Sed    }
330193326Sed    llvm::errs() << "}\n";
331193326Sed  }
332193326Sed}
333193326Sed
334193326Sedvoid Driver::PrintHelp(bool ShowHidden) const {
335204643Srdivacky  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
336204643Srdivacky                      ShowHidden);
337193326Sed}
338193326Sed
339198092Srdivackyvoid Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
340198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
341198092Srdivacky  // know what the client would like to do.
342202879Srdivacky  OS << getClangFullVersion() << '\n';
343193326Sed  const ToolChain &TC = C.getDefaultToolChain();
344198092Srdivacky  OS << "Target: " << TC.getTripleString() << '\n';
345194613Sed
346194613Sed  // Print the threading model.
347194613Sed  //
348194613Sed  // FIXME: Implement correctly.
349198092Srdivacky  OS << "Thread model: " << "posix" << '\n';
350193326Sed}
351193326Sed
352208600Srdivacky/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
353208600Srdivacky/// option.
354208600Srdivackystatic void PrintDiagnosticCategories(llvm::raw_ostream &OS) {
355208600Srdivacky  for (unsigned i = 1; // Skip the empty category.
356208600Srdivacky       const char *CategoryName = Diagnostic::getCategoryNameFromID(i); ++i)
357208600Srdivacky    OS << i << ',' << CategoryName << '\n';
358208600Srdivacky}
359208600Srdivacky
360193326Sedbool Driver::HandleImmediateArgs(const Compilation &C) {
361210299Sed  // The order these options are handled in gcc is all over the place, but we
362198092Srdivacky  // don't expect inconsistencies w.r.t. that to matter in practice.
363193326Sed
364193326Sed  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
365193326Sed    llvm::outs() << CLANG_VERSION_STRING "\n";
366193326Sed    return false;
367193326Sed  }
368210299Sed
369208600Srdivacky  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
370208600Srdivacky    PrintDiagnosticCategories(llvm::outs());
371208600Srdivacky    return false;
372208600Srdivacky  }
373193326Sed
374198092Srdivacky  if (C.getArgs().hasArg(options::OPT__help) ||
375193326Sed      C.getArgs().hasArg(options::OPT__help_hidden)) {
376193326Sed    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
377193326Sed    return false;
378193326Sed  }
379193326Sed
380193326Sed  if (C.getArgs().hasArg(options::OPT__version)) {
381198092Srdivacky    // Follow gcc behavior and use stdout for --version and stderr for -v.
382198092Srdivacky    PrintVersion(C, llvm::outs());
383193326Sed    return false;
384193326Sed  }
385193326Sed
386198092Srdivacky  if (C.getArgs().hasArg(options::OPT_v) ||
387193326Sed      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
388198092Srdivacky    PrintVersion(C, llvm::errs());
389193326Sed    SuppressMissingInputWarning = true;
390193326Sed  }
391193326Sed
392193326Sed  const ToolChain &TC = C.getDefaultToolChain();
393193326Sed  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
394193326Sed    llvm::outs() << "programs: =";
395193326Sed    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
396193326Sed           ie = TC.getProgramPaths().end(); it != ie; ++it) {
397193326Sed      if (it != TC.getProgramPaths().begin())
398193326Sed        llvm::outs() << ':';
399193326Sed      llvm::outs() << *it;
400193326Sed    }
401193326Sed    llvm::outs() << "\n";
402193326Sed    llvm::outs() << "libraries: =";
403198092Srdivacky    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
404193326Sed           ie = TC.getFilePaths().end(); it != ie; ++it) {
405193326Sed      if (it != TC.getFilePaths().begin())
406193326Sed        llvm::outs() << ':';
407193326Sed      llvm::outs() << *it;
408193326Sed    }
409193326Sed    llvm::outs() << "\n";
410193326Sed    return false;
411193326Sed  }
412193326Sed
413198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
414198092Srdivacky  // know what the client would like to do.
415193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
416198092Srdivacky    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
417193326Sed    return false;
418193326Sed  }
419193326Sed
420193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
421198092Srdivacky    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
422193326Sed    return false;
423193326Sed  }
424193326Sed
425193326Sed  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
426198092Srdivacky    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
427193326Sed    return false;
428193326Sed  }
429193326Sed
430194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
431194613Sed    // FIXME: We need tool chain support for this.
432194613Sed    llvm::outs() << ".;\n";
433194613Sed
434194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
435194613Sed    default:
436194613Sed      break;
437198092Srdivacky
438194613Sed    case llvm::Triple::x86_64:
439194613Sed      llvm::outs() << "x86_64;@m64" << "\n";
440194613Sed      break;
441194613Sed
442194613Sed    case llvm::Triple::ppc64:
443194613Sed      llvm::outs() << "ppc64;@m64" << "\n";
444194613Sed      break;
445194613Sed    }
446194613Sed    return false;
447194613Sed  }
448194613Sed
449194613Sed  // FIXME: What is the difference between print-multi-directory and
450194613Sed  // print-multi-os-directory?
451194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
452194613Sed      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
453194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
454194613Sed    default:
455194613Sed    case llvm::Triple::x86:
456194613Sed    case llvm::Triple::ppc:
457194613Sed      llvm::outs() << "." << "\n";
458194613Sed      break;
459198092Srdivacky
460194613Sed    case llvm::Triple::x86_64:
461194613Sed      llvm::outs() << "x86_64" << "\n";
462194613Sed      break;
463194613Sed
464194613Sed    case llvm::Triple::ppc64:
465194613Sed      llvm::outs() << "ppc64" << "\n";
466194613Sed      break;
467194613Sed    }
468194613Sed    return false;
469194613Sed  }
470194613Sed
471193326Sed  return true;
472193326Sed}
473193326Sed
474198092Srdivackystatic unsigned PrintActions1(const Compilation &C, Action *A,
475193326Sed                              std::map<Action*, unsigned> &Ids) {
476193326Sed  if (Ids.count(A))
477193326Sed    return Ids[A];
478198092Srdivacky
479193326Sed  std::string str;
480193326Sed  llvm::raw_string_ostream os(str);
481198092Srdivacky
482193326Sed  os << Action::getClassName(A->getKind()) << ", ";
483198092Srdivacky  if (InputAction *IA = dyn_cast<InputAction>(A)) {
484193326Sed    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
485193326Sed  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
486198092Srdivacky    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
487193326Sed                  C.getDefaultToolChain().getArchName()) << '"'
488193326Sed       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
489193326Sed  } else {
490193326Sed    os << "{";
491193326Sed    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
492193326Sed      os << PrintActions1(C, *it, Ids);
493193326Sed      ++it;
494193326Sed      if (it != ie)
495193326Sed        os << ", ";
496193326Sed    }
497193326Sed    os << "}";
498193326Sed  }
499193326Sed
500193326Sed  unsigned Id = Ids.size();
501193326Sed  Ids[A] = Id;
502198092Srdivacky  llvm::errs() << Id << ": " << os.str() << ", "
503193326Sed               << types::getTypeName(A->getType()) << "\n";
504193326Sed
505193326Sed  return Id;
506193326Sed}
507193326Sed
508193326Sedvoid Driver::PrintActions(const Compilation &C) const {
509193326Sed  std::map<Action*, unsigned> Ids;
510198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
511193326Sed         ie = C.getActions().end(); it != ie; ++it)
512193326Sed    PrintActions1(C, *it, Ids);
513193326Sed}
514193326Sed
515210299Sed/// \brief Check whether the given input tree contains any compilation (or
516210299Sed/// assembly) actions.
517210299Sedstatic bool ContainsCompileAction(const Action *A) {
518210299Sed  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
519210299Sed    return true;
520210299Sed
521210299Sed  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
522210299Sed    if (ContainsCompileAction(*it))
523210299Sed      return true;
524210299Sed
525210299Sed  return false;
526210299Sed}
527210299Sed
528198092Srdivackyvoid Driver::BuildUniversalActions(const ArgList &Args,
529193326Sed                                   ActionList &Actions) const {
530198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
531198092Srdivacky  // Collect the list of architectures. Duplicates are allowed, but should only
532198092Srdivacky  // be handled once (in the order seen).
533193326Sed  llvm::StringSet<> ArchNames;
534193326Sed  llvm::SmallVector<const char *, 4> Archs;
535198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
536193326Sed       it != ie; ++it) {
537193326Sed    Arg *A = *it;
538193326Sed
539199512Srdivacky    if (A->getOption().matches(options::OPT_arch)) {
540198092Srdivacky      // Validate the option here; we don't save the type here because its
541198092Srdivacky      // particular spelling may participate in other driver choices.
542198092Srdivacky      llvm::Triple::ArchType Arch =
543198092Srdivacky        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
544198092Srdivacky      if (Arch == llvm::Triple::UnknownArch) {
545198092Srdivacky        Diag(clang::diag::err_drv_invalid_arch_name)
546198092Srdivacky          << A->getAsString(Args);
547198092Srdivacky        continue;
548198092Srdivacky      }
549193326Sed
550193326Sed      A->claim();
551198092Srdivacky      if (ArchNames.insert(A->getValue(Args)))
552198092Srdivacky        Archs.push_back(A->getValue(Args));
553193326Sed    }
554193326Sed  }
555193326Sed
556198092Srdivacky  // When there is no explicit arch for this platform, make sure we still bind
557198092Srdivacky  // the architecture (to the default) so that -Xarch_ is handled correctly.
558193326Sed  if (!Archs.size())
559193326Sed    Archs.push_back(0);
560193326Sed
561198092Srdivacky  // FIXME: We killed off some others but these aren't yet detected in a
562198092Srdivacky  // functional manner. If we added information to jobs about which "auxiliary"
563198092Srdivacky  // files they wrote then we could detect the conflict these cause downstream.
564193326Sed  if (Archs.size() > 1) {
565193326Sed    // No recovery needed, the point of this is just to prevent
566193326Sed    // overwriting the same files.
567193326Sed    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
568198092Srdivacky      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
569193326Sed        << A->getAsString(Args);
570193326Sed  }
571193326Sed
572193326Sed  ActionList SingleActions;
573193326Sed  BuildActions(Args, SingleActions);
574193326Sed
575210299Sed  // Add in arch bindings for every top level action, as well as lipo and
576210299Sed  // dsymutil steps if needed.
577193326Sed  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
578193326Sed    Action *Act = SingleActions[i];
579193326Sed
580198092Srdivacky    // Make sure we can lipo this kind of output. If not (and it is an actual
581198092Srdivacky    // output) then we disallow, since we can't create an output file with the
582198092Srdivacky    // right name without overwriting it. We could remove this oddity by just
583198092Srdivacky    // changing the output names to include the arch, which would also fix
584193326Sed    // -save-temps. Compatibility wins for now.
585193326Sed
586193326Sed    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
587193326Sed      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
588193326Sed        << types::getTypeName(Act->getType());
589193326Sed
590193326Sed    ActionList Inputs;
591205219Srdivacky    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
592193326Sed      Inputs.push_back(new BindArchAction(Act, Archs[i]));
593205219Srdivacky      if (i != 0)
594205219Srdivacky        Inputs.back()->setOwnsInputs(false);
595205219Srdivacky    }
596193326Sed
597198092Srdivacky    // Lipo if necessary, we do it this way because we need to set the arch flag
598198092Srdivacky    // so that -Xarch_ gets overwritten.
599193326Sed    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
600193326Sed      Actions.append(Inputs.begin(), Inputs.end());
601193326Sed    else
602193326Sed      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
603210299Sed
604210299Sed    // Add a 'dsymutil' step if necessary, when debug info is enabled and we
605210299Sed    // have a compile input. We need to run 'dsymutil' ourselves in such cases
606210299Sed    // because the debug info will refer to a temporary object file which is
607210299Sed    // will be removed at the end of the compilation process.
608210299Sed    if (Act->getType() == types::TY_Image) {
609210299Sed      Arg *A = Args.getLastArg(options::OPT_g_Group);
610210299Sed      if (A && !A->getOption().matches(options::OPT_g0) &&
611210299Sed          !A->getOption().matches(options::OPT_gstabs) &&
612210299Sed          ContainsCompileAction(Actions.back())) {
613210299Sed        ActionList Inputs;
614210299Sed        Inputs.push_back(Actions.back());
615210299Sed        Actions.pop_back();
616210299Sed
617210299Sed        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
618210299Sed      }
619210299Sed    }
620193326Sed  }
621193326Sed}
622193326Sed
623193326Sedvoid Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
624193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
625193326Sed  // Start by constructing the list of inputs and their types.
626193326Sed
627198092Srdivacky  // Track the current user specified (-x) input. We also explicitly track the
628198092Srdivacky  // argument used to set the type; we only want to claim the type when we
629198092Srdivacky  // actually use it, so we warn about unused -x arguments.
630193326Sed  types::ID InputType = types::TY_Nothing;
631193326Sed  Arg *InputTypeArg = 0;
632193326Sed
633193326Sed  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
634198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
635193326Sed       it != ie; ++it) {
636193326Sed    Arg *A = *it;
637193326Sed
638193326Sed    if (isa<InputOption>(A->getOption())) {
639193326Sed      const char *Value = A->getValue(Args);
640193326Sed      types::ID Ty = types::TY_INVALID;
641193326Sed
642193326Sed      // Infer the input type if necessary.
643193326Sed      if (InputType == types::TY_Nothing) {
644193326Sed        // If there was an explicit arg for this, claim it.
645193326Sed        if (InputTypeArg)
646193326Sed          InputTypeArg->claim();
647193326Sed
648193326Sed        // stdin must be handled specially.
649193326Sed        if (memcmp(Value, "-", 2) == 0) {
650198092Srdivacky          // If running with -E, treat as a C input (this changes the builtin
651198092Srdivacky          // macros, for example). This may be overridden by -ObjC below.
652193326Sed          //
653198092Srdivacky          // Otherwise emit an error but still use a valid type to avoid
654198092Srdivacky          // spurious errors (e.g., no inputs).
655199512Srdivacky          if (!Args.hasArgNoClaim(options::OPT_E))
656193326Sed            Diag(clang::diag::err_drv_unknown_stdin_type);
657193326Sed          Ty = types::TY_C;
658193326Sed        } else {
659198092Srdivacky          // Otherwise lookup by extension, and fallback to ObjectType if not
660198092Srdivacky          // found. We use a host hook here because Darwin at least has its own
661198092Srdivacky          // idea of what .s is.
662193326Sed          if (const char *Ext = strrchr(Value, '.'))
663193326Sed            Ty = Host->lookupTypeForExtension(Ext + 1);
664193326Sed
665193326Sed          if (Ty == types::TY_INVALID)
666193326Sed            Ty = types::TY_Object;
667204643Srdivacky
668204643Srdivacky          // If the driver is invoked as C++ compiler (like clang++ or c++) it
669204643Srdivacky          // should autodetect some input files as C++ for g++ compatibility.
670204643Srdivacky          if (CCCIsCXX) {
671204643Srdivacky            types::ID OldTy = Ty;
672204643Srdivacky            Ty = types::lookupCXXTypeForCType(Ty);
673204643Srdivacky
674204643Srdivacky            if (Ty != OldTy)
675204643Srdivacky              Diag(clang::diag::warn_drv_treating_input_as_cxx)
676204643Srdivacky                << getTypeName(OldTy) << getTypeName(Ty);
677204643Srdivacky          }
678193326Sed        }
679193326Sed
680193326Sed        // -ObjC and -ObjC++ override the default language, but only for "source
681193326Sed        // files". We just treat everything that isn't a linker input as a
682193326Sed        // source file.
683198092Srdivacky        //
684193326Sed        // FIXME: Clean this up if we move the phase sequence into the type.
685193326Sed        if (Ty != types::TY_Object) {
686193326Sed          if (Args.hasArg(options::OPT_ObjC))
687193326Sed            Ty = types::TY_ObjC;
688193326Sed          else if (Args.hasArg(options::OPT_ObjCXX))
689193326Sed            Ty = types::TY_ObjCXX;
690193326Sed        }
691193326Sed      } else {
692193326Sed        assert(InputTypeArg && "InputType set w/o InputTypeArg");
693193326Sed        InputTypeArg->claim();
694193326Sed        Ty = InputType;
695193326Sed      }
696193326Sed
697203955Srdivacky      // Check that the file exists, if enabled.
698203955Srdivacky      if (CheckInputsExist && memcmp(Value, "-", 2) != 0 &&
699203955Srdivacky          !llvm::sys::Path(Value).exists())
700193326Sed        Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
701193326Sed      else
702193326Sed        Inputs.push_back(std::make_pair(Ty, A));
703193326Sed
704193326Sed    } else if (A->getOption().isLinkerInput()) {
705198092Srdivacky      // Just treat as object type, we could make a special type for this if
706198092Srdivacky      // necessary.
707193326Sed      Inputs.push_back(std::make_pair(types::TY_Object, A));
708193326Sed
709199512Srdivacky    } else if (A->getOption().matches(options::OPT_x)) {
710198092Srdivacky      InputTypeArg = A;
711193326Sed      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
712193326Sed
713193326Sed      // Follow gcc behavior and treat as linker input for invalid -x
714198092Srdivacky      // options. Its not clear why we shouldn't just revert to unknown; but
715198092Srdivacky      // this isn't very important, we might as well be bug comatible.
716193326Sed      if (!InputType) {
717193326Sed        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
718193326Sed        InputType = types::TY_Object;
719193326Sed      }
720193326Sed    }
721193326Sed  }
722193326Sed
723193326Sed  if (!SuppressMissingInputWarning && Inputs.empty()) {
724193326Sed    Diag(clang::diag::err_drv_no_input_files);
725193326Sed    return;
726193326Sed  }
727193326Sed
728198092Srdivacky  // Determine which compilation mode we are in. We look for options which
729198092Srdivacky  // affect the phase, starting with the earliest phases, and record which
730198092Srdivacky  // option we used to determine the final phase.
731193326Sed  Arg *FinalPhaseArg = 0;
732193326Sed  phases::ID FinalPhase;
733193326Sed
734193326Sed  // -{E,M,MM} only run the preprocessor.
735193326Sed  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
736193326Sed      (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
737193326Sed      (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
738193326Sed    FinalPhase = phases::Preprocess;
739198092Srdivacky
740198092Srdivacky    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
741193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
742203955Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_rewrite_objc)) ||
743193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
744193326Sed                                              options::OPT__analyze_auto)) ||
745198092Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
746193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
747193326Sed    FinalPhase = phases::Compile;
748193326Sed
749193326Sed    // -c only runs up to the assembler.
750193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
751193326Sed    FinalPhase = phases::Assemble;
752198092Srdivacky
753193326Sed    // Otherwise do everything.
754193326Sed  } else
755193326Sed    FinalPhase = phases::Link;
756193326Sed
757198092Srdivacky  // Reject -Z* at the top level, these options should never have been exposed
758198092Srdivacky  // by gcc.
759193326Sed  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
760193326Sed    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
761193326Sed
762193326Sed  // Construct the actions to perform.
763193326Sed  ActionList LinkerInputs;
764193326Sed  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
765193326Sed    types::ID InputType = Inputs[i].first;
766193326Sed    const Arg *InputArg = Inputs[i].second;
767193326Sed
768193326Sed    unsigned NumSteps = types::getNumCompilationPhases(InputType);
769193326Sed    assert(NumSteps && "Invalid number of steps!");
770193326Sed
771198092Srdivacky    // If the first step comes after the final phase we are doing as part of
772198092Srdivacky    // this compilation, warn the user about it.
773193326Sed    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
774193326Sed    if (InitialPhase > FinalPhase) {
775193326Sed      // Claim here to avoid the more general unused warning.
776193326Sed      InputArg->claim();
777198092Srdivacky
778198092Srdivacky      // Special case '-E' warning on a previously preprocessed file to make
779198092Srdivacky      // more sense.
780198092Srdivacky      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
781198092Srdivacky          getPreprocessedType(InputType) == types::TY_INVALID)
782198092Srdivacky        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
783198092Srdivacky          << InputArg->getAsString(Args)
784198092Srdivacky          << FinalPhaseArg->getOption().getName();
785198092Srdivacky      else
786198092Srdivacky        Diag(clang::diag::warn_drv_input_file_unused)
787198092Srdivacky          << InputArg->getAsString(Args)
788198092Srdivacky          << getPhaseName(InitialPhase)
789198092Srdivacky          << FinalPhaseArg->getOption().getName();
790193326Sed      continue;
791193326Sed    }
792198092Srdivacky
793193326Sed    // Build the pipeline for this file.
794202879Srdivacky    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
795193326Sed    for (unsigned i = 0; i != NumSteps; ++i) {
796193326Sed      phases::ID Phase = types::getCompilationPhase(InputType, i);
797193326Sed
798193326Sed      // We are done if this step is past what the user requested.
799193326Sed      if (Phase > FinalPhase)
800193326Sed        break;
801193326Sed
802193326Sed      // Queue linker inputs.
803193326Sed      if (Phase == phases::Link) {
804193326Sed        assert(i + 1 == NumSteps && "linking must be final compilation step.");
805202879Srdivacky        LinkerInputs.push_back(Current.take());
806193326Sed        break;
807193326Sed      }
808193326Sed
809198092Srdivacky      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
810198092Srdivacky      // encode this in the steps because the intermediate type depends on
811198092Srdivacky      // arguments. Just special case here.
812193326Sed      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
813193326Sed        continue;
814193326Sed
815193326Sed      // Otherwise construct the appropriate action.
816202879Srdivacky      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
817193326Sed      if (Current->getType() == types::TY_Nothing)
818193326Sed        break;
819193326Sed    }
820193326Sed
821193326Sed    // If we ended with something, add to the output list.
822193326Sed    if (Current)
823202879Srdivacky      Actions.push_back(Current.take());
824193326Sed  }
825193326Sed
826193326Sed  // Add a link action if necessary.
827193326Sed  if (!LinkerInputs.empty())
828193326Sed    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
829201361Srdivacky
830201361Srdivacky  // If we are linking, claim any options which are obviously only used for
831201361Srdivacky  // compilation.
832201361Srdivacky  if (FinalPhase == phases::Link)
833201361Srdivacky    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
834193326Sed}
835193326Sed
836193326SedAction *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
837193326Sed                                     Action *Input) const {
838193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
839193326Sed  // Build the appropriate action.
840193326Sed  switch (Phase) {
841193326Sed  case phases::Link: assert(0 && "link action invalid here.");
842193326Sed  case phases::Preprocess: {
843193326Sed    types::ID OutputTy;
844193326Sed    // -{M, MM} alter the output type.
845193326Sed    if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
846193326Sed      OutputTy = types::TY_Dependencies;
847193326Sed    } else {
848193326Sed      OutputTy = types::getPreprocessedType(Input->getType());
849193326Sed      assert(OutputTy != types::TY_INVALID &&
850193326Sed             "Cannot preprocess this input type!");
851193326Sed    }
852193326Sed    return new PreprocessJobAction(Input, OutputTy);
853193326Sed  }
854193326Sed  case phases::Precompile:
855198092Srdivacky    return new PrecompileJobAction(Input, types::TY_PCH);
856193326Sed  case phases::Compile: {
857201361Srdivacky    bool HasO4 = false;
858201361Srdivacky    if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
859201361Srdivacky      HasO4 = A->getOption().matches(options::OPT_O4);
860201361Srdivacky
861193326Sed    if (Args.hasArg(options::OPT_fsyntax_only)) {
862193326Sed      return new CompileJobAction(Input, types::TY_Nothing);
863203955Srdivacky    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
864203955Srdivacky      return new CompileJobAction(Input, types::TY_RewrittenObjC);
865193326Sed    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
866193326Sed      return new AnalyzeJobAction(Input, types::TY_Plist);
867198092Srdivacky    } else if (Args.hasArg(options::OPT_emit_ast)) {
868198092Srdivacky      return new CompileJobAction(Input, types::TY_AST);
869193326Sed    } else if (Args.hasArg(options::OPT_emit_llvm) ||
870201361Srdivacky               Args.hasArg(options::OPT_flto) || HasO4) {
871198092Srdivacky      types::ID Output =
872210299Sed        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
873193326Sed      return new CompileJobAction(Input, Output);
874193326Sed    } else {
875193326Sed      return new CompileJobAction(Input, types::TY_PP_Asm);
876193326Sed    }
877193326Sed  }
878193326Sed  case phases::Assemble:
879193326Sed    return new AssembleJobAction(Input, types::TY_Object);
880193326Sed  }
881193326Sed
882193326Sed  assert(0 && "invalid phase in ConstructPhaseAction");
883193326Sed  return 0;
884193326Sed}
885193326Sed
886193326Sedvoid Driver::BuildJobs(Compilation &C) const {
887193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
888193326Sed  bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
889193326Sed  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
890193326Sed
891198092Srdivacky  // FIXME: Pipes are forcibly disabled until we support executing them.
892193326Sed  if (!CCCPrintBindings)
893193326Sed    UsePipes = false;
894198092Srdivacky
895193326Sed  // -save-temps inhibits pipes.
896201361Srdivacky  if (SaveTemps && UsePipes)
897193326Sed    Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
898193326Sed
899193326Sed  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
900193326Sed
901198092Srdivacky  // It is an error to provide a -o option if we are making multiple output
902198092Srdivacky  // files.
903193326Sed  if (FinalOutput) {
904193326Sed    unsigned NumOutputs = 0;
905198092Srdivacky    for (ActionList::const_iterator it = C.getActions().begin(),
906193326Sed           ie = C.getActions().end(); it != ie; ++it)
907193326Sed      if ((*it)->getType() != types::TY_Nothing)
908193326Sed        ++NumOutputs;
909198092Srdivacky
910193326Sed    if (NumOutputs > 1) {
911193326Sed      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
912193326Sed      FinalOutput = 0;
913193326Sed    }
914193326Sed  }
915193326Sed
916198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
917193326Sed         ie = C.getActions().end(); it != ie; ++it) {
918193326Sed    Action *A = *it;
919193326Sed
920198092Srdivacky    // If we are linking an image for multiple archs then the linker wants
921198092Srdivacky    // -arch_multiple and -final_output <final image name>. Unfortunately, this
922198092Srdivacky    // doesn't fit in cleanly because we have to pass this information down.
923193326Sed    //
924198092Srdivacky    // FIXME: This is a hack; find a cleaner way to integrate this into the
925198092Srdivacky    // process.
926193326Sed    const char *LinkingOutput = 0;
927193326Sed    if (isa<LipoJobAction>(A)) {
928193326Sed      if (FinalOutput)
929193326Sed        LinkingOutput = FinalOutput->getValue(C.getArgs());
930193326Sed      else
931193326Sed        LinkingOutput = DefaultImageName.c_str();
932193326Sed    }
933193326Sed
934193326Sed    InputInfo II;
935198092Srdivacky    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
936198092Srdivacky                       /*BoundArch*/0,
937193326Sed                       /*CanAcceptPipe*/ true,
938193326Sed                       /*AtTopLevel*/ true,
939193326Sed                       /*LinkingOutput*/ LinkingOutput,
940193326Sed                       II);
941193326Sed  }
942193326Sed
943198092Srdivacky  // If the user passed -Qunused-arguments or there were errors, don't warn
944198092Srdivacky  // about any unused arguments.
945198092Srdivacky  if (Diags.getNumErrors() ||
946193326Sed      C.getArgs().hasArg(options::OPT_Qunused_arguments))
947193326Sed    return;
948193326Sed
949193326Sed  // Claim -### here.
950193326Sed  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
951198092Srdivacky
952193326Sed  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
953193326Sed       it != ie; ++it) {
954193326Sed    Arg *A = *it;
955198092Srdivacky
956193326Sed    // FIXME: It would be nice to be able to send the argument to the
957198092Srdivacky    // Diagnostic, so that extra values, position, and so on could be printed.
958193326Sed    if (!A->isClaimed()) {
959193326Sed      if (A->getOption().hasNoArgumentUnused())
960193326Sed        continue;
961193326Sed
962198092Srdivacky      // Suppress the warning automatically if this is just a flag, and it is an
963198092Srdivacky      // instance of an argument we already claimed.
964193326Sed      const Option &Opt = A->getOption();
965193326Sed      if (isa<FlagOption>(Opt)) {
966193326Sed        bool DuplicateClaimed = false;
967193326Sed
968199990Srdivacky        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
969199990Srdivacky               ie = C.getArgs().filtered_end(); it != ie; ++it) {
970199990Srdivacky          if ((*it)->isClaimed()) {
971193326Sed            DuplicateClaimed = true;
972193326Sed            break;
973193326Sed          }
974193326Sed        }
975193326Sed
976193326Sed        if (DuplicateClaimed)
977193326Sed          continue;
978193326Sed      }
979193326Sed
980198092Srdivacky      Diag(clang::diag::warn_drv_unused_argument)
981193326Sed        << A->getAsString(C.getArgs());
982193326Sed    }
983193326Sed  }
984193326Sed}
985193326Sed
986203955Srdivackystatic const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
987203955Srdivacky                                    const JobAction *JA,
988203955Srdivacky                                    const ActionList *&Inputs) {
989203955Srdivacky  const Tool *ToolForJob = 0;
990203955Srdivacky
991203955Srdivacky  // See if we should look for a compiler with an integrated assembler. We match
992203955Srdivacky  // bottom up, so what we are actually looking for is an assembler job with a
993203955Srdivacky  // compiler input.
994208600Srdivacky
995208600Srdivacky  // FIXME: This doesn't belong here, but ideally we will support static soon
996208600Srdivacky  // anyway.
997208600Srdivacky  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
998208600Srdivacky                    C.getArgs().hasArg(options::OPT_static) ||
999208600Srdivacky                    C.getArgs().hasArg(options::OPT_fapple_kext));
1000208600Srdivacky  bool IsIADefault = (TC->IsIntegratedAssemblerDefault() && !HasStatic);
1001208600Srdivacky  if (C.getArgs().hasFlag(options::OPT_integrated_as,
1002203955Srdivacky                         options::OPT_no_integrated_as,
1003208600Srdivacky                         IsIADefault) &&
1004203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1005203955Srdivacky      isa<AssembleJobAction>(JA) &&
1006203955Srdivacky      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1007203955Srdivacky    const Tool &Compiler = TC->SelectTool(C,cast<JobAction>(**Inputs->begin()));
1008203955Srdivacky    if (Compiler.hasIntegratedAssembler()) {
1009203955Srdivacky      Inputs = &(*Inputs)[0]->getInputs();
1010203955Srdivacky      ToolForJob = &Compiler;
1011203955Srdivacky    }
1012203955Srdivacky  }
1013203955Srdivacky
1014203955Srdivacky  // Otherwise use the tool for the current job.
1015203955Srdivacky  if (!ToolForJob)
1016203955Srdivacky    ToolForJob = &TC->SelectTool(C, *JA);
1017203955Srdivacky
1018203955Srdivacky  // See if we should use an integrated preprocessor. We do so when we have
1019203955Srdivacky  // exactly one input, since this is the only use case we care about
1020203955Srdivacky  // (irrelevant since we don't support combine yet).
1021203955Srdivacky  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1022203955Srdivacky      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1023203955Srdivacky      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1024203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1025203955Srdivacky      ToolForJob->hasIntegratedCPP())
1026203955Srdivacky    Inputs = &(*Inputs)[0]->getInputs();
1027203955Srdivacky
1028203955Srdivacky  return *ToolForJob;
1029203955Srdivacky}
1030203955Srdivacky
1031193326Sedvoid Driver::BuildJobsForAction(Compilation &C,
1032193326Sed                                const Action *A,
1033193326Sed                                const ToolChain *TC,
1034198092Srdivacky                                const char *BoundArch,
1035193326Sed                                bool CanAcceptPipe,
1036193326Sed                                bool AtTopLevel,
1037193326Sed                                const char *LinkingOutput,
1038193326Sed                                InputInfo &Result) const {
1039198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1040193326Sed
1041193326Sed  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
1042198092Srdivacky  // FIXME: Pipes are forcibly disabled until we support executing them.
1043193326Sed  if (!CCCPrintBindings)
1044193326Sed    UsePipes = false;
1045193326Sed
1046193326Sed  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1047198092Srdivacky    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1048198092Srdivacky    // just using Args was better?
1049193326Sed    const Arg &Input = IA->getInputArg();
1050193326Sed    Input.claim();
1051210299Sed    if (Input.getOption().matches(options::OPT_INPUT)) {
1052193326Sed      const char *Name = Input.getValue(C.getArgs());
1053193326Sed      Result = InputInfo(Name, A->getType(), Name);
1054193326Sed    } else
1055193326Sed      Result = InputInfo(&Input, A->getType(), "");
1056193326Sed    return;
1057193326Sed  }
1058193326Sed
1059193326Sed  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1060198092Srdivacky    const ToolChain *TC = &C.getDefaultToolChain();
1061198092Srdivacky
1062193326Sed    std::string Arch;
1063198092Srdivacky    if (BAA->getArchName())
1064198092Srdivacky      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1065198092Srdivacky
1066198092Srdivacky    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1067198092Srdivacky                       CanAcceptPipe, AtTopLevel, LinkingOutput, Result);
1068193326Sed    return;
1069193326Sed  }
1070193326Sed
1071203955Srdivacky  const ActionList *Inputs = &A->getInputs();
1072203955Srdivacky
1073193326Sed  const JobAction *JA = cast<JobAction>(A);
1074203955Srdivacky  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1075198092Srdivacky
1076193326Sed  // Only use pipes when there is exactly one input.
1077193326Sed  bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
1078193326Sed  InputInfoList InputInfos;
1079193326Sed  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1080193326Sed       it != ie; ++it) {
1081210299Sed    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1082210299Sed    // temporary output names.
1083210299Sed    //
1084210299Sed    // FIXME: Clean this up.
1085210299Sed    bool SubJobAtTopLevel = false;
1086210299Sed    if (AtTopLevel && isa<DsymutilJobAction>(A))
1087210299Sed      SubJobAtTopLevel = true;
1088210299Sed
1089193326Sed    InputInfo II;
1090198092Srdivacky    BuildJobsForAction(C, *it, TC, BoundArch, TryToUsePipeInput,
1091210299Sed                       SubJobAtTopLevel, LinkingOutput, II);
1092193326Sed    InputInfos.push_back(II);
1093193326Sed  }
1094193326Sed
1095193326Sed  // Determine if we should output to a pipe.
1096193326Sed  bool OutputToPipe = false;
1097193326Sed  if (CanAcceptPipe && T.canPipeOutput()) {
1098198092Srdivacky    // Some actions default to writing to a pipe if they are the top level phase
1099198092Srdivacky    // and there was no user override.
1100193326Sed    //
1101193326Sed    // FIXME: Is there a better way to handle this?
1102193326Sed    if (AtTopLevel) {
1103193326Sed      if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
1104193326Sed        OutputToPipe = true;
1105193326Sed    } else if (UsePipes)
1106193326Sed      OutputToPipe = true;
1107193326Sed  }
1108193326Sed
1109193326Sed  // Figure out where to put the job (pipes).
1110193326Sed  Job *Dest = &C.getJobs();
1111193326Sed  if (InputInfos[0].isPipe()) {
1112193326Sed    assert(TryToUsePipeInput && "Unrequested pipe!");
1113193326Sed    assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
1114193326Sed    Dest = &InputInfos[0].getPipe();
1115193326Sed  }
1116193326Sed
1117193326Sed  // Always use the first input as the base input.
1118193326Sed  const char *BaseInput = InputInfos[0].getBaseInput();
1119193326Sed
1120210299Sed  // ... except dsymutil actions, which use their actual input as the base
1121210299Sed  // input.
1122210299Sed  if (JA->getType() == types::TY_dSYM)
1123210299Sed    BaseInput = InputInfos[0].getFilename();
1124210299Sed
1125198092Srdivacky  // Determine the place to write output to (nothing, pipe, or filename) and
1126198092Srdivacky  // where to put the new job.
1127193326Sed  if (JA->getType() == types::TY_Nothing) {
1128193326Sed    Result = InputInfo(A->getType(), BaseInput);
1129193326Sed  } else if (OutputToPipe) {
1130193326Sed    // Append to current piped job or create a new one as appropriate.
1131193326Sed    PipedJob *PJ = dyn_cast<PipedJob>(Dest);
1132193326Sed    if (!PJ) {
1133193326Sed      PJ = new PipedJob();
1134198092Srdivacky      // FIXME: Temporary hack so that -ccc-print-bindings work until we have
1135198092Srdivacky      // pipe support. Please remove later.
1136193326Sed      if (!CCCPrintBindings)
1137193326Sed        cast<JobList>(Dest)->addJob(PJ);
1138193326Sed      Dest = PJ;
1139193326Sed    }
1140193326Sed    Result = InputInfo(PJ, A->getType(), BaseInput);
1141193326Sed  } else {
1142193326Sed    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1143193326Sed                       A->getType(), BaseInput);
1144193326Sed  }
1145193326Sed
1146193326Sed  if (CCCPrintBindings) {
1147193326Sed    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1148193326Sed                 << " - \"" << T.getName() << "\", inputs: [";
1149193326Sed    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1150193326Sed      llvm::errs() << InputInfos[i].getAsString();
1151193326Sed      if (i + 1 != e)
1152193326Sed        llvm::errs() << ", ";
1153193326Sed    }
1154193326Sed    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1155193326Sed  } else {
1156198092Srdivacky    T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
1157198092Srdivacky                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1158193326Sed  }
1159193326Sed}
1160193326Sed
1161198092Srdivackyconst char *Driver::GetNamedOutputPath(Compilation &C,
1162193326Sed                                       const JobAction &JA,
1163193326Sed                                       const char *BaseInput,
1164193326Sed                                       bool AtTopLevel) const {
1165193326Sed  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1166193326Sed  // Output to a user requested destination?
1167210299Sed  if (AtTopLevel && !isa<DsymutilJobAction>(JA)) {
1168193326Sed    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1169193326Sed      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1170193326Sed  }
1171193326Sed
1172193326Sed  // Output to a temporary file?
1173193326Sed  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1174198092Srdivacky    std::string TmpName =
1175193326Sed      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1176193326Sed    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1177193326Sed  }
1178193326Sed
1179193326Sed  llvm::sys::Path BasePath(BaseInput);
1180193326Sed  std::string BaseName(BasePath.getLast());
1181193326Sed
1182193326Sed  // Determine what the derived output name should be.
1183193326Sed  const char *NamedOutput;
1184193326Sed  if (JA.getType() == types::TY_Image) {
1185193326Sed    NamedOutput = DefaultImageName.c_str();
1186193326Sed  } else {
1187193326Sed    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1188193326Sed    assert(Suffix && "All types used for output should have a suffix.");
1189193326Sed
1190193326Sed    std::string::size_type End = std::string::npos;
1191193326Sed    if (!types::appendSuffixForType(JA.getType()))
1192193326Sed      End = BaseName.rfind('.');
1193193326Sed    std::string Suffixed(BaseName.substr(0, End));
1194193326Sed    Suffixed += '.';
1195193326Sed    Suffixed += Suffix;
1196193326Sed    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1197193326Sed  }
1198193326Sed
1199198092Srdivacky  // As an annoying special case, PCH generation doesn't strip the pathname.
1200193326Sed  if (JA.getType() == types::TY_PCH) {
1201193326Sed    BasePath.eraseComponent();
1202193326Sed    if (BasePath.isEmpty())
1203193326Sed      BasePath = NamedOutput;
1204193326Sed    else
1205193326Sed      BasePath.appendComponent(NamedOutput);
1206193326Sed    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1207193326Sed  } else {
1208193326Sed    return C.addResultFile(NamedOutput);
1209193326Sed  }
1210193326Sed}
1211193326Sed
1212198092Srdivackystd::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1213206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1214206084Srdivacky  // attempting to use this prefix when lokup up program paths.
1215206084Srdivacky  if (!PrefixDir.empty()) {
1216206084Srdivacky    llvm::sys::Path P(PrefixDir);
1217206084Srdivacky    P.appendComponent(Name);
1218206084Srdivacky    if (P.exists())
1219206084Srdivacky      return P.str();
1220206084Srdivacky  }
1221206084Srdivacky
1222193326Sed  const ToolChain::path_list &List = TC.getFilePaths();
1223198092Srdivacky  for (ToolChain::path_list::const_iterator
1224193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1225193326Sed    llvm::sys::Path P(*it);
1226193326Sed    P.appendComponent(Name);
1227193326Sed    if (P.exists())
1228198092Srdivacky      return P.str();
1229193326Sed  }
1230193326Sed
1231198092Srdivacky  return Name;
1232193326Sed}
1233193326Sed
1234198092Srdivackystd::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1235198092Srdivacky                                   bool WantFile) const {
1236206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1237206084Srdivacky  // attempting to use this prefix when lokup up program paths.
1238206084Srdivacky  if (!PrefixDir.empty()) {
1239206084Srdivacky    llvm::sys::Path P(PrefixDir);
1240206084Srdivacky    P.appendComponent(Name);
1241206084Srdivacky    if (WantFile ? P.exists() : P.canExecute())
1242206084Srdivacky      return P.str();
1243206084Srdivacky  }
1244206084Srdivacky
1245193326Sed  const ToolChain::path_list &List = TC.getProgramPaths();
1246198092Srdivacky  for (ToolChain::path_list::const_iterator
1247193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1248193326Sed    llvm::sys::Path P(*it);
1249193326Sed    P.appendComponent(Name);
1250193326Sed    if (WantFile ? P.exists() : P.canExecute())
1251198092Srdivacky      return P.str();
1252193326Sed  }
1253193326Sed
1254193326Sed  // If all else failed, search the path.
1255193326Sed  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1256193326Sed  if (!P.empty())
1257198092Srdivacky    return P.str();
1258193326Sed
1259198092Srdivacky  return Name;
1260193326Sed}
1261193326Sed
1262193326Sedstd::string Driver::GetTemporaryPath(const char *Suffix) const {
1263198092Srdivacky  // FIXME: This is lame; sys::Path should provide this function (in particular,
1264198092Srdivacky  // it should know how to find the temporary files dir).
1265193326Sed  std::string Error;
1266193326Sed  const char *TmpDir = ::getenv("TMPDIR");
1267193326Sed  if (!TmpDir)
1268193326Sed    TmpDir = ::getenv("TEMP");
1269193326Sed  if (!TmpDir)
1270193326Sed    TmpDir = ::getenv("TMP");
1271193326Sed  if (!TmpDir)
1272193326Sed    TmpDir = "/tmp";
1273193326Sed  llvm::sys::Path P(TmpDir);
1274193326Sed  P.appendComponent("cc");
1275193326Sed  if (P.makeUnique(false, &Error)) {
1276193326Sed    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1277193326Sed    return "";
1278193326Sed  }
1279193326Sed
1280198092Srdivacky  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1281193326Sed  P.eraseFromDisk(false, 0);
1282193326Sed
1283193326Sed  P.appendSuffix(Suffix);
1284198092Srdivacky  return P.str();
1285193326Sed}
1286193326Sed
1287193326Sedconst HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1288193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1289193326Sed  llvm::Triple Triple(TripleStr);
1290193326Sed
1291204793Srdivacky  // TCE is an osless target
1292204793Srdivacky  if (Triple.getArchName() == "tce")
1293210299Sed    return createTCEHostInfo(*this, Triple);
1294204793Srdivacky
1295193326Sed  switch (Triple.getOS()) {
1296198092Srdivacky  case llvm::Triple::AuroraUX:
1297198092Srdivacky    return createAuroraUXHostInfo(*this, Triple);
1298193326Sed  case llvm::Triple::Darwin:
1299193326Sed    return createDarwinHostInfo(*this, Triple);
1300193326Sed  case llvm::Triple::DragonFly:
1301193326Sed    return createDragonFlyHostInfo(*this, Triple);
1302195341Sed  case llvm::Triple::OpenBSD:
1303195341Sed    return createOpenBSDHostInfo(*this, Triple);
1304193326Sed  case llvm::Triple::FreeBSD:
1305193326Sed    return createFreeBSDHostInfo(*this, Triple);
1306210299Sed  case llvm::Triple::Minix:
1307210299Sed    return createMinixHostInfo(*this, Triple);
1308193326Sed  case llvm::Triple::Linux:
1309193326Sed    return createLinuxHostInfo(*this, Triple);
1310193326Sed  default:
1311193326Sed    return createUnknownHostInfo(*this, Triple);
1312193326Sed  }
1313193326Sed}
1314193326Sed
1315193326Sedbool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1316198092Srdivacky                                    const llvm::Triple &Triple) const {
1317198092Srdivacky  // Check if user requested no clang, or clang doesn't understand this type (we
1318198092Srdivacky  // only handle single inputs for now).
1319198092Srdivacky  if (!CCCUseClang || JA.size() != 1 ||
1320193326Sed      !types::isAcceptedByClang((*JA.begin())->getType()))
1321193326Sed    return false;
1322193326Sed
1323193326Sed  // Otherwise make sure this is an action clang understands.
1324193326Sed  if (isa<PreprocessJobAction>(JA)) {
1325193326Sed    if (!CCCUseClangCPP) {
1326193326Sed      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1327193326Sed      return false;
1328193326Sed    }
1329193326Sed  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1330193326Sed    return false;
1331193326Sed
1332193326Sed  // Use clang for C++?
1333193326Sed  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1334193326Sed    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1335193326Sed    return false;
1336193326Sed  }
1337193326Sed
1338203955Srdivacky  // Always use clang for precompiling, AST generation, and rewriting,
1339203955Srdivacky  // regardless of archs.
1340210299Sed  if (isa<PrecompileJobAction>(JA) ||
1341210299Sed      types::isOnlyAcceptedByClang(JA.getType()))
1342193326Sed    return true;
1343193326Sed
1344198092Srdivacky  // Finally, don't use clang if this isn't one of the user specified archs to
1345198092Srdivacky  // build.
1346198092Srdivacky  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1347198092Srdivacky    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1348193326Sed    return false;
1349193326Sed  }
1350193326Sed
1351193326Sed  return true;
1352193326Sed}
1353193326Sed
1354198092Srdivacky/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1355198092Srdivacky/// grouped values as integers. Numbers which are not provided are set to 0.
1356193326Sed///
1357198092Srdivacky/// \return True if the entire string was parsed (9.2), or all groups were
1358198092Srdivacky/// parsed (10.3.5extrastuff).
1359198092Srdivackybool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1360193326Sed                               unsigned &Minor, unsigned &Micro,
1361193326Sed                               bool &HadExtra) {
1362193326Sed  HadExtra = false;
1363193326Sed
1364193326Sed  Major = Minor = Micro = 0;
1365198092Srdivacky  if (*Str == '\0')
1366193326Sed    return true;
1367193326Sed
1368193326Sed  char *End;
1369193326Sed  Major = (unsigned) strtol(Str, &End, 10);
1370193326Sed  if (*Str != '\0' && *End == '\0')
1371193326Sed    return true;
1372193326Sed  if (*End != '.')
1373193326Sed    return false;
1374198092Srdivacky
1375193326Sed  Str = End+1;
1376193326Sed  Minor = (unsigned) strtol(Str, &End, 10);
1377193326Sed  if (*Str != '\0' && *End == '\0')
1378193326Sed    return true;
1379193326Sed  if (*End != '.')
1380193326Sed    return false;
1381193326Sed
1382193326Sed  Str = End+1;
1383193326Sed  Micro = (unsigned) strtol(Str, &End, 10);
1384193326Sed  if (*Str != '\0' && *End == '\0')
1385193326Sed    return true;
1386193326Sed  if (Str == End)
1387193326Sed    return false;
1388193326Sed  HadExtra = true;
1389193326Sed  return true;
1390193326Sed}
1391