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