Split out the IRReader header and the utility functions it provides into
[oota-llvm.git] / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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 is the llc code generator driver. It provides a convenient
11 // command-line interface for generating native assembly-language code
12 // or C code, given LLVM bitcode.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/CommandFlags.h"
20 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/MC/SubtargetFeature.h"
26 #include "llvm/Pass.h"
27 #include "llvm/PassManager.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/PluginLoader.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include <memory>
43 using namespace llvm;
44
45 // General options for llc.  Other pass-specific options are specified
46 // within the corresponding llc passes, and target-specific options
47 // and back-end code generation options are specified with the target machine.
48 //
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
51
52 static cl::opt<std::string>
53 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
54
55 static cl::opt<unsigned>
56 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
57                  cl::value_desc("N"),
58                  cl::desc("Repeat compilation N times for timing"));
59
60 // Determine optimization level.
61 static cl::opt<char>
62 OptLevel("O",
63          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
64                   "(default = '-O2')"),
65          cl::Prefix,
66          cl::ZeroOrMore,
67          cl::init(' '));
68
69 static cl::opt<std::string>
70 TargetTriple("mtriple", cl::desc("Override target triple for module"));
71
72 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
73                        cl::desc("Do not verify input module"));
74
75 cl::opt<bool>
76 DisableSimplifyLibCalls("disable-simplify-libcalls",
77                         cl::desc("Disable simplify-libcalls"),
78                         cl::init(false));
79
80 static int compileModule(char**, LLVMContext&);
81
82 // GetFileNameRoot - Helper function to get the basename of a filename.
83 static inline std::string
84 GetFileNameRoot(const std::string &InputFilename) {
85   std::string IFN = InputFilename;
86   std::string outputFilename;
87   int Len = IFN.length();
88   if ((Len > 2) &&
89       IFN[Len-3] == '.' &&
90       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
91        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
92     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
93   } else {
94     outputFilename = IFN;
95   }
96   return outputFilename;
97 }
98
99 static tool_output_file *GetOutputStream(const char *TargetName,
100                                          Triple::OSType OS,
101                                          const char *ProgName) {
102   // If we don't yet have an output filename, make one.
103   if (OutputFilename.empty()) {
104     if (InputFilename == "-")
105       OutputFilename = "-";
106     else {
107       OutputFilename = GetFileNameRoot(InputFilename);
108
109       switch (FileType) {
110       case TargetMachine::CGFT_AssemblyFile:
111         if (TargetName[0] == 'c') {
112           if (TargetName[1] == 0)
113             OutputFilename += ".cbe.c";
114           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
115             OutputFilename += ".cpp";
116           else
117             OutputFilename += ".s";
118         } else
119           OutputFilename += ".s";
120         break;
121       case TargetMachine::CGFT_ObjectFile:
122         if (OS == Triple::Win32)
123           OutputFilename += ".obj";
124         else
125           OutputFilename += ".o";
126         break;
127       case TargetMachine::CGFT_Null:
128         OutputFilename += ".null";
129         break;
130       }
131     }
132   }
133
134   // Decide if we need "binary" output.
135   bool Binary = false;
136   switch (FileType) {
137   case TargetMachine::CGFT_AssemblyFile:
138     break;
139   case TargetMachine::CGFT_ObjectFile:
140   case TargetMachine::CGFT_Null:
141     Binary = true;
142     break;
143   }
144
145   // Open the file.
146   std::string error;
147   unsigned OpenFlags = 0;
148   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
149   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
150                                                  OpenFlags);
151   if (!error.empty()) {
152     errs() << error << '\n';
153     delete FDOut;
154     return 0;
155   }
156
157   return FDOut;
158 }
159
160 // main - Entry point for the llc compiler.
161 //
162 int main(int argc, char **argv) {
163   sys::PrintStackTraceOnErrorSignal();
164   PrettyStackTraceProgram X(argc, argv);
165
166   // Enable debug stream buffering.
167   EnableDebugBuffering = true;
168
169   LLVMContext &Context = getGlobalContext();
170   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
171
172   // Initialize targets first, so that --version shows registered targets.
173   InitializeAllTargets();
174   InitializeAllTargetMCs();
175   InitializeAllAsmPrinters();
176   InitializeAllAsmParsers();
177
178   // Initialize codegen and IR passes used by llc so that the -print-after,
179   // -print-before, and -stop-after options work.
180   PassRegistry *Registry = PassRegistry::getPassRegistry();
181   initializeCore(*Registry);
182   initializeCodeGen(*Registry);
183   initializeLoopStrengthReducePass(*Registry);
184   initializeLowerIntrinsicsPass(*Registry);
185   initializeUnreachableBlockElimPass(*Registry);
186
187   // Register the target printer for --version.
188   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
189
190   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
191
192   // Compile the module TimeCompilations times to give better compile time
193   // metrics.
194   for (unsigned I = TimeCompilations; I; --I)
195     if (int RetVal = compileModule(argv, Context))
196       return RetVal;
197   return 0;
198 }
199
200 static int compileModule(char **argv, LLVMContext &Context) {
201   // Load the module to be compiled...
202   SMDiagnostic Err;
203   std::auto_ptr<Module> M;
204   Module *mod = 0;
205   Triple TheTriple;
206
207   bool SkipModule = MCPU == "help" ||
208                     (!MAttrs.empty() && MAttrs.front() == "help");
209
210   // If user just wants to list available options, skip module loading
211   if (!SkipModule) {
212     M.reset(ParseIRFile(InputFilename, Err, Context));
213     mod = M.get();
214     if (mod == 0) {
215       Err.print(argv[0], errs());
216       return 1;
217     }
218
219     // If we are supposed to override the target triple, do so now.
220     if (!TargetTriple.empty())
221       mod->setTargetTriple(Triple::normalize(TargetTriple));
222     TheTriple = Triple(mod->getTargetTriple());
223   } else {
224     TheTriple = Triple(Triple::normalize(TargetTriple));
225   }
226
227   if (TheTriple.getTriple().empty())
228     TheTriple.setTriple(sys::getDefaultTargetTriple());
229
230   // Get the target specific parser.
231   std::string Error;
232   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
233                                                          Error);
234   if (!TheTarget) {
235     errs() << argv[0] << ": " << Error;
236     return 1;
237   }
238
239   // Package up features to be passed to target/subtarget
240   std::string FeaturesStr;
241   if (MAttrs.size()) {
242     SubtargetFeatures Features;
243     for (unsigned i = 0; i != MAttrs.size(); ++i)
244       Features.AddFeature(MAttrs[i]);
245     FeaturesStr = Features.getString();
246   }
247
248   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
249   switch (OptLevel) {
250   default:
251     errs() << argv[0] << ": invalid optimization level.\n";
252     return 1;
253   case ' ': break;
254   case '0': OLvl = CodeGenOpt::None; break;
255   case '1': OLvl = CodeGenOpt::Less; break;
256   case '2': OLvl = CodeGenOpt::Default; break;
257   case '3': OLvl = CodeGenOpt::Aggressive; break;
258   }
259
260   TargetOptions Options;
261   Options.LessPreciseFPMADOption = EnableFPMAD;
262   Options.NoFramePointerElim = DisableFPElim;
263   Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
264   Options.AllowFPOpFusion = FuseFPOps;
265   Options.UnsafeFPMath = EnableUnsafeFPMath;
266   Options.NoInfsFPMath = EnableNoInfsFPMath;
267   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
268   Options.HonorSignDependentRoundingFPMathOption =
269       EnableHonorSignDependentRoundingFPMath;
270   Options.UseSoftFloat = GenerateSoftFloatCalls;
271   if (FloatABIForCalls != FloatABI::Default)
272     Options.FloatABIType = FloatABIForCalls;
273   Options.NoZerosInBSS = DontPlaceZerosInBSS;
274   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
275   Options.DisableTailCalls = DisableTailCalls;
276   Options.StackAlignmentOverride = OverrideStackAlignment;
277   Options.RealignStack = EnableRealignStack;
278   Options.TrapFuncName = TrapFuncName;
279   Options.PositionIndependentExecutable = EnablePIE;
280   Options.EnableSegmentedStacks = SegmentedStacks;
281   Options.UseInitArray = UseInitArray;
282   Options.SSPBufferSize = SSPBufferSize;
283
284   std::auto_ptr<TargetMachine>
285     target(TheTarget->createTargetMachine(TheTriple.getTriple(),
286                                           MCPU, FeaturesStr, Options,
287                                           RelocModel, CMModel, OLvl));
288   assert(target.get() && "Could not allocate target machine!");
289   assert(mod && "Should have exited after outputting help!");
290   TargetMachine &Target = *target.get();
291
292   if (DisableDotLoc)
293     Target.setMCUseLoc(false);
294
295   if (DisableCFI)
296     Target.setMCUseCFI(false);
297
298   if (EnableDwarfDirectory)
299     Target.setMCUseDwarfDirectory(true);
300
301   if (GenerateSoftFloatCalls)
302     FloatABIForCalls = FloatABI::Soft;
303
304   // Disable .loc support for older OS X versions.
305   if (TheTriple.isMacOSX() &&
306       TheTriple.isMacOSXVersionLT(10, 6))
307     Target.setMCUseLoc(false);
308
309   // Figure out where we are going to send the output.
310   OwningPtr<tool_output_file> Out
311     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
312   if (!Out) return 1;
313
314   // Build up all of the passes that we want to do to the module.
315   PassManager PM;
316
317   // Add an appropriate TargetLibraryInfo pass for the module's triple.
318   TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
319   if (DisableSimplifyLibCalls)
320     TLI->disableAllFunctions();
321   PM.add(TLI);
322
323   // Add intenal analysis passes from the target machine.
324   Target.addAnalysisPasses(PM);
325
326   // Add the target data from the target machine, if it exists, or the module.
327   if (const DataLayout *TD = Target.getDataLayout())
328     PM.add(new DataLayout(*TD));
329   else
330     PM.add(new DataLayout(mod));
331
332   // Override default to generate verbose assembly.
333   Target.setAsmVerbosityDefault(true);
334
335   if (RelaxAll) {
336     if (FileType != TargetMachine::CGFT_ObjectFile)
337       errs() << argv[0]
338              << ": warning: ignoring -mc-relax-all because filetype != obj";
339     else
340       Target.setMCRelaxAll(true);
341   }
342
343   {
344     formatted_raw_ostream FOS(Out->os());
345
346     AnalysisID StartAfterID = 0;
347     AnalysisID StopAfterID = 0;
348     const PassRegistry *PR = PassRegistry::getPassRegistry();
349     if (!StartAfter.empty()) {
350       const PassInfo *PI = PR->getPassInfo(StartAfter);
351       if (!PI) {
352         errs() << argv[0] << ": start-after pass is not registered.\n";
353         return 1;
354       }
355       StartAfterID = PI->getTypeInfo();
356     }
357     if (!StopAfter.empty()) {
358       const PassInfo *PI = PR->getPassInfo(StopAfter);
359       if (!PI) {
360         errs() << argv[0] << ": stop-after pass is not registered.\n";
361         return 1;
362       }
363       StopAfterID = PI->getTypeInfo();
364     }
365
366     // Ask the target to add backend passes as necessary.
367     if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
368                                    StartAfterID, StopAfterID)) {
369       errs() << argv[0] << ": target does not support generation of this"
370              << " file type!\n";
371       return 1;
372     }
373
374     // Before executing passes, print the final values of the LLVM options.
375     cl::PrintOptionValues();
376
377     PM.run(*mod);
378   }
379
380   // Declare success.
381   Out->keep();
382
383   return 0;
384 }