blob: dfd1f6b073eaeb32f2e56e7e8f6a953e16f8af7f [file] [log] [blame]
Chris Lattner5b836c42003-06-20 15:49:04 +00001//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnere737c7a2001-09-07 22:20:50 +00009//
Brian Gaekee40eae72004-03-16 21:47:20 +000010// This is the llc code generator driver. It provides a convenient
Misha Brukman3da94ae2005-04-22 00:00:37 +000011// command-line interface for generating native assembly-language code
Gabor Greifa99be512007-07-05 17:07:56 +000012// or C code, given LLVM bitcode.
Chris Lattnere737c7a2001-09-07 22:20:50 +000013//
Chris Lattnerb79757c2001-10-04 01:40:53 +000014//===----------------------------------------------------------------------===//
Vikram S. Advecb465fc2001-07-21 12:42:29 +000015
Chris Lattner1a735402007-05-06 04:55:19 +000016#include "llvm/Bitcode/ReaderWriter.h"
Bill Wendling546d0fb2007-02-08 01:41:07 +000017#include "llvm/CodeGen/FileWriters.h"
Chris Lattnerd3a680a2006-08-01 22:34:35 +000018#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Anton Korobeynikov2b110042008-08-17 14:33:01 +000019#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
Jim Laskeyb1e11802005-09-01 21:38:21 +000020#include "llvm/Target/SubtargetFeature.h"
Owen Anderson07000c62006-05-12 06:33:49 +000021#include "llvm/Target/TargetData.h"
Vikram S. Adve805eb962001-09-18 13:10:45 +000022#include "llvm/Target/TargetMachine.h"
Chris Lattnere45110e2004-07-11 04:03:24 +000023#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner65f1b892002-05-07 20:03:27 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattner46ac43c2001-09-07 21:26:31 +000025#include "llvm/Module.h"
Chris Lattner744879e2007-05-06 09:32:02 +000026#include "llvm/ModuleProvider.h"
Chris Lattnercd50d3f2002-01-31 00:46:45 +000027#include "llvm/PassManager.h"
Vikram S. Adve7d0ba022002-09-16 16:35:34 +000028#include "llvm/Pass.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/Support/CommandLine.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000030#include "llvm/Support/ManagedStatic.h"
Chris Lattner1a735402007-05-06 04:55:19 +000031#include "llvm/Support/MemoryBuffer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/PluginLoader.h"
Duraid Madinaea8aed72005-12-30 02:47:21 +000033#include "llvm/Support/FileUtilities.h"
Reid Spencer4418c2b2005-07-28 02:25:30 +000034#include "llvm/Analysis/Verifier.h"
Chris Lattnerbed85ff2004-05-27 05:41:36 +000035#include "llvm/System/Signals.h"
Chris Lattner812125a2005-06-25 03:32:05 +000036#include "llvm/Config/config.h"
Reid Spenceraf303d52006-06-07 23:03:13 +000037#include "llvm/LinkAllVMCore.h"
Chris Lattner78f7e1a2001-09-19 16:52:09 +000038#include <fstream>
Reid Spencer86f42bd2004-07-04 12:20:55 +000039#include <iostream>
40#include <memory>
Brian Gaeked0fde302003-11-11 22:41:34 +000041using namespace llvm;
42
Vikram S. Adve7d0ba022002-09-16 16:35:34 +000043// General options for llc. Other pass-specific options are specified
44// within the corresponding llc passes, and target-specific options
45// and back-end code generation options are specified with the target machine.
Misha Brukman3da94ae2005-04-22 00:00:37 +000046//
Chris Lattnerb5881f12003-04-25 05:26:11 +000047static cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000048InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000049
Chris Lattnerb5881f12003-04-25 05:26:11 +000050static cl::opt<std::string>
Chris Lattner5ff62e92002-07-22 02:10:13 +000051OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
52
53static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
54
Chris Lattner178e0c42005-11-08 02:12:17 +000055static cl::opt<bool> Fast("fast",
56 cl::desc("Generate code quickly, potentially sacrificing code quality"));
57
Chris Lattnerf33b8662005-12-16 04:59:57 +000058static cl::opt<std::string>
Chris Lattnerbe193832005-12-16 05:19:55 +000059TargetTriple("mtriple", cl::desc("Override target triple for module"));
Chris Lattner178e0c42005-11-08 02:12:17 +000060
Gordon Henriksen4b2b9402007-10-17 21:28:48 +000061static cl::opt<const TargetMachineRegistry::entry*, false,
62 TargetMachineRegistry::Parser>
Chris Lattnercbb34a72005-06-25 03:00:34 +000063MArch("march", cl::desc("Architecture to generate code for:"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000064
Jim Laskeyb1e11802005-09-01 21:38:21 +000065static cl::opt<std::string>
66MCPU("mcpu",
Chris Lattner7b7593c2005-10-23 22:35:42 +000067 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
Jim Laskeyb1e11802005-09-01 21:38:21 +000068 cl::value_desc("cpu-name"),
69 cl::init(""));
70
71static cl::list<std::string>
72MAttrs("mattr",
73 cl::CommaSeparated,
Chris Lattner7b7593c2005-10-23 22:35:42 +000074 cl::desc("Target specific attributes (-mattr=help for details)"),
Chris Lattner20947252005-10-23 22:37:13 +000075 cl::value_desc("a1,+a2,-a3,..."));
Jim Laskeyb1e11802005-09-01 21:38:21 +000076
Chris Lattner812125a2005-06-25 03:32:05 +000077cl::opt<TargetMachine::CodeGenFileType>
78FileType("filetype", cl::init(TargetMachine::AssemblyFile),
79 cl::desc("Choose a file type (not all types are supported by all targets):"),
80 cl::values(
81 clEnumValN(TargetMachine::AssemblyFile, "asm",
82 " Emit an assembly ('.s') file"),
83 clEnumValN(TargetMachine::ObjectFile, "obj",
Chris Lattner07be8d42005-10-22 22:00:45 +000084 " Emit a native object ('.o') file [experimental]"),
Chris Lattner812125a2005-06-25 03:32:05 +000085 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
Nate Begeman712b8352006-08-23 21:29:52 +000086 " Emit a native dynamic library ('.so') file"
87 " [experimental]"),
Chris Lattner812125a2005-06-25 03:32:05 +000088 clEnumValEnd));
89
Reid Spencer4418c2b2005-07-28 02:25:30 +000090cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
Jeff Cohend29b6aa2005-07-30 18:33:25 +000091 cl::desc("Do not verify input module"));
Reid Spencer4418c2b2005-07-28 02:25:30 +000092
Chris Lattner812125a2005-06-25 03:32:05 +000093
94// GetFileNameRoot - Helper function to get the basename of a filename.
Chris Lattnerb5881f12003-04-25 05:26:11 +000095static inline std::string
Chris Lattnere45110e2004-07-11 04:03:24 +000096GetFileNameRoot(const std::string &InputFilename) {
Chris Lattnerb5881f12003-04-25 05:26:11 +000097 std::string IFN = InputFilename;
98 std::string outputFilename;
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +000099 int Len = IFN.length();
John Criswellb5d09bf2003-08-28 21:42:29 +0000100 if ((Len > 2) &&
101 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
Chris Lattnerb5881f12003-04-25 05:26:11 +0000102 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +0000103 } else {
Chris Lattner3524fc22001-10-15 17:30:47 +0000104 outputFilename = IFN;
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +0000105 }
106 return outputFilename;
107}
108
Chris Lattner1911fd42006-09-04 04:14:57 +0000109static std::ostream *GetOutputStream(const char *ProgName) {
110 if (OutputFilename != "") {
111 if (OutputFilename == "-")
112 return &std::cout;
113
114 // Specified an output filename?
115 if (!Force && std::ifstream(OutputFilename.c_str())) {
116 // If force is not specified, make sure not to overwrite a file!
117 std::cerr << ProgName << ": error opening '" << OutputFilename
118 << "': file exists!\n"
119 << "Use -f command line argument to force output\n";
120 return 0;
121 }
122 // Make sure that the Out file gets unlinked from the disk if we get a
123 // SIGINT
124 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
125
126 return new std::ofstream(OutputFilename.c_str());
127 }
128
129 if (InputFilename == "-") {
130 OutputFilename = "-";
131 return &std::cout;
132 }
133
134 OutputFilename = GetFileNameRoot(InputFilename);
135
136 switch (FileType) {
137 case TargetMachine::AssemblyFile:
Anton Korobeynikov50276522008-04-23 22:29:24 +0000138 if (MArch->Name[0] == 'c') {
139 if (MArch->Name[1] == 0)
140 OutputFilename += ".cbe.c";
141 else if (MArch->Name[1] == 'p' && MArch->Name[2] == 'p')
142 OutputFilename += ".cpp";
143 else
144 OutputFilename += ".s";
145 } else
Chris Lattner1911fd42006-09-04 04:14:57 +0000146 OutputFilename += ".s";
Chris Lattner1911fd42006-09-04 04:14:57 +0000147 break;
148 case TargetMachine::ObjectFile:
149 OutputFilename += ".o";
150 break;
151 case TargetMachine::DynamicLibrary:
152 OutputFilename += LTDL_SHLIB_EXT;
153 break;
154 }
155
156 if (!Force && std::ifstream(OutputFilename.c_str())) {
157 // If force is not specified, make sure not to overwrite a file!
158 std::cerr << ProgName << ": error opening '" << OutputFilename
159 << "': file exists!\n"
160 << "Use -f command line argument to force output\n";
161 return 0;
162 }
163
164 // Make sure that the Out file gets unlinked from the disk if we get a
165 // SIGINT
166 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
167
168 std::ostream *Out = new std::ofstream(OutputFilename.c_str());
169 if (!Out->good()) {
170 std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
171 delete Out;
172 return 0;
173 }
174
175 return Out;
176}
Vikram S. Adve805eb962001-09-18 13:10:45 +0000177
Chris Lattner5b836c42003-06-20 15:49:04 +0000178// main - Entry point for the llc compiler.
179//
180int main(int argc, char **argv) {
Chris Lattnerc30598b2006-12-06 01:18:01 +0000181 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Dan Gohman82a13c92007-10-08 15:45:12 +0000182 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
Chris Lattner1a735402007-05-06 04:55:19 +0000183 sys::PrintStackTraceOnErrorSignal();
Chris Lattner364d1202004-02-19 20:32:39 +0000184
Chris Lattner1a735402007-05-06 04:55:19 +0000185 // Load the module to be compiled...
186 std::string ErrorMessage;
187 std::auto_ptr<Module> M;
188
Chris Lattner744879e2007-05-06 09:32:02 +0000189 std::auto_ptr<MemoryBuffer> Buffer(
Chris Lattner065344d2007-05-06 23:45:49 +0000190 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
Chris Lattner744879e2007-05-06 09:32:02 +0000191 if (Buffer.get())
192 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
Chris Lattner1a735402007-05-06 04:55:19 +0000193 if (M.get() == 0) {
Gabor Greifa99be512007-07-05 17:07:56 +0000194 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
Chris Lattner1a735402007-05-06 04:55:19 +0000195 std::cerr << "Reason: " << ErrorMessage << "\n";
196 return 1;
197 }
198 Module &mod = *M.get();
199
200 // If we are supposed to override the target triple, do so now.
201 if (!TargetTriple.empty())
202 mod.setTargetTriple(TargetTriple);
203
204 // Allocate target machine. First, check whether the user has
205 // explicitly specified an architecture to compile for.
206 if (MArch == 0) {
207 std::string Err;
208 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
209 if (MArch == 0) {
210 std::cerr << argv[0] << ": error auto-selecting target for module '"
211 << Err << "'. Please use the -march option to explicitly "
212 << "pick a target.\n";
Chris Lattnerbb433502003-08-24 14:02:14 +0000213 return 1;
Chris Lattnere45110e2004-07-11 04:03:24 +0000214 }
Chris Lattner63342052002-10-29 21:12:46 +0000215 }
Chris Lattner1a735402007-05-06 04:55:19 +0000216
217 // Package up features to be passed to target/subtarget
218 std::string FeaturesStr;
219 if (MCPU.size() || MAttrs.size()) {
220 SubtargetFeatures Features;
221 Features.setCPU(MCPU);
222 for (unsigned i = 0; i != MAttrs.size(); ++i)
223 Features.AddFeature(MAttrs[i]);
224 FeaturesStr = Features.getString();
225 }
226
227 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
228 assert(target.get() && "Could not allocate target machine!");
229 TargetMachine &Target = *target.get();
230
231 // Figure out where we are going to send the output...
232 std::ostream *Out = GetOutputStream(argv[0]);
233 if (Out == 0) return 1;
234
235 // If this target requires addPassesToEmitWholeFile, do it now. This is
236 // used by strange things like the C backend.
237 if (Target.WantsWholeFile()) {
238 PassManager PM;
239 PM.add(new TargetData(*Target.getTargetData()));
240 if (!NoVerify)
241 PM.add(createVerifierPass());
242
243 // Ask the target to add backend passes as necessary.
244 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
245 std::cerr << argv[0] << ": target does not support generation of this"
246 << " file type!\n";
247 if (Out != &std::cout) delete Out;
248 // And the Out file is empty and useless, so remove it now.
249 sys::Path(OutputFilename).eraseFromDisk();
250 return 1;
251 }
252 PM.run(mod);
253 } else {
254 // Build up all of the passes that we want to do to the module.
Dan Gohman33ef2bb2008-04-16 15:56:26 +0000255 ExistingModuleProvider Provider(M.release());
256 FunctionPassManager Passes(&Provider);
Chris Lattner1a735402007-05-06 04:55:19 +0000257 Passes.add(new TargetData(*Target.getTargetData()));
258
259#ifndef NDEBUG
260 if (!NoVerify)
261 Passes.add(createVerifierPass());
262#endif
263
264 // Ask the target to add backend passes as necessary.
265 MachineCodeEmitter *MCE = 0;
266
267 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
268 default:
269 assert(0 && "Invalid file model!");
270 return 1;
271 case FileModel::Error:
272 std::cerr << argv[0] << ": target does not support generation of this"
273 << " file type!\n";
274 if (Out != &std::cout) delete Out;
275 // And the Out file is empty and useless, so remove it now.
276 sys::Path(OutputFilename).eraseFromDisk();
277 return 1;
278 case FileModel::AsmFile:
279 break;
280 case FileModel::MachOFile:
281 MCE = AddMachOWriter(Passes, *Out, Target);
282 break;
283 case FileModel::ElfFile:
284 MCE = AddELFWriter(Passes, *Out, Target);
285 break;
286 }
287
288 if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) {
289 std::cerr << argv[0] << ": target does not support generation of this"
290 << " file type!\n";
291 if (Out != &std::cout) delete Out;
292 // And the Out file is empty and useless, so remove it now.
293 sys::Path(OutputFilename).eraseFromDisk();
294 return 1;
295 }
296
297 Passes.doInitialization();
298
299 // Run our queue of passes all at once now, efficiently.
300 // TODO: this could lazily stream functions out of the module.
301 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
302 if (!I->isDeclaration())
303 Passes.run(*I);
304
305 Passes.doFinalization();
306 }
307
308 // Delete the ostream if it's not a stdout stream
309 if (Out != &std::cout) delete Out;
310
311 return 0;
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +0000312}