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