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