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