1 //===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===//
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
7 //===----------------------------------------------------------------------===//
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
14 // --help - Output information about command line switches
16 //===----------------------------------------------------------------------===//
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/ModuleSummaryIndex.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/InitLLVM.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 #include "llvm/Support/WithColor.h"
36 #include <system_error>
39 static cl::OptionCategory
DisCategory("Disassembler Options");
41 static cl::list
<std::string
> InputFilenames(cl::Positional
,
42 cl::desc("[input bitcode]..."),
43 cl::cat(DisCategory
));
45 static cl::opt
<std::string
> OutputFilename("o",
46 cl::desc("Override output filename"),
47 cl::value_desc("filename"),
48 cl::cat(DisCategory
));
50 static cl::opt
<bool> Force("f", cl::desc("Enable binary output on terminals"),
51 cl::cat(DisCategory
));
53 static cl::opt
<bool> DontPrint("disable-output",
54 cl::desc("Don't output the .ll file"),
55 cl::Hidden
, cl::cat(DisCategory
));
58 SetImporting("set-importing",
59 cl::desc("Set lazy loading to pretend to import a module"),
60 cl::Hidden
, cl::cat(DisCategory
));
63 ShowAnnotations("show-annotations",
64 cl::desc("Add informational comments to the .ll file"),
65 cl::cat(DisCategory
));
67 static cl::opt
<bool> PreserveAssemblyUseListOrder(
68 "preserve-ll-uselistorder",
69 cl::desc("Preserve use-list order when writing LLVM assembly."),
70 cl::init(false), cl::Hidden
, cl::cat(DisCategory
));
73 MaterializeMetadata("materialize-metadata",
74 cl::desc("Load module without materializing metadata, "
75 "then materialize only the metadata"),
76 cl::cat(DisCategory
));
78 static cl::opt
<bool> PrintThinLTOIndexOnly(
79 "print-thinlto-index-only",
80 cl::desc("Only read thinlto index and print the index as LLVM assembly."),
81 cl::init(false), cl::Hidden
, cl::cat(DisCategory
));
85 static void printDebugLoc(const DebugLoc
&DL
, formatted_raw_ostream
&OS
) {
86 OS
<< DL
.getLine() << ":" << DL
.getCol();
87 if (DILocation
*IDL
= DL
.getInlinedAt()) {
89 printDebugLoc(IDL
, OS
);
92 class CommentWriter
: public AssemblyAnnotationWriter
{
94 void emitFunctionAnnot(const Function
*F
,
95 formatted_raw_ostream
&OS
) override
{
96 OS
<< "; [#uses=" << F
->getNumUses() << ']'; // Output # uses
99 void printInfoComment(const Value
&V
, formatted_raw_ostream
&OS
) override
{
101 if (!V
.getType()->isVoidTy()) {
104 // Output # uses and type
105 OS
<< "; [#uses=" << V
.getNumUses() << " type=" << *V
.getType() << "]";
107 if (const Instruction
*I
= dyn_cast
<Instruction
>(&V
)) {
108 if (const DebugLoc
&DL
= I
->getDebugLoc()) {
114 OS
<< " [debug line = ";
115 printDebugLoc(DL
,OS
);
118 if (const DbgDeclareInst
*DDI
= dyn_cast
<DbgDeclareInst
>(I
)) {
123 OS
<< " [debug variable = " << DDI
->getVariable()->getName() << "]";
125 else if (const DbgValueInst
*DVI
= dyn_cast
<DbgValueInst
>(I
)) {
130 OS
<< " [debug variable = " << DVI
->getVariable()->getName() << "]";
136 struct LLVMDisDiagnosticHandler
: public DiagnosticHandler
{
138 LLVMDisDiagnosticHandler(char *PrefixPtr
) : Prefix(PrefixPtr
) {}
139 bool handleDiagnostics(const DiagnosticInfo
&DI
) override
{
140 raw_ostream
&OS
= errs();
141 OS
<< Prefix
<< ": ";
142 switch (DI
.getSeverity()) {
143 case DS_Error
: WithColor::error(OS
); break;
144 case DS_Warning
: WithColor::warning(OS
); break;
145 case DS_Remark
: OS
<< "remark: "; break;
146 case DS_Note
: WithColor::note(OS
); break;
149 DiagnosticPrinterRawOStream
DP(OS
);
153 if (DI
.getSeverity() == DS_Error
)
158 } // end anon namespace
160 static ExitOnError ExitOnErr
;
162 int main(int argc
, char **argv
) {
163 InitLLVM
X(argc
, argv
);
165 ExitOnErr
.setBanner(std::string(argv
[0]) + ": error: ");
167 cl::HideUnrelatedOptions({&DisCategory
, &getColorCategory()});
168 cl::ParseCommandLineOptions(argc
, argv
, "llvm .bc -> .ll disassembler\n");
171 Context
.setDiagnosticHandler(
172 std::make_unique
<LLVMDisDiagnosticHandler
>(argv
[0]));
174 if (InputFilenames
.size() < 1) {
175 InputFilenames
.push_back("-");
176 } else if (InputFilenames
.size() > 1 && !OutputFilename
.empty()) {
178 << "error: output file name cannot be set for multiple input files\n";
182 for (std::string InputFilename
: InputFilenames
) {
183 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferOrErr
=
184 MemoryBuffer::getFileOrSTDIN(InputFilename
);
185 if (std::error_code EC
= BufferOrErr
.getError()) {
186 WithColor::error() << InputFilename
<< ": " << EC
.message() << '\n';
189 std::unique_ptr
<MemoryBuffer
> MB
= std::move(BufferOrErr
.get());
191 BitcodeFileContents IF
= ExitOnErr(llvm::getBitcodeFileContents(*MB
));
193 const size_t N
= IF
.Mods
.size();
195 if (OutputFilename
== "-" && N
> 1)
196 errs() << "only single module bitcode files can be written to stdout\n";
198 for (size_t I
= 0; I
< N
; ++I
) {
199 BitcodeModule MB
= IF
.Mods
[I
];
201 std::unique_ptr
<Module
> M
;
203 if (!PrintThinLTOIndexOnly
) {
205 MB
.getLazyModule(Context
, MaterializeMetadata
, SetImporting
));
206 if (MaterializeMetadata
)
207 ExitOnErr(M
->materializeMetadata());
209 ExitOnErr(M
->materializeAll());
212 BitcodeLTOInfo LTOInfo
= ExitOnErr(MB
.getLTOInfo());
213 std::unique_ptr
<ModuleSummaryIndex
> Index
;
214 if (LTOInfo
.HasSummary
)
215 Index
= ExitOnErr(MB
.getSummary());
217 std::string
FinalFilename(OutputFilename
);
219 // Just use stdout. We won't actually print anything on it.
223 if (FinalFilename
.empty()) { // Unspecified output, infer it.
224 if (InputFilename
== "-") {
227 StringRef IFN
= InputFilename
;
228 FinalFilename
= (IFN
.endswith(".bc") ? IFN
.drop_back(3) : IFN
).str();
230 FinalFilename
+= std::string(".") + std::to_string(I
);
231 FinalFilename
+= ".ll";
235 FinalFilename
+= std::string(".") + std::to_string(I
);
239 std::unique_ptr
<ToolOutputFile
> Out(
240 new ToolOutputFile(FinalFilename
, EC
, sys::fs::OF_TextWithCRLF
));
242 errs() << EC
.message() << '\n';
246 std::unique_ptr
<AssemblyAnnotationWriter
> Annotator
;
248 Annotator
.reset(new CommentWriter());
250 // All that llvm-dis does is write the assembly to a file.
253 M
->print(Out
->os(), Annotator
.get(), PreserveAssemblyUseListOrder
);
255 Index
->print(Out
->os());