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