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