Unbreak build with gcc 4.3: provide missed includes and silence most annoying warnings.
[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 is distributed under the University of Illinois Open Source
6 // 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/Support/CommandLine.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/System/Signals.h"
23 #include <iostream>
24 #include <cstring>
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 //===          PHASE OPTIONS
29 //===----------------------------------------------------------------------===//
30 static cl::opt<CompilerDriver::Phases> FinalPhase(cl::Optional,
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 static cl::opt<CompilerDriver::OptimizationLevels> OptLevel(cl::ZeroOrMore,
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 static 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 static cl::alias PreprocessorToolOptsAlias("Wp,", cl::ZeroOrMore,
78   cl::desc("Alias for -Tpre"), cl::aliasopt(PreprocessorToolOpts));
79
80 static cl::list<std::string> TranslatorToolOpts("Ttrn", cl::ZeroOrMore,
81   cl::desc("Pass specific options to the assembler"),
82   cl::value_desc("option"));
83
84 static cl::list<std::string> AssemblerToolOpts("Tasm", cl::ZeroOrMore,
85   cl::desc("Pass specific options to the assembler"),
86   cl::value_desc("option"));
87
88 static cl::alias AssemblerToolOptsAlias("Wa,", cl::ZeroOrMore,
89   cl::desc("Alias for -Tasm"), cl::aliasopt(AssemblerToolOpts));
90
91 static cl::list<std::string> OptimizerToolOpts("Topt", cl::ZeroOrMore,
92   cl::desc("Pass specific options to the optimizer"),
93   cl::value_desc("option"));
94
95 static cl::list<std::string> LinkerToolOpts("Tlnk", cl::ZeroOrMore,
96   cl::desc("Pass specific options to the linker"),
97   cl::value_desc("option"));
98
99 static cl::alias LinkerToolOptsAlias("Wl,", cl::ZeroOrMore,
100   cl::desc("Alias for -Tlnk"), cl::aliasopt(LinkerToolOpts));
101
102 static cl::list<std::string> fOpts("f", cl::ZeroOrMore, cl::Prefix,
103   cl::desc("Pass through -f options to compiler tools"),
104   cl::value_desc("option"));
105
106 static cl::list<std::string> MOpts("M", cl::ZeroOrMore, cl::Prefix,
107   cl::desc("Pass through -M options to compiler tools"),
108   cl::value_desc("option"));
109
110 static cl::list<std::string> WOpts("W", cl::ZeroOrMore, cl::Prefix,
111   cl::desc("Pass through -W options to compiler tools"),
112   cl::value_desc("option"));
113
114 static cl::list<std::string> BOpt("B", cl::ZeroOrMore, cl::Prefix,
115   cl::desc("Specify path to find llvmc sub-tools"),
116   cl::value_desc("dir"));
117
118 //===----------------------------------------------------------------------===//
119 //===          INPUT OPTIONS
120 //===----------------------------------------------------------------------===//
121
122 static cl::list<std::string> LibPaths("L", cl::Prefix,
123   cl::desc("Specify a library search path"), cl::value_desc("dir"));
124
125 static cl::list<std::string> Libraries("l", cl::Prefix,
126   cl::desc("Specify base name of libraries to link to"), cl::value_desc("lib"));
127
128 static cl::list<std::string> Includes("I", cl::Prefix,
129   cl::desc("Specify location to search for included source"),
130   cl::value_desc("dir"));
131
132 static cl::list<std::string> Defines("D", cl::Prefix,
133   cl::desc("Specify a pre-processor symbol to define"),
134   cl::value_desc("symbol"));
135
136 //===----------------------------------------------------------------------===//
137 //===          OUTPUT OPTIONS
138 //===----------------------------------------------------------------------===//
139
140 static cl::opt<std::string> OutputFilename("o",
141   cl::desc("Override output filename"), cl::value_desc("file"));
142
143 static cl::opt<std::string> OutputMachine("m", cl::Prefix,
144   cl::desc("Specify a target machine"), cl::value_desc("machine"));
145
146 static cl::opt<bool> Native("native", cl::init(false),
147   cl::desc("Generative native code instead of bitcode"));
148
149 static cl::opt<bool> DebugOutput("g", cl::init(false),
150   cl::desc("Generate objects that include debug symbols"));
151
152 static cl::opt<bool> StripOutput("strip", cl::init(false),
153   cl::desc("Strip all symbols from linked output file"));
154
155 static cl::opt<std::string> PrintFileName("print-fname", cl::Optional,
156   cl::value_desc("file"),
157   cl::desc("Print the full path for the option's value"));
158
159 //===----------------------------------------------------------------------===//
160 //===          INFORMATION OPTIONS
161 //===----------------------------------------------------------------------===//
162
163 static cl::opt<bool> DryRun("dry-run", cl::Optional, cl::init(false),
164   cl::desc("Do everything but perform the compilation actions"));
165
166 static cl::alias DryRunAlias("y", cl::Optional,
167   cl::desc("Alias for -dry-run"), cl::aliasopt(DryRun));
168
169 static cl::opt<bool> Verbose("verbose", cl::Optional, cl::init(false),
170   cl::desc("Print out each action taken"));
171
172 static cl::alias VerboseAlias("v", cl::Optional,
173   cl::desc("Alias for -verbose"), cl::aliasopt(Verbose));
174
175 static cl::opt<bool> Debug("debug", cl::Optional, cl::init(false),
176   cl::Hidden, cl::desc("Print out debugging information"));
177
178 static cl::alias DebugAlias("d", cl::Optional,
179   cl::desc("Alias for -debug"), cl::aliasopt(Debug));
180
181 static cl::opt<bool> TimeActions("time-actions", cl::Optional, cl::init(false),
182   cl::desc("Print execution time for each action taken"));
183
184 static cl::opt<bool> ShowStats("stats", cl::Optional, cl::init(false),
185   cl::desc("Print statistics accumulated during optimization"));
186
187 //===----------------------------------------------------------------------===//
188 //===          ADVANCED OPTIONS
189 //===----------------------------------------------------------------------===//
190
191 static cl::opt<std::string> ConfigDir("config-dir", cl::Optional,
192   cl::desc("Specify configuration directory to override defaults"),
193   cl::value_desc("dir"));
194
195 static cl::opt<bool> EmitRawCode("emit-raw-code", cl::Hidden, cl::Optional,
196   cl::desc("Emit raw, unoptimized code"));
197
198 static cl::opt<bool> PipeCommands("pipe", cl::Optional,
199   cl::desc("Invoke sub-commands by linking input/output with pipes"));
200
201 static cl::opt<bool> KeepTemps("keep-temps", cl::Optional,
202   cl::desc("Don't delete temporary files created by llvmc"));
203
204 //===----------------------------------------------------------------------===//
205 //===          POSITIONAL OPTIONS
206 //===----------------------------------------------------------------------===//
207
208 static cl::list<std::string> Files(cl::Positional, cl::ZeroOrMore,
209   cl::desc("[Sources/objects/libraries]"));
210
211 static cl::list<std::string> Languages("x", cl::ZeroOrMore,
212   cl::desc("Specify the source language for subsequent files"),
213   cl::value_desc("language"));
214
215 //===----------------------------------------------------------------------===//
216 //===          GetFileType - determine type of a file
217 //===----------------------------------------------------------------------===//
218 static const std::string GetFileType(const std::string& fname, unsigned pos) {
219   static std::vector<std::string>::iterator langIt = Languages.begin();
220   static std::string CurrLang = "";
221
222   // If a -x LANG option has been specified ..
223   if (langIt != Languages.end())
224     // If the -x LANG option came before the current file on command line
225     if (Languages.getPosition( langIt - Languages.begin() ) < pos) {
226       // use that language
227       CurrLang = *langIt++;
228       return CurrLang;
229     }
230
231   // If there's a current language in effect
232   if (!CurrLang.empty())
233     return CurrLang; // use that language
234
235   // otherwise just determine lang from the filename's suffix
236   return fname.substr(fname.rfind('.', fname.size()) + 1);
237 }
238
239 static void handleTerminatingOptions(CompilerDriver* CD) {
240   if (!PrintFileName.empty()) {
241     sys::Path path = CD->GetPathForLinkageItem(PrintFileName, false);
242     std::string p = path.toString();
243     if (p.empty())
244       std::cout << "Can't locate `" << PrintFileName << "'.\n";
245     else
246       std::cout << p << '\n';
247     exit(0);
248   }
249 }
250
251 /// @brief The main program for llvmc
252 int main(int argc, char **argv) {
253   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
254   // Make sure we print stack trace if we get bad signals
255   sys::PrintStackTraceOnErrorSignal();
256
257   std::cout << "NOTE: llvmc is highly experimental and mostly useless right "
258                "now.\nPlease use llvm-gcc directly instead.\n\n";
259
260   try {
261
262     // Parse the command line options
263     cl::ParseCommandLineOptions(argc, argv,
264       "LLVM Compiler Driver (llvmc)\n\n"
265       "  This program provides easy invocation of the LLVM tool set\n"
266       "  and other compiler tools.\n"
267     );
268
269     // Deal with unimplemented options.
270     if (PipeCommands)
271       throw std::string("Not implemented yet: -pipe");
272
273     if (OutputFilename.empty())
274       if (OptLevel == CompilerDriver::LINKING)
275         OutputFilename = "a.out";
276
277     // Construct the ConfigDataProvider object
278     LLVMC_ConfigDataProvider Provider;
279     Provider.setConfigDir(sys::Path(ConfigDir));
280
281     // Construct the CompilerDriver object
282     CompilerDriver* CD = CompilerDriver::Get(Provider);
283
284     // If the LLVM_LIB_SEARCH_PATH environment variable is
285     // set, append it to the list of places to search for libraries
286     char *srchPath = getenv("LLVM_LIB_SEARCH_PATH");
287     if (srchPath != NULL && strlen(srchPath) != 0)
288       LibPaths.push_back(std::string(srchPath));
289
290     // Set the driver flags based on command line options
291     unsigned flags = 0;
292     if (Verbose)        flags |= CompilerDriver::VERBOSE_FLAG;
293     if (Debug)          flags |= CompilerDriver::DEBUG_FLAG;
294     if (DryRun)         flags |= CompilerDriver::DRY_RUN_FLAG;
295     if (Native)         flags |= CompilerDriver::EMIT_NATIVE_FLAG;
296     if (EmitRawCode)    flags |= CompilerDriver::EMIT_RAW_FLAG;
297     if (KeepTemps)      flags |= CompilerDriver::KEEP_TEMPS_FLAG;
298     if (ShowStats)      flags |= CompilerDriver::SHOW_STATS_FLAG;
299     if (TimeActions)    flags |= CompilerDriver::TIME_ACTIONS_FLAG;
300     if (StripOutput)    flags |= CompilerDriver::STRIP_OUTPUT_FLAG;
301     CD->setDriverFlags(flags);
302
303     // Specify required parameters
304     CD->setFinalPhase(FinalPhase);
305     CD->setOptimization(OptLevel);
306     CD->setOutputMachine(OutputMachine);
307     CD->setIncludePaths(Includes);
308     CD->setSymbolDefines(Defines);
309     CD->setLibraryPaths(LibPaths);
310     CD->setfPassThrough(fOpts);
311     CD->setMPassThrough(MOpts);
312     CD->setWPassThrough(WOpts);
313
314     // Provide additional tool arguments
315     if (!PreprocessorToolOpts.empty())
316         CD->setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
317     if (!TranslatorToolOpts.empty())
318         CD->setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
319     if (!OptimizerToolOpts.empty())
320         CD->setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
321     if (!AssemblerToolOpts.empty())
322         CD->setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
323     if (!LinkerToolOpts.empty())
324         CD->setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);
325
326     // Check for options that cause us to terminate before any significant work
327     // is done.
328     handleTerminatingOptions(CD);
329
330     // Prepare the list of files to be compiled by the CompilerDriver.
331     CompilerDriver::InputList InpList;
332     std::vector<std::string>::iterator fileIt = Files.begin();
333     std::vector<std::string>::iterator libIt  = Libraries.begin();
334     unsigned libPos = 0, filePos = 0;
335     while ( 1 ) {
336       if (libIt != Libraries.end())
337         libPos = Libraries.getPosition( libIt - Libraries.begin() );
338       else
339         libPos = 0;
340       if (fileIt != Files.end())
341         filePos = Files.getPosition(fileIt - Files.begin());
342       else
343         filePos = 0;
344
345       if (filePos != 0 && (libPos == 0 || filePos < libPos)) {
346         // Add a source file
347         InpList.push_back(std::make_pair(*fileIt,
348                                          GetFileType(*fileIt, filePos)));
349         ++fileIt;
350       } else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
351         // Add a library
352         InpList.push_back(std::make_pair(*libIt++, ""));
353       }
354       else
355         break; // we're done with the list
356     }
357
358     // Tell the driver to do its thing
359     std::string ErrMsg;
360     int result = CD->execute(InpList, sys::Path(OutputFilename), ErrMsg);
361     if (result != 0) {
362       std::cerr << argv[0] << ": " << ErrMsg << '\n';
363       return result;
364     }
365
366     // All is good, return success
367     return 0;
368   } catch (const std::string& msg) {
369     std::cerr << argv[0] << ": " << msg << '\n';
370   } catch (...) {
371     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
372   }
373   return 1;
374 }