Change raw_fd_ostream to take flags as an optional bitmask
[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/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/Bitcode/ReaderWriter.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/FileUtilities.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/PluginLoader.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/System/Host.h"
38 #include "llvm/System/Signals.h"
39 #include "llvm/Target/SubtargetFeature.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Target/TargetSelect.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include <memory>
46 using namespace llvm;
47
48 // General options for llc.  Other pass-specific options are specified
49 // within the corresponding llc passes, and target-specific options
50 // and back-end code generation options are specified with the target machine.
51 //
52 static cl::opt<std::string>
53 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
54
55 static cl::opt<std::string>
56 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
57
58 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
59
60 // Determine optimization level.
61 static cl::opt<char>
62 OptLevel("O",
63          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
64                   "(default = '-O2')"),
65          cl::Prefix,
66          cl::ZeroOrMore,
67          cl::init(' '));
68
69 static cl::opt<std::string>
70 TargetTriple("mtriple", cl::desc("Override target triple for module"));
71
72 static cl::opt<std::string>
73 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
74
75 static cl::opt<std::string>
76 MCPU("mcpu",
77   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
78   cl::value_desc("cpu-name"),
79   cl::init(""));
80
81 static cl::list<std::string>
82 MAttrs("mattr",
83   cl::CommaSeparated,
84   cl::desc("Target specific attributes (-mattr=help for details)"),
85   cl::value_desc("a1,+a2,-a3,..."));
86
87 cl::opt<TargetMachine::CodeGenFileType>
88 FileType("filetype", cl::init(TargetMachine::AssemblyFile),
89   cl::desc("Choose a file type (not all types are supported by all targets):"),
90   cl::values(
91        clEnumValN(TargetMachine::AssemblyFile, "asm",
92                   "Emit an assembly ('.s') file"),
93        clEnumValN(TargetMachine::ObjectFile, "obj",
94                   "Emit a native object ('.o') file [experimental]"),
95        clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
96                   "Emit a native dynamic library ('.so') file"
97                   " [experimental]"),
98        clEnumValEnd));
99
100 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
101                        cl::desc("Do not verify input module"));
102
103
104 static cl::opt<bool>
105 DisableRedZone("disable-red-zone",
106   cl::desc("Do not emit code that uses the red zone."),
107   cl::init(false));
108
109 static cl::opt<bool>
110 NoImplicitFloats("no-implicit-float",
111   cl::desc("Don't generate implicit floating point instructions (x86-only)"),
112   cl::init(false));
113
114 // GetFileNameRoot - Helper function to get the basename of a filename.
115 static inline std::string
116 GetFileNameRoot(const std::string &InputFilename) {
117   std::string IFN = InputFilename;
118   std::string outputFilename;
119   int Len = IFN.length();
120   if ((Len > 2) &&
121       IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
122     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
123   } else {
124     outputFilename = IFN;
125   }
126   return outputFilename;
127 }
128
129 static formatted_raw_ostream *GetOutputStream(const char *TargetName, 
130                                               const char *ProgName) {
131   if (OutputFilename != "") {
132     if (OutputFilename == "-")
133       return &fouts();
134
135     // Make sure that the Out file gets unlinked from the disk if we get a
136     // SIGINT
137     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
138
139     std::string error;
140     raw_fd_ostream *FDOut =
141       new raw_fd_ostream(OutputFilename.c_str(), error,
142                          (Force ? raw_fd_ostream::F_Force : 0)|
143                          raw_fd_ostream::F_Binary);
144     if (!error.empty()) {
145       errs() << error << '\n';
146       if (!Force)
147         errs() << "Use -f command line argument to force output\n";
148       delete FDOut;
149       return 0;
150     }
151     formatted_raw_ostream *Out =
152       new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
153
154     return Out;
155   }
156
157   if (InputFilename == "-") {
158     OutputFilename = "-";
159     return &fouts();
160   }
161
162   OutputFilename = GetFileNameRoot(InputFilename);
163
164   bool Binary = false;
165   switch (FileType) {
166   case TargetMachine::AssemblyFile:
167     if (TargetName[0] == 'c') {
168       if (TargetName[1] == 0)
169         OutputFilename += ".cbe.c";
170       else if (TargetName[1] == 'p' && TargetName[2] == 'p')
171         OutputFilename += ".cpp";
172       else
173         OutputFilename += ".s";
174     } else
175       OutputFilename += ".s";
176     break;
177   case TargetMachine::ObjectFile:
178     OutputFilename += ".o";
179     Binary = true;
180     break;
181   case TargetMachine::DynamicLibrary:
182     OutputFilename += LTDL_SHLIB_EXT;
183     Binary = true;
184     break;
185   }
186
187   // Make sure that the Out file gets unlinked from the disk if we get a
188   // SIGINT
189   sys::RemoveFileOnSignal(sys::Path(OutputFilename));
190
191   std::string error;
192   unsigned OpenFlags = 0;
193   if (Force) OpenFlags |= raw_fd_ostream::F_Force;
194   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
195   raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
196                                              OpenFlags);
197   if (!error.empty()) {
198     errs() << error << '\n';
199     if (!Force)
200       errs() << "Use -f command line argument to force output\n";
201     delete FDOut;
202     return 0;
203   }
204
205   formatted_raw_ostream *Out =
206     new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
207
208   return Out;
209 }
210
211 // main - Entry point for the llc compiler.
212 //
213 int main(int argc, char **argv) {
214   sys::PrintStackTraceOnErrorSignal();
215   PrettyStackTraceProgram X(argc, argv);
216   LLVMContext &Context = getGlobalContext();
217   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
218
219   // Initialize targets first.
220   InitializeAllTargets();
221   InitializeAllAsmPrinters();
222
223   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
224   
225   // Load the module to be compiled...
226   std::string ErrorMessage;
227   std::auto_ptr<Module> M;
228
229   std::auto_ptr<MemoryBuffer> Buffer(
230                    MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
231   if (Buffer.get())
232     M.reset(ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage));
233   if (M.get() == 0) {
234     errs() << argv[0] << ": bitcode didn't read correctly.\n";
235     errs() << "Reason: " << ErrorMessage << "\n";
236     return 1;
237   }
238   Module &mod = *M.get();
239
240   // If we are supposed to override the target triple, do so now.
241   if (!TargetTriple.empty())
242     mod.setTargetTriple(TargetTriple);
243
244   Triple TheTriple(mod.getTargetTriple());
245   if (TheTriple.getTriple().empty())
246     TheTriple.setTriple(sys::getHostTriple());
247
248   // Allocate target machine.  First, check whether the user has explicitly
249   // specified an architecture to compile for. If so we have to look it up by
250   // name, because it might be a backend that has no mapping to a target triple.
251   const Target *TheTarget = 0;
252   if (!MArch.empty()) {
253     for (TargetRegistry::iterator it = TargetRegistry::begin(),
254            ie = TargetRegistry::end(); it != ie; ++it) {
255       if (MArch == it->getName()) {
256         TheTarget = &*it;
257         break;
258       }
259     }
260
261     if (!TheTarget) {
262       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
263       return 1;
264     }
265
266     // Adjust the triple to match (if known), otherwise stick with the
267     // module/host triple.
268     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
269     if (Type != Triple::UnknownArch)
270       TheTriple.setArch(Type);
271   } else {
272     std::string Err;
273     TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
274     if (TheTarget == 0) {
275       errs() << argv[0] << ": error auto-selecting target for module '"
276              << Err << "'.  Please use the -march option to explicitly "
277              << "pick a target.\n";
278       return 1;
279     }
280   }
281
282   // Package up features to be passed to target/subtarget
283   std::string FeaturesStr;
284   if (MCPU.size() || MAttrs.size()) {
285     SubtargetFeatures Features;
286     Features.setCPU(MCPU);
287     for (unsigned i = 0; i != MAttrs.size(); ++i)
288       Features.AddFeature(MAttrs[i]);
289     FeaturesStr = Features.getString();
290   }
291
292   std::auto_ptr<TargetMachine> 
293     target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
294   assert(target.get() && "Could not allocate target machine!");
295   TargetMachine &Target = *target.get();
296
297   // Figure out where we are going to send the output...
298   formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(), argv[0]);
299   if (Out == 0) return 1;
300
301   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
302   switch (OptLevel) {
303   default:
304     errs() << argv[0] << ": invalid optimization level.\n";
305     return 1;
306   case ' ': break;
307   case '0': OLvl = CodeGenOpt::None; break;
308   case '1':
309   case '2': OLvl = CodeGenOpt::Default; break;
310   case '3': OLvl = CodeGenOpt::Aggressive; break;
311   }
312
313   // If this target requires addPassesToEmitWholeFile, do it now.  This is
314   // used by strange things like the C backend.
315   if (Target.WantsWholeFile()) {
316     PassManager PM;
317
318     // Add the target data from the target machine, if it exists, or the module.
319     if (const TargetData *TD = Target.getTargetData())
320       PM.add(new TargetData(*TD));
321     else
322       PM.add(new TargetData(&mod));
323
324     if (!NoVerify)
325       PM.add(createVerifierPass());
326
327     // Ask the target to add backend passes as necessary.
328     if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, OLvl)) {
329       errs() << argv[0] << ": target does not support generation of this"
330              << " file type!\n";
331       if (Out != &fouts()) delete Out;
332       // And the Out file is empty and useless, so remove it now.
333       sys::Path(OutputFilename).eraseFromDisk();
334       return 1;
335     }
336     PM.run(mod);
337   } else {
338     // Build up all of the passes that we want to do to the module.
339     ExistingModuleProvider Provider(M.release());
340     FunctionPassManager Passes(&Provider);
341
342     // Add the target data from the target machine, if it exists, or the module.
343     if (const TargetData *TD = Target.getTargetData())
344       Passes.add(new TargetData(*TD));
345     else
346       Passes.add(new TargetData(&mod));
347
348 #ifndef NDEBUG
349     if (!NoVerify)
350       Passes.add(createVerifierPass());
351 #endif
352
353     // Ask the target to add backend passes as necessary.
354     ObjectCodeEmitter *OCE = 0;
355
356     // Override default to generate verbose assembly.
357     Target.setAsmVerbosityDefault(true);
358
359     switch (Target.addPassesToEmitFile(Passes, *Out, FileType, OLvl)) {
360     default:
361       assert(0 && "Invalid file model!");
362       return 1;
363     case FileModel::Error:
364       errs() << argv[0] << ": target does not support generation of this"
365              << " file type!\n";
366       if (Out != &fouts()) delete Out;
367       // And the Out file is empty and useless, so remove it now.
368       sys::Path(OutputFilename).eraseFromDisk();
369       return 1;
370     case FileModel::AsmFile:
371       break;
372     case FileModel::MachOFile:
373       OCE = AddMachOWriter(Passes, *Out, Target);
374       break;
375     case FileModel::ElfFile:
376       OCE = AddELFWriter(Passes, *Out, Target);
377       break;
378     }
379
380     if (Target.addPassesToEmitFileFinish(Passes, OCE, OLvl)) {
381       errs() << argv[0] << ": target does not support generation of this"
382              << " file type!\n";
383       if (Out != &fouts()) delete Out;
384       // And the Out file is empty and useless, so remove it now.
385       sys::Path(OutputFilename).eraseFromDisk();
386       return 1;
387     }
388
389     Passes.doInitialization();
390
391     // Run our queue of passes all at once now, efficiently.
392     // TODO: this could lazily stream functions out of the module.
393     for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
394       if (!I->isDeclaration()) {
395         if (DisableRedZone)
396           I->addFnAttr(Attribute::NoRedZone);
397         if (NoImplicitFloats)
398           I->addFnAttr(Attribute::NoImplicitFloat);
399         Passes.run(*I);
400       }
401
402     Passes.doFinalization();
403   }
404
405   Out->flush();
406
407   // Delete the ostream if it's not a stdout stream
408   if (Out != &fouts()) delete Out;
409
410   return 0;
411 }