Add new function attribute - noredzone.
[oota-llvm.git] / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/Target/SubtargetFeature.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetMachineRegistry.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Module.h"
26 #include "llvm/ModuleProvider.h"
27 #include "llvm/PassManager.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/FileUtilities.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/PluginLoader.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/RegistryParser.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Analysis/Verifier.h"
38 #include "llvm/System/Signals.h"
39 #include "llvm/Config/config.h"
40 #include "llvm/LinkAllVMCore.h"
41 #include <fstream>
42 #include <iostream>
43 #include <memory>
44 using namespace llvm;
45
46 // General options for llc.  Other pass-specific options are specified
47 // within the corresponding llc passes, and target-specific options
48 // and back-end code generation options are specified with the target machine.
49 //
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
52
53 static cl::opt<std::string>
54 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
55
56 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
57
58 // Determine optimization level.
59 static cl::opt<char>
60 OptLevel("O",
61          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
62                   "(default = '-O2')"),
63          cl::Prefix,
64          cl::ZeroOrMore,
65          cl::init(' '));
66
67 static cl::opt<std::string>
68 TargetTriple("mtriple", cl::desc("Override target triple for module"));
69
70 static cl::opt<const TargetMachineRegistry::entry*, false,
71                RegistryParser<TargetMachine> >
72 MArch("march", cl::desc("Architecture to generate code for:"));
73
74 static cl::opt<std::string>
75 MCPU("mcpu",
76   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
77   cl::value_desc("cpu-name"),
78   cl::init(""));
79
80 static cl::list<std::string>
81 MAttrs("mattr",
82   cl::CommaSeparated,
83   cl::desc("Target specific attributes (-mattr=help for details)"),
84   cl::value_desc("a1,+a2,-a3,..."));
85
86 cl::opt<TargetMachine::CodeGenFileType>
87 FileType("filetype", cl::init(TargetMachine::AssemblyFile),
88   cl::desc("Choose a file type (not all types are supported by all targets):"),
89   cl::values(
90        clEnumValN(TargetMachine::AssemblyFile, "asm",
91                   "Emit an assembly ('.s') file"),
92        clEnumValN(TargetMachine::ObjectFile, "obj",
93                   "Emit a native object ('.o') file [experimental]"),
94        clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
95                   "Emit a native dynamic library ('.so') file"
96                   " [experimental]"),
97        clEnumValEnd));
98
99 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
100                        cl::desc("Do not verify input module"));
101
102
103 static cl::opt<bool>
104 DisableRedZone("disable-red-zone",
105   cl::desc("Do not emit code that uses the red zone."),
106   cl::init(false));
107
108 // GetFileNameRoot - Helper function to get the basename of a filename.
109 static inline std::string
110 GetFileNameRoot(const std::string &InputFilename) {
111   std::string IFN = InputFilename;
112   std::string outputFilename;
113   int Len = IFN.length();
114   if ((Len > 2) &&
115       IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
116     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
117   } else {
118     outputFilename = IFN;
119   }
120   return outputFilename;
121 }
122
123 static raw_ostream *GetOutputStream(const char *ProgName) {
124   if (OutputFilename != "") {
125     if (OutputFilename == "-")
126       return &outs();
127
128     // Specified an output filename?
129     if (!Force && std::ifstream(OutputFilename.c_str())) {
130       // If force is not specified, make sure not to overwrite a file!
131       std::cerr << ProgName << ": error opening '" << OutputFilename
132                 << "': file exists!\n"
133                 << "Use -f command line argument to force output\n";
134       return 0;
135     }
136     // Make sure that the Out file gets unlinked from the disk if we get a
137     // SIGINT
138     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
139
140     std::string error;
141     raw_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), true, error);
142     if (!error.empty()) {
143       std::cerr << error << '\n';
144       delete Out;
145       return 0;
146     }
147
148     return Out;
149   }
150
151   if (InputFilename == "-") {
152     OutputFilename = "-";
153     return &outs();
154   }
155
156   OutputFilename = GetFileNameRoot(InputFilename);
157
158   bool Binary = false;
159   switch (FileType) {
160   case TargetMachine::AssemblyFile:
161     if (MArch->Name[0] == 'c') {
162       if (MArch->Name[1] == 0)
163         OutputFilename += ".cbe.c";
164       else if (MArch->Name[1] == 'p' && MArch->Name[2] == 'p')
165         OutputFilename += ".cpp";
166       else
167         OutputFilename += ".s";
168     } else
169       OutputFilename += ".s";
170     break;
171   case TargetMachine::ObjectFile:
172     OutputFilename += ".o";
173     Binary = true;
174     break;
175   case TargetMachine::DynamicLibrary:
176     OutputFilename += LTDL_SHLIB_EXT;
177     Binary = true;
178     break;
179   }
180
181   if (!Force && std::ifstream(OutputFilename.c_str())) {
182     // If force is not specified, make sure not to overwrite a file!
183     std::cerr << ProgName << ": error opening '" << OutputFilename
184                           << "': file exists!\n"
185                           << "Use -f command line argument to force output\n";
186     return 0;
187   }
188
189   // Make sure that the Out file gets unlinked from the disk if we get a
190   // SIGINT
191   sys::RemoveFileOnSignal(sys::Path(OutputFilename));
192
193   std::string error;
194   raw_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Binary, error);
195   if (!error.empty()) {
196     std::cerr << error << '\n';
197     delete Out;
198     return 0;
199   }
200
201   return Out;
202 }
203
204 // main - Entry point for the llc compiler.
205 //
206 int main(int argc, char **argv) {
207   sys::PrintStackTraceOnErrorSignal();
208   PrettyStackTraceProgram X(argc, argv);
209   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
210   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
211
212   // Load the module to be compiled...
213   std::string ErrorMessage;
214   std::auto_ptr<Module> M;
215
216   std::auto_ptr<MemoryBuffer> Buffer(
217                    MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
218   if (Buffer.get())
219     M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
220   if (M.get() == 0) {
221     std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
222     std::cerr << "Reason: " << ErrorMessage << "\n";
223     return 1;
224   }
225   Module &mod = *M.get();
226
227   // If we are supposed to override the target triple, do so now.
228   if (!TargetTriple.empty())
229     mod.setTargetTriple(TargetTriple);
230
231   // Allocate target machine.  First, check whether the user has
232   // explicitly specified an architecture to compile for.
233   if (MArch == 0) {
234     std::string Err;
235     MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
236     if (MArch == 0) {
237       std::cerr << argv[0] << ": error auto-selecting target for module '"
238                 << Err << "'.  Please use the -march option to explicitly "
239                 << "pick a target.\n";
240       return 1;
241     }
242   }
243
244   // Package up features to be passed to target/subtarget
245   std::string FeaturesStr;
246   if (MCPU.size() || MAttrs.size()) {
247     SubtargetFeatures Features;
248     Features.setCPU(MCPU);
249     for (unsigned i = 0; i != MAttrs.size(); ++i)
250       Features.AddFeature(MAttrs[i]);
251     FeaturesStr = Features.getString();
252   }
253
254   std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
255   assert(target.get() && "Could not allocate target machine!");
256   TargetMachine &Target = *target.get();
257
258   // Figure out where we are going to send the output...
259   raw_ostream *Out = GetOutputStream(argv[0]);
260   if (Out == 0) return 1;
261
262   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
263   switch (OptLevel) {
264   default:
265     std::cerr << argv[0] << ": invalid optimization level.\n";
266     return 1;
267   case ' ': break;
268   case '0': OLvl = CodeGenOpt::None; break;
269   case '1':
270   case '2': OLvl = CodeGenOpt::Default; break;
271   case '3': OLvl = CodeGenOpt::Aggressive; break;
272   }
273
274   // If this target requires addPassesToEmitWholeFile, do it now.  This is
275   // used by strange things like the C backend.
276   if (Target.WantsWholeFile()) {
277     PassManager PM;
278     PM.add(new TargetData(*Target.getTargetData()));
279     if (!NoVerify)
280       PM.add(createVerifierPass());
281
282     // Ask the target to add backend passes as necessary.
283     if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, OLvl)) {
284       std::cerr << argv[0] << ": target does not support generation of this"
285                 << " file type!\n";
286       if (Out != &outs()) delete Out;
287       // And the Out file is empty and useless, so remove it now.
288       sys::Path(OutputFilename).eraseFromDisk();
289       return 1;
290     }
291     PM.run(mod);
292   } else {
293     // Build up all of the passes that we want to do to the module.
294     ExistingModuleProvider Provider(M.release());
295     FunctionPassManager Passes(&Provider);
296     Passes.add(new TargetData(*Target.getTargetData()));
297
298 #ifndef NDEBUG
299     if (!NoVerify)
300       Passes.add(createVerifierPass());
301 #endif
302
303     // Ask the target to add backend passes as necessary.
304     MachineCodeEmitter *MCE = 0;
305
306     // Override default to generate verbose assembly.
307     Target.setAsmVerbosityDefault(true);
308
309     switch (Target.addPassesToEmitFile(Passes, *Out, FileType, OLvl)) {
310     default:
311       assert(0 && "Invalid file model!");
312       return 1;
313     case FileModel::Error:
314       std::cerr << argv[0] << ": target does not support generation of this"
315                 << " file type!\n";
316       if (Out != &outs()) delete Out;
317       // And the Out file is empty and useless, so remove it now.
318       sys::Path(OutputFilename).eraseFromDisk();
319       return 1;
320     case FileModel::AsmFile:
321       break;
322     case FileModel::MachOFile:
323       MCE = AddMachOWriter(Passes, *Out, Target);
324       break;
325     case FileModel::ElfFile:
326       MCE = AddELFWriter(Passes, *Out, Target);
327       break;
328     }
329
330     if (Target.addPassesToEmitFileFinish(Passes, MCE, OLvl)) {
331       std::cerr << argv[0] << ": target does not support generation of this"
332                 << " file type!\n";
333       if (Out != &outs()) delete Out;
334       // And the Out file is empty and useless, so remove it now.
335       sys::Path(OutputFilename).eraseFromDisk();
336       return 1;
337     }
338
339     Passes.doInitialization();
340
341     // Run our queue of passes all at once now, efficiently.
342     // TODO: this could lazily stream functions out of the module.
343     for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
344       if (!I->isDeclaration()) {
345         if (DisableRedZone)
346           I->addFnAttr(Attribute::NoRedZone);
347         Passes.run(*I);
348       }
349
350     Passes.doFinalization();
351   }
352
353   // Delete the ostream if it's not a stdout stream
354   if (Out != &outs()) delete Out;
355
356   return 0;
357 }