blob: 929f70215b947c90c260e78e1f8a4bf7ebcd962b [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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>
40using 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//
46static cl::opt<std::string>
47InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48
49static cl::opt<std::string>
50OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
53
54static cl::opt<bool> Fast("fast",
55 cl::desc("Generate code quickly, potentially sacrificing code quality"));
56
57static cl::opt<std::string>
58TargetTriple("mtriple", cl::desc("Override target triple for module"));
59
Gordon Henriksen99e34ab2007-10-17 21:28:48 +000060static cl::opt<const TargetMachineRegistry::entry*, false,
61 TargetMachineRegistry::Parser>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062MArch("march", cl::desc("Architecture to generate code for:"));
63
64static cl::opt<std::string>
65MCPU("mcpu",
66 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
67 cl::value_desc("cpu-name"),
68 cl::init(""));
69
70static cl::list<std::string>
71MAttrs("mattr",
72 cl::CommaSeparated,
73 cl::desc("Target specific attributes (-mattr=help for details)"),
74 cl::value_desc("a1,+a2,-a3,..."));
75
76cl::opt<TargetMachine::CodeGenFileType>
77FileType("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
89cl::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.
94static inline std::string
95GetFileNameRoot(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
108static 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' || MArch->Name[1] != 0) // not CBE
138 OutputFilename += ".s";
139 else
140 OutputFilename += ".cbe.c";
141 break;
142 case TargetMachine::ObjectFile:
143 OutputFilename += ".o";
144 break;
145 case TargetMachine::DynamicLibrary:
146 OutputFilename += LTDL_SHLIB_EXT;
147 break;
148 }
149
150 if (!Force && std::ifstream(OutputFilename.c_str())) {
151 // If force is not specified, make sure not to overwrite a file!
152 std::cerr << ProgName << ": error opening '" << OutputFilename
153 << "': file exists!\n"
154 << "Use -f command line argument to force output\n";
155 return 0;
156 }
157
158 // Make sure that the Out file gets unlinked from the disk if we get a
159 // SIGINT
160 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
161
162 std::ostream *Out = new std::ofstream(OutputFilename.c_str());
163 if (!Out->good()) {
164 std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
165 delete Out;
166 return 0;
167 }
168
169 return Out;
170}
171
172// main - Entry point for the llc compiler.
173//
174int main(int argc, char **argv) {
175 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Dan Gohman6099df82007-10-08 15:45:12 +0000176 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 sys::PrintStackTraceOnErrorSignal();
178
179 // Load the module to be compiled...
180 std::string ErrorMessage;
181 std::auto_ptr<Module> M;
182
183 std::auto_ptr<MemoryBuffer> Buffer(
184 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
185 if (Buffer.get())
186 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
187 if (M.get() == 0) {
188 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
189 std::cerr << "Reason: " << ErrorMessage << "\n";
190 return 1;
191 }
192 Module &mod = *M.get();
193
194 // If we are supposed to override the target triple, do so now.
195 if (!TargetTriple.empty())
196 mod.setTargetTriple(TargetTriple);
197
198 // Allocate target machine. First, check whether the user has
199 // explicitly specified an architecture to compile for.
200 if (MArch == 0) {
201 std::string Err;
202 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
203 if (MArch == 0) {
204 std::cerr << argv[0] << ": error auto-selecting target for module '"
205 << Err << "'. Please use the -march option to explicitly "
206 << "pick a target.\n";
207 return 1;
208 }
209 }
210
211 // Package up features to be passed to target/subtarget
212 std::string FeaturesStr;
213 if (MCPU.size() || MAttrs.size()) {
214 SubtargetFeatures Features;
215 Features.setCPU(MCPU);
216 for (unsigned i = 0; i != MAttrs.size(); ++i)
217 Features.AddFeature(MAttrs[i]);
218 FeaturesStr = Features.getString();
219 }
220
221 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
222 assert(target.get() && "Could not allocate target machine!");
223 TargetMachine &Target = *target.get();
224
225 // Figure out where we are going to send the output...
226 std::ostream *Out = GetOutputStream(argv[0]);
227 if (Out == 0) return 1;
228
229 // If this target requires addPassesToEmitWholeFile, do it now. This is
230 // used by strange things like the C backend.
231 if (Target.WantsWholeFile()) {
232 PassManager PM;
233 PM.add(new TargetData(*Target.getTargetData()));
234 if (!NoVerify)
235 PM.add(createVerifierPass());
236
237 // Ask the target to add backend passes as necessary.
238 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
239 std::cerr << argv[0] << ": target does not support generation of this"
240 << " file type!\n";
241 if (Out != &std::cout) delete Out;
242 // And the Out file is empty and useless, so remove it now.
243 sys::Path(OutputFilename).eraseFromDisk();
244 return 1;
245 }
246 PM.run(mod);
247 } else {
248 // Build up all of the passes that we want to do to the module.
249 FunctionPassManager Passes(new ExistingModuleProvider(M.get()));
250 Passes.add(new TargetData(*Target.getTargetData()));
251
252#ifndef NDEBUG
253 if (!NoVerify)
254 Passes.add(createVerifierPass());
255#endif
256
257 // Ask the target to add backend passes as necessary.
258 MachineCodeEmitter *MCE = 0;
259
260 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
261 default:
262 assert(0 && "Invalid file model!");
263 return 1;
264 case FileModel::Error:
265 std::cerr << argv[0] << ": target does not support generation of this"
266 << " file type!\n";
267 if (Out != &std::cout) delete Out;
268 // And the Out file is empty and useless, so remove it now.
269 sys::Path(OutputFilename).eraseFromDisk();
270 return 1;
271 case FileModel::AsmFile:
272 break;
273 case FileModel::MachOFile:
274 MCE = AddMachOWriter(Passes, *Out, Target);
275 break;
276 case FileModel::ElfFile:
277 MCE = AddELFWriter(Passes, *Out, Target);
278 break;
279 }
280
281 if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) {
282 std::cerr << argv[0] << ": target does not support generation of this"
283 << " file type!\n";
284 if (Out != &std::cout) delete Out;
285 // And the Out file is empty and useless, so remove it now.
286 sys::Path(OutputFilename).eraseFromDisk();
287 return 1;
288 }
289
290 Passes.doInitialization();
291
292 // Run our queue of passes all at once now, efficiently.
293 // TODO: this could lazily stream functions out of the module.
294 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
295 if (!I->isDeclaration())
296 Passes.run(*I);
297
298 Passes.doFinalization();
299 }
300
301 // Delete the ostream if it's not a stdout stream
302 if (Out != &std::cout) delete Out;
303
304 return 0;
305}