1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Pass.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Support/IRReader.h"
24 #include "llvm/CodeGen/FileWriters.h"
25 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
26 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
27 #include "llvm/CodeGen/ObjectCodeEmitter.h"
28 #include "llvm/Config/config.h"
29 #include "llvm/LinkAllVMCore.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PluginLoader.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/System/Host.h"
39 #include "llvm/System/Signals.h"
40 #include "llvm/Target/SubtargetFeature.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegistry.h"
44 #include "llvm/Target/TargetSelect.h"
45 #include "llvm/Transforms/Scalar.h"
49 // General options for llc. Other pass-specific options are specified
50 // within the corresponding llc passes, and target-specific options
51 // and back-end code generation options are specified with the target machine.
53 static cl::opt<std::string>
54 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
56 static cl::opt<std::string>
57 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
60 Force("f", cl::desc("Enable binary output on terminals"));
62 // Determine optimization level.
65 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
71 static cl::opt<std::string>
72 TargetTriple("mtriple", cl::desc("Override target triple for module"));
74 static cl::opt<std::string>
75 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
77 static cl::opt<std::string>
79 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
80 cl::value_desc("cpu-name"),
83 static cl::list<std::string>
86 cl::desc("Target specific attributes (-mattr=help for details)"),
87 cl::value_desc("a1,+a2,-a3,..."));
89 cl::opt<TargetMachine::CodeGenFileType>
90 FileType("filetype", cl::init(TargetMachine::AssemblyFile),
91 cl::desc("Choose a file type (not all types are supported by all targets):"),
93 clEnumValN(TargetMachine::AssemblyFile, "asm",
94 "Emit an assembly ('.s') file"),
95 clEnumValN(TargetMachine::ObjectFile, "obj",
96 "Emit a native object ('.o') file [experimental]"),
97 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
98 "Emit a native dynamic library ('.so') file"
102 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
103 cl::desc("Do not verify input module"));
107 DisableRedZone("disable-red-zone",
108 cl::desc("Do not emit code that uses the red zone."),
112 NoImplicitFloats("no-implicit-float",
113 cl::desc("Don't generate implicit floating point instructions (x86-only)"),
116 // GetFileNameRoot - Helper function to get the basename of a filename.
117 static inline std::string
118 GetFileNameRoot(const std::string &InputFilename) {
119 std::string IFN = InputFilename;
120 std::string outputFilename;
121 int Len = IFN.length();
124 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
125 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
126 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
128 outputFilename = IFN;
130 return outputFilename;
133 static formatted_raw_ostream *GetOutputStream(const char *TargetName,
134 const char *ProgName) {
135 if (OutputFilename != "") {
136 if (OutputFilename == "-")
139 // Make sure that the Out file gets unlinked from the disk if we get a
141 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
144 raw_fd_ostream *FDOut =
145 new raw_fd_ostream(OutputFilename.c_str(), error,
146 raw_fd_ostream::F_Binary);
147 if (!error.empty()) {
148 errs() << error << '\n';
152 formatted_raw_ostream *Out =
153 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
158 if (InputFilename == "-") {
159 OutputFilename = "-";
163 OutputFilename = GetFileNameRoot(InputFilename);
167 case TargetMachine::AssemblyFile:
168 if (TargetName[0] == 'c') {
169 if (TargetName[1] == 0)
170 OutputFilename += ".cbe.c";
171 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
172 OutputFilename += ".cpp";
174 OutputFilename += ".s";
176 OutputFilename += ".s";
178 case TargetMachine::ObjectFile:
179 OutputFilename += ".o";
182 case TargetMachine::DynamicLibrary:
183 OutputFilename += LTDL_SHLIB_EXT;
188 // Make sure that the Out file gets unlinked from the disk if we get a
190 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
193 unsigned OpenFlags = 0;
194 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
195 raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
197 if (!error.empty()) {
198 errs() << error << '\n';
203 formatted_raw_ostream *Out =
204 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
209 // main - Entry point for the llc compiler.
211 int main(int argc, char **argv) {
212 sys::PrintStackTraceOnErrorSignal();
213 PrettyStackTraceProgram X(argc, argv);
215 // Enable debug stream buffering.
216 EnableDebugBuffering = true;
218 LLVMContext &Context = getGlobalContext();
219 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
221 // Initialize targets first, so that --version shows registered targets.
222 InitializeAllTargets();
223 InitializeAllAsmPrinters();
225 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
227 // Load the module to be compiled...
229 std::auto_ptr<Module> M;
231 M.reset(ParseIRFile(InputFilename, Err, Context));
233 Err.Print(argv[0], errs());
236 Module &mod = *M.get();
238 // If we are supposed to override the target triple, do so now.
239 if (!TargetTriple.empty())
240 mod.setTargetTriple(TargetTriple);
242 Triple TheTriple(mod.getTargetTriple());
243 if (TheTriple.getTriple().empty())
244 TheTriple.setTriple(sys::getHostTriple());
246 // Allocate target machine. First, check whether the user has explicitly
247 // specified an architecture to compile for. If so we have to look it up by
248 // name, because it might be a backend that has no mapping to a target triple.
249 const Target *TheTarget = 0;
250 if (!MArch.empty()) {
251 for (TargetRegistry::iterator it = TargetRegistry::begin(),
252 ie = TargetRegistry::end(); it != ie; ++it) {
253 if (MArch == it->getName()) {
260 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
264 // Adjust the triple to match (if known), otherwise stick with the
265 // module/host triple.
266 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
267 if (Type != Triple::UnknownArch)
268 TheTriple.setArch(Type);
271 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
272 if (TheTarget == 0) {
273 errs() << argv[0] << ": error auto-selecting target for module '"
274 << Err << "'. Please use the -march option to explicitly "
275 << "pick a target.\n";
280 // Package up features to be passed to target/subtarget
281 std::string FeaturesStr;
282 if (MCPU.size() || MAttrs.size()) {
283 SubtargetFeatures Features;
284 Features.setCPU(MCPU);
285 for (unsigned i = 0; i != MAttrs.size(); ++i)
286 Features.AddFeature(MAttrs[i]);
287 FeaturesStr = Features.getString();
290 std::auto_ptr<TargetMachine>
291 target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
292 assert(target.get() && "Could not allocate target machine!");
293 TargetMachine &Target = *target.get();
295 // Figure out where we are going to send the output...
296 formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(), argv[0]);
297 if (Out == 0) return 1;
299 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
302 errs() << argv[0] << ": invalid optimization level.\n";
305 case '0': OLvl = CodeGenOpt::None; break;
306 case '1': OLvl = CodeGenOpt::Less; break;
307 case '2': OLvl = CodeGenOpt::Default; break;
308 case '3': OLvl = CodeGenOpt::Aggressive; break;
311 // If this target requires addPassesToEmitWholeFile, do it now. This is
312 // used by strange things like the C backend.
313 if (Target.WantsWholeFile()) {
316 // Add the target data from the target machine, if it exists, or the module.
317 if (const TargetData *TD = Target.getTargetData())
318 PM.add(new TargetData(*TD));
320 PM.add(new TargetData(&mod));
323 PM.add(createVerifierPass());
325 // Ask the target to add backend passes as necessary.
326 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, OLvl)) {
327 errs() << argv[0] << ": target does not support generation of this"
329 if (Out != &fouts()) delete Out;
330 // And the Out file is empty and useless, so remove it now.
331 sys::Path(OutputFilename).eraseFromDisk();
336 // Build up all of the passes that we want to do to the module.
337 ExistingModuleProvider Provider(M.release());
338 FunctionPassManager Passes(&Provider);
340 // Add the target data from the target machine, if it exists, or the module.
341 if (const TargetData *TD = Target.getTargetData())
342 Passes.add(new TargetData(*TD));
344 Passes.add(new TargetData(&mod));
348 Passes.add(createVerifierPass());
351 // Ask the target to add backend passes as necessary.
352 ObjectCodeEmitter *OCE = 0;
354 // Override default to generate verbose assembly.
355 Target.setAsmVerbosityDefault(true);
357 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, OLvl)) {
359 assert(0 && "Invalid file model!");
361 case FileModel::Error:
362 errs() << argv[0] << ": target does not support generation of this"
364 if (Out != &fouts()) delete Out;
365 // And the Out file is empty and useless, so remove it now.
366 sys::Path(OutputFilename).eraseFromDisk();
368 case FileModel::AsmFile:
369 case FileModel::MachOFile:
371 case FileModel::ElfFile:
372 OCE = AddELFWriter(Passes, *Out, Target);
376 if (Target.addPassesToEmitFileFinish(Passes, OCE, OLvl)) {
377 errs() << argv[0] << ": target does not support generation of this"
379 if (Out != &fouts()) delete Out;
380 // And the Out file is empty and useless, so remove it now.
381 sys::Path(OutputFilename).eraseFromDisk();
385 Passes.doInitialization();
387 // Run our queue of passes all at once now, efficiently.
388 // TODO: this could lazily stream functions out of the module.
389 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
390 if (!I->isDeclaration()) {
392 I->addFnAttr(Attribute::NoRedZone);
393 if (NoImplicitFloats)
394 I->addFnAttr(Attribute::NoImplicitFloat);
398 Passes.doFinalization();
401 // Delete the ostream if it's not a stdout stream
402 if (Out != &fouts()) delete Out;