Driver.cpp revision 194613
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"
19193326Sed#include "clang/Driver/Option.h"
20193326Sed#include "clang/Driver/Options.h"
21193326Sed#include "clang/Driver/Tool.h"
22193326Sed#include "clang/Driver/ToolChain.h"
23193326Sed#include "clang/Driver/Types.h"
24193326Sed
25193326Sed#include "clang/Basic/Version.h"
26193326Sed
27193326Sed#include "llvm/ADT/StringSet.h"
28193326Sed#include "llvm/Support/PrettyStackTrace.h"
29193326Sed#include "llvm/Support/raw_ostream.h"
30193326Sed#include "llvm/System/Path.h"
31193326Sed#include "llvm/System/Program.h"
32193326Sed
33193326Sed#include "InputInfo.h"
34193326Sed
35193326Sed#include <map>
36193326Sed
37193326Sedusing namespace clang::driver;
38193326Sedusing namespace clang;
39193326Sed
40193326SedDriver::Driver(const char *_Name, const char *_Dir,
41193326Sed               const char *_DefaultHostTriple,
42193326Sed               const char *_DefaultImageName,
43193326Sed               Diagnostic &_Diags)
44193326Sed  : Opts(new OptTable()), Diags(_Diags),
45193326Sed    Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
46193326Sed    DefaultImageName(_DefaultImageName),
47193326Sed    Host(0),
48193326Sed    CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
49193326Sed    CCCGenericGCCName("gcc"), CCCUseClang(true), CCCUseClangCXX(false),
50193326Sed    CCCUseClangCPP(true), CCCUsePCH(true),
51193326Sed    SuppressMissingInputWarning(false)
52193326Sed{
53193326Sed  // Only use clang on i386 and x86_64 by default.
54193326Sed  CCCClangArchs.insert("i386");
55193326Sed  CCCClangArchs.insert("x86_64");
56193326Sed}
57193326Sed
58193326SedDriver::~Driver() {
59193326Sed  delete Opts;
60193326Sed  delete Host;
61193326Sed}
62193326Sed
63193326SedInputArgList *Driver::ParseArgStrings(const char **ArgBegin,
64193326Sed                                      const char **ArgEnd) {
65193326Sed  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
66193326Sed  InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
67193326Sed
68193326Sed  // FIXME: Handle '@' args (or at least error on them).
69193326Sed
70193326Sed  unsigned Index = 0, End = ArgEnd - ArgBegin;
71193326Sed  while (Index < End) {
72193326Sed    // gcc's handling of empty arguments doesn't make
73193326Sed    // sense, but this is not a common use case. :)
74193326Sed    //
75193326Sed    // We just ignore them here (note that other things may
76193326Sed    // still take them as arguments).
77193326Sed    if (Args->getArgString(Index)[0] == '\0') {
78193326Sed      ++Index;
79193326Sed      continue;
80193326Sed    }
81193326Sed
82193326Sed    unsigned Prev = Index;
83193326Sed    Arg *A = getOpts().ParseOneArg(*Args, Index);
84193326Sed    assert(Index > Prev && "Parser failed to consume argument.");
85193326Sed
86193326Sed    // Check for missing argument error.
87193326Sed    if (!A) {
88193326Sed      assert(Index >= End && "Unexpected parser error.");
89193326Sed      Diag(clang::diag::err_drv_missing_argument)
90193326Sed        << Args->getArgString(Prev)
91193326Sed        << (Index - Prev - 1);
92193326Sed      break;
93193326Sed    }
94193326Sed
95193326Sed    if (A->getOption().isUnsupported()) {
96193326Sed      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
97193326Sed      continue;
98193326Sed    }
99193326Sed    Args->append(A);
100193326Sed  }
101193326Sed
102193326Sed  return Args;
103193326Sed}
104193326Sed
105193326SedCompilation *Driver::BuildCompilation(int argc, const char **argv) {
106193326Sed  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
107193326Sed
108193326Sed  // FIXME: Handle environment options which effect driver behavior,
109193326Sed  // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
110193326Sed  // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
111193326Sed
112193326Sed  // FIXME: What are we going to do with -V and -b?
113193326Sed
114193326Sed  // FIXME: This stuff needs to go into the Compilation, not the
115193326Sed  // driver.
116193326Sed  bool CCCPrintOptions = false, CCCPrintActions = false;
117193326Sed
118193326Sed  const char **Start = argv + 1, **End = argv + argc;
119193326Sed  const char *HostTriple = DefaultHostTriple.c_str();
120193326Sed
121193326Sed  // Read -ccc args.
122193326Sed  //
123193326Sed  // FIXME: We need to figure out where this behavior should
124193326Sed  // live. Most of it should be outside in the client; the parts that
125193326Sed  // aren't should have proper options, either by introducing new ones
126193326Sed  // or by overloading gcc ones like -V or -b.
127193326Sed  for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
128193326Sed    const char *Opt = *Start + 5;
129193326Sed
130193326Sed    if (!strcmp(Opt, "print-options")) {
131193326Sed      CCCPrintOptions = true;
132193326Sed    } else if (!strcmp(Opt, "print-phases")) {
133193326Sed      CCCPrintActions = true;
134193326Sed    } else if (!strcmp(Opt, "print-bindings")) {
135193326Sed      CCCPrintBindings = true;
136193326Sed    } else if (!strcmp(Opt, "cxx")) {
137193326Sed      CCCIsCXX = true;
138193326Sed    } else if (!strcmp(Opt, "echo")) {
139193326Sed      CCCEcho = true;
140193326Sed
141193326Sed    } else if (!strcmp(Opt, "gcc-name")) {
142193326Sed      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
143193326Sed      CCCGenericGCCName = *++Start;
144193326Sed
145193326Sed    } else if (!strcmp(Opt, "clang-cxx")) {
146193326Sed      CCCUseClangCXX = true;
147193326Sed    } else if (!strcmp(Opt, "pch-is-pch")) {
148193326Sed      CCCUsePCH = true;
149193326Sed    } else if (!strcmp(Opt, "pch-is-pth")) {
150193326Sed      CCCUsePCH = false;
151193326Sed    } else if (!strcmp(Opt, "no-clang")) {
152193326Sed      CCCUseClang = false;
153193326Sed    } else if (!strcmp(Opt, "no-clang-cpp")) {
154193326Sed      CCCUseClangCPP = false;
155193326Sed    } else if (!strcmp(Opt, "clang-archs")) {
156193326Sed      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
157193326Sed      const char *Cur = *++Start;
158193326Sed
159193326Sed      CCCClangArchs.clear();
160193326Sed      for (;;) {
161193326Sed        const char *Next = strchr(Cur, ',');
162193326Sed
163193326Sed        if (Next) {
164193326Sed          if (Cur != Next)
165193326Sed            CCCClangArchs.insert(std::string(Cur, Next));
166193326Sed          Cur = Next + 1;
167193326Sed        } else {
168193326Sed          if (*Cur != '\0')
169193326Sed            CCCClangArchs.insert(std::string(Cur));
170193326Sed          break;
171193326Sed        }
172193326Sed      }
173193326Sed
174193326Sed    } else if (!strcmp(Opt, "host-triple")) {
175193326Sed      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
176193326Sed      HostTriple = *++Start;
177193326Sed
178193326Sed    } else {
179193326Sed      // FIXME: Error handling.
180193326Sed      llvm::errs() << "invalid option: " << *Start << "\n";
181193326Sed      exit(1);
182193326Sed    }
183193326Sed  }
184193326Sed
185193326Sed  InputArgList *Args = ParseArgStrings(Start, End);
186193326Sed
187193326Sed  Host = GetHostInfo(HostTriple);
188193326Sed
189193326Sed  // The compilation takes ownership of Args.
190193326Sed  Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args);
191193326Sed
192193326Sed  // FIXME: This behavior shouldn't be here.
193193326Sed  if (CCCPrintOptions) {
194193326Sed    PrintOptions(C->getArgs());
195193326Sed    return C;
196193326Sed  }
197193326Sed
198193326Sed  if (!HandleImmediateArgs(*C))
199193326Sed    return C;
200193326Sed
201193326Sed  // Construct the list of abstract actions to perform for this
202193326Sed  // compilation. We avoid passing a Compilation here simply to
203193326Sed  // enforce the abstraction that pipelining is not host or toolchain
204193326Sed  // dependent (other than the driver driver test).
205193326Sed  if (Host->useDriverDriver())
206193326Sed    BuildUniversalActions(C->getArgs(), C->getActions());
207193326Sed  else
208193326Sed    BuildActions(C->getArgs(), C->getActions());
209193326Sed
210193326Sed  if (CCCPrintActions) {
211193326Sed    PrintActions(*C);
212193326Sed    return C;
213193326Sed  }
214193326Sed
215193326Sed  BuildJobs(*C);
216193326Sed
217193326Sed  return C;
218193326Sed}
219193326Sed
220193326Sedvoid Driver::PrintOptions(const ArgList &Args) const {
221193326Sed  unsigned i = 0;
222193326Sed  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
223193326Sed       it != ie; ++it, ++i) {
224193326Sed    Arg *A = *it;
225193326Sed    llvm::errs() << "Option " << i << " - "
226193326Sed                 << "Name: \"" << A->getOption().getName() << "\", "
227193326Sed                 << "Values: {";
228193326Sed    for (unsigned j = 0; j < A->getNumValues(); ++j) {
229193326Sed      if (j)
230193326Sed        llvm::errs() << ", ";
231193326Sed      llvm::errs() << '"' << A->getValue(Args, j) << '"';
232193326Sed    }
233193326Sed    llvm::errs() << "}\n";
234193326Sed  }
235193326Sed}
236193326Sed
237193326Sedstatic std::string getOptionHelpName(const OptTable &Opts, options::ID Id) {
238193326Sed  std::string Name = Opts.getOptionName(Id);
239193326Sed
240193326Sed  // Add metavar, if used.
241193326Sed  switch (Opts.getOptionKind(Id)) {
242193326Sed  case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
243193326Sed    assert(0 && "Invalid option with help text.");
244193326Sed
245193326Sed  case Option::MultiArgClass: case Option::JoinedAndSeparateClass:
246193326Sed    assert(0 && "Cannot print metavar for this kind of option.");
247193326Sed
248193326Sed  case Option::FlagClass:
249193326Sed    break;
250193326Sed
251193326Sed  case Option::SeparateClass: case Option::JoinedOrSeparateClass:
252193326Sed    Name += ' ';
253193326Sed    // FALLTHROUGH
254193326Sed  case Option::JoinedClass: case Option::CommaJoinedClass:
255193326Sed    Name += Opts.getOptionMetaVar(Id);
256193326Sed    break;
257193326Sed  }
258193326Sed
259193326Sed  return Name;
260193326Sed}
261193326Sed
262193326Sedvoid Driver::PrintHelp(bool ShowHidden) const {
263193326Sed  llvm::raw_ostream &OS = llvm::outs();
264193326Sed
265193326Sed  OS << "OVERVIEW: clang \"gcc-compatible\" driver\n";
266193326Sed  OS << '\n';
267193326Sed  OS << "USAGE: " << Name << " [options] <input files>\n";
268193326Sed  OS << '\n';
269193326Sed  OS << "OPTIONS:\n";
270193326Sed
271193326Sed  // Render help text into (option, help) pairs.
272193326Sed  std::vector< std::pair<std::string, const char*> > OptionHelp;
273193326Sed
274193326Sed  for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) {
275193326Sed    options::ID Id = (options::ID) i;
276193326Sed    if (const char *Text = getOpts().getOptionHelpText(Id))
277193326Sed      OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id),
278193326Sed                                          Text));
279193326Sed  }
280193326Sed
281193326Sed  if (ShowHidden) {
282193326Sed    OptionHelp.push_back(std::make_pair("\nDRIVER OPTIONS:",""));
283193326Sed    OptionHelp.push_back(std::make_pair("-ccc-cxx",
284193326Sed                                        "Act as a C++ driver"));
285193326Sed    OptionHelp.push_back(std::make_pair("-ccc-gcc-name",
286193326Sed                                        "Name for native GCC compiler"));
287193326Sed    OptionHelp.push_back(std::make_pair("-ccc-clang-cxx",
288193326Sed                                        "Use the clang compiler for C++"));
289193326Sed    OptionHelp.push_back(std::make_pair("-ccc-no-clang",
290193326Sed                                        "Never use the clang compiler"));
291193326Sed    OptionHelp.push_back(std::make_pair("-ccc-no-clang-cpp",
292193326Sed                                        "Never use the clang preprocessor"));
293193326Sed    OptionHelp.push_back(std::make_pair("-ccc-clang-archs",
294193326Sed                                        "Comma separate list of architectures "
295193326Sed                                        "to use the clang compiler for"));
296193326Sed    OptionHelp.push_back(std::make_pair("-ccc-pch-is-pch",
297193326Sed                                     "Use lazy PCH for precompiled headers"));
298193326Sed    OptionHelp.push_back(std::make_pair("-ccc-pch-is-pth",
299193326Sed                         "Use pretokenized headers for precompiled headers"));
300193326Sed
301193326Sed    OptionHelp.push_back(std::make_pair("\nDEBUG/DEVELOPMENT OPTIONS:",""));
302193326Sed    OptionHelp.push_back(std::make_pair("-ccc-host-triple",
303193326Sed                                        "Simulate running on the given target"));
304193326Sed    OptionHelp.push_back(std::make_pair("-ccc-print-options",
305193326Sed                                        "Dump parsed command line arguments"));
306193326Sed    OptionHelp.push_back(std::make_pair("-ccc-print-phases",
307193326Sed                                        "Dump list of actions to perform"));
308193326Sed    OptionHelp.push_back(std::make_pair("-ccc-print-bindings",
309193326Sed                                        "Show bindings of tools to actions"));
310193326Sed    OptionHelp.push_back(std::make_pair("CCC_ADD_ARGS",
311193326Sed                               "(ENVIRONMENT VARIABLE) Comma separated list of "
312193326Sed                               "arguments to prepend to the command line"));
313193326Sed  }
314193326Sed
315193326Sed  // Find the maximum option length.
316193326Sed  unsigned OptionFieldWidth = 0;
317193326Sed  for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
318193326Sed    // Skip titles.
319193326Sed    if (!OptionHelp[i].second)
320193326Sed      continue;
321193326Sed
322193326Sed    // Limit the amount of padding we are willing to give up for
323193326Sed    // alignment.
324193326Sed    unsigned Length = OptionHelp[i].first.size();
325193326Sed    if (Length <= 23)
326193326Sed      OptionFieldWidth = std::max(OptionFieldWidth, Length);
327193326Sed  }
328193326Sed
329193326Sed  for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
330193326Sed    const std::string &Option = OptionHelp[i].first;
331193326Sed    OS << "  " << Option;
332193326Sed    for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j)
333193326Sed      OS << ' ';
334193326Sed    OS << ' ' << OptionHelp[i].second << '\n';
335193326Sed  }
336193326Sed
337193326Sed  OS.flush();
338193326Sed}
339193326Sed
340193326Sedvoid Driver::PrintVersion(const Compilation &C) const {
341193326Sed  static char buf[] = "$URL: https://ed@llvm.org/svn/llvm-project/cfe/trunk/lib/Driver/Driver.cpp $";
342193326Sed  char *zap = strstr(buf, "/lib/Driver");
343193326Sed  if (zap)
344193326Sed    *zap = 0;
345193326Sed  zap = strstr(buf, "/clang/tools/clang");
346193326Sed  if (zap)
347193326Sed    *zap = 0;
348193326Sed  const char *vers = buf+6;
349193326Sed  // FIXME: Add cmake support and remove #ifdef
350193326Sed#ifdef SVN_REVISION
351193326Sed  const char *revision = SVN_REVISION;
352193326Sed#else
353193326Sed  const char *revision = "";
354193326Sed#endif
355193326Sed  // FIXME: The following handlers should use a callback mechanism, we
356193326Sed  // don't know what the client would like to do.
357193326Sed
358193326Sed  llvm::errs() << "clang version " CLANG_VERSION_STRING " ("
359194613Sed               << vers << " " << revision << ")" << '\n';
360193326Sed
361193326Sed  const ToolChain &TC = C.getDefaultToolChain();
362193326Sed  llvm::errs() << "Target: " << TC.getTripleString() << '\n';
363194613Sed
364194613Sed  // Print the threading model.
365194613Sed  //
366194613Sed  // FIXME: Implement correctly.
367194613Sed  llvm::errs() << "Thread model: " << "posix" << '\n';
368193326Sed}
369193326Sed
370193326Sedbool Driver::HandleImmediateArgs(const Compilation &C) {
371193326Sed  // The order these options are handled in in gcc is all over the
372193326Sed  // place, but we don't expect inconsistencies w.r.t. that to matter
373193326Sed  // in practice.
374193326Sed
375193326Sed  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
376193326Sed    llvm::outs() << CLANG_VERSION_STRING "\n";
377193326Sed    return false;
378193326Sed  }
379193326Sed
380193326Sed  if (C.getArgs().hasArg(options::OPT__help) ||
381193326Sed      C.getArgs().hasArg(options::OPT__help_hidden)) {
382193326Sed    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
383193326Sed    return false;
384193326Sed  }
385193326Sed
386193326Sed  if (C.getArgs().hasArg(options::OPT__version)) {
387193326Sed    PrintVersion(C);
388193326Sed    return false;
389193326Sed  }
390193326Sed
391193326Sed  if (C.getArgs().hasArg(options::OPT_v) ||
392193326Sed      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
393193326Sed    PrintVersion(C);
394193326Sed    SuppressMissingInputWarning = true;
395193326Sed  }
396193326Sed
397193326Sed  const ToolChain &TC = C.getDefaultToolChain();
398193326Sed  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
399193326Sed    llvm::outs() << "programs: =";
400193326Sed    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
401193326Sed           ie = TC.getProgramPaths().end(); it != ie; ++it) {
402193326Sed      if (it != TC.getProgramPaths().begin())
403193326Sed        llvm::outs() << ':';
404193326Sed      llvm::outs() << *it;
405193326Sed    }
406193326Sed    llvm::outs() << "\n";
407193326Sed    llvm::outs() << "libraries: =";
408193326Sed    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
409193326Sed           ie = TC.getFilePaths().end(); it != ie; ++it) {
410193326Sed      if (it != TC.getFilePaths().begin())
411193326Sed        llvm::outs() << ':';
412193326Sed      llvm::outs() << *it;
413193326Sed    }
414193326Sed    llvm::outs() << "\n";
415193326Sed    return false;
416193326Sed  }
417193326Sed
418193326Sed  // FIXME: The following handlers should use a callback mechanism, we
419193326Sed  // don't know what the client would like to do.
420193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
421193326Sed    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString()
422193326Sed                 << "\n";
423193326Sed    return false;
424193326Sed  }
425193326Sed
426193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
427193326Sed    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString()
428193326Sed                 << "\n";
429193326Sed    return false;
430193326Sed  }
431193326Sed
432193326Sed  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
433193326Sed    llvm::outs() << GetFilePath("libgcc.a", TC).toString() << "\n";
434193326Sed    return false;
435193326Sed  }
436193326Sed
437194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
438194613Sed    // FIXME: We need tool chain support for this.
439194613Sed    llvm::outs() << ".;\n";
440194613Sed
441194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
442194613Sed    default:
443194613Sed      break;
444194613Sed
445194613Sed    case llvm::Triple::x86_64:
446194613Sed      llvm::outs() << "x86_64;@m64" << "\n";
447194613Sed      break;
448194613Sed
449194613Sed    case llvm::Triple::ppc64:
450194613Sed      llvm::outs() << "ppc64;@m64" << "\n";
451194613Sed      break;
452194613Sed    }
453194613Sed    return false;
454194613Sed  }
455194613Sed
456194613Sed  // FIXME: What is the difference between print-multi-directory and
457194613Sed  // print-multi-os-directory?
458194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
459194613Sed      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
460194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
461194613Sed    default:
462194613Sed    case llvm::Triple::x86:
463194613Sed    case llvm::Triple::ppc:
464194613Sed      llvm::outs() << "." << "\n";
465194613Sed      break;
466194613Sed
467194613Sed    case llvm::Triple::x86_64:
468194613Sed      llvm::outs() << "x86_64" << "\n";
469194613Sed      break;
470194613Sed
471194613Sed    case llvm::Triple::ppc64:
472194613Sed      llvm::outs() << "ppc64" << "\n";
473194613Sed      break;
474194613Sed    }
475194613Sed    return false;
476194613Sed  }
477194613Sed
478193326Sed  return true;
479193326Sed}
480193326Sed
481193326Sedstatic unsigned PrintActions1(const Compilation &C,
482193326Sed                              Action *A,
483193326Sed                              std::map<Action*, unsigned> &Ids) {
484193326Sed  if (Ids.count(A))
485193326Sed    return Ids[A];
486193326Sed
487193326Sed  std::string str;
488193326Sed  llvm::raw_string_ostream os(str);
489193326Sed
490193326Sed  os << Action::getClassName(A->getKind()) << ", ";
491193326Sed  if (InputAction *IA = dyn_cast<InputAction>(A)) {
492193326Sed    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
493193326Sed  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
494193326Sed    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
495193326Sed                  C.getDefaultToolChain().getArchName()) << '"'
496193326Sed       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
497193326Sed  } else {
498193326Sed    os << "{";
499193326Sed    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
500193326Sed      os << PrintActions1(C, *it, Ids);
501193326Sed      ++it;
502193326Sed      if (it != ie)
503193326Sed        os << ", ";
504193326Sed    }
505193326Sed    os << "}";
506193326Sed  }
507193326Sed
508193326Sed  unsigned Id = Ids.size();
509193326Sed  Ids[A] = Id;
510193326Sed  llvm::errs() << Id << ": " << os.str() << ", "
511193326Sed               << types::getTypeName(A->getType()) << "\n";
512193326Sed
513193326Sed  return Id;
514193326Sed}
515193326Sed
516193326Sedvoid Driver::PrintActions(const Compilation &C) const {
517193326Sed  std::map<Action*, unsigned> Ids;
518193326Sed  for (ActionList::const_iterator it = C.getActions().begin(),
519193326Sed         ie = C.getActions().end(); it != ie; ++it)
520193326Sed    PrintActions1(C, *it, Ids);
521193326Sed}
522193326Sed
523193326Sedvoid Driver::BuildUniversalActions(const ArgList &Args,
524193326Sed                                   ActionList &Actions) const {
525193326Sed  llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
526193326Sed  // Collect the list of architectures. Duplicates are allowed, but
527193326Sed  // should only be handled once (in the order seen).
528193326Sed  llvm::StringSet<> ArchNames;
529193326Sed  llvm::SmallVector<const char *, 4> Archs;
530193326Sed  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
531193326Sed       it != ie; ++it) {
532193326Sed    Arg *A = *it;
533193326Sed
534193326Sed    if (A->getOption().getId() == options::OPT_arch) {
535193326Sed      const char *Name = A->getValue(Args);
536193326Sed
537193326Sed      // FIXME: We need to handle canonicalization of the specified
538193326Sed      // arch?
539193326Sed
540193326Sed      A->claim();
541193326Sed      if (ArchNames.insert(Name))
542193326Sed        Archs.push_back(Name);
543193326Sed    }
544193326Sed  }
545193326Sed
546193326Sed  // When there is no explicit arch for this platform, make sure we
547193326Sed  // still bind the architecture (to the default) so that -Xarch_ is
548193326Sed  // handled correctly.
549193326Sed  if (!Archs.size())
550193326Sed    Archs.push_back(0);
551193326Sed
552193326Sed  // FIXME: We killed off some others but these aren't yet detected in
553193326Sed  // a functional manner. If we added information to jobs about which
554193326Sed  // "auxiliary" files they wrote then we could detect the conflict
555193326Sed  // these cause downstream.
556193326Sed  if (Archs.size() > 1) {
557193326Sed    // No recovery needed, the point of this is just to prevent
558193326Sed    // overwriting the same files.
559193326Sed    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
560193326Sed      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
561193326Sed        << A->getAsString(Args);
562193326Sed  }
563193326Sed
564193326Sed  ActionList SingleActions;
565193326Sed  BuildActions(Args, SingleActions);
566193326Sed
567193326Sed  // Add in arch binding and lipo (if necessary) for every top level
568193326Sed  // action.
569193326Sed  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
570193326Sed    Action *Act = SingleActions[i];
571193326Sed
572193326Sed    // Make sure we can lipo this kind of output. If not (and it is an
573193326Sed    // actual output) then we disallow, since we can't create an
574193326Sed    // output file with the right name without overwriting it. We
575193326Sed    // could remove this oddity by just changing the output names to
576193326Sed    // include the arch, which would also fix
577193326Sed    // -save-temps. Compatibility wins for now.
578193326Sed
579193326Sed    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
580193326Sed      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
581193326Sed        << types::getTypeName(Act->getType());
582193326Sed
583193326Sed    ActionList Inputs;
584193326Sed    for (unsigned i = 0, e = Archs.size(); i != e; ++i)
585193326Sed      Inputs.push_back(new BindArchAction(Act, Archs[i]));
586193326Sed
587193326Sed    // Lipo if necessary, We do it this way because we need to set the
588193326Sed    // arch flag so that -Xarch_ gets overwritten.
589193326Sed    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
590193326Sed      Actions.append(Inputs.begin(), Inputs.end());
591193326Sed    else
592193326Sed      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
593193326Sed  }
594193326Sed}
595193326Sed
596193326Sedvoid Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
597193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
598193326Sed  // Start by constructing the list of inputs and their types.
599193326Sed
600193326Sed  // Track the current user specified (-x) input. We also explicitly
601193326Sed  // track the argument used to set the type; we only want to claim
602193326Sed  // the type when we actually use it, so we warn about unused -x
603193326Sed  // arguments.
604193326Sed  types::ID InputType = types::TY_Nothing;
605193326Sed  Arg *InputTypeArg = 0;
606193326Sed
607193326Sed  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
608193326Sed  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
609193326Sed       it != ie; ++it) {
610193326Sed    Arg *A = *it;
611193326Sed
612193326Sed    if (isa<InputOption>(A->getOption())) {
613193326Sed      const char *Value = A->getValue(Args);
614193326Sed      types::ID Ty = types::TY_INVALID;
615193326Sed
616193326Sed      // Infer the input type if necessary.
617193326Sed      if (InputType == types::TY_Nothing) {
618193326Sed        // If there was an explicit arg for this, claim it.
619193326Sed        if (InputTypeArg)
620193326Sed          InputTypeArg->claim();
621193326Sed
622193326Sed        // stdin must be handled specially.
623193326Sed        if (memcmp(Value, "-", 2) == 0) {
624193326Sed          // If running with -E, treat as a C input (this changes the
625193326Sed          // builtin macros, for example). This may be overridden by
626193326Sed          // -ObjC below.
627193326Sed          //
628193326Sed          // Otherwise emit an error but still use a valid type to
629193326Sed          // avoid spurious errors (e.g., no inputs).
630193326Sed          if (!Args.hasArg(options::OPT_E, false))
631193326Sed            Diag(clang::diag::err_drv_unknown_stdin_type);
632193326Sed          Ty = types::TY_C;
633193326Sed        } else {
634193326Sed          // Otherwise lookup by extension, and fallback to ObjectType
635193326Sed          // if not found. We use a host hook here because Darwin at
636193326Sed          // least has its own idea of what .s is.
637193326Sed          if (const char *Ext = strrchr(Value, '.'))
638193326Sed            Ty = Host->lookupTypeForExtension(Ext + 1);
639193326Sed
640193326Sed          if (Ty == types::TY_INVALID)
641193326Sed            Ty = types::TY_Object;
642193326Sed        }
643193326Sed
644193326Sed        // -ObjC and -ObjC++ override the default language, but only for "source
645193326Sed        // files". We just treat everything that isn't a linker input as a
646193326Sed        // source file.
647193326Sed        //
648193326Sed        // FIXME: Clean this up if we move the phase sequence into the type.
649193326Sed        if (Ty != types::TY_Object) {
650193326Sed          if (Args.hasArg(options::OPT_ObjC))
651193326Sed            Ty = types::TY_ObjC;
652193326Sed          else if (Args.hasArg(options::OPT_ObjCXX))
653193326Sed            Ty = types::TY_ObjCXX;
654193326Sed        }
655193326Sed      } else {
656193326Sed        assert(InputTypeArg && "InputType set w/o InputTypeArg");
657193326Sed        InputTypeArg->claim();
658193326Sed        Ty = InputType;
659193326Sed      }
660193326Sed
661193326Sed      // Check that the file exists. It isn't clear this is worth
662193326Sed      // doing, since the tool presumably does this anyway, and this
663193326Sed      // just adds an extra stat to the equation, but this is gcc
664193326Sed      // compatible.
665193326Sed      if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
666193326Sed        Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
667193326Sed      else
668193326Sed        Inputs.push_back(std::make_pair(Ty, A));
669193326Sed
670193326Sed    } else if (A->getOption().isLinkerInput()) {
671193326Sed      // Just treat as object type, we could make a special type for
672193326Sed      // this if necessary.
673193326Sed      Inputs.push_back(std::make_pair(types::TY_Object, A));
674193326Sed
675193326Sed    } else if (A->getOption().getId() == options::OPT_x) {
676193326Sed      InputTypeArg = A;
677193326Sed      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
678193326Sed
679193326Sed      // Follow gcc behavior and treat as linker input for invalid -x
680193326Sed      // options. Its not clear why we shouldn't just revert to
681193326Sed      // unknown; but this isn't very important, we might as well be
682193326Sed      // bug comatible.
683193326Sed      if (!InputType) {
684193326Sed        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
685193326Sed        InputType = types::TY_Object;
686193326Sed      }
687193326Sed    }
688193326Sed  }
689193326Sed
690193326Sed  if (!SuppressMissingInputWarning && Inputs.empty()) {
691193326Sed    Diag(clang::diag::err_drv_no_input_files);
692193326Sed    return;
693193326Sed  }
694193326Sed
695193326Sed  // Determine which compilation mode we are in. We look for options
696193326Sed  // which affect the phase, starting with the earliest phases, and
697193326Sed  // record which option we used to determine the final phase.
698193326Sed  Arg *FinalPhaseArg = 0;
699193326Sed  phases::ID FinalPhase;
700193326Sed
701193326Sed  // -{E,M,MM} only run the preprocessor.
702193326Sed  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
703193326Sed      (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
704193326Sed      (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
705193326Sed    FinalPhase = phases::Preprocess;
706193326Sed
707193326Sed    // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
708193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
709193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
710193326Sed                                              options::OPT__analyze_auto)) ||
711193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
712193326Sed    FinalPhase = phases::Compile;
713193326Sed
714193326Sed    // -c only runs up to the assembler.
715193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
716193326Sed    FinalPhase = phases::Assemble;
717193326Sed
718193326Sed    // Otherwise do everything.
719193326Sed  } else
720193326Sed    FinalPhase = phases::Link;
721193326Sed
722193326Sed  // Reject -Z* at the top level, these options should never have been
723193326Sed  // exposed by gcc.
724193326Sed  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
725193326Sed    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
726193326Sed
727193326Sed  // Construct the actions to perform.
728193326Sed  ActionList LinkerInputs;
729193326Sed  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
730193326Sed    types::ID InputType = Inputs[i].first;
731193326Sed    const Arg *InputArg = Inputs[i].second;
732193326Sed
733193326Sed    unsigned NumSteps = types::getNumCompilationPhases(InputType);
734193326Sed    assert(NumSteps && "Invalid number of steps!");
735193326Sed
736193326Sed    // If the first step comes after the final phase we are doing as
737193326Sed    // part of this compilation, warn the user about it.
738193326Sed    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
739193326Sed    if (InitialPhase > FinalPhase) {
740193326Sed      // Claim here to avoid the more general unused warning.
741193326Sed      InputArg->claim();
742193326Sed      Diag(clang::diag::warn_drv_input_file_unused)
743193326Sed        << InputArg->getAsString(Args)
744193326Sed        << getPhaseName(InitialPhase)
745193326Sed        << FinalPhaseArg->getOption().getName();
746193326Sed      continue;
747193326Sed    }
748193326Sed
749193326Sed    // Build the pipeline for this file.
750193326Sed    Action *Current = new InputAction(*InputArg, InputType);
751193326Sed    for (unsigned i = 0; i != NumSteps; ++i) {
752193326Sed      phases::ID Phase = types::getCompilationPhase(InputType, i);
753193326Sed
754193326Sed      // We are done if this step is past what the user requested.
755193326Sed      if (Phase > FinalPhase)
756193326Sed        break;
757193326Sed
758193326Sed      // Queue linker inputs.
759193326Sed      if (Phase == phases::Link) {
760193326Sed        assert(i + 1 == NumSteps && "linking must be final compilation step.");
761193326Sed        LinkerInputs.push_back(Current);
762193326Sed        Current = 0;
763193326Sed        break;
764193326Sed      }
765193326Sed
766193326Sed      // Some types skip the assembler phase (e.g., llvm-bc), but we
767193326Sed      // can't encode this in the steps because the intermediate type
768193326Sed      // depends on arguments. Just special case here.
769193326Sed      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
770193326Sed        continue;
771193326Sed
772193326Sed      // Otherwise construct the appropriate action.
773193326Sed      Current = ConstructPhaseAction(Args, Phase, Current);
774193326Sed      if (Current->getType() == types::TY_Nothing)
775193326Sed        break;
776193326Sed    }
777193326Sed
778193326Sed    // If we ended with something, add to the output list.
779193326Sed    if (Current)
780193326Sed      Actions.push_back(Current);
781193326Sed  }
782193326Sed
783193326Sed  // Add a link action if necessary.
784193326Sed  if (!LinkerInputs.empty())
785193326Sed    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
786193326Sed}
787193326Sed
788193326SedAction *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
789193326Sed                                     Action *Input) const {
790193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
791193326Sed  // Build the appropriate action.
792193326Sed  switch (Phase) {
793193326Sed  case phases::Link: assert(0 && "link action invalid here.");
794193326Sed  case phases::Preprocess: {
795193326Sed    types::ID OutputTy;
796193326Sed    // -{M, MM} alter the output type.
797193326Sed    if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
798193326Sed      OutputTy = types::TY_Dependencies;
799193326Sed    } else {
800193326Sed      OutputTy = types::getPreprocessedType(Input->getType());
801193326Sed      assert(OutputTy != types::TY_INVALID &&
802193326Sed             "Cannot preprocess this input type!");
803193326Sed    }
804193326Sed    return new PreprocessJobAction(Input, OutputTy);
805193326Sed  }
806193326Sed  case phases::Precompile:
807193326Sed    return new PrecompileJobAction(Input, types::TY_PCH);
808193326Sed  case phases::Compile: {
809193326Sed    if (Args.hasArg(options::OPT_fsyntax_only)) {
810193326Sed      return new CompileJobAction(Input, types::TY_Nothing);
811193326Sed    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
812193326Sed      return new AnalyzeJobAction(Input, types::TY_Plist);
813193326Sed    } else if (Args.hasArg(options::OPT_emit_llvm) ||
814193326Sed               Args.hasArg(options::OPT_flto) ||
815193326Sed               Args.hasArg(options::OPT_O4)) {
816193326Sed      types::ID Output =
817193326Sed        Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
818193326Sed      return new CompileJobAction(Input, Output);
819193326Sed    } else {
820193326Sed      return new CompileJobAction(Input, types::TY_PP_Asm);
821193326Sed    }
822193326Sed  }
823193326Sed  case phases::Assemble:
824193326Sed    return new AssembleJobAction(Input, types::TY_Object);
825193326Sed  }
826193326Sed
827193326Sed  assert(0 && "invalid phase in ConstructPhaseAction");
828193326Sed  return 0;
829193326Sed}
830193326Sed
831193326Sedvoid Driver::BuildJobs(Compilation &C) const {
832193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
833193326Sed  bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
834193326Sed  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
835193326Sed
836193326Sed  // FIXME: Pipes are forcibly disabled until we support executing
837193326Sed  // them.
838193326Sed  if (!CCCPrintBindings)
839193326Sed    UsePipes = false;
840193326Sed
841193326Sed  // -save-temps inhibits pipes.
842193326Sed  if (SaveTemps && UsePipes) {
843193326Sed    Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
844193326Sed    UsePipes = true;
845193326Sed  }
846193326Sed
847193326Sed  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
848193326Sed
849193326Sed  // It is an error to provide a -o option if we are making multiple
850193326Sed  // output files.
851193326Sed  if (FinalOutput) {
852193326Sed    unsigned NumOutputs = 0;
853193326Sed    for (ActionList::const_iterator it = C.getActions().begin(),
854193326Sed           ie = C.getActions().end(); it != ie; ++it)
855193326Sed      if ((*it)->getType() != types::TY_Nothing)
856193326Sed        ++NumOutputs;
857193326Sed
858193326Sed    if (NumOutputs > 1) {
859193326Sed      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
860193326Sed      FinalOutput = 0;
861193326Sed    }
862193326Sed  }
863193326Sed
864193326Sed  for (ActionList::const_iterator it = C.getActions().begin(),
865193326Sed         ie = C.getActions().end(); it != ie; ++it) {
866193326Sed    Action *A = *it;
867193326Sed
868193326Sed    // If we are linking an image for multiple archs then the linker
869193326Sed    // wants -arch_multiple and -final_output <final image
870193326Sed    // name>. Unfortunately, this doesn't fit in cleanly because we
871193326Sed    // have to pass this information down.
872193326Sed    //
873193326Sed    // FIXME: This is a hack; find a cleaner way to integrate this
874193326Sed    // into the process.
875193326Sed    const char *LinkingOutput = 0;
876193326Sed    if (isa<LipoJobAction>(A)) {
877193326Sed      if (FinalOutput)
878193326Sed        LinkingOutput = FinalOutput->getValue(C.getArgs());
879193326Sed      else
880193326Sed        LinkingOutput = DefaultImageName.c_str();
881193326Sed    }
882193326Sed
883193326Sed    InputInfo II;
884193326Sed    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
885193326Sed                       /*CanAcceptPipe*/ true,
886193326Sed                       /*AtTopLevel*/ true,
887193326Sed                       /*LinkingOutput*/ LinkingOutput,
888193326Sed                       II);
889193326Sed  }
890193326Sed
891193326Sed  // If the user passed -Qunused-arguments or there were errors, don't
892193326Sed  // warn about any unused arguments.
893193326Sed  if (Diags.getNumErrors() ||
894193326Sed      C.getArgs().hasArg(options::OPT_Qunused_arguments))
895193326Sed    return;
896193326Sed
897193326Sed  // Claim -### here.
898193326Sed  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
899193326Sed
900193326Sed  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
901193326Sed       it != ie; ++it) {
902193326Sed    Arg *A = *it;
903193326Sed
904193326Sed    // FIXME: It would be nice to be able to send the argument to the
905193326Sed    // Diagnostic, so that extra values, position, and so on could be
906193326Sed    // printed.
907193326Sed    if (!A->isClaimed()) {
908193326Sed      if (A->getOption().hasNoArgumentUnused())
909193326Sed        continue;
910193326Sed
911193326Sed      // Suppress the warning automatically if this is just a flag,
912193326Sed      // and it is an instance of an argument we already claimed.
913193326Sed      const Option &Opt = A->getOption();
914193326Sed      if (isa<FlagOption>(Opt)) {
915193326Sed        bool DuplicateClaimed = false;
916193326Sed
917193326Sed        // FIXME: Use iterator.
918193326Sed        for (ArgList::const_iterator it = C.getArgs().begin(),
919193326Sed               ie = C.getArgs().end(); it != ie; ++it) {
920193326Sed          if ((*it)->isClaimed() && (*it)->getOption().matches(Opt.getId())) {
921193326Sed            DuplicateClaimed = true;
922193326Sed            break;
923193326Sed          }
924193326Sed        }
925193326Sed
926193326Sed        if (DuplicateClaimed)
927193326Sed          continue;
928193326Sed      }
929193326Sed
930193326Sed      Diag(clang::diag::warn_drv_unused_argument)
931193326Sed        << A->getAsString(C.getArgs());
932193326Sed    }
933193326Sed  }
934193326Sed}
935193326Sed
936193326Sedvoid Driver::BuildJobsForAction(Compilation &C,
937193326Sed                                const Action *A,
938193326Sed                                const ToolChain *TC,
939193326Sed                                bool CanAcceptPipe,
940193326Sed                                bool AtTopLevel,
941193326Sed                                const char *LinkingOutput,
942193326Sed                                InputInfo &Result) const {
943193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
944193326Sed
945193326Sed  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
946193326Sed  // FIXME: Pipes are forcibly disabled until we support executing
947193326Sed  // them.
948193326Sed  if (!CCCPrintBindings)
949193326Sed    UsePipes = false;
950193326Sed
951193326Sed  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
952193326Sed    // FIXME: It would be nice to not claim this here; maybe the old
953193326Sed    // scheme of just using Args was better?
954193326Sed    const Arg &Input = IA->getInputArg();
955193326Sed    Input.claim();
956193326Sed    if (isa<PositionalArg>(Input)) {
957193326Sed      const char *Name = Input.getValue(C.getArgs());
958193326Sed      Result = InputInfo(Name, A->getType(), Name);
959193326Sed    } else
960193326Sed      Result = InputInfo(&Input, A->getType(), "");
961193326Sed    return;
962193326Sed  }
963193326Sed
964193326Sed  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
965193326Sed    const char *ArchName = BAA->getArchName();
966193326Sed    std::string Arch;
967193326Sed    if (!ArchName) {
968193326Sed      Arch = C.getDefaultToolChain().getArchName();
969193326Sed      ArchName = Arch.c_str();
970193326Sed    }
971193326Sed    BuildJobsForAction(C,
972193326Sed                       *BAA->begin(),
973193326Sed                       Host->getToolChain(C.getArgs(), ArchName),
974193326Sed                       CanAcceptPipe,
975193326Sed                       AtTopLevel,
976193326Sed                       LinkingOutput,
977193326Sed                       Result);
978193326Sed    return;
979193326Sed  }
980193326Sed
981193326Sed  const JobAction *JA = cast<JobAction>(A);
982193326Sed  const Tool &T = TC->SelectTool(C, *JA);
983193326Sed
984193326Sed  // See if we should use an integrated preprocessor. We do so when we
985193326Sed  // have exactly one input, since this is the only use case we care
986193326Sed  // about (irrelevant since we don't support combine yet).
987193326Sed  bool UseIntegratedCPP = false;
988193326Sed  const ActionList *Inputs = &A->getInputs();
989193326Sed  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
990193326Sed    if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
991193326Sed        !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
992193326Sed        !C.getArgs().hasArg(options::OPT_save_temps) &&
993193326Sed        T.hasIntegratedCPP()) {
994193326Sed      UseIntegratedCPP = true;
995193326Sed      Inputs = &(*Inputs)[0]->getInputs();
996193326Sed    }
997193326Sed  }
998193326Sed
999193326Sed  // Only use pipes when there is exactly one input.
1000193326Sed  bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
1001193326Sed  InputInfoList InputInfos;
1002193326Sed  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1003193326Sed       it != ie; ++it) {
1004193326Sed    InputInfo II;
1005193326Sed    BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
1006193326Sed                       /*AtTopLevel*/false,
1007193326Sed                       LinkingOutput,
1008193326Sed                       II);
1009193326Sed    InputInfos.push_back(II);
1010193326Sed  }
1011193326Sed
1012193326Sed  // Determine if we should output to a pipe.
1013193326Sed  bool OutputToPipe = false;
1014193326Sed  if (CanAcceptPipe && T.canPipeOutput()) {
1015193326Sed    // Some actions default to writing to a pipe if they are the top
1016193326Sed    // level phase and there was no user override.
1017193326Sed    //
1018193326Sed    // FIXME: Is there a better way to handle this?
1019193326Sed    if (AtTopLevel) {
1020193326Sed      if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
1021193326Sed        OutputToPipe = true;
1022193326Sed    } else if (UsePipes)
1023193326Sed      OutputToPipe = true;
1024193326Sed  }
1025193326Sed
1026193326Sed  // Figure out where to put the job (pipes).
1027193326Sed  Job *Dest = &C.getJobs();
1028193326Sed  if (InputInfos[0].isPipe()) {
1029193326Sed    assert(TryToUsePipeInput && "Unrequested pipe!");
1030193326Sed    assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
1031193326Sed    Dest = &InputInfos[0].getPipe();
1032193326Sed  }
1033193326Sed
1034193326Sed  // Always use the first input as the base input.
1035193326Sed  const char *BaseInput = InputInfos[0].getBaseInput();
1036193326Sed
1037193326Sed  // Determine the place to write output to (nothing, pipe, or
1038193326Sed  // filename) and where to put the new job.
1039193326Sed  if (JA->getType() == types::TY_Nothing) {
1040193326Sed    Result = InputInfo(A->getType(), BaseInput);
1041193326Sed  } else if (OutputToPipe) {
1042193326Sed    // Append to current piped job or create a new one as appropriate.
1043193326Sed    PipedJob *PJ = dyn_cast<PipedJob>(Dest);
1044193326Sed    if (!PJ) {
1045193326Sed      PJ = new PipedJob();
1046193326Sed      // FIXME: Temporary hack so that -ccc-print-bindings work until
1047193326Sed      // we have pipe support. Please remove later.
1048193326Sed      if (!CCCPrintBindings)
1049193326Sed        cast<JobList>(Dest)->addJob(PJ);
1050193326Sed      Dest = PJ;
1051193326Sed    }
1052193326Sed    Result = InputInfo(PJ, A->getType(), BaseInput);
1053193326Sed  } else {
1054193326Sed    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1055193326Sed                       A->getType(), BaseInput);
1056193326Sed  }
1057193326Sed
1058193326Sed  if (CCCPrintBindings) {
1059193326Sed    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1060193326Sed                 << " - \"" << T.getName() << "\", inputs: [";
1061193326Sed    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1062193326Sed      llvm::errs() << InputInfos[i].getAsString();
1063193326Sed      if (i + 1 != e)
1064193326Sed        llvm::errs() << ", ";
1065193326Sed    }
1066193326Sed    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1067193326Sed  } else {
1068193326Sed    T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
1069193326Sed                   C.getArgsForToolChain(TC), LinkingOutput);
1070193326Sed  }
1071193326Sed}
1072193326Sed
1073193326Sedconst char *Driver::GetNamedOutputPath(Compilation &C,
1074193326Sed                                       const JobAction &JA,
1075193326Sed                                       const char *BaseInput,
1076193326Sed                                       bool AtTopLevel) const {
1077193326Sed  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1078193326Sed  // Output to a user requested destination?
1079193326Sed  if (AtTopLevel) {
1080193326Sed    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1081193326Sed      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1082193326Sed  }
1083193326Sed
1084193326Sed  // Output to a temporary file?
1085193326Sed  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1086193326Sed    std::string TmpName =
1087193326Sed      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1088193326Sed    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1089193326Sed  }
1090193326Sed
1091193326Sed  llvm::sys::Path BasePath(BaseInput);
1092193326Sed  std::string BaseName(BasePath.getLast());
1093193326Sed
1094193326Sed  // Determine what the derived output name should be.
1095193326Sed  const char *NamedOutput;
1096193326Sed  if (JA.getType() == types::TY_Image) {
1097193326Sed    NamedOutput = DefaultImageName.c_str();
1098193326Sed  } else {
1099193326Sed    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1100193326Sed    assert(Suffix && "All types used for output should have a suffix.");
1101193326Sed
1102193326Sed    std::string::size_type End = std::string::npos;
1103193326Sed    if (!types::appendSuffixForType(JA.getType()))
1104193326Sed      End = BaseName.rfind('.');
1105193326Sed    std::string Suffixed(BaseName.substr(0, End));
1106193326Sed    Suffixed += '.';
1107193326Sed    Suffixed += Suffix;
1108193326Sed    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1109193326Sed  }
1110193326Sed
1111193326Sed  // As an annoying special case, PCH generation doesn't strip the
1112193326Sed  // pathname.
1113193326Sed  if (JA.getType() == types::TY_PCH) {
1114193326Sed    BasePath.eraseComponent();
1115193326Sed    if (BasePath.isEmpty())
1116193326Sed      BasePath = NamedOutput;
1117193326Sed    else
1118193326Sed      BasePath.appendComponent(NamedOutput);
1119193326Sed    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1120193326Sed  } else {
1121193326Sed    return C.addResultFile(NamedOutput);
1122193326Sed  }
1123193326Sed}
1124193326Sed
1125193326Sedllvm::sys::Path Driver::GetFilePath(const char *Name,
1126193326Sed                                    const ToolChain &TC) const {
1127193326Sed  const ToolChain::path_list &List = TC.getFilePaths();
1128193326Sed  for (ToolChain::path_list::const_iterator
1129193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1130193326Sed    llvm::sys::Path P(*it);
1131193326Sed    P.appendComponent(Name);
1132193326Sed    if (P.exists())
1133193326Sed      return P;
1134193326Sed  }
1135193326Sed
1136193326Sed  return llvm::sys::Path(Name);
1137193326Sed}
1138193326Sed
1139193326Sedllvm::sys::Path Driver::GetProgramPath(const char *Name,
1140193326Sed                                       const ToolChain &TC,
1141193326Sed                                       bool WantFile) const {
1142193326Sed  const ToolChain::path_list &List = TC.getProgramPaths();
1143193326Sed  for (ToolChain::path_list::const_iterator
1144193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1145193326Sed    llvm::sys::Path P(*it);
1146193326Sed    P.appendComponent(Name);
1147193326Sed    if (WantFile ? P.exists() : P.canExecute())
1148193326Sed      return P;
1149193326Sed  }
1150193326Sed
1151193326Sed  // If all else failed, search the path.
1152193326Sed  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1153193326Sed  if (!P.empty())
1154193326Sed    return P;
1155193326Sed
1156193326Sed  return llvm::sys::Path(Name);
1157193326Sed}
1158193326Sed
1159193326Sedstd::string Driver::GetTemporaryPath(const char *Suffix) const {
1160193326Sed  // FIXME: This is lame; sys::Path should provide this function (in
1161193326Sed  // particular, it should know how to find the temporary files dir).
1162193326Sed  std::string Error;
1163193326Sed  const char *TmpDir = ::getenv("TMPDIR");
1164193326Sed  if (!TmpDir)
1165193326Sed    TmpDir = ::getenv("TEMP");
1166193326Sed  if (!TmpDir)
1167193326Sed    TmpDir = ::getenv("TMP");
1168193326Sed  if (!TmpDir)
1169193326Sed    TmpDir = "/tmp";
1170193326Sed  llvm::sys::Path P(TmpDir);
1171193326Sed  P.appendComponent("cc");
1172193326Sed  if (P.makeUnique(false, &Error)) {
1173193326Sed    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1174193326Sed    return "";
1175193326Sed  }
1176193326Sed
1177193326Sed  // FIXME: Grumble, makeUnique sometimes leaves the file around!?
1178193326Sed  // PR3837.
1179193326Sed  P.eraseFromDisk(false, 0);
1180193326Sed
1181193326Sed  P.appendSuffix(Suffix);
1182193326Sed  return P.toString();
1183193326Sed}
1184193326Sed
1185193326Sedconst HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1186193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1187193326Sed  llvm::Triple Triple(TripleStr);
1188193326Sed
1189193326Sed  // Normalize Arch a bit.
1190193326Sed  //
1191193326Sed  // FIXME: We shouldn't need to do this once everything goes through the triple
1192193326Sed  // interface.
1193193326Sed  if (Triple.getArchName() == "i686")
1194193326Sed    Triple.setArchName("i386");
1195193326Sed  else if (Triple.getArchName() == "amd64")
1196193326Sed    Triple.setArchName("x86_64");
1197193326Sed  else if (Triple.getArchName() == "ppc" ||
1198193326Sed           Triple.getArchName() == "Power Macintosh")
1199193326Sed    Triple.setArchName("powerpc");
1200193326Sed  else if (Triple.getArchName() == "ppc64")
1201193326Sed    Triple.setArchName("powerpc64");
1202193326Sed
1203193326Sed  switch (Triple.getOS()) {
1204193326Sed  case llvm::Triple::Darwin:
1205193326Sed    return createDarwinHostInfo(*this, Triple);
1206193326Sed  case llvm::Triple::DragonFly:
1207193326Sed    return createDragonFlyHostInfo(*this, Triple);
1208193326Sed  case llvm::Triple::FreeBSD:
1209193326Sed    return createFreeBSDHostInfo(*this, Triple);
1210193326Sed  case llvm::Triple::Linux:
1211193326Sed    return createLinuxHostInfo(*this, Triple);
1212193326Sed  default:
1213193326Sed    return createUnknownHostInfo(*this, Triple);
1214193326Sed  }
1215193326Sed}
1216193326Sed
1217193326Sedbool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1218193326Sed                                    const std::string &ArchNameStr) const {
1219193326Sed  // FIXME: Remove this hack.
1220193326Sed  const char *ArchName = ArchNameStr.c_str();
1221193326Sed  if (ArchNameStr == "powerpc")
1222193326Sed    ArchName = "ppc";
1223193326Sed  else if (ArchNameStr == "powerpc64")
1224193326Sed    ArchName = "ppc64";
1225193326Sed
1226193326Sed  // Check if user requested no clang, or clang doesn't understand
1227193326Sed  // this type (we only handle single inputs for now).
1228193326Sed  if (!CCCUseClang || JA.size() != 1 ||
1229193326Sed      !types::isAcceptedByClang((*JA.begin())->getType()))
1230193326Sed    return false;
1231193326Sed
1232193326Sed  // Otherwise make sure this is an action clang understands.
1233193326Sed  if (isa<PreprocessJobAction>(JA)) {
1234193326Sed    if (!CCCUseClangCPP) {
1235193326Sed      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1236193326Sed      return false;
1237193326Sed    }
1238193326Sed  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1239193326Sed    return false;
1240193326Sed
1241193326Sed  // Use clang for C++?
1242193326Sed  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1243193326Sed    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1244193326Sed    return false;
1245193326Sed  }
1246193326Sed
1247193326Sed  // Always use clang for precompiling, regardless of archs. PTH is
1248193326Sed  // platform independent, and this allows the use of the static
1249193326Sed  // analyzer on platforms we don't have full IRgen support for.
1250193326Sed  if (isa<PrecompileJobAction>(JA))
1251193326Sed    return true;
1252193326Sed
1253193326Sed  // Finally, don't use clang if this isn't one of the user specified
1254193326Sed  // archs to build.
1255193326Sed  if (!CCCClangArchs.empty() && !CCCClangArchs.count(ArchName)) {
1256193326Sed    Diag(clang::diag::warn_drv_not_using_clang_arch) << ArchName;
1257193326Sed    return false;
1258193326Sed  }
1259193326Sed
1260193326Sed  return true;
1261193326Sed}
1262193326Sed
1263193326Sed/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
1264193326Sed/// return the grouped values as integers. Numbers which are not
1265193326Sed/// provided are set to 0.
1266193326Sed///
1267193326Sed/// \return True if the entire string was parsed (9.2), or all groups
1268193326Sed/// were parsed (10.3.5extrastuff).
1269193326Sedbool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1270193326Sed                               unsigned &Minor, unsigned &Micro,
1271193326Sed                               bool &HadExtra) {
1272193326Sed  HadExtra = false;
1273193326Sed
1274193326Sed  Major = Minor = Micro = 0;
1275193326Sed  if (*Str == '\0')
1276193326Sed    return true;
1277193326Sed
1278193326Sed  char *End;
1279193326Sed  Major = (unsigned) strtol(Str, &End, 10);
1280193326Sed  if (*Str != '\0' && *End == '\0')
1281193326Sed    return true;
1282193326Sed  if (*End != '.')
1283193326Sed    return false;
1284193326Sed
1285193326Sed  Str = End+1;
1286193326Sed  Minor = (unsigned) strtol(Str, &End, 10);
1287193326Sed  if (*Str != '\0' && *End == '\0')
1288193326Sed    return true;
1289193326Sed  if (*End != '.')
1290193326Sed    return false;
1291193326Sed
1292193326Sed  Str = End+1;
1293193326Sed  Micro = (unsigned) strtol(Str, &End, 10);
1294193326Sed  if (*Str != '\0' && *End == '\0')
1295193326Sed    return true;
1296193326Sed  if (Str == End)
1297193326Sed    return false;
1298193326Sed  HadExtra = true;
1299193326Sed  return true;
1300193326Sed}
1301