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