blob: d179efc03831c7cf22f4f344f5fb1655d54d223a [file] [log] [blame]
Chris Lattner67e08422003-06-20 15:49:04 +00001//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-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 Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2cf137b2001-09-07 22:20:50 +00009//
Brian Gaeke33e83b62004-03-16 21:47:20 +000010// This is the llc code generator driver. It provides a convenient
Misha Brukman650ba8e2005-04-22 00:00:37 +000011// command-line interface for generating native assembly-language code
Gabor Greife16561c2007-07-05 17:07:56 +000012// or C code, given LLVM bitcode.
Chris Lattner2cf137b2001-09-07 22:20:50 +000013//
Chris Lattnerb27d4742001-10-04 01:40:53 +000014//===----------------------------------------------------------------------===//
Vikram S. Adve2d94a342001-07-21 12:42:29 +000015
Chris Lattner6dd290a2007-05-06 04:55:19 +000016#include "llvm/Bitcode/ReaderWriter.h"
Bill Wendlingfe5ee142007-02-08 01:41:07 +000017#include "llvm/CodeGen/FileWriters.h"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000018#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Jim Laskey19058c32005-09-01 21:38:21 +000019#include "llvm/Target/SubtargetFeature.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000020#include "llvm/Target/TargetData.h"
Vikram S. Adve9d409352001-09-18 13:10:45 +000021#include "llvm/Target/TargetMachine.h"
Chris Lattner6142ca82004-07-11 04:03:24 +000022#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner89a20ef2002-05-07 20:03:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattnered226062001-09-07 21:26:31 +000024#include "llvm/Module.h"
Chris Lattnerf5599ef2007-05-06 09:32:02 +000025#include "llvm/ModuleProvider.h"
Chris Lattner7139f282002-01-31 00:46:45 +000026#include "llvm/PassManager.h"
Vikram S. Adveeb818692002-09-16 16:35:34 +000027#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
Chris Lattner76d46322006-12-06 01:18:01 +000029#include "llvm/Support/ManagedStatic.h"
Chris Lattner6dd290a2007-05-06 04:55:19 +000030#include "llvm/Support/MemoryBuffer.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/PluginLoader.h"
Duraid Madinace551ba2005-12-30 02:47:21 +000032#include "llvm/Support/FileUtilities.h"
Reid Spencer8e3830d2005-07-28 02:25:30 +000033#include "llvm/Analysis/Verifier.h"
Chris Lattner278f5152004-05-27 05:41:36 +000034#include "llvm/System/Signals.h"
Chris Lattner06fcc4c2005-06-25 03:32:05 +000035#include "llvm/Config/config.h"
Reid Spencer5113dc52006-06-07 23:03:13 +000036#include "llvm/LinkAllVMCore.h"
Chris Lattner46f1b612001-09-19 16:52:09 +000037#include <fstream>
Reid Spencerf0ebb252004-07-04 12:20:55 +000038#include <iostream>
39#include <memory>
Brian Gaeke960707c2003-11-11 22:41:34 +000040using namespace llvm;
41
Vikram S. Adveeb818692002-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 Brukman650ba8e2005-04-22 00:00:37 +000045//
Chris Lattnerd64b2de2003-04-25 05:26:11 +000046static cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000047InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000048
Chris Lattnerd64b2de2003-04-25 05:26:11 +000049static cl::opt<std::string>
Chris Lattnerf5cad152002-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 Lattner731055e2005-11-08 02:12:17 +000054static cl::opt<bool> Fast("fast",
55 cl::desc("Generate code quickly, potentially sacrificing code quality"));
56
Chris Lattnere568b882005-12-16 04:59:57 +000057static cl::opt<std::string>
Chris Lattner08a04cb2005-12-16 05:19:55 +000058TargetTriple("mtriple", cl::desc("Override target triple for module"));
Chris Lattner731055e2005-11-08 02:12:17 +000059
Gordon Henriksenef5d08f2007-10-17 21:28:48 +000060static cl::opt<const TargetMachineRegistry::entry*, false,
61 TargetMachineRegistry::Parser>
Chris Lattner09b0eb32005-06-25 03:00:34 +000062MArch("march", cl::desc("Architecture to generate code for:"));
Misha Brukman650ba8e2005-04-22 00:00:37 +000063
Jim Laskey19058c32005-09-01 21:38:21 +000064static cl::opt<std::string>
65MCPU("mcpu",
Chris Lattner0b2bf4c2005-10-23 22:35:42 +000066 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
Jim Laskey19058c32005-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 Lattner0b2bf4c2005-10-23 22:35:42 +000073 cl::desc("Target specific attributes (-mattr=help for details)"),
Chris Lattner41548482005-10-23 22:37:13 +000074 cl::value_desc("a1,+a2,-a3,..."));
Jim Laskey19058c32005-09-01 21:38:21 +000075
Chris Lattner06fcc4c2005-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 Lattner711a5fe2005-10-22 22:00:45 +000083 " Emit a native object ('.o') file [experimental]"),
Chris Lattner06fcc4c2005-06-25 03:32:05 +000084 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
Nate Begemana147cbf2006-08-23 21:29:52 +000085 " Emit a native dynamic library ('.so') file"
86 " [experimental]"),
Chris Lattner06fcc4c2005-06-25 03:32:05 +000087 clEnumValEnd));
88
Reid Spencer8e3830d2005-07-28 02:25:30 +000089cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
Jeff Cohen546fd592005-07-30 18:33:25 +000090 cl::desc("Do not verify input module"));
Reid Spencer8e3830d2005-07-28 02:25:30 +000091
Chris Lattner06fcc4c2005-06-25 03:32:05 +000092
93// GetFileNameRoot - Helper function to get the basename of a filename.
Chris Lattnerd64b2de2003-04-25 05:26:11 +000094static inline std::string
Chris Lattner6142ca82004-07-11 04:03:24 +000095GetFileNameRoot(const std::string &InputFilename) {
Chris Lattnerd64b2de2003-04-25 05:26:11 +000096 std::string IFN = InputFilename;
97 std::string outputFilename;
Vikram S. Adve2f084b22001-10-14 23:29:28 +000098 int Len = IFN.length();
John Criswella289abf2003-08-28 21:42:29 +000099 if ((Len > 2) &&
100 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
Chris Lattnerd64b2de2003-04-25 05:26:11 +0000101 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000102 } else {
Chris Lattner97fd6c42001-10-15 17:30:47 +0000103 outputFilename = IFN;
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000104 }
105 return outputFilename;
106}
107
Chris Lattner12e97302006-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:
Anton Korobeynikov78695032008-04-23 22:29:24 +0000137 if (MArch->Name[0] == 'c') {
138 if (MArch->Name[1] == 0)
139 OutputFilename += ".cbe.c";
140 else if (MArch->Name[1] == 'p' && MArch->Name[2] == 'p')
141 OutputFilename += ".cpp";
142 else
143 OutputFilename += ".s";
144 } else
Chris Lattner12e97302006-09-04 04:14:57 +0000145 OutputFilename += ".s";
Chris Lattner12e97302006-09-04 04:14:57 +0000146 break;
147 case TargetMachine::ObjectFile:
148 OutputFilename += ".o";
149 break;
150 case TargetMachine::DynamicLibrary:
151 OutputFilename += LTDL_SHLIB_EXT;
152 break;
153 }
154
155 if (!Force && std::ifstream(OutputFilename.c_str())) {
156 // If force is not specified, make sure not to overwrite a file!
157 std::cerr << ProgName << ": error opening '" << OutputFilename
158 << "': file exists!\n"
159 << "Use -f command line argument to force output\n";
160 return 0;
161 }
162
163 // Make sure that the Out file gets unlinked from the disk if we get a
164 // SIGINT
165 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
166
167 std::ostream *Out = new std::ofstream(OutputFilename.c_str());
168 if (!Out->good()) {
169 std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
170 delete Out;
171 return 0;
172 }
173
174 return Out;
175}
Vikram S. Adve9d409352001-09-18 13:10:45 +0000176
Chris Lattner67e08422003-06-20 15:49:04 +0000177// main - Entry point for the llc compiler.
178//
179int main(int argc, char **argv) {
Chris Lattner76d46322006-12-06 01:18:01 +0000180 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Dan Gohman2c6a8212007-10-08 15:45:12 +0000181 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
Chris Lattner6dd290a2007-05-06 04:55:19 +0000182 sys::PrintStackTraceOnErrorSignal();
Chris Lattner69e896b2004-02-19 20:32:39 +0000183
Chris Lattner6dd290a2007-05-06 04:55:19 +0000184 // Load the module to be compiled...
185 std::string ErrorMessage;
186 std::auto_ptr<Module> M;
187
Chris Lattnerf5599ef2007-05-06 09:32:02 +0000188 std::auto_ptr<MemoryBuffer> Buffer(
Chris Lattner9e9a34c2007-05-06 23:45:49 +0000189 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
Chris Lattnerf5599ef2007-05-06 09:32:02 +0000190 if (Buffer.get())
191 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
Chris Lattner6dd290a2007-05-06 04:55:19 +0000192 if (M.get() == 0) {
Gabor Greife16561c2007-07-05 17:07:56 +0000193 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
Chris Lattner6dd290a2007-05-06 04:55:19 +0000194 std::cerr << "Reason: " << ErrorMessage << "\n";
195 return 1;
196 }
197 Module &mod = *M.get();
198
199 // If we are supposed to override the target triple, do so now.
200 if (!TargetTriple.empty())
201 mod.setTargetTriple(TargetTriple);
202
203 // Allocate target machine. First, check whether the user has
204 // explicitly specified an architecture to compile for.
205 if (MArch == 0) {
206 std::string Err;
207 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
208 if (MArch == 0) {
209 std::cerr << argv[0] << ": error auto-selecting target for module '"
210 << Err << "'. Please use the -march option to explicitly "
211 << "pick a target.\n";
Chris Lattnerb1492402003-08-24 14:02:14 +0000212 return 1;
Chris Lattner6142ca82004-07-11 04:03:24 +0000213 }
Chris Lattner5667f0e2002-10-29 21:12:46 +0000214 }
Chris Lattner6dd290a2007-05-06 04:55:19 +0000215
216 // Package up features to be passed to target/subtarget
217 std::string FeaturesStr;
218 if (MCPU.size() || MAttrs.size()) {
219 SubtargetFeatures Features;
220 Features.setCPU(MCPU);
221 for (unsigned i = 0; i != MAttrs.size(); ++i)
222 Features.AddFeature(MAttrs[i]);
223 FeaturesStr = Features.getString();
224 }
225
226 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
227 assert(target.get() && "Could not allocate target machine!");
228 TargetMachine &Target = *target.get();
229
230 // Figure out where we are going to send the output...
231 std::ostream *Out = GetOutputStream(argv[0]);
232 if (Out == 0) return 1;
233
234 // If this target requires addPassesToEmitWholeFile, do it now. This is
235 // used by strange things like the C backend.
236 if (Target.WantsWholeFile()) {
237 PassManager PM;
238 PM.add(new TargetData(*Target.getTargetData()));
239 if (!NoVerify)
240 PM.add(createVerifierPass());
241
242 // Ask the target to add backend passes as necessary.
243 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
244 std::cerr << argv[0] << ": target does not support generation of this"
245 << " file type!\n";
246 if (Out != &std::cout) delete Out;
247 // And the Out file is empty and useless, so remove it now.
248 sys::Path(OutputFilename).eraseFromDisk();
249 return 1;
250 }
251 PM.run(mod);
252 } else {
253 // Build up all of the passes that we want to do to the module.
Dan Gohmanbd2613d2008-04-16 15:56:26 +0000254 ExistingModuleProvider Provider(M.release());
255 FunctionPassManager Passes(&Provider);
Chris Lattner6dd290a2007-05-06 04:55:19 +0000256 Passes.add(new TargetData(*Target.getTargetData()));
257
258#ifndef NDEBUG
259 if (!NoVerify)
260 Passes.add(createVerifierPass());
261#endif
262
263 // Ask the target to add backend passes as necessary.
264 MachineCodeEmitter *MCE = 0;
265
266 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
267 default:
268 assert(0 && "Invalid file model!");
269 return 1;
270 case FileModel::Error:
271 std::cerr << argv[0] << ": target does not support generation of this"
272 << " file type!\n";
273 if (Out != &std::cout) delete Out;
274 // And the Out file is empty and useless, so remove it now.
275 sys::Path(OutputFilename).eraseFromDisk();
276 return 1;
277 case FileModel::AsmFile:
278 break;
279 case FileModel::MachOFile:
280 MCE = AddMachOWriter(Passes, *Out, Target);
281 break;
282 case FileModel::ElfFile:
283 MCE = AddELFWriter(Passes, *Out, Target);
284 break;
285 }
286
287 if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) {
288 std::cerr << argv[0] << ": target does not support generation of this"
289 << " file type!\n";
290 if (Out != &std::cout) delete Out;
291 // And the Out file is empty and useless, so remove it now.
292 sys::Path(OutputFilename).eraseFromDisk();
293 return 1;
294 }
295
296 Passes.doInitialization();
297
298 // Run our queue of passes all at once now, efficiently.
299 // TODO: this could lazily stream functions out of the module.
300 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
301 if (!I->isDeclaration())
302 Passes.run(*I);
303
304 Passes.doFinalization();
305 }
306
307 // Delete the ostream if it's not a stdout stream
308 if (Out != &std::cout) delete Out;
309
310 return 0;
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000311}