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