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