At Chris' suggestion, move the liveness and worklist datastructures 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/Bitcode/ReaderWriter.h"
17 #include "llvm/CodeGen/FileWriters.h"
18 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
19 #include "llvm/Target/SubtargetFeature.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/TargetMachineRegistry.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Module.h"
25 #include "llvm/ModuleProvider.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Analysis/Verifier.h"
34 #include "llvm/System/Signals.h"
35 #include "llvm/Config/config.h"
36 #include "llvm/LinkAllVMCore.h"
37 #include <fstream>
38 #include <iostream>
39 #include <memory>
40 using namespace llvm;
41
42 // General options for llc.  Other pass-specific options are specified
43 // within the corresponding llc passes, and target-specific options
44 // and back-end code generation options are specified with the target machine.
45 //
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
53
54 static cl::opt<bool> Fast("fast", 
55       cl::desc("Generate code quickly, potentially sacrificing code quality"));
56
57 static cl::opt<std::string>
58 TargetTriple("mtriple", cl::desc("Override target triple for module"));
59
60 static cl::opt<const TargetMachineRegistry::entry*, false,
61                TargetMachineRegistry::Parser>
62 MArch("march", cl::desc("Architecture to generate code for:"));
63
64 static cl::opt<std::string>
65 MCPU("mcpu", 
66   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
67   cl::value_desc("cpu-name"),
68   cl::init(""));
69
70 static cl::list<std::string>
71 MAttrs("mattr", 
72   cl::CommaSeparated,
73   cl::desc("Target specific attributes (-mattr=help for details)"),
74   cl::value_desc("a1,+a2,-a3,..."));
75
76 cl::opt<TargetMachine::CodeGenFileType>
77 FileType("filetype", cl::init(TargetMachine::AssemblyFile),
78   cl::desc("Choose a file type (not all types are supported by all targets):"),
79   cl::values(
80        clEnumValN(TargetMachine::AssemblyFile,    "asm",
81                   "  Emit an assembly ('.s') file"),
82        clEnumValN(TargetMachine::ObjectFile,    "obj",
83                   "  Emit a native object ('.o') file [experimental]"),
84        clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
85                   "  Emit a native dynamic library ('.so') file"
86                   " [experimental]"),
87        clEnumValEnd));
88
89 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
90                        cl::desc("Do not verify input module"));
91
92
93 // GetFileNameRoot - Helper function to get the basename of a filename.
94 static inline std::string
95 GetFileNameRoot(const std::string &InputFilename) {
96   std::string IFN = InputFilename;
97   std::string outputFilename;
98   int Len = IFN.length();
99   if ((Len > 2) &&
100       IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
101     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
102   } else {
103     outputFilename = IFN;
104   }
105   return outputFilename;
106 }
107
108 static std::ostream *GetOutputStream(const char *ProgName) {
109   if (OutputFilename != "") {
110     if (OutputFilename == "-")
111       return &std::cout;
112
113     // Specified an output filename?
114     if (!Force && std::ifstream(OutputFilename.c_str())) {
115       // If force is not specified, make sure not to overwrite a file!
116       std::cerr << ProgName << ": error opening '" << OutputFilename
117                 << "': file exists!\n"
118                 << "Use -f command line argument to force output\n";
119       return 0;
120     }
121     // Make sure that the Out file gets unlinked from the disk if we get a
122     // SIGINT
123     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
124
125     return new std::ofstream(OutputFilename.c_str());
126   }
127   
128   if (InputFilename == "-") {
129     OutputFilename = "-";
130     return &std::cout;
131   }
132
133   OutputFilename = GetFileNameRoot(InputFilename);
134     
135   switch (FileType) {
136   case TargetMachine::AssemblyFile:
137     if (MArch->Name[0] == 'c') {
138       if (MArch->Name[1] == 0)
139         OutputFilename += ".cbe.c";
140       else if (MArch->Name[1] == 'p' && MArch->Name[2] == 'p')
141         OutputFilename += ".cpp";
142       else
143         OutputFilename += ".s";
144     } else
145       OutputFilename += ".s";
146     break;
147   case TargetMachine::ObjectFile:
148     OutputFilename += ".o";
149     break;
150   case TargetMachine::DynamicLibrary:
151     OutputFilename += LTDL_SHLIB_EXT;
152     break;
153   }
154   
155   if (!Force && std::ifstream(OutputFilename.c_str())) {
156     // If force is not specified, make sure not to overwrite a file!
157     std::cerr << ProgName << ": error opening '" << OutputFilename
158                           << "': file exists!\n"
159                           << "Use -f command line argument to force output\n";
160     return 0;
161   }
162   
163   // Make sure that the Out file gets unlinked from the disk if we get a
164   // SIGINT
165   sys::RemoveFileOnSignal(sys::Path(OutputFilename));
166   
167   std::ostream *Out = new std::ofstream(OutputFilename.c_str());
168   if (!Out->good()) {
169     std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
170     delete Out;
171     return 0;
172   }
173   
174   return Out;
175 }
176
177 // main - Entry point for the llc compiler.
178 //
179 int main(int argc, char **argv) {
180   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
181   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
182   sys::PrintStackTraceOnErrorSignal();
183
184   // Load the module to be compiled...
185   std::string ErrorMessage;
186   std::auto_ptr<Module> M;
187   
188   std::auto_ptr<MemoryBuffer> Buffer(
189                    MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
190   if (Buffer.get())
191     M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
192   if (M.get() == 0) {
193     std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
194     std::cerr << "Reason: " << ErrorMessage << "\n";
195     return 1;
196   }
197   Module &mod = *M.get();
198   
199   // If we are supposed to override the target triple, do so now.
200   if (!TargetTriple.empty())
201     mod.setTargetTriple(TargetTriple);
202   
203   // Allocate target machine.  First, check whether the user has
204   // explicitly specified an architecture to compile for.
205   if (MArch == 0) {
206     std::string Err;
207     MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
208     if (MArch == 0) {
209       std::cerr << argv[0] << ": error auto-selecting target for module '"
210                 << Err << "'.  Please use the -march option to explicitly "
211                 << "pick a target.\n";
212       return 1;
213     }
214   }
215
216   // Package up features to be passed to target/subtarget
217   std::string FeaturesStr;
218   if (MCPU.size() || MAttrs.size()) {
219     SubtargetFeatures Features;
220     Features.setCPU(MCPU);
221     for (unsigned i = 0; i != MAttrs.size(); ++i)
222       Features.AddFeature(MAttrs[i]);
223     FeaturesStr = Features.getString();
224   }
225   
226   std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
227   assert(target.get() && "Could not allocate target machine!");
228   TargetMachine &Target = *target.get();
229
230   // Figure out where we are going to send the output...
231   std::ostream *Out = GetOutputStream(argv[0]);
232   if (Out == 0) return 1;
233   
234   // If this target requires addPassesToEmitWholeFile, do it now.  This is
235   // used by strange things like the C backend.
236   if (Target.WantsWholeFile()) {
237     PassManager PM;
238     PM.add(new TargetData(*Target.getTargetData()));
239     if (!NoVerify)
240       PM.add(createVerifierPass());
241     
242     // Ask the target to add backend passes as necessary.
243     if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
244       std::cerr << argv[0] << ": target does not support generation of this"
245                 << " file type!\n";
246       if (Out != &std::cout) delete Out;
247       // And the Out file is empty and useless, so remove it now.
248       sys::Path(OutputFilename).eraseFromDisk();
249       return 1;
250     }
251     PM.run(mod);
252   } else {
253     // Build up all of the passes that we want to do to the module.
254     ExistingModuleProvider Provider(M.release());
255     FunctionPassManager Passes(&Provider);
256     Passes.add(new TargetData(*Target.getTargetData()));
257     
258 #ifndef NDEBUG
259     if (!NoVerify)
260       Passes.add(createVerifierPass());
261 #endif
262   
263     // Ask the target to add backend passes as necessary.
264     MachineCodeEmitter *MCE = 0;
265
266     switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
267     default:
268       assert(0 && "Invalid file model!");
269       return 1;
270     case FileModel::Error:
271       std::cerr << argv[0] << ": target does not support generation of this"
272                 << " file type!\n";
273       if (Out != &std::cout) delete Out;
274       // And the Out file is empty and useless, so remove it now.
275       sys::Path(OutputFilename).eraseFromDisk();
276       return 1;
277     case FileModel::AsmFile:
278       break;
279     case FileModel::MachOFile:
280       MCE = AddMachOWriter(Passes, *Out, Target);
281       break;
282     case FileModel::ElfFile:
283       MCE = AddELFWriter(Passes, *Out, Target);
284       break;
285     }
286
287     if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) {
288       std::cerr << argv[0] << ": target does not support generation of this"
289                 << " file type!\n";
290       if (Out != &std::cout) delete Out;
291       // And the Out file is empty and useless, so remove it now.
292       sys::Path(OutputFilename).eraseFromDisk();
293       return 1;
294     }
295   
296     Passes.doInitialization();
297   
298     // Run our queue of passes all at once now, efficiently.
299     // TODO: this could lazily stream functions out of the module.
300     for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
301       if (!I->isDeclaration())
302         Passes.run(*I);
303     
304     Passes.doFinalization();
305   }
306     
307   // Delete the ostream if it's not a stdout stream
308   if (Out != &std::cout) delete Out;
309
310   return 0;
311 }