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