Ressurrect the Stacker "st" configuration. Someday this will all go
[oota-llvm.git] / tools / llvmc / CompilerDriver.cpp
1 //===- CompilerDriver.cpp - The LLVM Compiler Driver ------------*- C++ -*-===//
2 //
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file was developed by Reid Spencer and is distributed under the
7 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file implements the bulk of the LLVM Compiler Driver (llvmc).
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CompilerDriver.h"
16 #include "ConfigLexer.h"
17 #include "llvm/Module.h"
18 #include "llvm/Bytecode/Reader.h"
19 #include "llvm/Support/Timer.h"
20 #include "llvm/System/Signals.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Config/alloca.h"
24 #include <iostream>
25 using namespace llvm;
26
27 namespace {
28
29 void WriteAction(CompilerDriver::Action* action ) {
30   std::cerr << action->program.c_str();
31   std::vector<std::string>::const_iterator I = action->args.begin();
32   while (I != action->args.end()) {
33     std::cerr << ' ' << *I;
34     ++I;
35   }
36   std::cerr << '\n';
37 }
38
39 void DumpAction(CompilerDriver::Action* action) {
40   std::cerr << "command = " << action->program.c_str();
41   std::vector<std::string>::const_iterator I = action->args.begin();
42   while (I != action->args.end()) {
43     std::cerr << ' ' << *I;
44     ++I;
45   }
46   std::cerr << '\n';
47   std::cerr << "flags = " << action->flags << '\n';
48 }
49
50 void DumpConfigData(CompilerDriver::ConfigData* cd, const std::string& type ){
51   std::cerr << "Configuration Data For '" << cd->langName << "' (" << type
52     << ")\n";
53   std::cerr << "PreProcessor: ";
54   DumpAction(&cd->PreProcessor);
55   std::cerr << "Translator: ";
56   DumpAction(&cd->Translator);
57   std::cerr << "Optimizer: ";
58   DumpAction(&cd->Optimizer);
59   std::cerr << "Assembler: ";
60   DumpAction(&cd->Assembler);
61   std::cerr << "Linker: ";
62   DumpAction(&cd->Linker);
63 }
64
65 class CompilerDriverImpl : public CompilerDriver {
66 /// @name Constructors
67 /// @{
68 public:
69   CompilerDriverImpl(ConfigDataProvider& confDatProv )
70     : cdp(&confDatProv)
71     , finalPhase(LINKING)
72     , optLevel(OPT_FAST_COMPILE)
73     , Flags(0)
74     , machine()
75     , LibraryPaths()
76     , TempDir()
77     , AdditionalArgs()
78   {
79     AdditionalArgs.reserve(NUM_PHASES);
80     StringVector emptyVec;
81     for (unsigned i = 0; i < NUM_PHASES; ++i)
82       AdditionalArgs.push_back(emptyVec);
83   }
84
85   virtual ~CompilerDriverImpl() {
86     cleanup();
87     cdp = 0;
88     LibraryPaths.clear();
89     IncludePaths.clear();
90     Defines.clear();
91     TempDir.clear();
92     AdditionalArgs.clear();
93     fOptions.clear();
94     MOptions.clear();
95     WOptions.clear();
96   }
97
98 /// @}
99 /// @name Methods
100 /// @{
101 public:
102   virtual void setFinalPhase(Phases phase) {
103     finalPhase = phase;
104   }
105
106   virtual void setOptimization(OptimizationLevels level) {
107     optLevel = level;
108   }
109
110   virtual void setDriverFlags(unsigned flags) {
111     Flags = flags & DRIVER_FLAGS_MASK;
112   }
113
114   virtual void setOutputMachine(const std::string& machineName) {
115     machine = machineName;
116   }
117
118   virtual void setPhaseArgs(Phases phase, const StringVector& opts) {
119     assert(phase <= LINKING && phase >= PREPROCESSING);
120     AdditionalArgs[phase] = opts;
121   }
122
123   virtual void setIncludePaths(const StringVector& paths) {
124     StringVector::const_iterator I = paths.begin();
125     StringVector::const_iterator E = paths.end();
126     while (I != E) {
127       sys::Path tmp;
128       tmp.set(*I);
129       IncludePaths.push_back(tmp);
130       ++I;
131     }
132   }
133
134   virtual void setSymbolDefines(const StringVector& defs) {
135     Defines = defs;
136   }
137
138   virtual void setLibraryPaths(const StringVector& paths) {
139     StringVector::const_iterator I = paths.begin();
140     StringVector::const_iterator E = paths.end();
141     while (I != E) {
142       sys::Path tmp;
143       tmp.set(*I);
144       LibraryPaths.push_back(tmp);
145       ++I;
146     }
147   }
148
149   virtual void addLibraryPath(const sys::Path& libPath) {
150     LibraryPaths.push_back(libPath);
151   }
152
153   virtual void addToolPath(const sys::Path& toolPath) {
154     ToolPaths.push_back(toolPath);
155   }
156
157   virtual void setfPassThrough(const StringVector& fOpts) {
158     fOptions = fOpts;
159   }
160
161   /// @brief Set the list of -M options to be passed through
162   virtual void setMPassThrough(const StringVector& MOpts) {
163     MOptions = MOpts;
164   }
165
166   /// @brief Set the list of -W options to be passed through
167   virtual void setWPassThrough(const StringVector& WOpts) {
168     WOptions = WOpts;
169   }
170
171 /// @}
172 /// @name Functions
173 /// @{
174 private:
175   bool isSet(DriverFlags flag) {
176     return 0 != ((flag & DRIVER_FLAGS_MASK) & Flags);
177   }
178
179   void cleanup() {
180     if (!isSet(KEEP_TEMPS_FLAG)) {
181       sys::FileStatus Status;
182       if (!TempDir.getFileStatus(Status) && Status.isDir)
183         TempDir.eraseFromDisk(/*remove_contents=*/true);
184     } else {
185       std::cout << "Temporary files are in " << TempDir << "\n";
186     }
187   }
188
189   sys::Path MakeTempFile(const std::string& basename,
190                          const std::string& suffix,
191                          std::string* ErrMsg) {
192     if (TempDir.isEmpty()) {
193       TempDir = sys::Path::GetTemporaryDirectory(ErrMsg);
194       if (TempDir.isEmpty())
195         return sys::Path();
196       sys::RemoveDirectoryOnSignal(TempDir);
197     }
198     sys::Path result(TempDir);
199     if (!result.appendComponent(basename)) {
200       if (ErrMsg)
201         *ErrMsg = basename + ": can't use this file name";
202       return sys::Path();
203     }
204     if (!result.appendSuffix(suffix)) {
205       if (ErrMsg)
206         *ErrMsg = suffix + ": can't use this file suffix";
207       return sys::Path();
208     }
209     return result;
210   }
211
212   Action* GetAction(ConfigData* cd,
213                     const sys::Path& input,
214                     const sys::Path& output,
215                     Phases phase)
216   {
217     Action* pat = 0; ///< The pattern/template for the action
218     Action* action = new Action; ///< The actual action to execute
219
220     // Get the action pattern
221     switch (phase) {
222       case PREPROCESSING: pat = &cd->PreProcessor; break;
223       case TRANSLATION:   pat = &cd->Translator; break;
224       case OPTIMIZATION:  pat = &cd->Optimizer; break;
225       case ASSEMBLY:      pat = &cd->Assembler; break;
226       case LINKING:       pat = &cd->Linker; break;
227       default:
228         assert(!"Invalid driver phase!");
229         break;
230     }
231     assert(pat != 0 && "Invalid command pattern");
232
233     // Copy over some pattern things that don't need to change
234     action->flags = pat->flags;
235
236     // See if program starts with wildcard...
237     std::string programName=pat->program.toString();
238     if (programName[0] == '%' && programName.length() >2) {
239       switch(programName[1]){
240       case 'b':
241         if (programName.substr(0,8) == "%bindir%") {
242           std::string tmp(LLVM_BINDIR);
243           tmp.append(programName.substr(8));
244           pat->program.set(tmp);
245         }
246         break;
247       case 'l':
248         if (programName.substr(0,12) == "%llvmgccdir%"){
249           std::string tmp(LLVMGCCDIR);
250           tmp.append(programName.substr(12));
251           pat->program.set(tmp);
252         }else if (programName.substr(0,13) == "%llvmgccarch%"){
253           std::string tmp(LLVMGCCARCH);
254           tmp.append(programName.substr(13));
255           pat->program.set(tmp);
256         }else if (programName.substr(0,9) == "%llvmgcc%"){
257           std::string tmp(LLVMGCC);
258           tmp.append(programName.substr(9));
259           pat->program.set(tmp);
260         }else if (programName.substr(0,9) == "%llvmgxx%"){
261           std::string tmp(LLVMGXX);
262           tmp.append(programName.substr(9));
263           pat->program.set(tmp);
264         }else if (programName.substr(0,9) == "%llvmcc1%"){
265           std::string tmp(LLVMCC1);
266           tmp.append(programName.substr(9));
267           pat->program.set(tmp);
268         }else if (programName.substr(0,13) == "%llvmcc1plus%"){
269           std::string tmp(LLVMCC1PLUS);
270           tmp.append(programName.substr(13));
271           pat->program.set(tmp);
272         }else if (programName.substr(0,8) == "%libdir%") {
273           std::string tmp(LLVM_LIBDIR);
274           tmp.append(programName.substr(8));
275           pat->program.set(tmp);
276         }
277           break;
278       }
279     }
280     action->program = pat->program;
281
282     // Do the substitutions from the pattern to the actual
283     StringVector::iterator PI = pat->args.begin();
284     StringVector::iterator PE = pat->args.end();
285     while (PI != PE) {
286       if ((*PI)[0] == '%' && PI->length() >2) {
287         bool found = true;
288         switch ((*PI)[1]) {
289           case 'a':
290             if (*PI == "%args%") {
291               if (AdditionalArgs.size() > unsigned(phase))
292                 if (!AdditionalArgs[phase].empty()) {
293                   // Get specific options for each kind of action type
294                   StringVector& addargs = AdditionalArgs[phase];
295                   // Add specific options for each kind of action type
296                   action->args.insert(action->args.end(), addargs.begin(),
297                                       addargs.end());
298                 }
299             } else
300               found = false;
301             break;
302           case 'b':
303             if (*PI == "%bindir%") {
304               std::string tmp(*PI);
305               tmp.replace(0,8,LLVM_BINDIR);
306               action->args.push_back(tmp);
307             } else
308               found = false;
309             break;
310           case 'd':
311             if (*PI == "%defs%") {
312               StringVector::iterator I = Defines.begin();
313               StringVector::iterator E = Defines.end();
314               while (I != E) {
315                 action->args.push_back( std::string("-D") + *I);
316                 ++I;
317               }
318             } else
319               found = false;
320             break;
321           case 'f':
322             if (*PI == "%fOpts%") {
323               if (!fOptions.empty())
324                 action->args.insert(action->args.end(), fOptions.begin(),
325                                     fOptions.end());
326             } else
327               found = false;
328             break;
329           case 'i':
330             if (*PI == "%in%") {
331               action->args.push_back(input.toString());
332             } else if (*PI == "%incls%") {
333               PathVector::iterator I = IncludePaths.begin();
334               PathVector::iterator E = IncludePaths.end();
335               while (I != E) {
336                 action->args.push_back( std::string("-I") + I->toString() );
337                 ++I;
338               }
339             } else
340               found = false;
341             break;
342           case 'l':
343             if ((*PI)[1] == 'l') {
344               std::string tmp(*PI);
345               if (*PI == "%llvmgccdir%")
346                 tmp.replace(0,12,LLVMGCCDIR);
347               else if (*PI == "%llvmgccarch%")
348                 tmp.replace(0,13,LLVMGCCARCH);
349               else if (*PI == "%llvmgcc%")
350                 tmp.replace(0,9,LLVMGCC);
351               else if (*PI == "%llvmgxx%")
352                 tmp.replace(0,9,LLVMGXX);
353               else if (*PI == "%llvmcc1%")
354                 tmp.replace(0,9,LLVMCC1);
355               else if (*PI == "%llvmcc1plus%")
356                 tmp.replace(0,9,LLVMCC1);
357               else
358                 found = false;
359               if (found)
360                 action->args.push_back(tmp);
361             } else if (*PI == "%libs%") {
362               PathVector::iterator I = LibraryPaths.begin();
363               PathVector::iterator E = LibraryPaths.end();
364               while (I != E) {
365                 action->args.push_back( std::string("-L") + I->toString() );
366                 ++I;
367               }
368             } else if (*PI == "%libdir%") {
369               std::string tmp(*PI);
370               tmp.replace(0,8,LLVM_LIBDIR);
371               action->args.push_back(tmp);
372             } else
373               found = false;
374             break;
375           case 'o':
376             if (*PI == "%out%") {
377               action->args.push_back(output.toString());
378             } else if (*PI == "%opt%") {
379               if (!isSet(EMIT_RAW_FLAG)) {
380                 if (cd->opts.size() > static_cast<unsigned>(optLevel) &&
381                     !cd->opts[optLevel].empty())
382                   action->args.insert(action->args.end(),
383                                       cd->opts[optLevel].begin(),
384                                       cd->opts[optLevel].end());
385                 else
386                   throw std::string("Optimization options for level ") +
387                         utostr(unsigned(optLevel)) + " were not specified";
388               }
389             } else
390               found = false;
391             break;
392           case 's':
393             if (*PI == "%stats%") {
394               if (isSet(SHOW_STATS_FLAG))
395                 action->args.push_back("-stats");
396             } else
397               found = false;
398             break;
399           case 't':
400             if (*PI == "%target%") {
401               action->args.push_back(std::string("-march=") + machine);
402             } else if (*PI == "%time%") {
403               if (isSet(TIME_PASSES_FLAG))
404                 action->args.push_back("-time-passes");
405             } else
406               found = false;
407             break;
408           case 'v':
409             if (*PI == "%verbose%") {
410               if (isSet(VERBOSE_FLAG))
411                 action->args.push_back("-v");
412             } else
413               found  = false;
414             break;
415           case 'M':
416             if (*PI == "%Mopts%") {
417               if (!MOptions.empty())
418                 action->args.insert(action->args.end(), MOptions.begin(),
419                                     MOptions.end());
420             } else
421               found = false;
422             break;
423           case 'W':
424             if (*PI == "%Wopts%") {
425               for (StringVector::iterator I = WOptions.begin(),
426                    E = WOptions.end(); I != E ; ++I ) {
427                 action->args.push_back(std::string("-W") + *I);
428               }
429             } else
430               found = false;
431             break;
432           default:
433             found = false;
434             break;
435         }
436         if (!found) {
437           // Did it even look like a substitution?
438           if (PI->length()>1 && (*PI)[0] == '%' &&
439               (*PI)[PI->length()-1] == '%') {
440             throw std::string("Invalid substitution token: '") + *PI +
441                   "' for command '" + pat->program.toString() + "'";
442           } else if (!PI->empty()) {
443             // It's not a legal substitution, just pass it through
444             action->args.push_back(*PI);
445           }
446         }
447       } else if (!PI->empty()) {
448         // Its not a substitution, just put it in the action
449         action->args.push_back(*PI);
450       }
451       PI++;
452     }
453
454     // Finally, we're done
455     return action;
456   }
457
458   int DoAction(Action*action, std::string& ErrMsg) {
459     assert(action != 0 && "Invalid Action!");
460     if (isSet(VERBOSE_FLAG))
461       WriteAction(action);
462     if (!isSet(DRY_RUN_FLAG)) {
463       sys::Path progpath = sys::Program::FindProgramByName(
464         action->program.toString());
465       if (progpath.isEmpty())
466         throw std::string("Can't find program '" +
467                           action->program.toString()+"'");
468       else if (progpath.canExecute())
469         action->program = progpath;
470       else
471         throw std::string("Program '"+action->program.toString()+
472                           "' is not executable.");
473
474       // Invoke the program
475       const char** Args = (const char**)
476         alloca(sizeof(const char*)*(action->args.size()+2));
477       Args[0] = action->program.toString().c_str();
478       for (unsigned i = 1; i <= action->args.size(); ++i)
479         Args[i] = action->args[i-1].c_str();
480       Args[action->args.size()+1] = 0;  // null terminate list.
481       if (isSet(TIME_ACTIONS_FLAG)) {
482         Timer timer(action->program.toString());
483         timer.startTimer();
484         int resultCode = 
485           sys::Program::ExecuteAndWait(action->program, Args,0,0,0,&ErrMsg);
486         timer.stopTimer();
487         timer.print(timer,std::cerr);
488         return resultCode;
489       }
490       else
491         return 
492           sys::Program::ExecuteAndWait(action->program, Args, 0,0,0, &ErrMsg);
493     }
494     return 0;
495   }
496
497   /// This method tries various variants of a linkage item's file
498   /// name to see if it can find an appropriate file to link with
499   /// in the directories of the LibraryPaths.
500   llvm::sys::Path GetPathForLinkageItem(const std::string& link_item,
501                                         bool native = false) {
502     sys::Path fullpath;
503     fullpath.set(link_item);
504     if (fullpath.canRead())
505       return fullpath;
506     for (PathVector::iterator PI = LibraryPaths.begin(),
507          PE = LibraryPaths.end(); PI != PE; ++PI) {
508       fullpath.set(PI->toString());
509       fullpath.appendComponent(link_item);
510       if (fullpath.canRead())
511         return fullpath;
512       if (native) {
513         fullpath.appendSuffix("a");
514       } else {
515         fullpath.appendSuffix("bc");
516         if (fullpath.canRead())
517           return fullpath;
518         fullpath.eraseSuffix();
519         fullpath.appendSuffix("o");
520         if (fullpath.canRead())
521           return fullpath;
522         fullpath = *PI;
523         fullpath.appendComponent(std::string("lib") + link_item);
524         fullpath.appendSuffix("a");
525         if (fullpath.canRead())
526           return fullpath;
527         fullpath.eraseSuffix();
528         fullpath.appendSuffix("so");
529         if (fullpath.canRead())
530           return fullpath;
531       }
532     }
533
534     // Didn't find one.
535     fullpath.clear();
536     return fullpath;
537   }
538
539   /// This method processes a linkage item. The item could be a
540   /// Bytecode file needing translation to native code and that is
541   /// dependent on other bytecode libraries, or a native code
542   /// library that should just be linked into the program.
543   bool ProcessLinkageItem(const llvm::sys::Path& link_item,
544                           SetVector<sys::Path>& set,
545                           std::string& err) {
546     // First, see if the unadorned file name is not readable. If so,
547     // we must track down the file in the lib search path.
548     sys::Path fullpath;
549     if (!link_item.canRead()) {
550       // look for the library using the -L arguments specified
551       // on the command line.
552       fullpath = GetPathForLinkageItem(link_item.toString());
553
554       // If we didn't find the file in any of the library search paths
555       // we have to bail. No where else to look.
556       if (fullpath.isEmpty()) {
557         err =
558           std::string("Can't find linkage item '") + link_item.toString() + "'";
559         return false;
560       }
561     } else {
562       fullpath = link_item;
563     }
564
565     // If we got here fullpath is the path to the file, and its readable.
566     set.insert(fullpath);
567
568     // If its an LLVM bytecode file ...
569     if (fullpath.isBytecodeFile()) {
570       // Process the dependent libraries recursively
571       Module::LibraryListType modlibs;
572       if (GetBytecodeDependentLibraries(fullpath.toString(),modlibs,&err)) {
573         // Traverse the dependent libraries list
574         Module::lib_iterator LI = modlibs.begin();
575         Module::lib_iterator LE = modlibs.end();
576         while ( LI != LE ) {
577           if (!ProcessLinkageItem(sys::Path(*LI),set,err)) {
578             if (err.empty()) {
579               err = std::string("Library '") + *LI +
580                     "' is not valid for linking but is required by file '" +
581                     fullpath.toString() + "'";
582             } else {
583               err += " which is required by file '" + fullpath.toString() + "'";
584             }
585             return false;
586           }
587           ++LI;
588         }
589       } else if (err.empty()) {
590         err = std::string(
591           "The dependent libraries could not be extracted from '") +
592           fullpath.toString();
593         return false;
594       } else 
595         return false;
596     }
597     return true;
598   }
599
600 /// @}
601 /// @name Methods
602 /// @{
603 public:
604   virtual int execute(const InputList& InpList, const sys::Path& Output, std::string& ErrMsg ) {
605     try {
606       // Echo the configuration of options if we're running verbose
607       if (isSet(DEBUG_FLAG)) {
608         std::cerr << "Compiler Driver Options:\n";
609         std::cerr << "DryRun = " << isSet(DRY_RUN_FLAG) << "\n";
610         std::cerr << "Verbose = " << isSet(VERBOSE_FLAG) << " \n";
611         std::cerr << "TimeActions = " << isSet(TIME_ACTIONS_FLAG) << "\n";
612         std::cerr << "TimePasses = " << isSet(TIME_PASSES_FLAG) << "\n";
613         std::cerr << "ShowStats = " << isSet(SHOW_STATS_FLAG) << "\n";
614         std::cerr << "EmitRawCode = " << isSet(EMIT_RAW_FLAG) << "\n";
615         std::cerr << "EmitNativeCode = " << isSet(EMIT_NATIVE_FLAG) << "\n";
616         std::cerr << "KeepTemps = " << isSet(KEEP_TEMPS_FLAG) << "\n";
617         std::cerr << "OutputMachine = " << machine << "\n";
618         InputList::const_iterator I = InpList.begin();
619         while ( I != InpList.end() ) {
620           std::cerr << "Input: " << I->first << "(" << I->second
621                     << ")\n";
622           ++I;
623         }
624         std::cerr << "Output: " << Output << "\n";
625       }
626
627       // If there's no input, we're done.
628       if (InpList.empty())
629         throw std::string("Nothing to compile.");
630
631       // If they are asking for linking and didn't provide an output
632       // file then its an error (no way for us to "make up" a meaningful
633       // file name based on the various linker input files).
634       if (finalPhase == LINKING && Output.isEmpty())
635         throw std::string(
636           "An output file name must be specified for linker output");
637
638       // If they are not asking for linking, provided an output file and
639       // there is more than one input file, its an error
640       if (finalPhase != LINKING && !Output.isEmpty() && InpList.size() > 1)
641         throw std::string("An output file name cannot be specified ") +
642           "with more than one input file name when not linking";
643
644       // This vector holds all the resulting actions of the following loop.
645       std::vector<Action*> actions;
646
647       /// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases
648       // for each input item
649       SetVector<sys::Path> LinkageItems;
650       StringVector LibFiles;
651       InputList::const_iterator I = InpList.begin();
652       for (InputList::const_iterator I = InpList.begin(), E = InpList.end();
653            I != E; ++I ) {
654         // Get the suffix of the file name
655         const std::string& ftype = I->second;
656
657         // If its a library, bytecode file, or object file, save
658         // it for linking below and short circuit the
659         // pre-processing/translation/assembly phases
660         if (ftype.empty() ||  ftype == "o" || ftype == "bc" || ftype=="a") {
661           // We shouldn't get any of these types of files unless we're
662           // later going to link. Enforce this limit now.
663           if (finalPhase != LINKING) {
664             throw std::string(
665               "Pre-compiled objects found but linking not requested");
666           }
667           if (ftype.empty())
668             LibFiles.push_back(I->first.toString());
669           else
670             LinkageItems.insert(I->first);
671           continue; // short circuit remainder of loop
672         }
673
674         // At this point, we know its something we need to translate
675         // and/or optimize. See if we can get the configuration data
676         // for this kind of file.
677         ConfigData* cd = cdp->ProvideConfigData(I->second);
678         if (cd == 0)
679           throw std::string("Files of type '") + I->second +
680                 "' are not recognized.";
681         if (isSet(DEBUG_FLAG))
682           DumpConfigData(cd,I->second);
683
684         // Add the config data's library paths to the end of the list
685         for (StringVector::iterator LPI = cd->libpaths.begin(),
686              LPE = cd->libpaths.end(); LPI != LPE; ++LPI){
687           LibraryPaths.push_back(sys::Path(*LPI));
688         }
689
690         // Initialize the input and output files
691         sys::Path InFile(I->first);
692         sys::Path OutFile(I->first.getBasename());
693
694         // PRE-PROCESSING PHASE
695         Action& action = cd->PreProcessor;
696
697         // Get the preprocessing action, if needed, or error if appropriate
698         if (!action.program.isEmpty()) {
699           if (action.isSet(REQUIRED_FLAG) || finalPhase == PREPROCESSING) {
700             if (finalPhase == PREPROCESSING) {
701               if (Output.isEmpty()) {
702                 OutFile.appendSuffix("E");
703                 actions.push_back(GetAction(cd,InFile,OutFile,PREPROCESSING));
704               } else {
705                 actions.push_back(GetAction(cd,InFile,Output,PREPROCESSING));
706               }
707             } else {
708               sys::Path TempFile(
709                   MakeTempFile(I->first.getBasename(),"E",&ErrMsg));
710               if (TempFile.isEmpty())
711                 return 1;
712               actions.push_back(GetAction(cd,InFile,TempFile,
713                 PREPROCESSING));
714               InFile = TempFile;
715             }
716           }
717         } else if (finalPhase == PREPROCESSING) {
718           throw cd->langName + " does not support pre-processing";
719         } else if (action.isSet(REQUIRED_FLAG)) {
720           throw std::string("Don't know how to pre-process ") +
721                 cd->langName + " files";
722         }
723
724         // Short-circuit remaining actions if all they want is
725         // pre-processing
726         if (finalPhase == PREPROCESSING) { continue; };
727
728         /// TRANSLATION PHASE
729         action = cd->Translator;
730
731         // Get the translation action, if needed, or error if appropriate
732         if (!action.program.isEmpty()) {
733           if (action.isSet(REQUIRED_FLAG) || finalPhase == TRANSLATION) {
734             if (finalPhase == TRANSLATION) {
735               if (Output.isEmpty()) {
736                 OutFile.appendSuffix("o");
737                 actions.push_back(GetAction(cd,InFile,OutFile,TRANSLATION));
738               } else {
739                 actions.push_back(GetAction(cd,InFile,Output,TRANSLATION));
740               }
741             } else {
742               sys::Path TempFile(
743                   MakeTempFile(I->first.getBasename(),"trans", &ErrMsg));
744               if (TempFile.isEmpty())
745                 return 1;
746               actions.push_back(GetAction(cd,InFile,TempFile,TRANSLATION));
747               InFile = TempFile;
748             }
749
750             // ll -> bc Helper
751             if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
752               /// The output of the translator is an LLVM Assembly program
753               /// We need to translate it to bytecode
754               Action* action = new Action();
755               action->program.set("llvm-as");
756               action->args.push_back(InFile.toString());
757               action->args.push_back("-o");
758               InFile.appendSuffix("bc");
759               action->args.push_back(InFile.toString());
760               actions.push_back(action);
761             }
762           }
763         } else if (finalPhase == TRANSLATION) {
764           throw cd->langName + " does not support translation";
765         } else if (action.isSet(REQUIRED_FLAG)) {
766           throw std::string("Don't know how to translate ") +
767                 cd->langName + " files";
768         }
769
770         // Short-circuit remaining actions if all they want is translation
771         if (finalPhase == TRANSLATION) { continue; }
772
773         /// OPTIMIZATION PHASE
774         action = cd->Optimizer;
775
776         // Get the optimization action, if needed, or error if appropriate
777         if (!isSet(EMIT_RAW_FLAG)) {
778           if (!action.program.isEmpty()) {
779             if (action.isSet(REQUIRED_FLAG) || finalPhase == OPTIMIZATION) {
780               if (finalPhase == OPTIMIZATION) {
781                 if (Output.isEmpty()) {
782                   OutFile.appendSuffix("o");
783                   actions.push_back(GetAction(cd,InFile,OutFile,OPTIMIZATION));
784                 } else {
785                   actions.push_back(GetAction(cd,InFile,Output,OPTIMIZATION));
786                 }
787               } else {
788                 sys::Path TempFile(
789                   MakeTempFile(I->first.getBasename(),"opt", &ErrMsg));
790                 if (TempFile.isEmpty())
791                   return 1;
792                 actions.push_back(GetAction(cd,InFile,TempFile,OPTIMIZATION));
793                 InFile = TempFile;
794               }
795               // ll -> bc Helper
796               if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
797                 /// The output of the optimizer is an LLVM Assembly program
798                 /// We need to translate it to bytecode with llvm-as
799                 Action* action = new Action();
800                 action->program.set("llvm-as");
801                 action->args.push_back(InFile.toString());
802                 action->args.push_back("-f");
803                 action->args.push_back("-o");
804                 InFile.appendSuffix("bc");
805                 action->args.push_back(InFile.toString());
806                 actions.push_back(action);
807               }
808             }
809           } else if (finalPhase == OPTIMIZATION) {
810             throw cd->langName + " does not support optimization";
811           } else if (action.isSet(REQUIRED_FLAG)) {
812             throw std::string("Don't know how to optimize ") +
813                 cd->langName + " files";
814           }
815         }
816
817         // Short-circuit remaining actions if all they want is optimization
818         if (finalPhase == OPTIMIZATION) { continue; }
819
820         /// ASSEMBLY PHASE
821         action = cd->Assembler;
822
823         if (finalPhase == ASSEMBLY) {
824
825           // Build either a native compilation action or a disassembly action
826           Action* action = new Action();
827           if (isSet(EMIT_NATIVE_FLAG)) {
828             // Use llc to get the native assembly file
829             action->program.set("llc");
830             action->args.push_back(InFile.toString());
831             action->args.push_back("-f");
832             action->args.push_back("-o");
833             if (Output.isEmpty()) {
834               OutFile.appendSuffix("o");
835               action->args.push_back(OutFile.toString());
836             } else {
837               action->args.push_back(Output.toString());
838             }
839             actions.push_back(action);
840           } else {
841             // Just convert back to llvm assembly with llvm-dis
842             action->program.set("llvm-dis");
843             action->args.push_back(InFile.toString());
844             action->args.push_back("-f");
845             action->args.push_back("-o");
846             if (Output.isEmpty()) {
847               OutFile.appendSuffix("ll");
848               action->args.push_back(OutFile.toString());
849             } else {
850               action->args.push_back(Output.toString());
851             }
852           }
853
854           // Put the action on the list
855           actions.push_back(action);
856
857           // Short circuit the rest of the loop, we don't want to link
858           continue;
859         }
860
861         // Register the result of the actions as a link candidate
862         LinkageItems.insert(InFile);
863
864       } // end while loop over each input file
865
866       /// RUN THE COMPILATION ACTIONS
867       std::vector<Action*>::iterator AI = actions.begin();
868       std::vector<Action*>::iterator AE = actions.end();
869       while (AI != AE) {
870         int ActionResult = DoAction(*AI, ErrMsg);
871         if (ActionResult != 0)
872           return ActionResult;
873         AI++;
874       }
875
876       /// LINKING PHASE
877       if (finalPhase == LINKING) {
878
879         // Insert the platform-specific system libraries to the path list
880         std::vector<sys::Path> SysLibs;
881         sys::Path::GetSystemLibraryPaths(SysLibs);
882         LibraryPaths.insert(LibraryPaths.end(), SysLibs.begin(), SysLibs.end());
883
884         // Set up the linking action with llvm-ld
885         Action* link = new Action();
886         link->program.set("llvm-ld");
887
888         // Add in the optimization level requested
889         switch (optLevel) {
890           case OPT_FAST_COMPILE:
891             link->args.push_back("-O1");
892             break;
893           case OPT_SIMPLE:
894             link->args.push_back("-O2");
895             break;
896           case OPT_AGGRESSIVE:
897             link->args.push_back("-O3");
898             break;
899           case OPT_LINK_TIME:
900             link->args.push_back("-O4");
901             break;
902           case OPT_AGGRESSIVE_LINK_TIME:
903             link->args.push_back("-O5");
904             break;
905           case OPT_NONE:
906             break;
907         }
908
909         // Add in all the linkage items we generated. This includes the
910         // output from the translation/optimization phases as well as any
911         // -l arguments specified.
912         for (PathVector::const_iterator I=LinkageItems.begin(),
913              E=LinkageItems.end(); I != E; ++I )
914           link->args.push_back(I->toString());
915
916         // Add in all the libraries we found.
917         for (StringVector::const_iterator I=LibFiles.begin(),
918              E=LibFiles.end(); I != E; ++I )
919           link->args.push_back(std::string("-l")+*I);
920
921         // Add in all the library paths to the command line
922         for (PathVector::const_iterator I=LibraryPaths.begin(),
923              E=LibraryPaths.end(); I != E; ++I)
924           link->args.push_back( std::string("-L") + I->toString());
925
926         // Add in the additional linker arguments requested
927         for (StringVector::const_iterator I=AdditionalArgs[LINKING].begin(),
928              E=AdditionalArgs[LINKING].end(); I != E; ++I)
929           link->args.push_back( *I );
930
931         // Add in other optional flags
932         if (isSet(EMIT_NATIVE_FLAG))
933           link->args.push_back("-native");
934         if (isSet(VERBOSE_FLAG))
935           link->args.push_back("-v");
936         if (isSet(TIME_PASSES_FLAG))
937           link->args.push_back("-time-passes");
938         if (isSet(SHOW_STATS_FLAG))
939           link->args.push_back("-stats");
940         if (isSet(STRIP_OUTPUT_FLAG))
941           link->args.push_back("-s");
942         if (isSet(DEBUG_FLAG)) {
943           link->args.push_back("-debug");
944           link->args.push_back("-debug-pass=Details");
945         }
946
947         // Add in mandatory flags
948         link->args.push_back("-o");
949         link->args.push_back(Output.toString());
950
951         // Execute the link
952         int ActionResult = DoAction(link, ErrMsg);
953         if (ActionResult != 0)
954           return ActionResult;
955       }
956     } catch (std::string& msg) {
957       cleanup();
958       throw;
959     } catch (...) {
960       cleanup();
961       throw std::string("Unspecified error");
962     }
963     cleanup();
964     return 0;
965   }
966
967 /// @}
968 /// @name Data
969 /// @{
970 private:
971   ConfigDataProvider* cdp;      ///< Where we get configuration data from
972   Phases finalPhase;            ///< The final phase of compilation
973   OptimizationLevels optLevel;  ///< The optimization level to apply
974   unsigned Flags;               ///< The driver flags
975   std::string machine;          ///< Target machine name
976   PathVector LibraryPaths;      ///< -L options
977   PathVector IncludePaths;      ///< -I options
978   PathVector ToolPaths;         ///< -B options
979   StringVector Defines;         ///< -D options
980   sys::Path TempDir;            ///< Name of the temporary directory.
981   StringTable AdditionalArgs;   ///< The -Txyz options
982   StringVector fOptions;        ///< -f options
983   StringVector MOptions;        ///< -M options
984   StringVector WOptions;        ///< -W options
985
986 /// @}
987 };
988 }
989
990 CompilerDriver::~CompilerDriver() {
991 }
992
993 CompilerDriver::ConfigDataProvider::~ConfigDataProvider() {}
994
995 CompilerDriver*
996 CompilerDriver::Get(ConfigDataProvider& CDP) {
997   return new CompilerDriverImpl(CDP);
998 }
999
1000 CompilerDriver::ConfigData::ConfigData()
1001   : langName()
1002   , PreProcessor()
1003   , Translator()
1004   , Optimizer()
1005   , Assembler()
1006   , Linker()
1007 {
1008   StringVector emptyVec;
1009   for (unsigned i = 0; i < NUM_PHASES; ++i)
1010     opts.push_back(emptyVec);
1011 }