llvm-dis.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. //===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This utility may be invoked in the following manner:
  10. // llvm-dis [options] - Read LLVM bitcode from stdin, write asm to stdout
  11. // llvm-dis [options] x.bc - Read LLVM bitcode from the x.bc file, write asm
  12. // to the x.ll file.
  13. // Options:
  14. // --help - Output information about command line switches
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Bitcode/BitcodeReader.h"
  18. #include "llvm/IR/AssemblyAnnotationWriter.h"
  19. #include "llvm/IR/DebugInfo.h"
  20. #include "llvm/IR/DiagnosticInfo.h"
  21. #include "llvm/IR/DiagnosticPrinter.h"
  22. #include "llvm/IR/IntrinsicInst.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/Type.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Error.h"
  28. #include "llvm/Support/FileSystem.h"
  29. #include "llvm/Support/FormattedStream.h"
  30. #include "llvm/Support/InitLLVM.h"
  31. #include "llvm/Support/MemoryBuffer.h"
  32. #include "llvm/Support/ToolOutputFile.h"
  33. #include "llvm/Support/WithColor.h"
  34. #include <system_error>
  35. using namespace llvm;
  36. static cl::opt<std::string>
  37. InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
  38. static cl::opt<std::string>
  39. OutputFilename("o", cl::desc("Override output filename"),
  40. cl::value_desc("filename"));
  41. static cl::opt<bool>
  42. Force("f", cl::desc("Enable binary output on terminals"));
  43. static cl::opt<bool>
  44. DontPrint("disable-output", cl::desc("Don't output the .ll file"), cl::Hidden);
  45. static cl::opt<bool>
  46. SetImporting("set-importing",
  47. cl::desc("Set lazy loading to pretend to import a module"),
  48. cl::Hidden);
  49. static cl::opt<bool>
  50. ShowAnnotations("show-annotations",
  51. cl::desc("Add informational comments to the .ll file"));
  52. static cl::opt<bool> PreserveAssemblyUseListOrder(
  53. "preserve-ll-uselistorder",
  54. cl::desc("Preserve use-list order when writing LLVM assembly."),
  55. cl::init(false), cl::Hidden);
  56. static cl::opt<bool>
  57. MaterializeMetadata("materialize-metadata",
  58. cl::desc("Load module without materializing metadata, "
  59. "then materialize only the metadata"));
  60. namespace {
  61. static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
  62. OS << DL.getLine() << ":" << DL.getCol();
  63. if (DILocation *IDL = DL.getInlinedAt()) {
  64. OS << "@";
  65. printDebugLoc(IDL, OS);
  66. }
  67. }
  68. class CommentWriter : public AssemblyAnnotationWriter {
  69. public:
  70. void emitFunctionAnnot(const Function *F,
  71. formatted_raw_ostream &OS) override {
  72. OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses
  73. OS << '\n';
  74. }
  75. void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
  76. bool Padded = false;
  77. if (!V.getType()->isVoidTy()) {
  78. OS.PadToColumn(50);
  79. Padded = true;
  80. // Output # uses and type
  81. OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]";
  82. }
  83. if (const Instruction *I = dyn_cast<Instruction>(&V)) {
  84. if (const DebugLoc &DL = I->getDebugLoc()) {
  85. if (!Padded) {
  86. OS.PadToColumn(50);
  87. Padded = true;
  88. OS << ";";
  89. }
  90. OS << " [debug line = ";
  91. printDebugLoc(DL,OS);
  92. OS << "]";
  93. }
  94. if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  95. if (!Padded) {
  96. OS.PadToColumn(50);
  97. OS << ";";
  98. }
  99. OS << " [debug variable = " << DDI->getVariable()->getName() << "]";
  100. }
  101. else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  102. if (!Padded) {
  103. OS.PadToColumn(50);
  104. OS << ";";
  105. }
  106. OS << " [debug variable = " << DVI->getVariable()->getName() << "]";
  107. }
  108. }
  109. }
  110. };
  111. struct LLVMDisDiagnosticHandler : public DiagnosticHandler {
  112. char *Prefix;
  113. LLVMDisDiagnosticHandler(char *PrefixPtr) : Prefix(PrefixPtr) {}
  114. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  115. raw_ostream &OS = errs();
  116. OS << Prefix << ": ";
  117. switch (DI.getSeverity()) {
  118. case DS_Error: WithColor::error(OS); break;
  119. case DS_Warning: WithColor::warning(OS); break;
  120. case DS_Remark: OS << "remark: "; break;
  121. case DS_Note: WithColor::note(OS); break;
  122. }
  123. DiagnosticPrinterRawOStream DP(OS);
  124. DI.print(DP);
  125. OS << '\n';
  126. if (DI.getSeverity() == DS_Error)
  127. exit(1);
  128. return true;
  129. }
  130. };
  131. } // end anon namespace
  132. static ExitOnError ExitOnErr;
  133. int main(int argc, char **argv) {
  134. InitLLVM X(argc, argv);
  135. ExitOnErr.setBanner(std::string(argv[0]) + ": error: ");
  136. LLVMContext Context;
  137. Context.setDiagnosticHandler(
  138. llvm::make_unique<LLVMDisDiagnosticHandler>(argv[0]));
  139. cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
  140. std::unique_ptr<MemoryBuffer> MB =
  141. ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
  142. std::unique_ptr<Module> M = ExitOnErr(getLazyBitcodeModule(
  143. *MB, Context, /*ShouldLazyLoadMetadata=*/true, SetImporting));
  144. if (MaterializeMetadata)
  145. ExitOnErr(M->materializeMetadata());
  146. else
  147. ExitOnErr(M->materializeAll());
  148. BitcodeLTOInfo LTOInfo = ExitOnErr(getBitcodeLTOInfo(*MB));
  149. std::unique_ptr<ModuleSummaryIndex> Index;
  150. if (LTOInfo.HasSummary)
  151. Index = ExitOnErr(getModuleSummaryIndex(*MB));
  152. // Just use stdout. We won't actually print anything on it.
  153. if (DontPrint)
  154. OutputFilename = "-";
  155. if (OutputFilename.empty()) { // Unspecified output, infer it.
  156. if (InputFilename == "-") {
  157. OutputFilename = "-";
  158. } else {
  159. StringRef IFN = InputFilename;
  160. OutputFilename = (IFN.endswith(".bc") ? IFN.drop_back(3) : IFN).str();
  161. OutputFilename += ".ll";
  162. }
  163. }
  164. std::error_code EC;
  165. std::unique_ptr<ToolOutputFile> Out(
  166. new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
  167. if (EC) {
  168. errs() << EC.message() << '\n';
  169. return 1;
  170. }
  171. std::unique_ptr<AssemblyAnnotationWriter> Annotator;
  172. if (ShowAnnotations)
  173. Annotator.reset(new CommentWriter());
  174. // All that llvm-dis does is write the assembly to a file.
  175. if (!DontPrint) {
  176. M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);
  177. if (Index)
  178. Index->print(Out->os());
  179. }
  180. // Declare success.
  181. Out->keep();
  182. return 0;
  183. }