llvm-dis.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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::OptionCategory DisCategory("Disassembler Options");
  37. static cl::list<std::string> InputFilenames(cl::Positional, cl::ZeroOrMore,
  38. cl::desc("[input bitcode]..."),
  39. cl::cat(DisCategory));
  40. static cl::opt<std::string> OutputFilename("o",
  41. cl::desc("Override output filename"),
  42. cl::value_desc("filename"),
  43. cl::cat(DisCategory));
  44. static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"),
  45. cl::cat(DisCategory));
  46. static cl::opt<bool> DontPrint("disable-output",
  47. cl::desc("Don't output the .ll file"),
  48. cl::Hidden, cl::cat(DisCategory));
  49. static cl::opt<bool>
  50. SetImporting("set-importing",
  51. cl::desc("Set lazy loading to pretend to import a module"),
  52. cl::Hidden, cl::cat(DisCategory));
  53. static cl::opt<bool>
  54. ShowAnnotations("show-annotations",
  55. cl::desc("Add informational comments to the .ll file"),
  56. cl::cat(DisCategory));
  57. static cl::opt<bool> PreserveAssemblyUseListOrder(
  58. "preserve-ll-uselistorder",
  59. cl::desc("Preserve use-list order when writing LLVM assembly."),
  60. cl::init(false), cl::Hidden, cl::cat(DisCategory));
  61. static cl::opt<bool>
  62. MaterializeMetadata("materialize-metadata",
  63. cl::desc("Load module without materializing metadata, "
  64. "then materialize only the metadata"),
  65. cl::cat(DisCategory));
  66. static cl::opt<bool> PrintThinLTOIndexOnly(
  67. "print-thinlto-index-only",
  68. cl::desc("Only read thinlto index and print the index as LLVM assembly."),
  69. cl::init(false), cl::Hidden, cl::cat(DisCategory));
  70. namespace {
  71. static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
  72. OS << DL.getLine() << ":" << DL.getCol();
  73. if (DILocation *IDL = DL.getInlinedAt()) {
  74. OS << "@";
  75. printDebugLoc(IDL, OS);
  76. }
  77. }
  78. class CommentWriter : public AssemblyAnnotationWriter {
  79. public:
  80. void emitFunctionAnnot(const Function *F,
  81. formatted_raw_ostream &OS) override {
  82. OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses
  83. OS << '\n';
  84. }
  85. void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
  86. bool Padded = false;
  87. if (!V.getType()->isVoidTy()) {
  88. OS.PadToColumn(50);
  89. Padded = true;
  90. // Output # uses and type
  91. OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]";
  92. }
  93. if (const Instruction *I = dyn_cast<Instruction>(&V)) {
  94. if (const DebugLoc &DL = I->getDebugLoc()) {
  95. if (!Padded) {
  96. OS.PadToColumn(50);
  97. Padded = true;
  98. OS << ";";
  99. }
  100. OS << " [debug line = ";
  101. printDebugLoc(DL,OS);
  102. OS << "]";
  103. }
  104. if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  105. if (!Padded) {
  106. OS.PadToColumn(50);
  107. OS << ";";
  108. }
  109. OS << " [debug variable = " << DDI->getVariable()->getName() << "]";
  110. }
  111. else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  112. if (!Padded) {
  113. OS.PadToColumn(50);
  114. OS << ";";
  115. }
  116. OS << " [debug variable = " << DVI->getVariable()->getName() << "]";
  117. }
  118. }
  119. }
  120. };
  121. struct LLVMDisDiagnosticHandler : public DiagnosticHandler {
  122. char *Prefix;
  123. LLVMDisDiagnosticHandler(char *PrefixPtr) : Prefix(PrefixPtr) {}
  124. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  125. raw_ostream &OS = errs();
  126. OS << Prefix << ": ";
  127. switch (DI.getSeverity()) {
  128. case DS_Error: WithColor::error(OS); break;
  129. case DS_Warning: WithColor::warning(OS); break;
  130. case DS_Remark: OS << "remark: "; break;
  131. case DS_Note: WithColor::note(OS); break;
  132. }
  133. DiagnosticPrinterRawOStream DP(OS);
  134. DI.print(DP);
  135. OS << '\n';
  136. if (DI.getSeverity() == DS_Error)
  137. exit(1);
  138. return true;
  139. }
  140. };
  141. } // end anon namespace
  142. static ExitOnError ExitOnErr;
  143. int main(int argc, char **argv) {
  144. InitLLVM X(argc, argv);
  145. ExitOnErr.setBanner(std::string(argv[0]) + ": error: ");
  146. cl::HideUnrelatedOptions({&DisCategory, &getColorCategory()});
  147. cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
  148. LLVMContext Context;
  149. Context.setDiagnosticHandler(
  150. std::make_unique<LLVMDisDiagnosticHandler>(argv[0]));
  151. if (InputFilenames.size() < 1) {
  152. InputFilenames.push_back("-");
  153. } else if (InputFilenames.size() > 1 && !OutputFilename.empty()) {
  154. errs()
  155. << "error: output file name cannot be set for multiple input files\n";
  156. return 1;
  157. }
  158. for (std::string InputFilename : InputFilenames) {
  159. std::unique_ptr<MemoryBuffer> MB = ExitOnErr(
  160. errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
  161. BitcodeFileContents IF = ExitOnErr(llvm::getBitcodeFileContents(*MB));
  162. const size_t N = IF.Mods.size();
  163. if (OutputFilename == "-" && N > 1)
  164. errs() << "only single module bitcode files can be written to stdout\n";
  165. for (size_t I = 0; I < N; ++I) {
  166. BitcodeModule MB = IF.Mods[I];
  167. std::unique_ptr<Module> M;
  168. if (!PrintThinLTOIndexOnly) {
  169. M = ExitOnErr(
  170. MB.getLazyModule(Context, MaterializeMetadata, SetImporting));
  171. if (MaterializeMetadata)
  172. ExitOnErr(M->materializeMetadata());
  173. else
  174. ExitOnErr(M->materializeAll());
  175. }
  176. BitcodeLTOInfo LTOInfo = ExitOnErr(MB.getLTOInfo());
  177. std::unique_ptr<ModuleSummaryIndex> Index;
  178. if (LTOInfo.HasSummary)
  179. Index = ExitOnErr(MB.getSummary());
  180. std::string FinalFilename(OutputFilename);
  181. // Just use stdout. We won't actually print anything on it.
  182. if (DontPrint)
  183. FinalFilename = "-";
  184. if (FinalFilename.empty()) { // Unspecified output, infer it.
  185. if (InputFilename == "-") {
  186. FinalFilename = "-";
  187. } else {
  188. StringRef IFN = InputFilename;
  189. FinalFilename = (IFN.endswith(".bc") ? IFN.drop_back(3) : IFN).str();
  190. if (N > 1)
  191. FinalFilename += std::string(".") + std::to_string(I);
  192. FinalFilename += ".ll";
  193. }
  194. } else {
  195. if (N > 1)
  196. FinalFilename += std::string(".") + std::to_string(I);
  197. }
  198. std::error_code EC;
  199. std::unique_ptr<ToolOutputFile> Out(
  200. new ToolOutputFile(FinalFilename, EC, sys::fs::OF_TextWithCRLF));
  201. if (EC) {
  202. errs() << EC.message() << '\n';
  203. return 1;
  204. }
  205. std::unique_ptr<AssemblyAnnotationWriter> Annotator;
  206. if (ShowAnnotations)
  207. Annotator.reset(new CommentWriter());
  208. // All that llvm-dis does is write the assembly to a file.
  209. if (!DontPrint) {
  210. if (M)
  211. M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);
  212. if (Index)
  213. Index->print(Out->os());
  214. }
  215. // Declare success.
  216. Out->keep();
  217. }
  218. }
  219. return 0;
  220. }