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