blob: 929f70215b947c90c260e78e1f8a4bf7ebcd962b [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"
Jim Laskeyb1e11802005-09-01 21:38:21 +000019#include "llvm/Target/SubtargetFeature.h"
Owen Anderson07000c62006-05-12 06:33:49 +000020#include "llvm/Target/TargetData.h"
Vikram S. Adve805eb962001-09-18 13:10:45 +000021#include "llvm/Target/TargetMachine.h"
Chris Lattnere45110e2004-07-11 04:03:24 +000022#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner65f1b892002-05-07 20:03:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner46ac43c2001-09-07 21:26:31 +000024#include "llvm/Module.h"
Chris Lattner744879e2007-05-06 09:32:02 +000025#include "llvm/ModuleProvider.h"
Chris Lattnercd50d3f2002-01-31 00:46:45 +000026#include "llvm/PassManager.h"
Vikram S. Adve7d0ba022002-09-16 16:35:34 +000027#include "llvm/Pass.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000029#include "llvm/Support/ManagedStatic.h"
Chris Lattner1a735402007-05-06 04:55:19 +000030#include "llvm/Support/MemoryBuffer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/PluginLoader.h"
Duraid Madinaea8aed72005-12-30 02:47:21 +000032#include "llvm/Support/FileUtilities.h"
Reid Spencer4418c2b2005-07-28 02:25:30 +000033#include "llvm/Analysis/Verifier.h"
Chris Lattnerbed85ff2004-05-27 05:41:36 +000034#include "llvm/System/Signals.h"
Chris Lattner812125a2005-06-25 03:32:05 +000035#include "llvm/Config/config.h"
Reid Spenceraf303d52006-06-07 23:03:13 +000036#include "llvm/LinkAllVMCore.h"
Chris Lattner78f7e1a2001-09-19 16:52:09 +000037#include <fstream>
Reid Spencer86f42bd2004-07-04 12:20:55 +000038#include <iostream>
39#include <memory>
Brian Gaeked0fde302003-11-11 22:41:34 +000040using namespace llvm;
41
Vikram S. Adve7d0ba022002-09-16 16:35:34 +000042// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +000045//
Chris Lattnerb5881f12003-04-25 05:26:11 +000046static cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000047InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000048
Chris Lattnerb5881f12003-04-25 05:26:11 +000049static cl::opt<std::string>
Chris Lattner5ff62e92002-07-22 02:10:13 +000050OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
53
Chris Lattner178e0c42005-11-08 02:12:17 +000054static cl::opt<bool> Fast("fast",
55 cl::desc("Generate code quickly, potentially sacrificing code quality"));
56
Chris Lattnerf33b8662005-12-16 04:59:57 +000057static cl::opt<std::string>
Chris Lattnerbe193832005-12-16 05:19:55 +000058TargetTriple("mtriple", cl::desc("Override target triple for module"));
Chris Lattner178e0c42005-11-08 02:12:17 +000059
Gordon Henriksen4b2b9402007-10-17 21:28:48 +000060static cl::opt<const TargetMachineRegistry::entry*, false,
61 TargetMachineRegistry::Parser>
Chris Lattnercbb34a72005-06-25 03:00:34 +000062MArch("march", cl::desc("Architecture to generate code for:"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000063
Jim Laskeyb1e11802005-09-01 21:38:21 +000064static cl::opt<std::string>
65MCPU("mcpu",
Chris Lattner7b7593c2005-10-23 22:35:42 +000066 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
Jim Laskeyb1e11802005-09-01 21:38:21 +000067 cl::value_desc("cpu-name"),
68 cl::init(""));
69
70static cl::list<std::string>
71MAttrs("mattr",
72 cl::CommaSeparated,
Chris Lattner7b7593c2005-10-23 22:35:42 +000073 cl::desc("Target specific attributes (-mattr=help for details)"),
Chris Lattner20947252005-10-23 22:37:13 +000074 cl::value_desc("a1,+a2,-a3,..."));
Jim Laskeyb1e11802005-09-01 21:38:21 +000075
Chris Lattner812125a2005-06-25 03:32:05 +000076cl::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",
Chris Lattner07be8d42005-10-22 22:00:45 +000083 " Emit a native object ('.o') file [experimental]"),
Chris Lattner812125a2005-06-25 03:32:05 +000084 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
Nate Begeman712b8352006-08-23 21:29:52 +000085 " Emit a native dynamic library ('.so') file"
86 " [experimental]"),
Chris Lattner812125a2005-06-25 03:32:05 +000087 clEnumValEnd));
88
Reid Spencer4418c2b2005-07-28 02:25:30 +000089cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
Jeff Cohend29b6aa2005-07-30 18:33:25 +000090 cl::desc("Do not verify input module"));
Reid Spencer4418c2b2005-07-28 02:25:30 +000091
Chris Lattner812125a2005-06-25 03:32:05 +000092
93// GetFileNameRoot - Helper function to get the basename of a filename.
Chris Lattnerb5881f12003-04-25 05:26:11 +000094static inline std::string
Chris Lattnere45110e2004-07-11 04:03:24 +000095GetFileNameRoot(const std::string &InputFilename) {
Chris Lattnerb5881f12003-04-25 05:26:11 +000096 std::string IFN = InputFilename;
97 std::string outputFilename;
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +000098 int Len = IFN.length();
John Criswellb5d09bf2003-08-28 21:42:29 +000099 if ((Len > 2) &&
100 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
Chris Lattnerb5881f12003-04-25 05:26:11 +0000101 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +0000102 } else {
Chris Lattner3524fc22001-10-15 17:30:47 +0000103 outputFilename = IFN;
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +0000104 }
105 return outputFilename;
106}
107
Chris Lattner1911fd42006-09-04 04:14:57 +0000108static 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}
Vikram S. Adve805eb962001-09-18 13:10:45 +0000171
Chris Lattner5b836c42003-06-20 15:49:04 +0000172// main - Entry point for the llc compiler.
173//
174int main(int argc, char **argv) {
Chris Lattnerc30598b2006-12-06 01:18:01 +0000175 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Dan Gohman82a13c92007-10-08 15:45:12 +0000176 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
Chris Lattner1a735402007-05-06 04:55:19 +0000177 sys::PrintStackTraceOnErrorSignal();
Chris Lattner364d1202004-02-19 20:32:39 +0000178
Chris Lattner1a735402007-05-06 04:55:19 +0000179 // Load the module to be compiled...
180 std::string ErrorMessage;
181 std::auto_ptr<Module> M;
182
Chris Lattner744879e2007-05-06 09:32:02 +0000183 std::auto_ptr<MemoryBuffer> Buffer(
Chris Lattner065344d2007-05-06 23:45:49 +0000184 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
Chris Lattner744879e2007-05-06 09:32:02 +0000185 if (Buffer.get())
186 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
Chris Lattner1a735402007-05-06 04:55:19 +0000187 if (M.get() == 0) {
Gabor Greifa99be512007-07-05 17:07:56 +0000188 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
Chris Lattner1a735402007-05-06 04:55:19 +0000189 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";
Chris Lattnerbb433502003-08-24 14:02:14 +0000207 return 1;
Chris Lattnere45110e2004-07-11 04:03:24 +0000208 }
Chris Lattner63342052002-10-29 21:12:46 +0000209 }
Chris Lattner1a735402007-05-06 04:55:19 +0000210
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;
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +0000305}