]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llc/llc.cpp
MFV r329770: 9035 zfs: this statement may fall through
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/CodeGen/CommandFlags.def"
20 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/CodeGen/MIRParser/MIRParser.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Transforms/Utils/Cloning.h"
53 #include <memory>
54 using namespace llvm;
55
56 // General options for llc.  Other pass-specific options are specified
57 // within the corresponding llc passes, and target-specific options
58 // and back-end code generation options are specified with the target machine.
59 //
60 static cl::opt<std::string>
61 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
62
63 static cl::opt<std::string>
64 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
65
66 static cl::opt<std::string>
67 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
68
69 static cl::opt<unsigned>
70 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
71                  cl::value_desc("N"),
72                  cl::desc("Repeat compilation N times for timing"));
73
74 static cl::opt<bool>
75 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
76                       cl::desc("Disable integrated assembler"));
77
78 static cl::opt<bool>
79     PreserveComments("preserve-as-comments", cl::Hidden,
80                      cl::desc("Preserve Comments in outputted assembly"),
81                      cl::init(true));
82
83 // Determine optimization level.
84 static cl::opt<char>
85 OptLevel("O",
86          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
87                   "(default = '-O2')"),
88          cl::Prefix,
89          cl::ZeroOrMore,
90          cl::init(' '));
91
92 static cl::opt<std::string>
93 TargetTriple("mtriple", cl::desc("Override target triple for module"));
94
95 static cl::opt<std::string> SplitDwarfFile(
96     "split-dwarf-file",
97     cl::desc(
98         "Specify the name of the .dwo file to encode in the DWARF output"));
99
100 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
101                               cl::desc("Do not verify input module"));
102
103 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
104                                              cl::desc("Disable simplify-libcalls"));
105
106 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
107                                     cl::desc("Show encoding in .s output"));
108
109 static cl::opt<bool> EnableDwarfDirectory(
110     "enable-dwarf-directory", cl::Hidden,
111     cl::desc("Use .file directives with an explicit directory."));
112
113 static cl::opt<bool> AsmVerbose("asm-verbose",
114                                 cl::desc("Add comments to directives."),
115                                 cl::init(true));
116
117 static cl::opt<bool>
118     CompileTwice("compile-twice", cl::Hidden,
119                  cl::desc("Run everything twice, re-using the same pass "
120                           "manager and verify the result is the same."),
121                  cl::init(false));
122
123 static cl::opt<bool> DiscardValueNames(
124     "discard-value-names",
125     cl::desc("Discard names from Value (other than GlobalValue)."),
126     cl::init(false), cl::Hidden);
127
128 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
129
130 static cl::opt<bool> PassRemarksWithHotness(
131     "pass-remarks-with-hotness",
132     cl::desc("With PGO, include profile count in optimization remarks"),
133     cl::Hidden);
134
135 static cl::opt<unsigned> PassRemarksHotnessThreshold(
136     "pass-remarks-hotness-threshold",
137     cl::desc("Minimum profile count required for an optimization remark to be output"),
138     cl::Hidden);
139
140 static cl::opt<std::string>
141     RemarksFilename("pass-remarks-output",
142                     cl::desc("YAML output filename for pass remarks"),
143                     cl::value_desc("filename"));
144
145 namespace {
146 static ManagedStatic<std::vector<std::string>> RunPassNames;
147
148 struct RunPassOption {
149   void operator=(const std::string &Val) const {
150     if (Val.empty())
151       return;
152     SmallVector<StringRef, 8> PassNames;
153     StringRef(Val).split(PassNames, ',', -1, false);
154     for (auto PassName : PassNames)
155       RunPassNames->push_back(PassName);
156   }
157 };
158 }
159
160 static RunPassOption RunPassOpt;
161
162 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
163     "run-pass",
164     cl::desc("Run compiler only for specified passes (comma separated list)"),
165     cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
166
167 static int compileModule(char **, LLVMContext &);
168
169 static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
170                                                        Triple::OSType OS,
171                                                        const char *ProgName) {
172   // If we don't yet have an output filename, make one.
173   if (OutputFilename.empty()) {
174     if (InputFilename == "-")
175       OutputFilename = "-";
176     else {
177       // If InputFilename ends in .bc or .ll, remove it.
178       StringRef IFN = InputFilename;
179       if (IFN.endswith(".bc") || IFN.endswith(".ll"))
180         OutputFilename = IFN.drop_back(3);
181       else if (IFN.endswith(".mir"))
182         OutputFilename = IFN.drop_back(4);
183       else
184         OutputFilename = IFN;
185
186       switch (FileType) {
187       case TargetMachine::CGFT_AssemblyFile:
188         if (TargetName[0] == 'c') {
189           if (TargetName[1] == 0)
190             OutputFilename += ".cbe.c";
191           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
192             OutputFilename += ".cpp";
193           else
194             OutputFilename += ".s";
195         } else
196           OutputFilename += ".s";
197         break;
198       case TargetMachine::CGFT_ObjectFile:
199         if (OS == Triple::Win32)
200           OutputFilename += ".obj";
201         else
202           OutputFilename += ".o";
203         break;
204       case TargetMachine::CGFT_Null:
205         OutputFilename += ".null";
206         break;
207       }
208     }
209   }
210
211   // Decide if we need "binary" output.
212   bool Binary = false;
213   switch (FileType) {
214   case TargetMachine::CGFT_AssemblyFile:
215     break;
216   case TargetMachine::CGFT_ObjectFile:
217   case TargetMachine::CGFT_Null:
218     Binary = true;
219     break;
220   }
221
222   // Open the file.
223   std::error_code EC;
224   sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
225   if (!Binary)
226     OpenFlags |= sys::fs::F_Text;
227   auto FDOut = llvm::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
228   if (EC) {
229     errs() << EC.message() << '\n';
230     return nullptr;
231   }
232
233   return FDOut;
234 }
235
236 struct LLCDiagnosticHandler : public DiagnosticHandler {
237   bool *HasError;
238   LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
239   bool handleDiagnostics(const DiagnosticInfo &DI) override {
240     if (DI.getSeverity() == DS_Error)
241       *HasError = true;
242
243     if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
244       if (!Remark->isEnabled())
245         return true;
246
247     DiagnosticPrinterRawOStream DP(errs());
248     errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
249     DI.print(DP);
250     errs() << "\n";
251     return true;
252   }
253 };
254
255 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
256                                  unsigned LocCookie) {
257   bool *HasError = static_cast<bool *>(Context);
258   if (SMD.getKind() == SourceMgr::DK_Error)
259     *HasError = true;
260
261   SMD.print(nullptr, errs());
262
263   // For testing purposes, we print the LocCookie here.
264   if (LocCookie)
265     errs() << "note: !srcloc = " << LocCookie << "\n";
266 }
267
268 // main - Entry point for the llc compiler.
269 //
270 int main(int argc, char **argv) {
271   sys::PrintStackTraceOnErrorSignal(argv[0]);
272   PrettyStackTraceProgram X(argc, argv);
273
274   // Enable debug stream buffering.
275   EnableDebugBuffering = true;
276
277   LLVMContext Context;
278   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
279
280   // Initialize targets first, so that --version shows registered targets.
281   InitializeAllTargets();
282   InitializeAllTargetMCs();
283   InitializeAllAsmPrinters();
284   InitializeAllAsmParsers();
285
286   // Initialize codegen and IR passes used by llc so that the -print-after,
287   // -print-before, and -stop-after options work.
288   PassRegistry *Registry = PassRegistry::getPassRegistry();
289   initializeCore(*Registry);
290   initializeCodeGen(*Registry);
291   initializeLoopStrengthReducePass(*Registry);
292   initializeLowerIntrinsicsPass(*Registry);
293   initializeEntryExitInstrumenterPass(*Registry);
294   initializePostInlineEntryExitInstrumenterPass(*Registry);
295   initializeUnreachableBlockElimLegacyPassPass(*Registry);
296   initializeConstantHoistingLegacyPassPass(*Registry);
297   initializeScalarOpts(*Registry);
298   initializeVectorization(*Registry);
299   initializeScalarizeMaskedMemIntrinPass(*Registry);
300   initializeExpandReductionsPass(*Registry);
301
302   // Initialize debugging passes.
303   initializeScavengerTestPass(*Registry);
304
305   // Register the target printer for --version.
306   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
307
308   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
309
310   Context.setDiscardValueNames(DiscardValueNames);
311
312   // Set a diagnostic handler that doesn't exit on the first error
313   bool HasError = false;
314   Context.setDiagnosticHandler(
315       llvm::make_unique<LLCDiagnosticHandler>(&HasError));
316   Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
317
318   if (PassRemarksWithHotness)
319     Context.setDiagnosticsHotnessRequested(true);
320
321   if (PassRemarksHotnessThreshold)
322     Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
323
324   std::unique_ptr<ToolOutputFile> YamlFile;
325   if (RemarksFilename != "") {
326     std::error_code EC;
327     YamlFile =
328         llvm::make_unique<ToolOutputFile>(RemarksFilename, EC, sys::fs::F_None);
329     if (EC) {
330       errs() << EC.message() << '\n';
331       return 1;
332     }
333     Context.setDiagnosticsOutputFile(
334         llvm::make_unique<yaml::Output>(YamlFile->os()));
335   }
336
337   if (InputLanguage != "" && InputLanguage != "ir" &&
338       InputLanguage != "mir") {
339     errs() << argv[0] << "Input language must be '', 'IR' or 'MIR'\n";
340     return 1;
341   }
342
343   // Compile the module TimeCompilations times to give better compile time
344   // metrics.
345   for (unsigned I = TimeCompilations; I; --I)
346     if (int RetVal = compileModule(argv, Context))
347       return RetVal;
348
349   if (YamlFile)
350     YamlFile->keep();
351   return 0;
352 }
353
354 static bool addPass(PassManagerBase &PM, const char *argv0,
355                     StringRef PassName, TargetPassConfig &TPC) {
356   if (PassName == "none")
357     return false;
358
359   const PassRegistry *PR = PassRegistry::getPassRegistry();
360   const PassInfo *PI = PR->getPassInfo(PassName);
361   if (!PI) {
362     errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
363     return true;
364   }
365
366   Pass *P;
367   if (PI->getNormalCtor())
368     P = PI->getNormalCtor()();
369   else {
370     errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
371     return true;
372   }
373   std::string Banner = std::string("After ") + std::string(P->getPassName());
374   PM.add(P);
375   TPC.printAndVerify(Banner);
376
377   return false;
378 }
379
380 static int compileModule(char **argv, LLVMContext &Context) {
381   // Load the module to be compiled...
382   SMDiagnostic Err;
383   std::unique_ptr<Module> M;
384   std::unique_ptr<MIRParser> MIR;
385   Triple TheTriple;
386
387   bool SkipModule = MCPU == "help" ||
388                     (!MAttrs.empty() && MAttrs.front() == "help");
389
390   // If user just wants to list available options, skip module loading
391   if (!SkipModule) {
392     if (InputLanguage == "mir" ||
393         (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
394       MIR = createMIRParserFromFile(InputFilename, Err, Context);
395       if (MIR)
396         M = MIR->parseIRModule();
397     } else
398       M = parseIRFile(InputFilename, Err, Context);
399     if (!M) {
400       Err.print(argv[0], errs());
401       return 1;
402     }
403
404     // Verify module immediately to catch problems before doInitialization() is
405     // called on any passes.
406     if (!NoVerify && verifyModule(*M, &errs())) {
407       errs() << argv[0] << ": " << InputFilename
408              << ": error: input module is broken!\n";
409       return 1;
410     }
411
412     // If we are supposed to override the target triple, do so now.
413     if (!TargetTriple.empty())
414       M->setTargetTriple(Triple::normalize(TargetTriple));
415     TheTriple = Triple(M->getTargetTriple());
416   } else {
417     TheTriple = Triple(Triple::normalize(TargetTriple));
418   }
419
420   if (TheTriple.getTriple().empty())
421     TheTriple.setTriple(sys::getDefaultTargetTriple());
422
423   // Get the target specific parser.
424   std::string Error;
425   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
426                                                          Error);
427   if (!TheTarget) {
428     errs() << argv[0] << ": " << Error;
429     return 1;
430   }
431
432   std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
433
434   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
435   switch (OptLevel) {
436   default:
437     errs() << argv[0] << ": invalid optimization level.\n";
438     return 1;
439   case ' ': break;
440   case '0': OLvl = CodeGenOpt::None; break;
441   case '1': OLvl = CodeGenOpt::Less; break;
442   case '2': OLvl = CodeGenOpt::Default; break;
443   case '3': OLvl = CodeGenOpt::Aggressive; break;
444   }
445
446   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
447   Options.DisableIntegratedAS = NoIntegratedAssembler;
448   Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
449   Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
450   Options.MCOptions.AsmVerbose = AsmVerbose;
451   Options.MCOptions.PreserveAsmComments = PreserveComments;
452   Options.MCOptions.IASSearchPaths = IncludeDirs;
453   Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
454
455   std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine(
456       TheTriple.getTriple(), CPUStr, FeaturesStr, Options, getRelocModel(),
457       getCodeModel(), OLvl));
458
459   assert(Target && "Could not allocate target machine!");
460
461   // If we don't have a module then just exit now. We do this down
462   // here since the CPU/Feature help is underneath the target machine
463   // creation.
464   if (SkipModule)
465     return 0;
466
467   assert(M && "Should have exited if we didn't have a module!");
468   if (FloatABIForCalls != FloatABI::Default)
469     Options.FloatABIType = FloatABIForCalls;
470
471   // Figure out where we are going to send the output.
472   std::unique_ptr<ToolOutputFile> Out =
473       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
474   if (!Out) return 1;
475
476   // Build up all of the passes that we want to do to the module.
477   legacy::PassManager PM;
478
479   // Add an appropriate TargetLibraryInfo pass for the module's triple.
480   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
481
482   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
483   if (DisableSimplifyLibCalls)
484     TLII.disableAllFunctions();
485   PM.add(new TargetLibraryInfoWrapperPass(TLII));
486
487   // Add the target data from the target machine, if it exists, or the module.
488   M->setDataLayout(Target->createDataLayout());
489
490   // Override function attributes based on CPUStr, FeaturesStr, and command line
491   // flags.
492   setFunctionAttributes(CPUStr, FeaturesStr, *M);
493
494   if (RelaxAll.getNumOccurrences() > 0 &&
495       FileType != TargetMachine::CGFT_ObjectFile)
496     errs() << argv[0]
497              << ": warning: ignoring -mc-relax-all because filetype != obj";
498
499   {
500     raw_pwrite_stream *OS = &Out->os();
501
502     // Manually do the buffering rather than using buffer_ostream,
503     // so we can memcmp the contents in CompileTwice mode
504     SmallVector<char, 0> Buffer;
505     std::unique_ptr<raw_svector_ostream> BOS;
506     if ((FileType != TargetMachine::CGFT_AssemblyFile &&
507          !Out->os().supportsSeeking()) ||
508         CompileTwice) {
509       BOS = make_unique<raw_svector_ostream>(Buffer);
510       OS = BOS.get();
511     }
512
513     const char *argv0 = argv[0];
514     LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
515     MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
516
517     // Construct a custom pass pipeline that starts after instruction
518     // selection.
519     if (!RunPassNames->empty()) {
520       if (!MIR) {
521         errs() << argv0 << ": run-pass is for .mir file only.\n";
522         return 1;
523       }
524       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
525       if (TPC.hasLimitedCodeGenPipeline()) {
526         errs() << argv0 << ": run-pass cannot be used with "
527                << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
528         return 1;
529       }
530
531       TPC.setDisableVerify(NoVerify);
532       PM.add(&TPC);
533       PM.add(MMI);
534       TPC.printAndVerify("");
535       for (const std::string &RunPassName : *RunPassNames) {
536         if (addPass(PM, argv0, RunPassName, TPC))
537           return 1;
538       }
539       TPC.setInitialized();
540       PM.add(createPrintMIRPass(*OS));
541       PM.add(createFreeMachineFunctionPass());
542     } else if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, MMI)) {
543       errs() << argv0 << ": target does not support generation of this"
544              << " file type!\n";
545       return 1;
546     }
547
548     if (MIR) {
549       assert(MMI && "Forgot to create MMI?");
550       if (MIR->parseMachineFunctions(*M, *MMI))
551         return 1;
552     }
553
554     // Before executing passes, print the final values of the LLVM options.
555     cl::PrintOptionValues();
556
557     // If requested, run the pass manager over the same module again,
558     // to catch any bugs due to persistent state in the passes. Note that
559     // opt has the same functionality, so it may be worth abstracting this out
560     // in the future.
561     SmallVector<char, 0> CompileTwiceBuffer;
562     if (CompileTwice) {
563       std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
564       PM.run(*M2);
565       CompileTwiceBuffer = Buffer;
566       Buffer.clear();
567     }
568
569     PM.run(*M);
570
571     auto HasError =
572         ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
573     if (*HasError)
574       return 1;
575
576     // Compare the two outputs and make sure they're the same
577     if (CompileTwice) {
578       if (Buffer.size() != CompileTwiceBuffer.size() ||
579           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
580            0)) {
581         errs()
582             << "Running the pass manager twice changed the output.\n"
583                "Writing the result of the second run to the specified output\n"
584                "To generate the one-run comparison binary, just run without\n"
585                "the compile-twice option\n";
586         Out->os() << Buffer;
587         Out->keep();
588         return 1;
589       }
590     }
591
592     if (BOS) {
593       Out->os() << Buffer;
594     }
595   }
596
597   // Declare success.
598   Out->keep();
599
600   return 0;
601 }