Add the directory specified by LLVM_LIB_SEARCH_PATH to the list of
[oota-llvm.git] / tools / llvmc / llvmc.cpp
1 //===--- llvmc.cpp - The LLVM Compiler Driver -------------------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 //  This tool provides a single point of access to the LLVM compilation tools.
11 //  It has many options. To discover the options supported please refer to the
12 //  tools' manual page (docs/CommandGuide/html/llvmc.html) or run the tool with
13 //  the --help option.
14 // 
15 //===------------------------------------------------------------------------===
16
17 #include "CompilerDriver.h"
18 #include "Configuration.h"
19 #include "llvm/Pass.h"
20 #include "llvm/System/Signals.h"
21 #include "Support/CommandLine.h"
22 #include <iostream>
23
24 using namespace llvm;
25
26 namespace {
27 //===------------------------------------------------------------------------===
28 //===          PHASE OPTIONS
29 //===------------------------------------------------------------------------===
30 cl::opt<CompilerDriver::Phases> FinalPhase(
31   cl::desc("Choose final phase of compilation:"), 
32   cl::init(CompilerDriver::LINKING),
33   cl::values(
34     clEnumValN(CompilerDriver::PREPROCESSING,"E",
35       "Stop compilation after pre-processing phase"),
36     clEnumValN(CompilerDriver::TRANSLATION, "t",
37       "Stop compilation after translation phase"),
38     clEnumValN(CompilerDriver::OPTIMIZATION,"c",
39       "Stop compilation after optimization phase"),
40     clEnumValN(CompilerDriver::ASSEMBLY,"S",
41       "Stop compilation after assembly phase"),
42     clEnumValEnd
43   )
44 );
45
46 //===------------------------------------------------------------------------===
47 //===          OPTIMIZATION OPTIONS
48 //===------------------------------------------------------------------------===
49 cl::opt<CompilerDriver::OptimizationLevels> OptLevel(
50   cl::desc("Choose level of optimization to apply:"),
51   cl::init(CompilerDriver::OPT_FAST_COMPILE),
52   cl::values(
53     clEnumValN(CompilerDriver::OPT_FAST_COMPILE,"O0",
54       "An alias for the -O1 option."),
55     clEnumValN(CompilerDriver::OPT_FAST_COMPILE,"O1",
56       "Optimize for compilation speed, not execution speed."),
57     clEnumValN(CompilerDriver::OPT_SIMPLE,"O2",
58       "Perform simple translation time optimizations"),
59     clEnumValN(CompilerDriver::OPT_AGGRESSIVE,"O3",
60       "Perform aggressive translation time optimizations"),
61     clEnumValN(CompilerDriver::OPT_LINK_TIME,"O4",
62       "Perform link time optimizations"),
63     clEnumValN(CompilerDriver::OPT_AGGRESSIVE_LINK_TIME,"O5",
64       "Perform aggressive link time optimizations"),
65     clEnumValEnd
66   )
67 );
68
69 //===------------------------------------------------------------------------===
70 //===          TOOL OPTIONS
71 //===------------------------------------------------------------------------===
72
73 cl::list<std::string> PreprocessorToolOpts("Tpre", cl::ZeroOrMore,
74   cl::desc("Pass specific options to the pre-processor"), 
75   cl::value_desc("option"));
76
77 cl::list<std::string> TranslatorToolOpts("Ttrn", cl::ZeroOrMore,
78   cl::desc("Pass specific options to the assembler"),
79   cl::value_desc("option"));
80
81 cl::list<std::string> AssemblerToolOpts("Tasm", cl::ZeroOrMore,
82   cl::desc("Pass specific options to the assembler"),
83   cl::value_desc("option"));
84
85 cl::list<std::string> OptimizerToolOpts("Topt", cl::ZeroOrMore,
86   cl::desc("Pass specific options to the optimizer"),
87   cl::value_desc("option"));
88
89 cl::list<std::string> LinkerToolOpts("Tlnk", cl::ZeroOrMore,
90   cl::desc("Pass specific options to the linker"),
91   cl::value_desc("option"));
92
93 //===------------------------------------------------------------------------===
94 //===          INPUT OPTIONS
95 //===------------------------------------------------------------------------===
96
97 cl::list<std::string> LibPaths("L", cl::Prefix,
98   cl::desc("Specify a library search path"), cl::value_desc("directory"));
99                                                                                                                                             
100 cl::list<std::string> Libraries("l", cl::Prefix,
101   cl::desc("Specify libraries to link to"), cl::value_desc("library prefix"));
102
103
104 //===------------------------------------------------------------------------===
105 //===          OUTPUT OPTIONS
106 //===------------------------------------------------------------------------===
107
108 cl::opt<std::string> OutputFilename("o", 
109   cl::desc("Override output filename"), cl::value_desc("filename"));
110
111 cl::opt<std::string> OutputMachine("m", cl::Prefix,
112   cl::desc("Specify a target machine"), cl::value_desc("machine"));
113                                                                                                                                             
114 cl::opt<bool> Native("native", cl::init(false),
115   cl::desc("Generative native object and executables instead of bytecode"));
116
117 //===------------------------------------------------------------------------===
118 //===          INFORMATION OPTIONS
119 //===------------------------------------------------------------------------===
120
121 cl::opt<bool> DryRun("dry-run", cl::Optional, cl::init(false),
122   cl::desc("Do everything but perform the compilation actions"));
123
124 cl::alias DryRunAlias("y", cl::Optional,
125   cl::desc("Alias for -dry-run"), cl::aliasopt(DryRun));
126
127 cl::opt<bool> Verbose("verbose", cl::Optional, cl::init(false),
128   cl::desc("Print out each action taken"));
129
130 cl::alias VerboseAlias("v", cl::Optional, 
131   cl::desc("Alias for -verbose"), cl::aliasopt(Verbose));
132
133 cl::opt<bool> Debug("debug", cl::Optional, cl::init(false), 
134   cl::Hidden, cl::desc("Print out debugging information"));
135
136 cl::alias DebugAlias("d", cl::Optional,
137   cl::desc("Alias for -debug"), cl::aliasopt(Debug));
138
139 cl::opt<bool> TimeActions("time-actions", cl::Optional, cl::init(false),
140   cl::desc("Print execution time for each action taken"));
141
142 cl::opt<bool> ShowStats("stats", cl::Optional, cl::init(false),
143   cl::desc("Print statistics accumulated during optimization"));
144
145 //===------------------------------------------------------------------------===
146 //===          ADVANCED OPTIONS
147 //===------------------------------------------------------------------------===
148
149 static cl::opt<std::string> ConfigDir("config-dir", cl::Optional,
150   cl::desc("Specify a configuration directory to override defaults"),
151   cl::value_desc("directory"));
152
153 static cl::opt<bool> EmitRawCode("emit-raw-code", cl::Hidden, cl::Optional,
154   cl::desc("Emit raw, unoptimized code"));
155
156 static cl::opt<bool> PipeCommands("pipe", cl::Optional,
157   cl::desc("Invoke sub-commands by linking input/output with pipes"));
158
159 static cl::opt<bool> KeepTemporaries("keep-temps", cl::Optional,
160   cl::desc("Don't delete the temporary files created during compilation"));
161
162 //===------------------------------------------------------------------------===
163 //===          POSITIONAL OPTIONS
164 //===------------------------------------------------------------------------===
165
166 static cl::list<std::string> Files(cl::Positional, cl::OneOrMore,
167   cl::desc("[Sources/objects/libraries]"));
168
169 static cl::list<std::string> Languages("x", cl::ZeroOrMore,
170   cl::desc("Specify the source language for subsequent files"),
171   cl::value_desc("language"));
172
173 //===------------------------------------------------------------------------===
174 //===          GetFileType - determine type of a file
175 //===------------------------------------------------------------------------===
176 const std::string GetFileType(const std::string& fname, unsigned pos ) {
177   static std::vector<std::string>::iterator langIt = Languages.begin();
178   static std::string CurrLang = "";
179
180   // If a -x LANG option has been specified ..
181   if ( langIt != Languages.end() )
182     // If the -x LANG option came before the current file on command line
183     if ( Languages.getPosition( langIt - Languages.begin() ) < pos ) {
184       // use that language
185       CurrLang = *langIt++;
186       return CurrLang;
187     }
188
189   // If there's a current language in effect
190   if (!CurrLang.empty())
191     return CurrLang; // use that language
192
193   // otherwise just determine lang from the filename's suffix
194   return fname.substr( fname.rfind('.',fname.size()) + 1 );
195 }
196
197 } // end anonymous namespace
198
199
200 /// @brief The main program for llvmc
201 int main(int argc, char **argv) {
202   try {
203     // Make sure we print stack trace if we get bad signals
204     PrintStackTraceOnErrorSignal();
205
206     // Parse the command line options
207     cl::ParseCommandLineOptions(argc, argv, 
208       " LLVM Compilation Driver (llvmc)\n\n"
209       "  This program provides easy invocation of the LLVM tool set\n"
210       "  and source language compiler tools.\n"
211     );
212
213     // Deal with unimplemented options.
214     if (PipeCommands)
215       throw "Not implemented yet: -pipe";
216
217     if (OutputFilename.empty())
218       if (OptLevel == CompilerDriver::LINKING)
219         OutputFilename = "a.out";
220       else
221         throw "An output file must be specified. Please use the -o option";
222
223
224     // Construct the ConfigDataProvider object
225     LLVMC_ConfigDataProvider Provider;
226     Provider.setConfigDir(ConfigDir);
227
228     // Construct the CompilerDriver object
229     CompilerDriver CD(Provider);
230
231     // If the LLVM_LIB_SEARCH_PATH environment variable is
232     // set, append it to the list of places to search for libraries
233     std::string srchPath = getenv("LLVM_LIB_SEARCH_PATH");
234     if (!srchPath.empty())
235       LibPaths.push_back(srchPath);
236
237     // Configure the driver based on options
238     CD.setVerbose(Verbose);
239     CD.setDebug(Debug);
240     CD.setDryRun(DryRun);
241     CD.setFinalPhase(FinalPhase);
242     CD.setOptimization(OptLevel);
243     CD.setOutputMachine(OutputMachine);
244     CD.setEmitNativeCode(Native);
245     CD.setEmitRawCode(EmitRawCode);
246     CD.setTimeActions(TimeActions);
247     CD.setTimePasses(TimePassesIsEnabled);
248     CD.setShowStats(ShowStats);
249     CD.setKeepTemporaries(KeepTemporaries);
250     CD.setLibraryPaths(LibPaths);
251     if (!PreprocessorToolOpts.empty())
252         CD.setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
253     if (!TranslatorToolOpts.empty())
254         CD.setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
255     if (!OptimizerToolOpts.empty())
256         CD.setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
257     if (!AssemblerToolOpts.empty())
258         CD.setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
259     if (!LinkerToolOpts.empty())
260         CD.setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);
261
262     // Prepare the list of files to be compiled by the CompilerDriver.
263     CompilerDriver::InputList InpList;
264     std::vector<std::string>::iterator fileIt = Files.begin();
265     std::vector<std::string>::iterator libIt  = Libraries.begin();
266     unsigned libPos = 0, filePos = 0;
267     while ( 1 ) {
268       if ( libIt != Libraries.end() )
269         libPos = Libraries.getPosition( libIt - Libraries.begin() );
270       else
271         libPos = 0;
272       if ( fileIt != Files.end() )
273         filePos = Files.getPosition( fileIt - Files.begin() );
274       else
275         filePos = 0;
276
277       if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
278         // Add a source file
279         InpList.push_back( std::make_pair(*fileIt, GetFileType(*fileIt,filePos)));
280         ++fileIt;
281       }
282       else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
283         // Add a library
284         InpList.push_back( std::make_pair(*libIt++,""));
285       }
286       else
287         break; // we're done with the list
288     }
289
290     // Tell the driver to do its thing
291     int result = CD.execute(InpList,OutputFilename);
292     if (result != 0) {
293       throw "Error executing actions. Terminated.\n";
294       return result;
295     }
296
297     // All is good, return success
298     return 0;
299   } catch (std::string& msg) {
300     std::cerr << argv[0] << ": " << msg << "\n";
301   } catch (...) {
302     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
303   }
304 }