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
16 // --color - Use colors in output (default=autodetect)
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
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
32 //===----------------------------------------------------------------------===//
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>
55 static cl::OptionCategory
DisCategory("Disassembler Options");
57 static cl::list
<std::string
> InputFilenames(cl::Positional
,
58 cl::desc("[input bitcode]..."),
59 cl::cat(DisCategory
));
61 static cl::opt
<std::string
> OutputFilename("o",
62 cl::desc("Override output filename"),
63 cl::value_desc("filename"),
64 cl::cat(DisCategory
));
66 static cl::opt
<bool> Force("f", cl::desc("Enable binary output on terminals"),
67 cl::cat(DisCategory
));
69 static cl::opt
<bool> DontPrint("disable-output",
70 cl::desc("Don't output the .ll file"),
71 cl::Hidden
, cl::cat(DisCategory
));
74 SetImporting("set-importing",
75 cl::desc("Set lazy loading to pretend to import a module"),
76 cl::Hidden
, cl::cat(DisCategory
));
79 ShowAnnotations("show-annotations",
80 cl::desc("Add informational comments to the .ll file"),
81 cl::cat(DisCategory
));
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
));
89 MaterializeMetadata("materialize-metadata",
90 cl::desc("Load module without materializing metadata, "
91 "then materialize only the metadata"),
92 cl::cat(DisCategory
));
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
));
99 extern cl::opt
<bool> WriteNewDbgInfoFormat
;
101 extern cl::opt
<cl::boolOrDefault
> LoadBitcodeIntoNewDbgInfoFormat
;
105 static void printDebugLoc(const DebugLoc
&DL
, formatted_raw_ostream
&OS
) {
106 OS
<< DL
.getLine() << ":" << DL
.getCol();
107 if (DILocation
*IDL
= DL
.getInlinedAt()) {
109 printDebugLoc(IDL
, OS
);
112 class CommentWriter
: public AssemblyAnnotationWriter
{
114 void emitFunctionAnnot(const Function
*F
,
115 formatted_raw_ostream
&OS
) override
{
116 OS
<< "; [#uses=" << F
->getNumUses() << ']'; // Output # uses
119 void printInfoComment(const Value
&V
, formatted_raw_ostream
&OS
) override
{
121 if (!V
.getType()->isVoidTy()) {
124 // Output # uses and type
125 OS
<< "; [#uses=" << V
.getNumUses() << " type=" << *V
.getType() << "]";
127 if (const Instruction
*I
= dyn_cast
<Instruction
>(&V
)) {
128 if (const DebugLoc
&DL
= I
->getDebugLoc()) {
134 OS
<< " [debug line = ";
135 printDebugLoc(DL
,OS
);
138 if (const DbgDeclareInst
*DDI
= dyn_cast
<DbgDeclareInst
>(I
)) {
143 OS
<< " [debug variable = " << DDI
->getVariable()->getName() << "]";
145 else if (const DbgValueInst
*DVI
= dyn_cast
<DbgValueInst
>(I
)) {
150 OS
<< " [debug variable = " << DVI
->getVariable()->getName() << "]";
156 struct LLVMDisDiagnosticHandler
: public DiagnosticHandler
{
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;
169 DiagnosticPrinterRawOStream
DP(OS
);
173 if (DI
.getSeverity() == DS_Error
)
178 } // end anon namespace
180 static ExitOnError ExitOnErr
;
182 int main(int argc
, char **argv
) {
183 InitLLVM
X(argc
, argv
);
185 ExitOnErr
.setBanner(std::string(argv
[0]) + ": error: ");
187 cl::HideUnrelatedOptions({&DisCategory
, &getColorCategory()});
188 cl::ParseCommandLineOptions(argc
, argv
, "llvm .bc -> .ll disassembler\n");
190 // Load bitcode into the new debug info format by default.
191 if (LoadBitcodeIntoNewDbgInfoFormat
== cl::boolOrDefault::BOU_UNSET
)
192 LoadBitcodeIntoNewDbgInfoFormat
= cl::boolOrDefault::BOU_TRUE
;
194 if (InputFilenames
.size() < 1) {
195 InputFilenames
.push_back("-");
196 } else if (InputFilenames
.size() > 1 && !OutputFilename
.empty()) {
198 << "error: output file name cannot be set for multiple input files\n";
202 for (const auto &InputFilename
: InputFilenames
) {
203 // Use a fresh context for each input to avoid state
204 // cross-contamination across inputs (e.g. type name collisions).
206 Context
.setDiagnosticHandler(
207 std::make_unique
<LLVMDisDiagnosticHandler
>(argv
[0]));
209 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferOrErr
=
210 MemoryBuffer::getFileOrSTDIN(InputFilename
);
211 if (std::error_code EC
= BufferOrErr
.getError()) {
212 WithColor::error() << InputFilename
<< ": " << EC
.message() << '\n';
215 std::unique_ptr
<MemoryBuffer
> MB
= std::move(BufferOrErr
.get());
217 BitcodeFileContents IF
= ExitOnErr(llvm::getBitcodeFileContents(*MB
));
219 const size_t N
= IF
.Mods
.size();
221 if (OutputFilename
== "-" && N
> 1)
222 errs() << "only single module bitcode files can be written to stdout\n";
224 for (size_t I
= 0; I
< N
; ++I
) {
225 BitcodeModule MB
= IF
.Mods
[I
];
227 std::unique_ptr
<Module
> M
;
229 if (!PrintThinLTOIndexOnly
) {
231 MB
.getLazyModule(Context
, MaterializeMetadata
, SetImporting
));
232 if (MaterializeMetadata
)
233 ExitOnErr(M
->materializeMetadata());
235 ExitOnErr(M
->materializeAll());
238 BitcodeLTOInfo LTOInfo
= ExitOnErr(MB
.getLTOInfo());
239 std::unique_ptr
<ModuleSummaryIndex
> Index
;
240 if (LTOInfo
.HasSummary
)
241 Index
= ExitOnErr(MB
.getSummary());
243 std::string
FinalFilename(OutputFilename
);
245 // Just use stdout. We won't actually print anything on it.
249 if (FinalFilename
.empty()) { // Unspecified output, infer it.
250 if (InputFilename
== "-") {
253 StringRef IFN
= InputFilename
;
254 FinalFilename
= (IFN
.ends_with(".bc") ? IFN
.drop_back(3) : IFN
).str();
256 FinalFilename
+= std::string(".") + std::to_string(I
);
257 FinalFilename
+= ".ll";
261 FinalFilename
+= std::string(".") + std::to_string(I
);
265 std::unique_ptr
<ToolOutputFile
> Out(
266 new ToolOutputFile(FinalFilename
, EC
, sys::fs::OF_TextWithCRLF
));
268 errs() << EC
.message() << '\n';
272 std::unique_ptr
<AssemblyAnnotationWriter
> Annotator
;
274 Annotator
.reset(new CommentWriter());
276 // All that llvm-dis does is write the assembly to a file.
279 M
->setIsNewDbgInfoFormat(WriteNewDbgInfoFormat
);
280 if (WriteNewDbgInfoFormat
)
281 M
->removeDebugIntrinsicDeclarations();
282 M
->print(Out
->os(), Annotator
.get(), PreserveAssemblyUseListOrder
);
285 Index
->print(Out
->os());