Driver.cpp revision 218893
1//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifdef HAVE_CLANG_CONFIG_H
11# include "clang/Config/config.h"
12#endif
13
14#include "clang/Driver/Driver.h"
15
16#include "clang/Driver/Action.h"
17#include "clang/Driver/Arg.h"
18#include "clang/Driver/ArgList.h"
19#include "clang/Driver/Compilation.h"
20#include "clang/Driver/DriverDiagnostic.h"
21#include "clang/Driver/HostInfo.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/OptTable.h"
24#include "clang/Driver/Option.h"
25#include "clang/Driver/Options.h"
26#include "clang/Driver/Tool.h"
27#include "clang/Driver/ToolChain.h"
28#include "clang/Driver/Types.h"
29
30#include "clang/Basic/Version.h"
31
32#include "llvm/Config/config.h"
33#include "llvm/ADT/StringSet.h"
34#include "llvm/ADT/OwningPtr.h"
35#include "llvm/Support/PrettyStackTrace.h"
36#include "llvm/Support/raw_ostream.h"
37#include "llvm/Support/FileSystem.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Program.h"
40
41#include "InputInfo.h"
42
43#include <map>
44
45#ifdef __CYGWIN__
46#include <cygwin/version.h>
47#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
48#define IS_CYGWIN15 1
49#endif
50#endif
51
52using namespace clang::driver;
53using namespace clang;
54
55Driver::Driver(llvm::StringRef _ClangExecutable,
56               llvm::StringRef _DefaultHostTriple,
57               llvm::StringRef _DefaultImageName,
58               bool IsProduction, bool CXXIsProduction,
59               Diagnostic &_Diags)
60  : Opts(createDriverOptTable()), Diags(_Diags),
61    ClangExecutable(_ClangExecutable), DefaultHostTriple(_DefaultHostTriple),
62    DefaultImageName(_DefaultImageName),
63    DriverTitle("clang \"gcc-compatible\" driver"),
64    Host(0),
65    CCPrintOptionsFilename(0), CCPrintHeadersFilename(0), CCCIsCXX(false),
66    CCCEcho(false), CCCPrintBindings(false), CCPrintOptions(false),
67    CCPrintHeaders(false), CCCGenericGCCName("gcc"),
68    CheckInputsExist(true), CCCUseClang(true), CCCUseClangCXX(true),
69    CCCUseClangCPP(true), CCCUsePCH(true), SuppressMissingInputWarning(false) {
70  if (IsProduction) {
71    // In a "production" build, only use clang on architectures we expect to
72    // work, and don't use clang C++.
73    //
74    // During development its more convenient to always have the driver use
75    // clang, but we don't want users to be confused when things don't work, or
76    // to file bugs for things we don't support.
77    CCCClangArchs.insert(llvm::Triple::x86);
78    CCCClangArchs.insert(llvm::Triple::x86_64);
79    CCCClangArchs.insert(llvm::Triple::arm);
80
81    if (!CXXIsProduction)
82      CCCUseClangCXX = false;
83  }
84
85  Name = llvm::sys::path::stem(ClangExecutable);
86  Dir  = llvm::sys::path::parent_path(ClangExecutable);
87
88  // Compute the path to the resource directory.
89  llvm::StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
90  llvm::SmallString<128> P(Dir);
91  if (ClangResourceDir != "")
92    llvm::sys::path::append(P, ClangResourceDir);
93  else
94    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
95  ResourceDir = P.str();
96}
97
98Driver::~Driver() {
99  delete Opts;
100  delete Host;
101}
102
103InputArgList *Driver::ParseArgStrings(const char **ArgBegin,
104                                      const char **ArgEnd) {
105  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
106  unsigned MissingArgIndex, MissingArgCount;
107  InputArgList *Args = getOpts().ParseArgs(ArgBegin, ArgEnd,
108                                           MissingArgIndex, MissingArgCount);
109
110  // Check for missing argument error.
111  if (MissingArgCount)
112    Diag(clang::diag::err_drv_missing_argument)
113      << Args->getArgString(MissingArgIndex) << MissingArgCount;
114
115  // Check for unsupported options.
116  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
117       it != ie; ++it) {
118    Arg *A = *it;
119    if (A->getOption().isUnsupported()) {
120      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
121      continue;
122    }
123  }
124
125  return Args;
126}
127
128DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
129  DerivedArgList *DAL = new DerivedArgList(Args);
130
131  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
132  for (ArgList::const_iterator it = Args.begin(),
133         ie = Args.end(); it != ie; ++it) {
134    const Arg *A = *it;
135
136    // Unfortunately, we have to parse some forwarding options (-Xassembler,
137    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
138    // (assembler and preprocessor), or bypass a previous driver ('collect2').
139
140    // Rewrite linker options, to replace --no-demangle with a custom internal
141    // option.
142    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
143         A->getOption().matches(options::OPT_Xlinker)) &&
144        A->containsValue("--no-demangle")) {
145      // Add the rewritten no-demangle argument.
146      DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
147
148      // Add the remaining values as Xlinker arguments.
149      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
150        if (llvm::StringRef(A->getValue(Args, i)) != "--no-demangle")
151          DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
152                              A->getValue(Args, i));
153
154      continue;
155    }
156
157    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
158    // some build systems. We don't try to be complete here because we don't
159    // care to encourage this usage model.
160    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
161        A->getNumValues() == 2 &&
162        (A->getValue(Args, 0) == llvm::StringRef("-MD") ||
163         A->getValue(Args, 0) == llvm::StringRef("-MMD"))) {
164      // Rewrite to -MD/-MMD along with -MF.
165      if (A->getValue(Args, 0) == llvm::StringRef("-MD"))
166        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
167      else
168        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
169      DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
170                          A->getValue(Args, 1));
171      continue;
172    }
173
174    // Rewrite reserved library names.
175    if (A->getOption().matches(options::OPT_l)) {
176      llvm::StringRef Value = A->getValue(Args);
177
178      // Rewrite unless -nostdlib is present.
179      if (!HasNostdlib && Value == "stdc++") {
180        DAL->AddFlagArg(A, Opts->getOption(
181                              options::OPT_Z_reserved_lib_stdcxx));
182        continue;
183      }
184
185      // Rewrite unconditionally.
186      if (Value == "cc_kext") {
187        DAL->AddFlagArg(A, Opts->getOption(
188                              options::OPT_Z_reserved_lib_cckext));
189        continue;
190      }
191    }
192
193    DAL->append(*it);
194  }
195
196  // Add a default value of -mlinker-version=, if one was given and the user
197  // didn't specify one.
198#if defined(HOST_LINK_VERSION)
199  if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
200    DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
201                      HOST_LINK_VERSION);
202    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
203  }
204#endif
205
206  return DAL;
207}
208
209Compilation *Driver::BuildCompilation(int argc, const char **argv) {
210  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
211
212  // FIXME: Handle environment options which effect driver behavior, somewhere
213  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
214  // CC_PRINT_OPTIONS.
215
216  // FIXME: What are we going to do with -V and -b?
217
218  // FIXME: This stuff needs to go into the Compilation, not the driver.
219  bool CCCPrintOptions = false, CCCPrintActions = false;
220
221  const char **Start = argv + 1, **End = argv + argc;
222
223  InputArgList *Args = ParseArgStrings(Start, End);
224
225  // -no-canonical-prefixes is used very early in main.
226  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
227
228  // Ignore -pipe.
229  Args->ClaimAllArgs(options::OPT_pipe);
230
231  // Extract -ccc args.
232  //
233  // FIXME: We need to figure out where this behavior should live. Most of it
234  // should be outside in the client; the parts that aren't should have proper
235  // options, either by introducing new ones or by overloading gcc ones like -V
236  // or -b.
237  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
238  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
239  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
240  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
241  if (CCCIsCXX) {
242#ifdef IS_CYGWIN15
243    CCCGenericGCCName = "g++-4";
244#else
245    CCCGenericGCCName = "g++";
246#endif
247  }
248  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
249  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
250    CCCGenericGCCName = A->getValue(*Args);
251  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
252                                 options::OPT_ccc_no_clang_cxx,
253                                 CCCUseClangCXX);
254  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
255                            options::OPT_ccc_pch_is_pth);
256  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
257  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
258  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
259    llvm::StringRef Cur = A->getValue(*Args);
260
261    CCCClangArchs.clear();
262    while (!Cur.empty()) {
263      std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
264
265      if (!Split.first.empty()) {
266        llvm::Triple::ArchType Arch =
267          llvm::Triple(Split.first, "", "").getArch();
268
269        if (Arch == llvm::Triple::UnknownArch)
270          Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
271
272        CCCClangArchs.insert(Arch);
273      }
274
275      Cur = Split.second;
276    }
277  }
278  // FIXME: We shouldn't overwrite the default host triple here, but we have
279  // nowhere else to put this currently.
280  if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple))
281    DefaultHostTriple = A->getValue(*Args);
282  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
283    Dir = InstalledDir = A->getValue(*Args);
284  for (arg_iterator it = Args->filtered_begin(options::OPT_B),
285         ie = Args->filtered_end(); it != ie; ++it) {
286    const Arg *A = *it;
287    A->claim();
288    PrefixDirs.push_back(A->getValue(*Args, 0));
289  }
290
291  Host = GetHostInfo(DefaultHostTriple.c_str());
292
293  // Perform the default argument translations.
294  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
295
296  // The compilation takes ownership of Args.
297  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args,
298                                   TranslatedArgs);
299
300  // FIXME: This behavior shouldn't be here.
301  if (CCCPrintOptions) {
302    PrintOptions(C->getInputArgs());
303    return C;
304  }
305
306  if (!HandleImmediateArgs(*C))
307    return C;
308
309  // Construct the list of abstract actions to perform for this compilation.
310  if (Host->useDriverDriver())
311    BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
312                          C->getActions());
313  else
314    BuildActions(C->getDefaultToolChain(), C->getArgs(), C->getActions());
315
316  if (CCCPrintActions) {
317    PrintActions(*C);
318    return C;
319  }
320
321  BuildJobs(*C);
322
323  return C;
324}
325
326int Driver::ExecuteCompilation(const Compilation &C) const {
327  // Just print if -### was present.
328  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
329    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
330    return 0;
331  }
332
333  // If there were errors building the compilation, quit now.
334  if (getDiags().hasErrorOccurred())
335    return 1;
336
337  const Command *FailingCommand = 0;
338  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
339
340  // Remove temp files.
341  C.CleanupFileList(C.getTempFiles());
342
343  // If the command succeeded, we are done.
344  if (Res == 0)
345    return Res;
346
347  // Otherwise, remove result files as well.
348  if (!C.getArgs().hasArg(options::OPT_save_temps))
349    C.CleanupFileList(C.getResultFiles(), true);
350
351  // Print extra information about abnormal failures, if possible.
352  //
353  // This is ad-hoc, but we don't want to be excessively noisy. If the result
354  // status was 1, assume the command failed normally. In particular, if it was
355  // the compiler then assume it gave a reasonable error code. Failures in other
356  // tools are less common, and they generally have worse diagnostics, so always
357  // print the diagnostic there.
358  const Tool &FailingTool = FailingCommand->getCreator();
359
360  if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
361    // FIXME: See FIXME above regarding result code interpretation.
362    if (Res < 0)
363      Diag(clang::diag::err_drv_command_signalled)
364        << FailingTool.getShortName() << -Res;
365    else
366      Diag(clang::diag::err_drv_command_failed)
367        << FailingTool.getShortName() << Res;
368  }
369
370  return Res;
371}
372
373void Driver::PrintOptions(const ArgList &Args) const {
374  unsigned i = 0;
375  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
376       it != ie; ++it, ++i) {
377    Arg *A = *it;
378    llvm::errs() << "Option " << i << " - "
379                 << "Name: \"" << A->getOption().getName() << "\", "
380                 << "Values: {";
381    for (unsigned j = 0; j < A->getNumValues(); ++j) {
382      if (j)
383        llvm::errs() << ", ";
384      llvm::errs() << '"' << A->getValue(Args, j) << '"';
385    }
386    llvm::errs() << "}\n";
387  }
388}
389
390void Driver::PrintHelp(bool ShowHidden) const {
391  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
392                      ShowHidden);
393}
394
395void Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
396  // FIXME: The following handlers should use a callback mechanism, we don't
397  // know what the client would like to do.
398  OS << getClangFullVersion() << '\n';
399  const ToolChain &TC = C.getDefaultToolChain();
400  OS << "Target: " << TC.getTripleString() << '\n';
401
402  // Print the threading model.
403  //
404  // FIXME: Implement correctly.
405  OS << "Thread model: " << "posix" << '\n';
406}
407
408/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
409/// option.
410static void PrintDiagnosticCategories(llvm::raw_ostream &OS) {
411  for (unsigned i = 1; // Skip the empty category.
412       const char *CategoryName = DiagnosticIDs::getCategoryNameFromID(i); ++i)
413    OS << i << ',' << CategoryName << '\n';
414}
415
416bool Driver::HandleImmediateArgs(const Compilation &C) {
417  // The order these options are handled in gcc is all over the place, but we
418  // don't expect inconsistencies w.r.t. that to matter in practice.
419
420  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
421    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
422    return false;
423  }
424
425  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
426    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
427    // return an answer which matches our definition of __VERSION__.
428    //
429    // If we want to return a more correct answer some day, then we should
430    // introduce a non-pedantically GCC compatible mode to Clang in which we
431    // provide sensible definitions for -dumpversion, __VERSION__, etc.
432    llvm::outs() << "4.2.1\n";
433    return false;
434  }
435
436  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
437    PrintDiagnosticCategories(llvm::outs());
438    return false;
439  }
440
441  if (C.getArgs().hasArg(options::OPT__help) ||
442      C.getArgs().hasArg(options::OPT__help_hidden)) {
443    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
444    return false;
445  }
446
447  if (C.getArgs().hasArg(options::OPT__version)) {
448    // Follow gcc behavior and use stdout for --version and stderr for -v.
449    PrintVersion(C, llvm::outs());
450    return false;
451  }
452
453  if (C.getArgs().hasArg(options::OPT_v) ||
454      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
455    PrintVersion(C, llvm::errs());
456    SuppressMissingInputWarning = true;
457  }
458
459  const ToolChain &TC = C.getDefaultToolChain();
460  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
461    llvm::outs() << "programs: =";
462    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
463           ie = TC.getProgramPaths().end(); it != ie; ++it) {
464      if (it != TC.getProgramPaths().begin())
465        llvm::outs() << ':';
466      llvm::outs() << *it;
467    }
468    llvm::outs() << "\n";
469    llvm::outs() << "libraries: =";
470    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
471           ie = TC.getFilePaths().end(); it != ie; ++it) {
472      if (it != TC.getFilePaths().begin())
473        llvm::outs() << ':';
474      llvm::outs() << *it;
475    }
476    llvm::outs() << "\n";
477    return false;
478  }
479
480  // FIXME: The following handlers should use a callback mechanism, we don't
481  // know what the client would like to do.
482  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
483    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
484    return false;
485  }
486
487  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
488    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
489    return false;
490  }
491
492  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
493    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
494    return false;
495  }
496
497  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
498    // FIXME: We need tool chain support for this.
499    llvm::outs() << ".;\n";
500
501    switch (C.getDefaultToolChain().getTriple().getArch()) {
502    default:
503      break;
504
505    case llvm::Triple::x86_64:
506      llvm::outs() << "x86_64;@m64" << "\n";
507      break;
508
509    case llvm::Triple::ppc64:
510      llvm::outs() << "ppc64;@m64" << "\n";
511      break;
512    }
513    return false;
514  }
515
516  // FIXME: What is the difference between print-multi-directory and
517  // print-multi-os-directory?
518  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
519      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
520    switch (C.getDefaultToolChain().getTriple().getArch()) {
521    default:
522    case llvm::Triple::x86:
523    case llvm::Triple::ppc:
524      llvm::outs() << "." << "\n";
525      break;
526
527    case llvm::Triple::x86_64:
528      llvm::outs() << "." << "\n";
529      break;
530
531    case llvm::Triple::ppc64:
532      llvm::outs() << "ppc64" << "\n";
533      break;
534    }
535    return false;
536  }
537
538  return true;
539}
540
541static unsigned PrintActions1(const Compilation &C, Action *A,
542                              std::map<Action*, unsigned> &Ids) {
543  if (Ids.count(A))
544    return Ids[A];
545
546  std::string str;
547  llvm::raw_string_ostream os(str);
548
549  os << Action::getClassName(A->getKind()) << ", ";
550  if (InputAction *IA = dyn_cast<InputAction>(A)) {
551    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
552  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
553    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
554                  C.getDefaultToolChain().getArchName()) << '"'
555       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
556  } else {
557    os << "{";
558    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
559      os << PrintActions1(C, *it, Ids);
560      ++it;
561      if (it != ie)
562        os << ", ";
563    }
564    os << "}";
565  }
566
567  unsigned Id = Ids.size();
568  Ids[A] = Id;
569  llvm::errs() << Id << ": " << os.str() << ", "
570               << types::getTypeName(A->getType()) << "\n";
571
572  return Id;
573}
574
575void Driver::PrintActions(const Compilation &C) const {
576  std::map<Action*, unsigned> Ids;
577  for (ActionList::const_iterator it = C.getActions().begin(),
578         ie = C.getActions().end(); it != ie; ++it)
579    PrintActions1(C, *it, Ids);
580}
581
582/// \brief Check whether the given input tree contains any compilation (or
583/// assembly) actions.
584static bool ContainsCompileAction(const Action *A) {
585  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
586    return true;
587
588  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
589    if (ContainsCompileAction(*it))
590      return true;
591
592  return false;
593}
594
595void Driver::BuildUniversalActions(const ToolChain &TC,
596                                   const ArgList &Args,
597                                   ActionList &Actions) const {
598  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
599  // Collect the list of architectures. Duplicates are allowed, but should only
600  // be handled once (in the order seen).
601  llvm::StringSet<> ArchNames;
602  llvm::SmallVector<const char *, 4> Archs;
603  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
604       it != ie; ++it) {
605    Arg *A = *it;
606
607    if (A->getOption().matches(options::OPT_arch)) {
608      // Validate the option here; we don't save the type here because its
609      // particular spelling may participate in other driver choices.
610      llvm::Triple::ArchType Arch =
611        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
612      if (Arch == llvm::Triple::UnknownArch) {
613        Diag(clang::diag::err_drv_invalid_arch_name)
614          << A->getAsString(Args);
615        continue;
616      }
617
618      A->claim();
619      if (ArchNames.insert(A->getValue(Args)))
620        Archs.push_back(A->getValue(Args));
621    }
622  }
623
624  // When there is no explicit arch for this platform, make sure we still bind
625  // the architecture (to the default) so that -Xarch_ is handled correctly.
626  if (!Archs.size())
627    Archs.push_back(0);
628
629  // FIXME: We killed off some others but these aren't yet detected in a
630  // functional manner. If we added information to jobs about which "auxiliary"
631  // files they wrote then we could detect the conflict these cause downstream.
632  if (Archs.size() > 1) {
633    // No recovery needed, the point of this is just to prevent
634    // overwriting the same files.
635    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
636      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
637        << A->getAsString(Args);
638  }
639
640  ActionList SingleActions;
641  BuildActions(TC, Args, SingleActions);
642
643  // Add in arch bindings for every top level action, as well as lipo and
644  // dsymutil steps if needed.
645  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
646    Action *Act = SingleActions[i];
647
648    // Make sure we can lipo this kind of output. If not (and it is an actual
649    // output) then we disallow, since we can't create an output file with the
650    // right name without overwriting it. We could remove this oddity by just
651    // changing the output names to include the arch, which would also fix
652    // -save-temps. Compatibility wins for now.
653
654    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
655      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
656        << types::getTypeName(Act->getType());
657
658    ActionList Inputs;
659    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
660      Inputs.push_back(new BindArchAction(Act, Archs[i]));
661      if (i != 0)
662        Inputs.back()->setOwnsInputs(false);
663    }
664
665    // Lipo if necessary, we do it this way because we need to set the arch flag
666    // so that -Xarch_ gets overwritten.
667    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
668      Actions.append(Inputs.begin(), Inputs.end());
669    else
670      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
671
672    // Add a 'dsymutil' step if necessary, when debug info is enabled and we
673    // have a compile input. We need to run 'dsymutil' ourselves in such cases
674    // because the debug info will refer to a temporary object file which is
675    // will be removed at the end of the compilation process.
676    if (Act->getType() == types::TY_Image) {
677      Arg *A = Args.getLastArg(options::OPT_g_Group);
678      if (A && !A->getOption().matches(options::OPT_g0) &&
679          !A->getOption().matches(options::OPT_gstabs) &&
680          ContainsCompileAction(Actions.back())) {
681        ActionList Inputs;
682        Inputs.push_back(Actions.back());
683        Actions.pop_back();
684
685        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
686      }
687    }
688  }
689}
690
691void Driver::BuildActions(const ToolChain &TC, const ArgList &Args,
692                          ActionList &Actions) const {
693  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
694  // Start by constructing the list of inputs and their types.
695
696  // Track the current user specified (-x) input. We also explicitly track the
697  // argument used to set the type; we only want to claim the type when we
698  // actually use it, so we warn about unused -x arguments.
699  types::ID InputType = types::TY_Nothing;
700  Arg *InputTypeArg = 0;
701
702  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
703  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
704       it != ie; ++it) {
705    Arg *A = *it;
706
707    if (isa<InputOption>(A->getOption())) {
708      const char *Value = A->getValue(Args);
709      types::ID Ty = types::TY_INVALID;
710
711      // Infer the input type if necessary.
712      if (InputType == types::TY_Nothing) {
713        // If there was an explicit arg for this, claim it.
714        if (InputTypeArg)
715          InputTypeArg->claim();
716
717        // stdin must be handled specially.
718        if (memcmp(Value, "-", 2) == 0) {
719          // If running with -E, treat as a C input (this changes the builtin
720          // macros, for example). This may be overridden by -ObjC below.
721          //
722          // Otherwise emit an error but still use a valid type to avoid
723          // spurious errors (e.g., no inputs).
724          if (!Args.hasArgNoClaim(options::OPT_E))
725            Diag(clang::diag::err_drv_unknown_stdin_type);
726          Ty = types::TY_C;
727        } else {
728          // Otherwise lookup by extension, and fallback to ObjectType if not
729          // found. We use a host hook here because Darwin at least has its own
730          // idea of what .s is.
731          if (const char *Ext = strrchr(Value, '.'))
732            Ty = TC.LookupTypeForExtension(Ext + 1);
733
734          if (Ty == types::TY_INVALID)
735            Ty = types::TY_Object;
736
737          // If the driver is invoked as C++ compiler (like clang++ or c++) it
738          // should autodetect some input files as C++ for g++ compatibility.
739          if (CCCIsCXX) {
740            types::ID OldTy = Ty;
741            Ty = types::lookupCXXTypeForCType(Ty);
742
743            if (Ty != OldTy)
744              Diag(clang::diag::warn_drv_treating_input_as_cxx)
745                << getTypeName(OldTy) << getTypeName(Ty);
746          }
747        }
748
749        // -ObjC and -ObjC++ override the default language, but only for "source
750        // files". We just treat everything that isn't a linker input as a
751        // source file.
752        //
753        // FIXME: Clean this up if we move the phase sequence into the type.
754        if (Ty != types::TY_Object) {
755          if (Args.hasArg(options::OPT_ObjC))
756            Ty = types::TY_ObjC;
757          else if (Args.hasArg(options::OPT_ObjCXX))
758            Ty = types::TY_ObjCXX;
759        }
760      } else {
761        assert(InputTypeArg && "InputType set w/o InputTypeArg");
762        InputTypeArg->claim();
763        Ty = InputType;
764      }
765
766      // Check that the file exists, if enabled.
767      if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
768        llvm::SmallString<64> Path(Value);
769        if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory))
770          if (llvm::sys::path::is_absolute(Path.str())) {
771            Path = WorkDir->getValue(Args);
772            llvm::sys::path::append(Path, Value);
773          }
774
775        bool exists = false;
776        if (/*error_code ec =*/llvm::sys::fs::exists(Value, exists) || !exists)
777          Diag(clang::diag::err_drv_no_such_file) << Path.str();
778        else
779          Inputs.push_back(std::make_pair(Ty, A));
780      } else
781        Inputs.push_back(std::make_pair(Ty, A));
782
783    } else if (A->getOption().isLinkerInput()) {
784      // Just treat as object type, we could make a special type for this if
785      // necessary.
786      Inputs.push_back(std::make_pair(types::TY_Object, A));
787
788    } else if (A->getOption().matches(options::OPT_x)) {
789      InputTypeArg = A;
790      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
791
792      // Follow gcc behavior and treat as linker input for invalid -x
793      // options. Its not clear why we shouldn't just revert to unknown; but
794      // this isn't very important, we might as well be bug compatible.
795      if (!InputType) {
796        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
797        InputType = types::TY_Object;
798      }
799    }
800  }
801
802  if (!SuppressMissingInputWarning && Inputs.empty()) {
803    Diag(clang::diag::err_drv_no_input_files);
804    return;
805  }
806
807  // Determine which compilation mode we are in. We look for options which
808  // affect the phase, starting with the earliest phases, and record which
809  // option we used to determine the final phase.
810  Arg *FinalPhaseArg = 0;
811  phases::ID FinalPhase;
812
813  // -{E,M,MM} only run the preprocessor.
814  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
815      (FinalPhaseArg = Args.getLastArg(options::OPT_M, options::OPT_MM))) {
816    FinalPhase = phases::Preprocess;
817
818    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
819  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
820             (FinalPhaseArg = Args.getLastArg(options::OPT_rewrite_objc)) ||
821             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
822                                              options::OPT__analyze_auto)) ||
823             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
824             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
825    FinalPhase = phases::Compile;
826
827    // -c only runs up to the assembler.
828  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
829    FinalPhase = phases::Assemble;
830
831    // Otherwise do everything.
832  } else
833    FinalPhase = phases::Link;
834
835  // Reject -Z* at the top level, these options should never have been exposed
836  // by gcc.
837  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
838    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
839
840  // Construct the actions to perform.
841  ActionList LinkerInputs;
842  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
843    types::ID InputType = Inputs[i].first;
844    const Arg *InputArg = Inputs[i].second;
845
846    unsigned NumSteps = types::getNumCompilationPhases(InputType);
847    assert(NumSteps && "Invalid number of steps!");
848
849    // If the first step comes after the final phase we are doing as part of
850    // this compilation, warn the user about it.
851    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
852    if (InitialPhase > FinalPhase) {
853      // Claim here to avoid the more general unused warning.
854      InputArg->claim();
855
856      // Special case '-E' warning on a previously preprocessed file to make
857      // more sense.
858      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
859          getPreprocessedType(InputType) == types::TY_INVALID)
860        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
861          << InputArg->getAsString(Args)
862          << FinalPhaseArg->getOption().getName();
863      else
864        Diag(clang::diag::warn_drv_input_file_unused)
865          << InputArg->getAsString(Args)
866          << getPhaseName(InitialPhase)
867          << FinalPhaseArg->getOption().getName();
868      continue;
869    }
870
871    // Build the pipeline for this file.
872    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
873    for (unsigned i = 0; i != NumSteps; ++i) {
874      phases::ID Phase = types::getCompilationPhase(InputType, i);
875
876      // We are done if this step is past what the user requested.
877      if (Phase > FinalPhase)
878        break;
879
880      // Queue linker inputs.
881      if (Phase == phases::Link) {
882        assert(i + 1 == NumSteps && "linking must be final compilation step.");
883        LinkerInputs.push_back(Current.take());
884        break;
885      }
886
887      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
888      // encode this in the steps because the intermediate type depends on
889      // arguments. Just special case here.
890      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
891        continue;
892
893      // Otherwise construct the appropriate action.
894      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
895      if (Current->getType() == types::TY_Nothing)
896        break;
897    }
898
899    // If we ended with something, add to the output list.
900    if (Current)
901      Actions.push_back(Current.take());
902  }
903
904  // Add a link action if necessary.
905  if (!LinkerInputs.empty())
906    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
907
908  // If we are linking, claim any options which are obviously only used for
909  // compilation.
910  if (FinalPhase == phases::Link)
911    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
912}
913
914Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
915                                     Action *Input) const {
916  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
917  // Build the appropriate action.
918  switch (Phase) {
919  case phases::Link: assert(0 && "link action invalid here.");
920  case phases::Preprocess: {
921    types::ID OutputTy;
922    // -{M, MM} alter the output type.
923    if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
924      OutputTy = types::TY_Dependencies;
925    } else {
926      OutputTy = types::getPreprocessedType(Input->getType());
927      assert(OutputTy != types::TY_INVALID &&
928             "Cannot preprocess this input type!");
929    }
930    return new PreprocessJobAction(Input, OutputTy);
931  }
932  case phases::Precompile:
933    return new PrecompileJobAction(Input, types::TY_PCH);
934  case phases::Compile: {
935    bool HasO4 = false;
936    if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
937      HasO4 = A->getOption().matches(options::OPT_O4);
938
939    if (Args.hasArg(options::OPT_fsyntax_only)) {
940      return new CompileJobAction(Input, types::TY_Nothing);
941    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
942      return new CompileJobAction(Input, types::TY_RewrittenObjC);
943    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
944      return new AnalyzeJobAction(Input, types::TY_Plist);
945    } else if (Args.hasArg(options::OPT_emit_ast)) {
946      return new CompileJobAction(Input, types::TY_AST);
947    } else if (Args.hasArg(options::OPT_emit_llvm) ||
948               Args.hasArg(options::OPT_flto) || HasO4) {
949      types::ID Output =
950        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
951      return new CompileJobAction(Input, Output);
952    } else {
953      return new CompileJobAction(Input, types::TY_PP_Asm);
954    }
955  }
956  case phases::Assemble:
957    return new AssembleJobAction(Input, types::TY_Object);
958  }
959
960  assert(0 && "invalid phase in ConstructPhaseAction");
961  return 0;
962}
963
964void Driver::BuildJobs(Compilation &C) const {
965  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
966
967  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
968
969  // It is an error to provide a -o option if we are making multiple output
970  // files.
971  if (FinalOutput) {
972    unsigned NumOutputs = 0;
973    for (ActionList::const_iterator it = C.getActions().begin(),
974           ie = C.getActions().end(); it != ie; ++it)
975      if ((*it)->getType() != types::TY_Nothing)
976        ++NumOutputs;
977
978    if (NumOutputs > 1) {
979      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
980      FinalOutput = 0;
981    }
982  }
983
984  for (ActionList::const_iterator it = C.getActions().begin(),
985         ie = C.getActions().end(); it != ie; ++it) {
986    Action *A = *it;
987
988    // If we are linking an image for multiple archs then the linker wants
989    // -arch_multiple and -final_output <final image name>. Unfortunately, this
990    // doesn't fit in cleanly because we have to pass this information down.
991    //
992    // FIXME: This is a hack; find a cleaner way to integrate this into the
993    // process.
994    const char *LinkingOutput = 0;
995    if (isa<LipoJobAction>(A)) {
996      if (FinalOutput)
997        LinkingOutput = FinalOutput->getValue(C.getArgs());
998      else
999        LinkingOutput = DefaultImageName.c_str();
1000    }
1001
1002    InputInfo II;
1003    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1004                       /*BoundArch*/0,
1005                       /*AtTopLevel*/ true,
1006                       /*LinkingOutput*/ LinkingOutput,
1007                       II);
1008  }
1009
1010  // If the user passed -Qunused-arguments or there were errors, don't warn
1011  // about any unused arguments.
1012  if (Diags.hasErrorOccurred() ||
1013      C.getArgs().hasArg(options::OPT_Qunused_arguments))
1014    return;
1015
1016  // Claim -### here.
1017  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1018
1019  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1020       it != ie; ++it) {
1021    Arg *A = *it;
1022
1023    // FIXME: It would be nice to be able to send the argument to the
1024    // Diagnostic, so that extra values, position, and so on could be printed.
1025    if (!A->isClaimed()) {
1026      if (A->getOption().hasNoArgumentUnused())
1027        continue;
1028
1029      // Suppress the warning automatically if this is just a flag, and it is an
1030      // instance of an argument we already claimed.
1031      const Option &Opt = A->getOption();
1032      if (isa<FlagOption>(Opt)) {
1033        bool DuplicateClaimed = false;
1034
1035        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1036               ie = C.getArgs().filtered_end(); it != ie; ++it) {
1037          if ((*it)->isClaimed()) {
1038            DuplicateClaimed = true;
1039            break;
1040          }
1041        }
1042
1043        if (DuplicateClaimed)
1044          continue;
1045      }
1046
1047      Diag(clang::diag::warn_drv_unused_argument)
1048        << A->getAsString(C.getArgs());
1049    }
1050  }
1051}
1052
1053static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1054                                    const JobAction *JA,
1055                                    const ActionList *&Inputs) {
1056  const Tool *ToolForJob = 0;
1057
1058  // See if we should look for a compiler with an integrated assembler. We match
1059  // bottom up, so what we are actually looking for is an assembler job with a
1060  // compiler input.
1061
1062  // FIXME: This doesn't belong here, but ideally we will support static soon
1063  // anyway.
1064  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
1065                    C.getArgs().hasArg(options::OPT_static) ||
1066                    C.getArgs().hasArg(options::OPT_fapple_kext));
1067  bool IsIADefault = (TC->IsIntegratedAssemblerDefault() && !HasStatic);
1068  if (C.getArgs().hasFlag(options::OPT_integrated_as,
1069                         options::OPT_no_integrated_as,
1070                         IsIADefault) &&
1071      !C.getArgs().hasArg(options::OPT_save_temps) &&
1072      isa<AssembleJobAction>(JA) &&
1073      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1074    const Tool &Compiler = TC->SelectTool(C,cast<JobAction>(**Inputs->begin()));
1075    if (Compiler.hasIntegratedAssembler()) {
1076      Inputs = &(*Inputs)[0]->getInputs();
1077      ToolForJob = &Compiler;
1078    }
1079  }
1080
1081  // Otherwise use the tool for the current job.
1082  if (!ToolForJob)
1083    ToolForJob = &TC->SelectTool(C, *JA);
1084
1085  // See if we should use an integrated preprocessor. We do so when we have
1086  // exactly one input, since this is the only use case we care about
1087  // (irrelevant since we don't support combine yet).
1088  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1089      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1090      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1091      !C.getArgs().hasArg(options::OPT_save_temps) &&
1092      ToolForJob->hasIntegratedCPP())
1093    Inputs = &(*Inputs)[0]->getInputs();
1094
1095  return *ToolForJob;
1096}
1097
1098void Driver::BuildJobsForAction(Compilation &C,
1099                                const Action *A,
1100                                const ToolChain *TC,
1101                                const char *BoundArch,
1102                                bool AtTopLevel,
1103                                const char *LinkingOutput,
1104                                InputInfo &Result) const {
1105  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1106
1107  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1108    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1109    // just using Args was better?
1110    const Arg &Input = IA->getInputArg();
1111    Input.claim();
1112    if (Input.getOption().matches(options::OPT_INPUT)) {
1113      const char *Name = Input.getValue(C.getArgs());
1114      Result = InputInfo(Name, A->getType(), Name);
1115    } else
1116      Result = InputInfo(&Input, A->getType(), "");
1117    return;
1118  }
1119
1120  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1121    const ToolChain *TC = &C.getDefaultToolChain();
1122
1123    std::string Arch;
1124    if (BAA->getArchName())
1125      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1126
1127    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1128                       AtTopLevel, LinkingOutput, Result);
1129    return;
1130  }
1131
1132  const ActionList *Inputs = &A->getInputs();
1133
1134  const JobAction *JA = cast<JobAction>(A);
1135  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1136
1137  // Only use pipes when there is exactly one input.
1138  InputInfoList InputInfos;
1139  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1140       it != ie; ++it) {
1141    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1142    // temporary output names.
1143    //
1144    // FIXME: Clean this up.
1145    bool SubJobAtTopLevel = false;
1146    if (AtTopLevel && isa<DsymutilJobAction>(A))
1147      SubJobAtTopLevel = true;
1148
1149    InputInfo II;
1150    BuildJobsForAction(C, *it, TC, BoundArch,
1151                       SubJobAtTopLevel, LinkingOutput, II);
1152    InputInfos.push_back(II);
1153  }
1154
1155  // Always use the first input as the base input.
1156  const char *BaseInput = InputInfos[0].getBaseInput();
1157
1158  // ... except dsymutil actions, which use their actual input as the base
1159  // input.
1160  if (JA->getType() == types::TY_dSYM)
1161    BaseInput = InputInfos[0].getFilename();
1162
1163  // Determine the place to write output to, if any.
1164  if (JA->getType() == types::TY_Nothing) {
1165    Result = InputInfo(A->getType(), BaseInput);
1166  } else {
1167    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1168                       A->getType(), BaseInput);
1169  }
1170
1171  if (CCCPrintBindings) {
1172    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1173                 << " - \"" << T.getName() << "\", inputs: [";
1174    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1175      llvm::errs() << InputInfos[i].getAsString();
1176      if (i + 1 != e)
1177        llvm::errs() << ", ";
1178    }
1179    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1180  } else {
1181    T.ConstructJob(C, *JA, Result, InputInfos,
1182                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1183  }
1184}
1185
1186const char *Driver::GetNamedOutputPath(Compilation &C,
1187                                       const JobAction &JA,
1188                                       const char *BaseInput,
1189                                       bool AtTopLevel) const {
1190  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1191  // Output to a user requested destination?
1192  if (AtTopLevel && !isa<DsymutilJobAction>(JA)) {
1193    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1194      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1195  }
1196
1197  // Default to writing to stdout?
1198  if (AtTopLevel && isa<PreprocessJobAction>(JA))
1199    return "-";
1200
1201  // Output to a temporary file?
1202  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1203    std::string TmpName =
1204      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1205    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1206  }
1207
1208  llvm::SmallString<128> BasePath(BaseInput);
1209  llvm::StringRef BaseName = llvm::sys::path::filename(BasePath);
1210
1211  // Determine what the derived output name should be.
1212  const char *NamedOutput;
1213  if (JA.getType() == types::TY_Image) {
1214    NamedOutput = DefaultImageName.c_str();
1215  } else {
1216    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1217    assert(Suffix && "All types used for output should have a suffix.");
1218
1219    std::string::size_type End = std::string::npos;
1220    if (!types::appendSuffixForType(JA.getType()))
1221      End = BaseName.rfind('.');
1222    std::string Suffixed(BaseName.substr(0, End));
1223    Suffixed += '.';
1224    Suffixed += Suffix;
1225    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1226  }
1227
1228  // As an annoying special case, PCH generation doesn't strip the pathname.
1229  if (JA.getType() == types::TY_PCH) {
1230    llvm::sys::path::remove_filename(BasePath);
1231    if (BasePath.empty())
1232      BasePath = NamedOutput;
1233    else
1234      llvm::sys::path::append(BasePath, NamedOutput);
1235    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1236  } else {
1237    return C.addResultFile(NamedOutput);
1238  }
1239}
1240
1241std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1242  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1243  // attempting to use this prefix when lokup up program paths.
1244  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1245       ie = PrefixDirs.end(); it != ie; ++it) {
1246    llvm::sys::Path P(*it);
1247    P.appendComponent(Name);
1248    bool Exists;
1249    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1250      return P.str();
1251  }
1252
1253  const ToolChain::path_list &List = TC.getFilePaths();
1254  for (ToolChain::path_list::const_iterator
1255         it = List.begin(), ie = List.end(); it != ie; ++it) {
1256    llvm::sys::Path P(*it);
1257    P.appendComponent(Name);
1258    bool Exists;
1259    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1260      return P.str();
1261  }
1262
1263  return Name;
1264}
1265
1266std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1267                                   bool WantFile) const {
1268  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1269  // attempting to use this prefix when lokup up program paths.
1270  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1271       ie = PrefixDirs.end(); it != ie; ++it) {
1272    llvm::sys::Path P(*it);
1273    P.appendComponent(Name);
1274    bool Exists;
1275    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1276                 : P.canExecute())
1277      return P.str();
1278  }
1279
1280  const ToolChain::path_list &List = TC.getProgramPaths();
1281  for (ToolChain::path_list::const_iterator
1282         it = List.begin(), ie = List.end(); it != ie; ++it) {
1283    llvm::sys::Path P(*it);
1284    P.appendComponent(Name);
1285    bool Exists;
1286    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1287                 : P.canExecute())
1288      return P.str();
1289  }
1290
1291  // If all else failed, search the path.
1292  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1293  if (!P.empty())
1294    return P.str();
1295
1296  return Name;
1297}
1298
1299std::string Driver::GetTemporaryPath(const char *Suffix) const {
1300  // FIXME: This is lame; sys::Path should provide this function (in particular,
1301  // it should know how to find the temporary files dir).
1302  std::string Error;
1303  const char *TmpDir = ::getenv("TMPDIR");
1304  if (!TmpDir)
1305    TmpDir = ::getenv("TEMP");
1306  if (!TmpDir)
1307    TmpDir = ::getenv("TMP");
1308  if (!TmpDir)
1309    TmpDir = "/tmp";
1310  llvm::sys::Path P(TmpDir);
1311  P.appendComponent("cc");
1312  if (P.makeUnique(false, &Error)) {
1313    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1314    return "";
1315  }
1316
1317  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1318  P.eraseFromDisk(false, 0);
1319
1320  P.appendSuffix(Suffix);
1321  return P.str();
1322}
1323
1324const HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1325  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1326  llvm::Triple Triple(TripleStr);
1327
1328  // TCE is an osless target
1329  if (Triple.getArchName() == "tce")
1330    return createTCEHostInfo(*this, Triple);
1331
1332  switch (Triple.getOS()) {
1333  case llvm::Triple::AuroraUX:
1334    return createAuroraUXHostInfo(*this, Triple);
1335  case llvm::Triple::Darwin:
1336    return createDarwinHostInfo(*this, Triple);
1337  case llvm::Triple::DragonFly:
1338    return createDragonFlyHostInfo(*this, Triple);
1339  case llvm::Triple::OpenBSD:
1340    return createOpenBSDHostInfo(*this, Triple);
1341  case llvm::Triple::NetBSD:
1342    return createNetBSDHostInfo(*this, Triple);
1343  case llvm::Triple::FreeBSD:
1344    return createFreeBSDHostInfo(*this, Triple);
1345  case llvm::Triple::Minix:
1346    return createMinixHostInfo(*this, Triple);
1347  case llvm::Triple::Linux:
1348    return createLinuxHostInfo(*this, Triple);
1349  case llvm::Triple::Win32:
1350    return createWindowsHostInfo(*this, Triple);
1351  case llvm::Triple::MinGW32:
1352    return createMinGWHostInfo(*this, Triple);
1353  default:
1354    return createUnknownHostInfo(*this, Triple);
1355  }
1356}
1357
1358bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1359                                    const llvm::Triple &Triple) const {
1360  // Check if user requested no clang, or clang doesn't understand this type (we
1361  // only handle single inputs for now).
1362  if (!CCCUseClang || JA.size() != 1 ||
1363      !types::isAcceptedByClang((*JA.begin())->getType()))
1364    return false;
1365
1366  // Otherwise make sure this is an action clang understands.
1367  if (isa<PreprocessJobAction>(JA)) {
1368    if (!CCCUseClangCPP) {
1369      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1370      return false;
1371    }
1372  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1373    return false;
1374
1375  // Use clang for C++?
1376  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1377    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1378    return false;
1379  }
1380
1381  // Always use clang for precompiling, AST generation, and rewriting,
1382  // regardless of archs.
1383  if (isa<PrecompileJobAction>(JA) ||
1384      types::isOnlyAcceptedByClang(JA.getType()))
1385    return true;
1386
1387  // Finally, don't use clang if this isn't one of the user specified archs to
1388  // build.
1389  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1390    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1391    return false;
1392  }
1393
1394  return true;
1395}
1396
1397/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1398/// grouped values as integers. Numbers which are not provided are set to 0.
1399///
1400/// \return True if the entire string was parsed (9.2), or all groups were
1401/// parsed (10.3.5extrastuff).
1402bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1403                               unsigned &Minor, unsigned &Micro,
1404                               bool &HadExtra) {
1405  HadExtra = false;
1406
1407  Major = Minor = Micro = 0;
1408  if (*Str == '\0')
1409    return true;
1410
1411  char *End;
1412  Major = (unsigned) strtol(Str, &End, 10);
1413  if (*Str != '\0' && *End == '\0')
1414    return true;
1415  if (*End != '.')
1416    return false;
1417
1418  Str = End+1;
1419  Minor = (unsigned) strtol(Str, &End, 10);
1420  if (*Str != '\0' && *End == '\0')
1421    return true;
1422  if (*End != '.')
1423    return false;
1424
1425  Str = End+1;
1426  Micro = (unsigned) strtol(Str, &End, 10);
1427  if (*Str != '\0' && *End == '\0')
1428    return true;
1429  if (Str == End)
1430    return false;
1431  HadExtra = true;
1432  return true;
1433}
1434