Replace the F_Binary flag with a F_Text one.
[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
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Pass.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/PluginLoader.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetMachine.h"
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<unsigned>
57 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
58                  cl::value_desc("N"),
59                  cl::desc("Repeat compilation N times for timing"));
60
61 static cl::opt<bool>
62 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
63                       cl::desc("Disable integrated assembler"));
64
65 // Determine optimization level.
66 static cl::opt<char>
67 OptLevel("O",
68          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
69                   "(default = '-O2')"),
70          cl::Prefix,
71          cl::ZeroOrMore,
72          cl::init(' '));
73
74 static cl::opt<std::string>
75 TargetTriple("mtriple", cl::desc("Override target triple for module"));
76
77 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
78                        cl::desc("Do not verify input module"));
79
80 cl::opt<bool>
81 DisableSimplifyLibCalls("disable-simplify-libcalls",
82                         cl::desc("Disable simplify-libcalls"),
83                         cl::init(false));
84
85 static int compileModule(char**, LLVMContext&);
86
87 // GetFileNameRoot - Helper function to get the basename of a filename.
88 static inline std::string
89 GetFileNameRoot(const std::string &InputFilename) {
90   std::string IFN = InputFilename;
91   std::string outputFilename;
92   int Len = IFN.length();
93   if ((Len > 2) &&
94       IFN[Len-3] == '.' &&
95       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
96        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
97     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
98   } else {
99     outputFilename = IFN;
100   }
101   return outputFilename;
102 }
103
104 static tool_output_file *GetOutputStream(const char *TargetName,
105                                          Triple::OSType OS,
106                                          const char *ProgName) {
107   // If we don't yet have an output filename, make one.
108   if (OutputFilename.empty()) {
109     if (InputFilename == "-")
110       OutputFilename = "-";
111     else {
112       OutputFilename = GetFileNameRoot(InputFilename);
113
114       switch (FileType) {
115       case TargetMachine::CGFT_AssemblyFile:
116         if (TargetName[0] == 'c') {
117           if (TargetName[1] == 0)
118             OutputFilename += ".cbe.c";
119           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
120             OutputFilename += ".cpp";
121           else
122             OutputFilename += ".s";
123         } else
124           OutputFilename += ".s";
125         break;
126       case TargetMachine::CGFT_ObjectFile:
127         if (OS == Triple::Win32)
128           OutputFilename += ".obj";
129         else
130           OutputFilename += ".o";
131         break;
132       case TargetMachine::CGFT_Null:
133         OutputFilename += ".null";
134         break;
135       }
136     }
137   }
138
139   // Decide if we need "binary" output.
140   bool Binary = false;
141   switch (FileType) {
142   case TargetMachine::CGFT_AssemblyFile:
143     break;
144   case TargetMachine::CGFT_ObjectFile:
145   case TargetMachine::CGFT_Null:
146     Binary = true;
147     break;
148   }
149
150   // Open the file.
151   std::string error;
152   sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
153   if (!Binary)
154     OpenFlags |= sys::fs::F_Text;
155   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
156                                                  OpenFlags);
157   if (!error.empty()) {
158     errs() << error << '\n';
159     delete FDOut;
160     return 0;
161   }
162
163   return FDOut;
164 }
165
166 // main - Entry point for the llc compiler.
167 //
168 int main(int argc, char **argv) {
169   sys::PrintStackTraceOnErrorSignal();
170   PrettyStackTraceProgram X(argc, argv);
171
172   // Enable debug stream buffering.
173   EnableDebugBuffering = true;
174
175   LLVMContext &Context = getGlobalContext();
176   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
177
178   // Initialize targets first, so that --version shows registered targets.
179   InitializeAllTargets();
180   InitializeAllTargetMCs();
181   InitializeAllAsmPrinters();
182   InitializeAllAsmParsers();
183
184   // Initialize codegen and IR passes used by llc so that the -print-after,
185   // -print-before, and -stop-after options work.
186   PassRegistry *Registry = PassRegistry::getPassRegistry();
187   initializeCore(*Registry);
188   initializeCodeGen(*Registry);
189   initializeLoopStrengthReducePass(*Registry);
190   initializeLowerIntrinsicsPass(*Registry);
191   initializeUnreachableBlockElimPass(*Registry);
192
193   // Register the target printer for --version.
194   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
195
196   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
197
198   // Compile the module TimeCompilations times to give better compile time
199   // metrics.
200   for (unsigned I = TimeCompilations; I; --I)
201     if (int RetVal = compileModule(argv, Context))
202       return RetVal;
203   return 0;
204 }
205
206 static int compileModule(char **argv, LLVMContext &Context) {
207   // Load the module to be compiled...
208   SMDiagnostic Err;
209   OwningPtr<Module> M;
210   Module *mod = 0;
211   Triple TheTriple;
212
213   bool SkipModule = MCPU == "help" ||
214                     (!MAttrs.empty() && MAttrs.front() == "help");
215
216   // If user just wants to list available options, skip module loading
217   if (!SkipModule) {
218     M.reset(ParseIRFile(InputFilename, Err, Context));
219     mod = M.get();
220     if (mod == 0) {
221       Err.print(argv[0], errs());
222       return 1;
223     }
224
225     // If we are supposed to override the target triple, do so now.
226     if (!TargetTriple.empty())
227       mod->setTargetTriple(Triple::normalize(TargetTriple));
228     TheTriple = Triple(mod->getTargetTriple());
229   } else {
230     TheTriple = Triple(Triple::normalize(TargetTriple));
231   }
232
233   if (TheTriple.getTriple().empty())
234     TheTriple.setTriple(sys::getDefaultTargetTriple());
235
236   // Get the target specific parser.
237   std::string Error;
238   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
239                                                          Error);
240   if (!TheTarget) {
241     errs() << argv[0] << ": " << Error;
242     return 1;
243   }
244
245   // Package up features to be passed to target/subtarget
246   std::string FeaturesStr;
247   if (MAttrs.size()) {
248     SubtargetFeatures Features;
249     for (unsigned i = 0; i != MAttrs.size(); ++i)
250       Features.AddFeature(MAttrs[i]);
251     FeaturesStr = Features.getString();
252   }
253
254   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
255   switch (OptLevel) {
256   default:
257     errs() << argv[0] << ": invalid optimization level.\n";
258     return 1;
259   case ' ': break;
260   case '0': OLvl = CodeGenOpt::None; break;
261   case '1': OLvl = CodeGenOpt::Less; break;
262   case '2': OLvl = CodeGenOpt::Default; break;
263   case '3': OLvl = CodeGenOpt::Aggressive; break;
264   }
265
266   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
267   Options.DisableIntegratedAS = NoIntegratedAssembler;
268
269   OwningPtr<TargetMachine>
270     target(TheTarget->createTargetMachine(TheTriple.getTriple(),
271                                           MCPU, FeaturesStr, Options,
272                                           RelocModel, CMModel, OLvl));
273   assert(target.get() && "Could not allocate target machine!");
274   assert(mod && "Should have exited after outputting help!");
275   TargetMachine &Target = *target.get();
276
277   if (DisableCFI)
278     Target.setMCUseCFI(false);
279
280   if (EnableDwarfDirectory)
281     Target.setMCUseDwarfDirectory(true);
282
283   if (GenerateSoftFloatCalls)
284     FloatABIForCalls = FloatABI::Soft;
285
286   // Figure out where we are going to send the output.
287   OwningPtr<tool_output_file> Out
288     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
289   if (!Out) return 1;
290
291   // Build up all of the passes that we want to do to the module.
292   PassManager PM;
293
294   // Add an appropriate TargetLibraryInfo pass for the module's triple.
295   TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
296   if (DisableSimplifyLibCalls)
297     TLI->disableAllFunctions();
298   PM.add(TLI);
299
300   // Add the target data from the target machine, if it exists, or the module.
301   if (const DataLayout *DL = Target.getDataLayout())
302     PM.add(new DataLayout(*DL));
303   else
304     PM.add(new DataLayout(mod));
305
306   // Override default to generate verbose assembly.
307   Target.setAsmVerbosityDefault(true);
308
309   if (RelaxAll) {
310     if (FileType != TargetMachine::CGFT_ObjectFile)
311       errs() << argv[0]
312              << ": warning: ignoring -mc-relax-all because filetype != obj";
313     else
314       Target.setMCRelaxAll(true);
315   }
316
317   {
318     formatted_raw_ostream FOS(Out->os());
319
320     AnalysisID StartAfterID = 0;
321     AnalysisID StopAfterID = 0;
322     const PassRegistry *PR = PassRegistry::getPassRegistry();
323     if (!StartAfter.empty()) {
324       const PassInfo *PI = PR->getPassInfo(StartAfter);
325       if (!PI) {
326         errs() << argv[0] << ": start-after pass is not registered.\n";
327         return 1;
328       }
329       StartAfterID = PI->getTypeInfo();
330     }
331     if (!StopAfter.empty()) {
332       const PassInfo *PI = PR->getPassInfo(StopAfter);
333       if (!PI) {
334         errs() << argv[0] << ": stop-after pass is not registered.\n";
335         return 1;
336       }
337       StopAfterID = PI->getTypeInfo();
338     }
339
340     // Ask the target to add backend passes as necessary.
341     if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
342                                    StartAfterID, StopAfterID)) {
343       errs() << argv[0] << ": target does not support generation of this"
344              << " file type!\n";
345       return 1;
346     }
347
348     // Before executing passes, print the final values of the LLVM options.
349     cl::PrintOptionValues();
350
351     PM.run(*mod);
352   }
353
354   // Declare success.
355   Out->keep();
356
357   return 0;
358 }