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 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Driver/Action.h"
15 #include "clang/Driver/Arg.h"
16 #include "clang/Driver/ArgList.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Job.h"
20 #include "clang/Driver/OptTable.h"
21 #include "clang/Driver/Option.h"
22 #include "clang/Driver/Options.h"
23 #include "clang/Driver/Tool.h"
24 #include "clang/Driver/ToolChain.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/OwningPtr.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/Program.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <map>
35 
36 // FIXME: It would prevent to include llvm-config.h
37 // if it were included before system_error.h.
38 #include "clang/Config/config.h"
39 
40 using namespace clang::driver;
41 using namespace clang;
42 
43 Driver::Driver(StringRef ClangExecutable,
44                StringRef DefaultTargetTriple,
45                StringRef DefaultImageName,
46                DiagnosticsEngine &Diags)
47   : Opts(createDriverOptTable()), Diags(Diags),
48     ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
49     UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
50     DefaultImageName(DefaultImageName),
51     DriverTitle("clang LLVM compiler"),
52     CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
53     CCLogDiagnosticsFilename(0), CCCIsCXX(false),
54     CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
55     CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
56     CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
57     CCCUsePCH(true), SuppressMissingInputWarning(false) {
58 
59   Name = llvm::sys::path::stem(ClangExecutable);
60   Dir  = llvm::sys::path::parent_path(ClangExecutable);
61 
62   // Compute the path to the resource directory.
63   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
64   SmallString<128> P(Dir);
65   if (ClangResourceDir != "")
66     llvm::sys::path::append(P, ClangResourceDir);
67   else
68     llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
69   ResourceDir = P.str();
70 }
71 
72 Driver::~Driver() {
73   delete Opts;
74 
75   for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(),
76                                               E = ToolChains.end();
77        I != E; ++I)
78     delete I->second;
79 }
80 
81 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
82   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
83   unsigned MissingArgIndex, MissingArgCount;
84   InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
85                                            MissingArgIndex, MissingArgCount);
86 
87   // Check for missing argument error.
88   if (MissingArgCount)
89     Diag(clang::diag::err_drv_missing_argument)
90       << Args->getArgString(MissingArgIndex) << MissingArgCount;
91 
92   // Check for unsupported options.
93   for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
94        it != ie; ++it) {
95     Arg *A = *it;
96     if (A->getOption().hasFlag(options::Unsupported)) {
97       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
98       continue;
99     }
100 
101     // Warn about -mcpu= without an argument.
102     if (A->getOption().matches(options::OPT_mcpu_EQ) &&
103         A->containsValue("")) {
104       Diag(clang::diag::warn_drv_empty_joined_argument) <<
105         A->getAsString(*Args);
106     }
107   }
108 
109   return Args;
110 }
111 
112 // Determine which compilation mode we are in. We look for options which
113 // affect the phase, starting with the earliest phases, and record which
114 // option we used to determine the final phase.
115 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
116 const {
117   Arg *PhaseArg = 0;
118   phases::ID FinalPhase;
119 
120   // -{E,M,MM} only run the preprocessor.
121   if (CCCIsCPP ||
122       (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
123       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
124     FinalPhase = phases::Preprocess;
125 
126     // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
127   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
128              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
129              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
130              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
131              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
132                                         options::OPT__analyze_auto)) ||
133              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
134              (PhaseArg = DAL.getLastArg(options::OPT_S))) {
135     FinalPhase = phases::Compile;
136 
137     // -c only runs up to the assembler.
138   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
139     FinalPhase = phases::Assemble;
140 
141     // Otherwise do everything.
142   } else
143     FinalPhase = phases::Link;
144 
145   if (FinalPhaseArg)
146     *FinalPhaseArg = PhaseArg;
147 
148   return FinalPhase;
149 }
150 
151 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
152   DerivedArgList *DAL = new DerivedArgList(Args);
153 
154   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
155   for (ArgList::const_iterator it = Args.begin(),
156          ie = Args.end(); it != ie; ++it) {
157     const Arg *A = *it;
158 
159     // Unfortunately, we have to parse some forwarding options (-Xassembler,
160     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
161     // (assembler and preprocessor), or bypass a previous driver ('collect2').
162 
163     // Rewrite linker options, to replace --no-demangle with a custom internal
164     // option.
165     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
166          A->getOption().matches(options::OPT_Xlinker)) &&
167         A->containsValue("--no-demangle")) {
168       // Add the rewritten no-demangle argument.
169       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
170 
171       // Add the remaining values as Xlinker arguments.
172       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
173         if (StringRef(A->getValue(i)) != "--no-demangle")
174           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
175                               A->getValue(i));
176 
177       continue;
178     }
179 
180     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
181     // some build systems. We don't try to be complete here because we don't
182     // care to encourage this usage model.
183     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
184         (A->getValue(0) == StringRef("-MD") ||
185          A->getValue(0) == StringRef("-MMD"))) {
186       // Rewrite to -MD/-MMD along with -MF.
187       if (A->getValue(0) == StringRef("-MD"))
188         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
189       else
190         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
191       if (A->getNumValues() == 2)
192         DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
193                             A->getValue(1));
194       continue;
195     }
196 
197     // Rewrite reserved library names.
198     if (A->getOption().matches(options::OPT_l)) {
199       StringRef Value = A->getValue();
200 
201       // Rewrite unless -nostdlib is present.
202       if (!HasNostdlib && Value == "stdc++") {
203         DAL->AddFlagArg(A, Opts->getOption(
204                               options::OPT_Z_reserved_lib_stdcxx));
205         continue;
206       }
207 
208       // Rewrite unconditionally.
209       if (Value == "cc_kext") {
210         DAL->AddFlagArg(A, Opts->getOption(
211                               options::OPT_Z_reserved_lib_cckext));
212         continue;
213       }
214     }
215 
216     DAL->append(*it);
217   }
218 
219   // Add a default value of -mlinker-version=, if one was given and the user
220   // didn't specify one.
221 #if defined(HOST_LINK_VERSION)
222   if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
223     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
224                       HOST_LINK_VERSION);
225     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
226   }
227 #endif
228 
229   return DAL;
230 }
231 
232 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
233   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
234 
235   // FIXME: Handle environment options which affect driver behavior, somewhere
236   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
237 
238   if (char *env = ::getenv("COMPILER_PATH")) {
239     StringRef CompilerPath = env;
240     while (!CompilerPath.empty()) {
241       std::pair<StringRef, StringRef> Split = CompilerPath.split(':');
242       PrefixDirs.push_back(Split.first);
243       CompilerPath = Split.second;
244     }
245   }
246 
247   // FIXME: What are we going to do with -V and -b?
248 
249   // FIXME: This stuff needs to go into the Compilation, not the driver.
250   bool CCCPrintOptions = false, CCCPrintActions = false;
251 
252   InputArgList *Args = ParseArgStrings(ArgList.slice(1));
253 
254   // -no-canonical-prefixes is used very early in main.
255   Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
256 
257   // Ignore -pipe.
258   Args->ClaimAllArgs(options::OPT_pipe);
259 
260   // Extract -ccc args.
261   //
262   // FIXME: We need to figure out where this behavior should live. Most of it
263   // should be outside in the client; the parts that aren't should have proper
264   // options, either by introducing new ones or by overloading gcc ones like -V
265   // or -b.
266   CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
267   CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
268   CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
269   CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
270   CCCEcho = Args->hasArg(options::OPT_ccc_echo);
271   if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
272     CCCGenericGCCName = A->getValue();
273   CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
274                             options::OPT_ccc_pch_is_pth);
275   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
276   // and getToolChain is const.
277   if (const Arg *A = Args->getLastArg(options::OPT_target))
278     DefaultTargetTriple = A->getValue();
279   if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
280     Dir = InstalledDir = A->getValue();
281   for (arg_iterator it = Args->filtered_begin(options::OPT_B),
282          ie = Args->filtered_end(); it != ie; ++it) {
283     const Arg *A = *it;
284     A->claim();
285     PrefixDirs.push_back(A->getValue(0));
286   }
287   if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
288     SysRoot = A->getValue();
289   if (Args->hasArg(options::OPT_nostdlib))
290     UseStdLib = false;
291 
292   // Perform the default argument translations.
293   DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
294 
295   // Owned by the host.
296   const ToolChain &TC = getToolChain(*Args);
297 
298   // The compilation takes ownership of Args.
299   Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
300 
301   // FIXME: This behavior shouldn't be here.
302   if (CCCPrintOptions) {
303     PrintOptions(C->getInputArgs());
304     return C;
305   }
306 
307   if (!HandleImmediateArgs(*C))
308     return C;
309 
310   // Construct the list of inputs.
311   InputList Inputs;
312   BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
313 
314   // Construct the list of abstract actions to perform for this compilation. On
315   // Darwin target OSes this uses the driver-driver and universal actions.
316   if (TC.getTriple().isOSDarwin())
317     BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
318                           Inputs, C->getActions());
319   else
320     BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
321                  C->getActions());
322 
323   if (CCCPrintActions) {
324     PrintActions(*C);
325     return C;
326   }
327 
328   BuildJobs(*C);
329 
330   return C;
331 }
332 
333 // When clang crashes, produce diagnostic information including the fully
334 // preprocessed source file(s).  Request that the developer attach the
335 // diagnostic information to a bug report.
336 void Driver::generateCompilationDiagnostics(Compilation &C,
337                                             const Command *FailingCommand) {
338   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
339     return;
340 
341   // Don't try to generate diagnostics for link jobs.
342   if (FailingCommand && FailingCommand->getCreator().isLinkJob())
343     return;
344 
345   // Print the version of the compiler.
346   PrintVersion(C, llvm::errs());
347 
348   Diag(clang::diag::note_drv_command_failed_diag_msg)
349     << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
350     "crash backtrace, preprocessed source, and associated run script.";
351 
352   // Suppress driver output and emit preprocessor output to temp file.
353   CCCIsCPP = true;
354   CCGenDiagnostics = true;
355   C.getArgs().AddFlagArg(0, Opts->getOption(options::OPT_frewrite_includes));
356 
357   // Save the original job command(s).
358   std::string Cmd;
359   llvm::raw_string_ostream OS(Cmd);
360   if (FailingCommand)
361     C.PrintDiagnosticJob(OS, *FailingCommand);
362   else
363     // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an
364     // associated FailingCommand, so just pass all jobs.
365     C.PrintDiagnosticJob(OS, C.getJobs());
366   OS.flush();
367 
368   // Clear stale state and suppress tool output.
369   C.initCompilationForDiagnostics();
370   Diags.Reset();
371 
372   // Construct the list of inputs.
373   InputList Inputs;
374   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
375 
376   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
377     bool IgnoreInput = false;
378 
379     // Ignore input from stdin or any inputs that cannot be preprocessed.
380     if (!strcmp(it->second->getValue(), "-")) {
381       Diag(clang::diag::note_drv_command_failed_diag_msg)
382         << "Error generating preprocessed source(s) - ignoring input from stdin"
383         ".";
384       IgnoreInput = true;
385     } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
386       IgnoreInput = true;
387     }
388 
389     if (IgnoreInput) {
390       it = Inputs.erase(it);
391       ie = Inputs.end();
392     } else {
393       ++it;
394     }
395   }
396 
397   // Don't attempt to generate preprocessed files if multiple -arch options are
398   // used, unless they're all duplicates.
399   llvm::StringSet<> ArchNames;
400   for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
401        it != ie; ++it) {
402     Arg *A = *it;
403     if (A->getOption().matches(options::OPT_arch)) {
404       StringRef ArchName = A->getValue();
405       ArchNames.insert(ArchName);
406     }
407   }
408   if (ArchNames.size() > 1) {
409     Diag(clang::diag::note_drv_command_failed_diag_msg)
410       << "Error generating preprocessed source(s) - cannot generate "
411       "preprocessed source with multiple -arch options.";
412     return;
413   }
414 
415   if (Inputs.empty()) {
416     Diag(clang::diag::note_drv_command_failed_diag_msg)
417       << "Error generating preprocessed source(s) - no preprocessable inputs.";
418     return;
419   }
420 
421   // Construct the list of abstract actions to perform for this compilation. On
422   // Darwin OSes this uses the driver-driver and builds universal actions.
423   const ToolChain &TC = C.getDefaultToolChain();
424   if (TC.getTriple().isOSDarwin())
425     BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
426   else
427     BuildActions(TC, C.getArgs(), Inputs, C.getActions());
428 
429   BuildJobs(C);
430 
431   // If there were errors building the compilation, quit now.
432   if (Diags.hasErrorOccurred()) {
433     Diag(clang::diag::note_drv_command_failed_diag_msg)
434       << "Error generating preprocessed source(s).";
435     return;
436   }
437 
438   // Generate preprocessed output.
439   FailingCommand = 0;
440   int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
441 
442   // If the command succeeded, we are done.
443   if (Res == 0) {
444     Diag(clang::diag::note_drv_command_failed_diag_msg)
445       << "\n********************\n\n"
446       "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
447       "Preprocessed source(s) and associated run script(s) are located at:";
448     ArgStringList Files = C.getTempFiles();
449     for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
450          it != ie; ++it) {
451       Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
452 
453       std::string Err;
454       std::string Script = StringRef(*it).rsplit('.').first;
455       Script += ".sh";
456       llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
457                                     llvm::raw_fd_ostream::F_Excl |
458                                     llvm::raw_fd_ostream::F_Binary);
459       if (!Err.empty()) {
460         Diag(clang::diag::note_drv_command_failed_diag_msg)
461           << "Error generating run script: " + Script + " " + Err;
462       } else {
463         // Append the new filename with correct preprocessed suffix.
464         size_t I, E;
465         I = Cmd.find("-main-file-name ");
466         assert (I != std::string::npos && "Expected to find -main-file-name");
467         I += 16;
468         E = Cmd.find(" ", I);
469         assert (E != std::string::npos && "-main-file-name missing argument?");
470         StringRef OldFilename = StringRef(Cmd).slice(I, E);
471         StringRef NewFilename = llvm::sys::path::filename(*it);
472         I = StringRef(Cmd).rfind(OldFilename);
473         E = I + OldFilename.size();
474         I = Cmd.rfind(" ", I) + 1;
475         Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size());
476         ScriptOS << Cmd;
477         Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
478       }
479     }
480     Diag(clang::diag::note_drv_command_failed_diag_msg)
481       << "\n\n********************";
482   } else {
483     // Failure, remove preprocessed files.
484     if (!C.getArgs().hasArg(options::OPT_save_temps))
485       C.CleanupFileList(C.getTempFiles(), true);
486 
487     Diag(clang::diag::note_drv_command_failed_diag_msg)
488       << "Error generating preprocessed source(s).";
489   }
490 }
491 
492 int Driver::ExecuteCompilation(const Compilation &C,
493                                const Command *&FailingCommand) const {
494   // Just print if -### was present.
495   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
496     C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
497     return 0;
498   }
499 
500   // If there were errors building the compilation, quit now.
501   if (Diags.hasErrorOccurred())
502     return 1;
503 
504   int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
505 
506   // Remove temp files.
507   C.CleanupFileList(C.getTempFiles());
508 
509   // If the command succeeded, we are done.
510   if (Res == 0)
511     return Res;
512 
513   // Otherwise, remove result files as well.
514   if (!C.getArgs().hasArg(options::OPT_save_temps)) {
515     C.CleanupFileList(C.getResultFiles(), true);
516 
517     // Failure result files are valid unless we crashed.
518     if (Res < 0)
519       C.CleanupFileList(C.getFailureResultFiles(), true);
520   }
521 
522   // Print extra information about abnormal failures, if possible.
523   //
524   // This is ad-hoc, but we don't want to be excessively noisy. If the result
525   // status was 1, assume the command failed normally. In particular, if it was
526   // the compiler then assume it gave a reasonable error code. Failures in other
527   // tools are less common, and they generally have worse diagnostics, so always
528   // print the diagnostic there.
529   const Tool &FailingTool = FailingCommand->getCreator();
530 
531   if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
532     // FIXME: See FIXME above regarding result code interpretation.
533     if (Res < 0)
534       Diag(clang::diag::err_drv_command_signalled)
535         << FailingTool.getShortName();
536     else
537       Diag(clang::diag::err_drv_command_failed)
538         << FailingTool.getShortName() << Res;
539   }
540 
541   return Res;
542 }
543 
544 void Driver::PrintOptions(const ArgList &Args) const {
545   unsigned i = 0;
546   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
547        it != ie; ++it, ++i) {
548     Arg *A = *it;
549     llvm::errs() << "Option " << i << " - "
550                  << "Name: \"" << A->getOption().getPrefixedName() << "\", "
551                  << "Values: {";
552     for (unsigned j = 0; j < A->getNumValues(); ++j) {
553       if (j)
554         llvm::errs() << ", ";
555       llvm::errs() << '"' << A->getValue(j) << '"';
556     }
557     llvm::errs() << "}\n";
558   }
559 }
560 
561 void Driver::PrintHelp(bool ShowHidden) const {
562   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
563                       /*Include*/0,
564                       /*Exclude*/options::NoDriverOption |
565                       (ShowHidden ? 0 : options::HelpHidden));
566 }
567 
568 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
569   // FIXME: The following handlers should use a callback mechanism, we don't
570   // know what the client would like to do.
571   OS << getClangFullVersion() << '\n';
572   const ToolChain &TC = C.getDefaultToolChain();
573   OS << "Target: " << TC.getTripleString() << '\n';
574 
575   // Print the threading model.
576   //
577   // FIXME: Implement correctly.
578   OS << "Thread model: " << "posix" << '\n';
579 }
580 
581 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
582 /// option.
583 static void PrintDiagnosticCategories(raw_ostream &OS) {
584   // Skip the empty category.
585   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
586        i != max; ++i)
587     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
588 }
589 
590 bool Driver::HandleImmediateArgs(const Compilation &C) {
591   // The order these options are handled in gcc is all over the place, but we
592   // don't expect inconsistencies w.r.t. that to matter in practice.
593 
594   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
595     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
596     return false;
597   }
598 
599   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
600     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
601     // return an answer which matches our definition of __VERSION__.
602     //
603     // If we want to return a more correct answer some day, then we should
604     // introduce a non-pedantically GCC compatible mode to Clang in which we
605     // provide sensible definitions for -dumpversion, __VERSION__, etc.
606     llvm::outs() << "4.2.1\n";
607     return false;
608   }
609 
610   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
611     PrintDiagnosticCategories(llvm::outs());
612     return false;
613   }
614 
615   if (C.getArgs().hasArg(options::OPT_help) ||
616       C.getArgs().hasArg(options::OPT__help_hidden)) {
617     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
618     return false;
619   }
620 
621   if (C.getArgs().hasArg(options::OPT__version)) {
622     // Follow gcc behavior and use stdout for --version and stderr for -v.
623     PrintVersion(C, llvm::outs());
624     return false;
625   }
626 
627   if (C.getArgs().hasArg(options::OPT_v) ||
628       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
629     PrintVersion(C, llvm::errs());
630     SuppressMissingInputWarning = true;
631   }
632 
633   const ToolChain &TC = C.getDefaultToolChain();
634   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
635     llvm::outs() << "programs: =";
636     for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
637            ie = TC.getProgramPaths().end(); it != ie; ++it) {
638       if (it != TC.getProgramPaths().begin())
639         llvm::outs() << ':';
640       llvm::outs() << *it;
641     }
642     llvm::outs() << "\n";
643     llvm::outs() << "libraries: =" << ResourceDir;
644 
645     StringRef sysroot = C.getSysRoot();
646 
647     for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
648            ie = TC.getFilePaths().end(); it != ie; ++it) {
649       llvm::outs() << ':';
650       const char *path = it->c_str();
651       if (path[0] == '=')
652         llvm::outs() << sysroot << path + 1;
653       else
654         llvm::outs() << path;
655     }
656     llvm::outs() << "\n";
657     return false;
658   }
659 
660   // FIXME: The following handlers should use a callback mechanism, we don't
661   // know what the client would like to do.
662   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
663     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
664     return false;
665   }
666 
667   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
668     llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
669     return false;
670   }
671 
672   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
673     llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
674     return false;
675   }
676 
677   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
678     // FIXME: We need tool chain support for this.
679     llvm::outs() << ".;\n";
680 
681     switch (C.getDefaultToolChain().getTriple().getArch()) {
682     default:
683       break;
684 
685     case llvm::Triple::x86_64:
686       llvm::outs() << "x86_64;@m64" << "\n";
687       break;
688 
689     case llvm::Triple::ppc64:
690       llvm::outs() << "ppc64;@m64" << "\n";
691       break;
692     }
693     return false;
694   }
695 
696   // FIXME: What is the difference between print-multi-directory and
697   // print-multi-os-directory?
698   if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
699       C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
700     switch (C.getDefaultToolChain().getTriple().getArch()) {
701     default:
702     case llvm::Triple::x86:
703     case llvm::Triple::ppc:
704       llvm::outs() << "." << "\n";
705       break;
706 
707     case llvm::Triple::x86_64:
708       llvm::outs() << "x86_64" << "\n";
709       break;
710 
711     case llvm::Triple::ppc64:
712       llvm::outs() << "ppc64" << "\n";
713       break;
714     }
715     return false;
716   }
717 
718   return true;
719 }
720 
721 static unsigned PrintActions1(const Compilation &C, Action *A,
722                               std::map<Action*, unsigned> &Ids) {
723   if (Ids.count(A))
724     return Ids[A];
725 
726   std::string str;
727   llvm::raw_string_ostream os(str);
728 
729   os << Action::getClassName(A->getKind()) << ", ";
730   if (InputAction *IA = dyn_cast<InputAction>(A)) {
731     os << "\"" << IA->getInputArg().getValue() << "\"";
732   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
733     os << '"' << BIA->getArchName() << '"'
734        << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
735   } else {
736     os << "{";
737     for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
738       os << PrintActions1(C, *it, Ids);
739       ++it;
740       if (it != ie)
741         os << ", ";
742     }
743     os << "}";
744   }
745 
746   unsigned Id = Ids.size();
747   Ids[A] = Id;
748   llvm::errs() << Id << ": " << os.str() << ", "
749                << types::getTypeName(A->getType()) << "\n";
750 
751   return Id;
752 }
753 
754 void Driver::PrintActions(const Compilation &C) const {
755   std::map<Action*, unsigned> Ids;
756   for (ActionList::const_iterator it = C.getActions().begin(),
757          ie = C.getActions().end(); it != ie; ++it)
758     PrintActions1(C, *it, Ids);
759 }
760 
761 /// \brief Check whether the given input tree contains any compilation or
762 /// assembly actions.
763 static bool ContainsCompileOrAssembleAction(const Action *A) {
764   if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
765     return true;
766 
767   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
768     if (ContainsCompileOrAssembleAction(*it))
769       return true;
770 
771   return false;
772 }
773 
774 void Driver::BuildUniversalActions(const ToolChain &TC,
775                                    const DerivedArgList &Args,
776                                    const InputList &BAInputs,
777                                    ActionList &Actions) const {
778   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
779   // Collect the list of architectures. Duplicates are allowed, but should only
780   // be handled once (in the order seen).
781   llvm::StringSet<> ArchNames;
782   SmallVector<const char *, 4> Archs;
783   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
784        it != ie; ++it) {
785     Arg *A = *it;
786 
787     if (A->getOption().matches(options::OPT_arch)) {
788       // Validate the option here; we don't save the type here because its
789       // particular spelling may participate in other driver choices.
790       llvm::Triple::ArchType Arch =
791         tools::darwin::getArchTypeForDarwinArchName(A->getValue());
792       if (Arch == llvm::Triple::UnknownArch) {
793         Diag(clang::diag::err_drv_invalid_arch_name)
794           << A->getAsString(Args);
795         continue;
796       }
797 
798       A->claim();
799       if (ArchNames.insert(A->getValue()))
800         Archs.push_back(A->getValue());
801     }
802   }
803 
804   // When there is no explicit arch for this platform, make sure we still bind
805   // the architecture (to the default) so that -Xarch_ is handled correctly.
806   if (!Archs.size())
807     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
808 
809   // FIXME: We killed off some others but these aren't yet detected in a
810   // functional manner. If we added information to jobs about which "auxiliary"
811   // files they wrote then we could detect the conflict these cause downstream.
812   if (Archs.size() > 1) {
813     // No recovery needed, the point of this is just to prevent
814     // overwriting the same files.
815     if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
816       Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
817         << A->getAsString(Args);
818   }
819 
820   ActionList SingleActions;
821   BuildActions(TC, Args, BAInputs, SingleActions);
822 
823   // Add in arch bindings for every top level action, as well as lipo and
824   // dsymutil steps if needed.
825   for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
826     Action *Act = SingleActions[i];
827 
828     // Make sure we can lipo this kind of output. If not (and it is an actual
829     // output) then we disallow, since we can't create an output file with the
830     // right name without overwriting it. We could remove this oddity by just
831     // changing the output names to include the arch, which would also fix
832     // -save-temps. Compatibility wins for now.
833 
834     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
835       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
836         << types::getTypeName(Act->getType());
837 
838     ActionList Inputs;
839     for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
840       Inputs.push_back(new BindArchAction(Act, Archs[i]));
841       if (i != 0)
842         Inputs.back()->setOwnsInputs(false);
843     }
844 
845     // Lipo if necessary, we do it this way because we need to set the arch flag
846     // so that -Xarch_ gets overwritten.
847     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
848       Actions.append(Inputs.begin(), Inputs.end());
849     else
850       Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
851 
852     // Handle debug info queries.
853     Arg *A = Args.getLastArg(options::OPT_g_Group);
854     if (A && !A->getOption().matches(options::OPT_g0) &&
855         !A->getOption().matches(options::OPT_gstabs) &&
856         ContainsCompileOrAssembleAction(Actions.back())) {
857 
858       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
859       // have a compile input. We need to run 'dsymutil' ourselves in such cases
860       // because the debug info will refer to a temporary object file which is
861       // will be removed at the end of the compilation process.
862       if (Act->getType() == types::TY_Image) {
863         ActionList Inputs;
864         Inputs.push_back(Actions.back());
865         Actions.pop_back();
866         Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
867       }
868 
869       // Verify the output (debug information only) if we passed '-verify'.
870       if (Args.hasArg(options::OPT_verify)) {
871         ActionList VerifyInputs;
872         VerifyInputs.push_back(Actions.back());
873         Actions.pop_back();
874         Actions.push_back(new VerifyJobAction(VerifyInputs,
875                                               types::TY_Nothing));
876       }
877     }
878   }
879 }
880 
881 // Construct a the list of inputs and their types.
882 void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
883                          InputList &Inputs) const {
884   // Track the current user specified (-x) input. We also explicitly track the
885   // argument used to set the type; we only want to claim the type when we
886   // actually use it, so we warn about unused -x arguments.
887   types::ID InputType = types::TY_Nothing;
888   Arg *InputTypeArg = 0;
889 
890   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
891        it != ie; ++it) {
892     Arg *A = *it;
893 
894     if (A->getOption().getKind() == Option::InputClass) {
895       const char *Value = A->getValue();
896       types::ID Ty = types::TY_INVALID;
897 
898       // Infer the input type if necessary.
899       if (InputType == types::TY_Nothing) {
900         // If there was an explicit arg for this, claim it.
901         if (InputTypeArg)
902           InputTypeArg->claim();
903 
904         // stdin must be handled specially.
905         if (memcmp(Value, "-", 2) == 0) {
906           // If running with -E, treat as a C input (this changes the builtin
907           // macros, for example). This may be overridden by -ObjC below.
908           //
909           // Otherwise emit an error but still use a valid type to avoid
910           // spurious errors (e.g., no inputs).
911           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
912             Diag(clang::diag::err_drv_unknown_stdin_type);
913           Ty = types::TY_C;
914         } else {
915           // Otherwise lookup by extension.
916           // Fallback is C if invoked as C preprocessor or Object otherwise.
917           // We use a host hook here because Darwin at least has its own
918           // idea of what .s is.
919           if (const char *Ext = strrchr(Value, '.'))
920             Ty = TC.LookupTypeForExtension(Ext + 1);
921 
922           if (Ty == types::TY_INVALID) {
923             if (CCCIsCPP)
924               Ty = types::TY_C;
925             else
926               Ty = types::TY_Object;
927           }
928 
929           // If the driver is invoked as C++ compiler (like clang++ or c++) it
930           // should autodetect some input files as C++ for g++ compatibility.
931           if (CCCIsCXX) {
932             types::ID OldTy = Ty;
933             Ty = types::lookupCXXTypeForCType(Ty);
934 
935             if (Ty != OldTy)
936               Diag(clang::diag::warn_drv_treating_input_as_cxx)
937                 << getTypeName(OldTy) << getTypeName(Ty);
938           }
939         }
940 
941         // -ObjC and -ObjC++ override the default language, but only for "source
942         // files". We just treat everything that isn't a linker input as a
943         // source file.
944         //
945         // FIXME: Clean this up if we move the phase sequence into the type.
946         if (Ty != types::TY_Object) {
947           if (Args.hasArg(options::OPT_ObjC))
948             Ty = types::TY_ObjC;
949           else if (Args.hasArg(options::OPT_ObjCXX))
950             Ty = types::TY_ObjCXX;
951         }
952       } else {
953         assert(InputTypeArg && "InputType set w/o InputTypeArg");
954         InputTypeArg->claim();
955         Ty = InputType;
956       }
957 
958       // Check that the file exists, if enabled.
959       if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
960         SmallString<64> Path(Value);
961         if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
962           if (!llvm::sys::path::is_absolute(Path.str())) {
963             SmallString<64> Directory(WorkDir->getValue());
964             llvm::sys::path::append(Directory, Value);
965             Path.assign(Directory);
966           }
967         }
968 
969         bool exists = false;
970         if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
971           Diag(clang::diag::err_drv_no_such_file) << Path.str();
972         else
973           Inputs.push_back(std::make_pair(Ty, A));
974       } else
975         Inputs.push_back(std::make_pair(Ty, A));
976 
977     } else if (A->getOption().hasFlag(options::LinkerInput)) {
978       // Just treat as object type, we could make a special type for this if
979       // necessary.
980       Inputs.push_back(std::make_pair(types::TY_Object, A));
981 
982     } else if (A->getOption().matches(options::OPT_x)) {
983       InputTypeArg = A;
984       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
985       A->claim();
986 
987       // Follow gcc behavior and treat as linker input for invalid -x
988       // options. Its not clear why we shouldn't just revert to unknown; but
989       // this isn't very important, we might as well be bug compatible.
990       if (!InputType) {
991         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
992         InputType = types::TY_Object;
993       }
994     }
995   }
996   if (CCCIsCPP && Inputs.empty()) {
997     // If called as standalone preprocessor, stdin is processed
998     // if no other input is present.
999     unsigned Index = Args.getBaseArgs().MakeIndex("-");
1000     Arg *A = Opts->ParseOneArg(Args, Index);
1001     A->claim();
1002     Inputs.push_back(std::make_pair(types::TY_C, A));
1003   }
1004 }
1005 
1006 void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
1007                           const InputList &Inputs, ActionList &Actions) const {
1008   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1009 
1010   if (!SuppressMissingInputWarning && Inputs.empty()) {
1011     Diag(clang::diag::err_drv_no_input_files);
1012     return;
1013   }
1014 
1015   Arg *FinalPhaseArg;
1016   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1017 
1018   // Reject -Z* at the top level, these options should never have been exposed
1019   // by gcc.
1020   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1021     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1022 
1023   // Construct the actions to perform.
1024   ActionList LinkerInputs;
1025   unsigned NumSteps = 0;
1026   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1027     types::ID InputType = Inputs[i].first;
1028     const Arg *InputArg = Inputs[i].second;
1029 
1030     NumSteps = types::getNumCompilationPhases(InputType);
1031     assert(NumSteps && "Invalid number of steps!");
1032 
1033     // If the first step comes after the final phase we are doing as part of
1034     // this compilation, warn the user about it.
1035     phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
1036     if (InitialPhase > FinalPhase) {
1037       // Claim here to avoid the more general unused warning.
1038       InputArg->claim();
1039 
1040       // Suppress all unused style warnings with -Qunused-arguments
1041       if (Args.hasArg(options::OPT_Qunused_arguments))
1042         continue;
1043 
1044       // Special case when final phase determined by binary name, rather than
1045       // by a command-line argument with a corresponding Arg.
1046       if (CCCIsCPP)
1047         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1048           << InputArg->getAsString(Args)
1049           << getPhaseName(InitialPhase);
1050       // Special case '-E' warning on a previously preprocessed file to make
1051       // more sense.
1052       else if (InitialPhase == phases::Compile &&
1053                FinalPhase == phases::Preprocess &&
1054                getPreprocessedType(InputType) == types::TY_INVALID)
1055         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1056           << InputArg->getAsString(Args)
1057           << !!FinalPhaseArg
1058           << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "";
1059       else
1060         Diag(clang::diag::warn_drv_input_file_unused)
1061           << InputArg->getAsString(Args)
1062           << getPhaseName(InitialPhase)
1063           << !!FinalPhaseArg
1064           << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "";
1065       continue;
1066     }
1067 
1068     // Build the pipeline for this file.
1069     OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
1070     for (unsigned i = 0; i != NumSteps; ++i) {
1071       phases::ID Phase = types::getCompilationPhase(InputType, i);
1072 
1073       // We are done if this step is past what the user requested.
1074       if (Phase > FinalPhase)
1075         break;
1076 
1077       // Queue linker inputs.
1078       if (Phase == phases::Link) {
1079         assert(i + 1 == NumSteps && "linking must be final compilation step.");
1080         LinkerInputs.push_back(Current.take());
1081         break;
1082       }
1083 
1084       // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1085       // encode this in the steps because the intermediate type depends on
1086       // arguments. Just special case here.
1087       if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1088         continue;
1089 
1090       // Otherwise construct the appropriate action.
1091       Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
1092       if (Current->getType() == types::TY_Nothing)
1093         break;
1094     }
1095 
1096     // If we ended with something, add to the output list.
1097     if (Current)
1098       Actions.push_back(Current.take());
1099   }
1100 
1101   // Add a link action if necessary.
1102   if (!LinkerInputs.empty())
1103     Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1104 
1105   // If we are linking, claim any options which are obviously only used for
1106   // compilation.
1107   if (FinalPhase == phases::Link && (NumSteps == 1))
1108     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1109 }
1110 
1111 Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
1112                                      Action *Input) const {
1113   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1114   // Build the appropriate action.
1115   switch (Phase) {
1116   case phases::Link: llvm_unreachable("link action invalid here.");
1117   case phases::Preprocess: {
1118     types::ID OutputTy;
1119     // -{M, MM} alter the output type.
1120     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1121       OutputTy = types::TY_Dependencies;
1122     } else {
1123       OutputTy = Input->getType();
1124       if (!Args.hasFlag(options::OPT_frewrite_includes,
1125                         options::OPT_fno_rewrite_includes, false))
1126         OutputTy = types::getPreprocessedType(OutputTy);
1127       assert(OutputTy != types::TY_INVALID &&
1128              "Cannot preprocess this input type!");
1129     }
1130     return new PreprocessJobAction(Input, OutputTy);
1131   }
1132   case phases::Precompile: {
1133     types::ID OutputTy = types::TY_PCH;
1134     if (Args.hasArg(options::OPT_fsyntax_only)) {
1135       // Syntax checks should not emit a PCH file
1136       OutputTy = types::TY_Nothing;
1137     }
1138     return new PrecompileJobAction(Input, OutputTy);
1139   }
1140   case phases::Compile: {
1141     if (Args.hasArg(options::OPT_fsyntax_only)) {
1142       return new CompileJobAction(Input, types::TY_Nothing);
1143     } else if (Args.hasArg(options::OPT_rewrite_objc)) {
1144       return new CompileJobAction(Input, types::TY_RewrittenObjC);
1145     } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
1146       return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
1147     } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
1148       return new AnalyzeJobAction(Input, types::TY_Plist);
1149     } else if (Args.hasArg(options::OPT__migrate)) {
1150       return new MigrateJobAction(Input, types::TY_Remap);
1151     } else if (Args.hasArg(options::OPT_emit_ast)) {
1152       return new CompileJobAction(Input, types::TY_AST);
1153     } else if (IsUsingLTO(Args)) {
1154       types::ID Output =
1155         Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1156       return new CompileJobAction(Input, Output);
1157     } else {
1158       return new CompileJobAction(Input, types::TY_PP_Asm);
1159     }
1160   }
1161   case phases::Assemble:
1162     return new AssembleJobAction(Input, types::TY_Object);
1163   }
1164 
1165   llvm_unreachable("invalid phase in ConstructPhaseAction");
1166 }
1167 
1168 bool Driver::IsUsingLTO(const ArgList &Args) const {
1169   // Check for -emit-llvm or -flto.
1170   if (Args.hasArg(options::OPT_emit_llvm) ||
1171       Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
1172     return true;
1173 
1174   // Check for -O4.
1175   if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
1176       return A->getOption().matches(options::OPT_O4);
1177 
1178   return false;
1179 }
1180 
1181 void Driver::BuildJobs(Compilation &C) const {
1182   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1183 
1184   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1185 
1186   // It is an error to provide a -o option if we are making multiple output
1187   // files.
1188   if (FinalOutput) {
1189     unsigned NumOutputs = 0;
1190     for (ActionList::const_iterator it = C.getActions().begin(),
1191            ie = C.getActions().end(); it != ie; ++it)
1192       if ((*it)->getType() != types::TY_Nothing)
1193         ++NumOutputs;
1194 
1195     if (NumOutputs > 1) {
1196       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1197       FinalOutput = 0;
1198     }
1199   }
1200 
1201   for (ActionList::const_iterator it = C.getActions().begin(),
1202          ie = C.getActions().end(); it != ie; ++it) {
1203     Action *A = *it;
1204 
1205     // If we are linking an image for multiple archs then the linker wants
1206     // -arch_multiple and -final_output <final image name>. Unfortunately, this
1207     // doesn't fit in cleanly because we have to pass this information down.
1208     //
1209     // FIXME: This is a hack; find a cleaner way to integrate this into the
1210     // process.
1211     const char *LinkingOutput = 0;
1212     if (isa<LipoJobAction>(A)) {
1213       if (FinalOutput)
1214         LinkingOutput = FinalOutput->getValue();
1215       else
1216         LinkingOutput = DefaultImageName.c_str();
1217     }
1218 
1219     InputInfo II;
1220     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1221                        /*BoundArch*/0,
1222                        /*AtTopLevel*/ true,
1223                        /*LinkingOutput*/ LinkingOutput,
1224                        II);
1225   }
1226 
1227   // If the user passed -Qunused-arguments or there were errors, don't warn
1228   // about any unused arguments.
1229   if (Diags.hasErrorOccurred() ||
1230       C.getArgs().hasArg(options::OPT_Qunused_arguments))
1231     return;
1232 
1233   // Claim -### here.
1234   (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1235 
1236   for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1237        it != ie; ++it) {
1238     Arg *A = *it;
1239 
1240     // FIXME: It would be nice to be able to send the argument to the
1241     // DiagnosticsEngine, so that extra values, position, and so on could be
1242     // printed.
1243     if (!A->isClaimed()) {
1244       if (A->getOption().hasFlag(options::NoArgumentUnused))
1245         continue;
1246 
1247       // Suppress the warning automatically if this is just a flag, and it is an
1248       // instance of an argument we already claimed.
1249       const Option &Opt = A->getOption();
1250       if (Opt.getKind() == Option::FlagClass) {
1251         bool DuplicateClaimed = false;
1252 
1253         for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1254                ie = C.getArgs().filtered_end(); it != ie; ++it) {
1255           if ((*it)->isClaimed()) {
1256             DuplicateClaimed = true;
1257             break;
1258           }
1259         }
1260 
1261         if (DuplicateClaimed)
1262           continue;
1263       }
1264 
1265       Diag(clang::diag::warn_drv_unused_argument)
1266         << A->getAsString(C.getArgs());
1267     }
1268   }
1269 }
1270 
1271 static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1272                                     const JobAction *JA,
1273                                     const ActionList *&Inputs) {
1274   const Tool *ToolForJob = 0;
1275 
1276   // See if we should look for a compiler with an integrated assembler. We match
1277   // bottom up, so what we are actually looking for is an assembler job with a
1278   // compiler input.
1279 
1280   if (C.getArgs().hasFlag(options::OPT_integrated_as,
1281                           options::OPT_no_integrated_as,
1282                           TC->IsIntegratedAssemblerDefault()) &&
1283       !C.getArgs().hasArg(options::OPT_save_temps) &&
1284       isa<AssembleJobAction>(JA) &&
1285       Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1286     const Tool &Compiler = TC->SelectTool(
1287       C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
1288     if (Compiler.hasIntegratedAssembler()) {
1289       Inputs = &(*Inputs)[0]->getInputs();
1290       ToolForJob = &Compiler;
1291     }
1292   }
1293 
1294   // Otherwise use the tool for the current job.
1295   if (!ToolForJob)
1296     ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
1297 
1298   // See if we should use an integrated preprocessor. We do so when we have
1299   // exactly one input, since this is the only use case we care about
1300   // (irrelevant since we don't support combine yet).
1301   if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1302       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1303       !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1304       !C.getArgs().hasArg(options::OPT_save_temps) &&
1305       !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
1306       ToolForJob->hasIntegratedCPP())
1307     Inputs = &(*Inputs)[0]->getInputs();
1308 
1309   return *ToolForJob;
1310 }
1311 
1312 void Driver::BuildJobsForAction(Compilation &C,
1313                                 const Action *A,
1314                                 const ToolChain *TC,
1315                                 const char *BoundArch,
1316                                 bool AtTopLevel,
1317                                 const char *LinkingOutput,
1318                                 InputInfo &Result) const {
1319   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1320 
1321   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1322     // FIXME: It would be nice to not claim this here; maybe the old scheme of
1323     // just using Args was better?
1324     const Arg &Input = IA->getInputArg();
1325     Input.claim();
1326     if (Input.getOption().matches(options::OPT_INPUT)) {
1327       const char *Name = Input.getValue();
1328       Result = InputInfo(Name, A->getType(), Name);
1329     } else
1330       Result = InputInfo(&Input, A->getType(), "");
1331     return;
1332   }
1333 
1334   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1335     const ToolChain *TC;
1336     const char *ArchName = BAA->getArchName();
1337 
1338     if (ArchName)
1339       TC = &getToolChain(C.getArgs(), ArchName);
1340     else
1341       TC = &C.getDefaultToolChain();
1342 
1343     BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1344                        AtTopLevel, LinkingOutput, Result);
1345     return;
1346   }
1347 
1348   const ActionList *Inputs = &A->getInputs();
1349 
1350   const JobAction *JA = cast<JobAction>(A);
1351   const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1352 
1353   // Only use pipes when there is exactly one input.
1354   InputInfoList InputInfos;
1355   for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1356        it != ie; ++it) {
1357     // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1358     // temporary output names.
1359     //
1360     // FIXME: Clean this up.
1361     bool SubJobAtTopLevel = false;
1362     if (AtTopLevel && isa<DsymutilJobAction>(A))
1363       SubJobAtTopLevel = true;
1364 
1365     // Also treat verify sub-jobs as being at the top-level. They don't
1366     // produce any output and so don't need temporary output names.
1367     if (AtTopLevel && isa<VerifyJobAction>(A))
1368       SubJobAtTopLevel = true;
1369 
1370     InputInfo II;
1371     BuildJobsForAction(C, *it, TC, BoundArch,
1372                        SubJobAtTopLevel, LinkingOutput, II);
1373     InputInfos.push_back(II);
1374   }
1375 
1376   // Always use the first input as the base input.
1377   const char *BaseInput = InputInfos[0].getBaseInput();
1378 
1379   // ... except dsymutil actions, which use their actual input as the base
1380   // input.
1381   if (JA->getType() == types::TY_dSYM)
1382     BaseInput = InputInfos[0].getFilename();
1383 
1384   // Determine the place to write output to, if any.
1385   if (JA->getType() == types::TY_Nothing) {
1386     Result = InputInfo(A->getType(), BaseInput);
1387   } else {
1388     Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1389                        A->getType(), BaseInput);
1390   }
1391 
1392   if (CCCPrintBindings && !CCGenDiagnostics) {
1393     llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1394                  << " - \"" << T.getName() << "\", inputs: [";
1395     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1396       llvm::errs() << InputInfos[i].getAsString();
1397       if (i + 1 != e)
1398         llvm::errs() << ", ";
1399     }
1400     llvm::errs() << "], output: " << Result.getAsString() << "\n";
1401   } else {
1402     T.ConstructJob(C, *JA, Result, InputInfos,
1403                    C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1404   }
1405 }
1406 
1407 const char *Driver::GetNamedOutputPath(Compilation &C,
1408                                        const JobAction &JA,
1409                                        const char *BaseInput,
1410                                        bool AtTopLevel) const {
1411   llvm::PrettyStackTraceString CrashInfo("Computing output path");
1412   // Output to a user requested destination?
1413   if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
1414       !isa<VerifyJobAction>(JA)) {
1415     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1416       return C.addResultFile(FinalOutput->getValue());
1417   }
1418 
1419   // Default to writing to stdout?
1420   if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics)
1421     return "-";
1422 
1423   // Output to a temporary file?
1424   if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
1425       CCGenDiagnostics) {
1426     StringRef Name = llvm::sys::path::filename(BaseInput);
1427     std::pair<StringRef, StringRef> Split = Name.split('.');
1428     std::string TmpName =
1429       GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
1430     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1431   }
1432 
1433   SmallString<128> BasePath(BaseInput);
1434   StringRef BaseName;
1435 
1436   // Dsymutil actions should use the full path.
1437   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
1438     BaseName = BasePath;
1439   else
1440     BaseName = llvm::sys::path::filename(BasePath);
1441 
1442   // Determine what the derived output name should be.
1443   const char *NamedOutput;
1444   if (JA.getType() == types::TY_Image) {
1445     NamedOutput = DefaultImageName.c_str();
1446   } else {
1447     const char *Suffix = types::getTypeTempSuffix(JA.getType());
1448     assert(Suffix && "All types used for output should have a suffix.");
1449 
1450     std::string::size_type End = std::string::npos;
1451     if (!types::appendSuffixForType(JA.getType()))
1452       End = BaseName.rfind('.');
1453     std::string Suffixed(BaseName.substr(0, End));
1454     Suffixed += '.';
1455     Suffixed += Suffix;
1456     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1457   }
1458 
1459   // If we're saving temps and the temp file conflicts with the input file,
1460   // then avoid overwriting input file.
1461   if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
1462       NamedOutput == BaseName) {
1463 
1464     bool SameFile = false;
1465     SmallString<256> Result;
1466     llvm::sys::fs::current_path(Result);
1467     llvm::sys::path::append(Result, BaseName);
1468     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
1469     // Must share the same path to conflict.
1470     if (SameFile) {
1471       StringRef Name = llvm::sys::path::filename(BaseInput);
1472       std::pair<StringRef, StringRef> Split = Name.split('.');
1473       std::string TmpName =
1474         GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
1475       return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1476     }
1477   }
1478 
1479   // As an annoying special case, PCH generation doesn't strip the pathname.
1480   if (JA.getType() == types::TY_PCH) {
1481     llvm::sys::path::remove_filename(BasePath);
1482     if (BasePath.empty())
1483       BasePath = NamedOutput;
1484     else
1485       llvm::sys::path::append(BasePath, NamedOutput);
1486     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1487   } else {
1488     return C.addResultFile(NamedOutput);
1489   }
1490 }
1491 
1492 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1493   // Respect a limited subset of the '-Bprefix' functionality in GCC by
1494   // attempting to use this prefix when looking for file paths.
1495   for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1496        ie = PrefixDirs.end(); it != ie; ++it) {
1497     std::string Dir(*it);
1498     if (Dir.empty())
1499       continue;
1500     if (Dir[0] == '=')
1501       Dir = SysRoot + Dir.substr(1);
1502     llvm::sys::Path P(Dir);
1503     P.appendComponent(Name);
1504     bool Exists;
1505     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1506       return P.str();
1507   }
1508 
1509   llvm::sys::Path P(ResourceDir);
1510   P.appendComponent(Name);
1511   bool Exists;
1512   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1513     return P.str();
1514 
1515   const ToolChain::path_list &List = TC.getFilePaths();
1516   for (ToolChain::path_list::const_iterator
1517          it = List.begin(), ie = List.end(); it != ie; ++it) {
1518     std::string Dir(*it);
1519     if (Dir.empty())
1520       continue;
1521     if (Dir[0] == '=')
1522       Dir = SysRoot + Dir.substr(1);
1523     llvm::sys::Path P(Dir);
1524     P.appendComponent(Name);
1525     bool Exists;
1526     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1527       return P.str();
1528   }
1529 
1530   return Name;
1531 }
1532 
1533 std::string Driver::GetProgramPath(const char *Name,
1534                                    const ToolChain &TC) const {
1535   // FIXME: Needs a better variable than DefaultTargetTriple
1536   std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
1537   // Respect a limited subset of the '-Bprefix' functionality in GCC by
1538   // attempting to use this prefix when looking for program paths.
1539   for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1540        ie = PrefixDirs.end(); it != ie; ++it) {
1541     bool IsDirectory;
1542     if (!llvm::sys::fs::is_directory(*it, IsDirectory) && IsDirectory) {
1543       llvm::sys::Path P(*it);
1544       P.appendComponent(TargetSpecificExecutable);
1545       if (P.canExecute()) return P.str();
1546       P.eraseComponent();
1547       P.appendComponent(Name);
1548       if (P.canExecute()) return P.str();
1549     } else {
1550       llvm::sys::Path P(*it + Name);
1551       if (P.canExecute()) return P.str();
1552     }
1553   }
1554 
1555   const ToolChain::path_list &List = TC.getProgramPaths();
1556   for (ToolChain::path_list::const_iterator
1557          it = List.begin(), ie = List.end(); it != ie; ++it) {
1558     llvm::sys::Path P(*it);
1559     P.appendComponent(TargetSpecificExecutable);
1560     if (P.canExecute()) return P.str();
1561     P.eraseComponent();
1562     P.appendComponent(Name);
1563     if (P.canExecute()) return P.str();
1564   }
1565 
1566   // If all else failed, search the path.
1567   llvm::sys::Path
1568       P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
1569   if (!P.empty())
1570     return P.str();
1571 
1572   P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
1573   if (!P.empty())
1574     return P.str();
1575 
1576   return Name;
1577 }
1578 
1579 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
1580   const {
1581   // FIXME: This is lame; sys::Path should provide this function (in particular,
1582   // it should know how to find the temporary files dir).
1583   std::string Error;
1584   const char *TmpDir = ::getenv("TMPDIR");
1585   if (!TmpDir)
1586     TmpDir = ::getenv("TEMP");
1587   if (!TmpDir)
1588     TmpDir = ::getenv("TMP");
1589   if (!TmpDir)
1590     TmpDir = "/tmp";
1591   llvm::sys::Path P(TmpDir);
1592   P.appendComponent(Prefix);
1593   if (P.makeUnique(false, &Error)) {
1594     Diag(clang::diag::err_unable_to_make_temp) << Error;
1595     return "";
1596   }
1597 
1598   // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1599   P.eraseFromDisk(false, 0);
1600 
1601   if (Suffix)
1602     P.appendSuffix(Suffix);
1603   return P.str();
1604 }
1605 
1606 /// \brief Compute target triple from args.
1607 ///
1608 /// This routine provides the logic to compute a target triple from various
1609 /// args passed to the driver and the default triple string.
1610 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
1611                                         const ArgList &Args,
1612                                         StringRef DarwinArchName) {
1613   // FIXME: Already done in Compilation *Driver::BuildCompilation
1614   if (const Arg *A = Args.getLastArg(options::OPT_target))
1615     DefaultTargetTriple = A->getValue();
1616 
1617   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1618 
1619   // Handle Darwin-specific options available here.
1620   if (Target.isOSDarwin()) {
1621     // If an explict Darwin arch name is given, that trumps all.
1622     if (!DarwinArchName.empty()) {
1623       Target.setArch(
1624         tools::darwin::getArchTypeForDarwinArchName(DarwinArchName));
1625       return Target;
1626     }
1627 
1628     // Handle the Darwin '-arch' flag.
1629     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
1630       llvm::Triple::ArchType DarwinArch
1631         = tools::darwin::getArchTypeForDarwinArchName(A->getValue());
1632       if (DarwinArch != llvm::Triple::UnknownArch)
1633         Target.setArch(DarwinArch);
1634     }
1635   }
1636 
1637   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
1638   if (Target.getArchName() == "tce" ||
1639       Target.getOS() == llvm::Triple::AuroraUX ||
1640       Target.getOS() == llvm::Triple::Minix)
1641     return Target;
1642 
1643   // Handle pseudo-target flags '-m32' and '-m64'.
1644   // FIXME: Should this information be in llvm::Triple?
1645   if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
1646     if (A->getOption().matches(options::OPT_m32)) {
1647       if (Target.getArch() == llvm::Triple::x86_64)
1648         Target.setArch(llvm::Triple::x86);
1649       if (Target.getArch() == llvm::Triple::ppc64)
1650         Target.setArch(llvm::Triple::ppc);
1651     } else {
1652       if (Target.getArch() == llvm::Triple::x86)
1653         Target.setArch(llvm::Triple::x86_64);
1654       if (Target.getArch() == llvm::Triple::ppc)
1655         Target.setArch(llvm::Triple::ppc64);
1656     }
1657   }
1658 
1659   return Target;
1660 }
1661 
1662 const ToolChain &Driver::getToolChain(const ArgList &Args,
1663                                       StringRef DarwinArchName) const {
1664   llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
1665                                             DarwinArchName);
1666 
1667   ToolChain *&TC = ToolChains[Target.str()];
1668   if (!TC) {
1669     switch (Target.getOS()) {
1670     case llvm::Triple::AuroraUX:
1671       TC = new toolchains::AuroraUX(*this, Target, Args);
1672       break;
1673     case llvm::Triple::Darwin:
1674     case llvm::Triple::MacOSX:
1675     case llvm::Triple::IOS:
1676       if (Target.getArch() == llvm::Triple::x86 ||
1677           Target.getArch() == llvm::Triple::x86_64 ||
1678           Target.getArch() == llvm::Triple::arm ||
1679           Target.getArch() == llvm::Triple::thumb)
1680         TC = new toolchains::DarwinClang(*this, Target);
1681       else
1682         TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args);
1683       break;
1684     case llvm::Triple::DragonFly:
1685       TC = new toolchains::DragonFly(*this, Target, Args);
1686       break;
1687     case llvm::Triple::OpenBSD:
1688       TC = new toolchains::OpenBSD(*this, Target, Args);
1689       break;
1690     case llvm::Triple::Bitrig:
1691       TC = new toolchains::Bitrig(*this, Target, Args);
1692       break;
1693     case llvm::Triple::NetBSD:
1694       TC = new toolchains::NetBSD(*this, Target, Args);
1695       break;
1696     case llvm::Triple::FreeBSD:
1697       TC = new toolchains::FreeBSD(*this, Target, Args);
1698       break;
1699     case llvm::Triple::Minix:
1700       TC = new toolchains::Minix(*this, Target, Args);
1701       break;
1702     case llvm::Triple::Linux:
1703       if (Target.getArch() == llvm::Triple::hexagon)
1704         TC = new toolchains::Hexagon_TC(*this, Target, Args);
1705       else
1706         TC = new toolchains::Linux(*this, Target, Args);
1707       break;
1708     case llvm::Triple::Solaris:
1709       TC = new toolchains::Solaris(*this, Target, Args);
1710       break;
1711     case llvm::Triple::Win32:
1712       TC = new toolchains::Windows(*this, Target);
1713       break;
1714     case llvm::Triple::MinGW32:
1715       // FIXME: We need a MinGW toolchain. Fallthrough for now.
1716     default:
1717       // TCE is an OSless target
1718       if (Target.getArchName() == "tce") {
1719         TC = new toolchains::TCEToolChain(*this, Target);
1720         break;
1721       }
1722 
1723       TC = new toolchains::Generic_GCC(*this, Target, Args);
1724       break;
1725     }
1726   }
1727   return *TC;
1728 }
1729 
1730 bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1731                                     const llvm::Triple &Triple) const {
1732   // Check if user requested no clang, or clang doesn't understand this type (we
1733   // only handle single inputs for now).
1734   if (JA.size() != 1 ||
1735       !types::isAcceptedByClang((*JA.begin())->getType()))
1736     return false;
1737 
1738   // Otherwise make sure this is an action clang understands.
1739   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
1740       !isa<CompileJobAction>(JA))
1741     return false;
1742 
1743   return true;
1744 }
1745 
1746 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1747 /// grouped values as integers. Numbers which are not provided are set to 0.
1748 ///
1749 /// \return True if the entire string was parsed (9.2), or all groups were
1750 /// parsed (10.3.5extrastuff).
1751 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1752                                unsigned &Minor, unsigned &Micro,
1753                                bool &HadExtra) {
1754   HadExtra = false;
1755 
1756   Major = Minor = Micro = 0;
1757   if (*Str == '\0')
1758     return true;
1759 
1760   char *End;
1761   Major = (unsigned) strtol(Str, &End, 10);
1762   if (*Str != '\0' && *End == '\0')
1763     return true;
1764   if (*End != '.')
1765     return false;
1766 
1767   Str = End+1;
1768   Minor = (unsigned) strtol(Str, &End, 10);
1769   if (*Str != '\0' && *End == '\0')
1770     return true;
1771   if (*End != '.')
1772     return false;
1773 
1774   Str = End+1;
1775   Micro = (unsigned) strtol(Str, &End, 10);
1776   if (*Str != '\0' && *End == '\0')
1777     return true;
1778   if (Str == End)
1779     return false;
1780   HadExtra = true;
1781   return true;
1782 }
1783