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