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