Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / tools / llvm-dis / llvm-dis.cpp
blob4996fc12ae32afa5578290c83b559335494a4ec0
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
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>
37 using namespace llvm;
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));
57 static cl::opt<bool>
58 SetImporting("set-importing",
59 cl::desc("Set lazy loading to pretend to import a module"),
60 cl::Hidden, cl::cat(DisCategory));
62 static cl::opt<bool>
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));
72 static cl::opt<bool>
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));
83 namespace {
85 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
86 OS << DL.getLine() << ":" << DL.getCol();
87 if (DILocation *IDL = DL.getInlinedAt()) {
88 OS << "@";
89 printDebugLoc(IDL, OS);
92 class CommentWriter : public AssemblyAnnotationWriter {
93 public:
94 void emitFunctionAnnot(const Function *F,
95 formatted_raw_ostream &OS) override {
96 OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses
97 OS << '\n';
99 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
100 bool Padded = false;
101 if (!V.getType()->isVoidTy()) {
102 OS.PadToColumn(50);
103 Padded = true;
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()) {
109 if (!Padded) {
110 OS.PadToColumn(50);
111 Padded = true;
112 OS << ";";
114 OS << " [debug line = ";
115 printDebugLoc(DL,OS);
116 OS << "]";
118 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
119 if (!Padded) {
120 OS.PadToColumn(50);
121 OS << ";";
123 OS << " [debug variable = " << DDI->getVariable()->getName() << "]";
125 else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
126 if (!Padded) {
127 OS.PadToColumn(50);
128 OS << ";";
130 OS << " [debug variable = " << DVI->getVariable()->getName() << "]";
136 struct LLVMDisDiagnosticHandler : public DiagnosticHandler {
137 char *Prefix;
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);
150 DI.print(DP);
151 OS << '\n';
153 if (DI.getSeverity() == DS_Error)
154 exit(1);
155 return true;
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");
170 LLVMContext Context;
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()) {
177 errs()
178 << "error: output file name cannot be set for multiple input files\n";
179 return 1;
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';
187 return 1;
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) {
204 M = ExitOnErr(
205 MB.getLazyModule(Context, MaterializeMetadata, SetImporting));
206 if (MaterializeMetadata)
207 ExitOnErr(M->materializeMetadata());
208 else
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.
220 if (DontPrint)
221 FinalFilename = "-";
223 if (FinalFilename.empty()) { // Unspecified output, infer it.
224 if (InputFilename == "-") {
225 FinalFilename = "-";
226 } else {
227 StringRef IFN = InputFilename;
228 FinalFilename = (IFN.endswith(".bc") ? IFN.drop_back(3) : IFN).str();
229 if (N > 1)
230 FinalFilename += std::string(".") + std::to_string(I);
231 FinalFilename += ".ll";
233 } else {
234 if (N > 1)
235 FinalFilename += std::string(".") + std::to_string(I);
238 std::error_code EC;
239 std::unique_ptr<ToolOutputFile> Out(
240 new ToolOutputFile(FinalFilename, EC, sys::fs::OF_TextWithCRLF));
241 if (EC) {
242 errs() << EC.message() << '\n';
243 return 1;
246 std::unique_ptr<AssemblyAnnotationWriter> Annotator;
247 if (ShowAnnotations)
248 Annotator.reset(new CommentWriter());
250 // All that llvm-dis does is write the assembly to a file.
251 if (!DontPrint) {
252 if (M)
253 M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);
254 if (Index)
255 Index->print(Out->os());
258 // Declare success.
259 Out->keep();
263 return 0;