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