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