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