]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-dis/llvm-dis.cpp
MFV 331704:
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-dis / llvm-dis.cpp
1 //===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility may be invoked in the following manner:
11 //  llvm-dis [options]      - Read LLVM bitcode from stdin, write asm to stdout
12 //  llvm-dis [options] x.bc - Read LLVM bitcode from the x.bc file, write asm
13 //                            to the x.ll file.
14 //  Options:
15 //      --help   - Output information about command line switches
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/Bitcode/BitcodeReader.h"
21 #include "llvm/IR/AssemblyAnnotationWriter.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/DiagnosticPrinter.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Module.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/ManagedStatic.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/ToolOutputFile.h"
37 #include <system_error>
38 using namespace llvm;
39
40 static cl::opt<std::string>
41 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
42
43 static cl::opt<std::string>
44 OutputFilename("o", cl::desc("Override output filename"),
45                cl::value_desc("filename"));
46
47 static cl::opt<bool>
48 Force("f", cl::desc("Enable binary output on terminals"));
49
50 static cl::opt<bool>
51 DontPrint("disable-output", cl::desc("Don't output the .ll file"), cl::Hidden);
52
53 static cl::opt<bool>
54     SetImporting("set-importing",
55                  cl::desc("Set lazy loading to pretend to import a module"),
56                  cl::Hidden);
57
58 static cl::opt<bool>
59     ShowAnnotations("show-annotations",
60                     cl::desc("Add informational comments to the .ll file"));
61
62 static cl::opt<bool> PreserveAssemblyUseListOrder(
63     "preserve-ll-uselistorder",
64     cl::desc("Preserve use-list order when writing LLVM assembly."),
65     cl::init(false), cl::Hidden);
66
67 static cl::opt<bool>
68     MaterializeMetadata("materialize-metadata",
69                         cl::desc("Load module without materializing metadata, "
70                                  "then materialize only the metadata"));
71
72 namespace {
73
74 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
75   OS << DL.getLine() << ":" << DL.getCol();
76   if (DILocation *IDL = DL.getInlinedAt()) {
77     OS << "@";
78     printDebugLoc(IDL, OS);
79   }
80 }
81 class CommentWriter : public AssemblyAnnotationWriter {
82 public:
83   void emitFunctionAnnot(const Function *F,
84                          formatted_raw_ostream &OS) override {
85     OS << "; [#uses=" << F->getNumUses() << ']';  // Output # uses
86     OS << '\n';
87   }
88   void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
89     bool Padded = false;
90     if (!V.getType()->isVoidTy()) {
91       OS.PadToColumn(50);
92       Padded = true;
93       // Output # uses and type
94       OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]";
95     }
96     if (const Instruction *I = dyn_cast<Instruction>(&V)) {
97       if (const DebugLoc &DL = I->getDebugLoc()) {
98         if (!Padded) {
99           OS.PadToColumn(50);
100           Padded = true;
101           OS << ";";
102         }
103         OS << " [debug line = ";
104         printDebugLoc(DL,OS);
105         OS << "]";
106       }
107       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
108         if (!Padded) {
109           OS.PadToColumn(50);
110           OS << ";";
111         }
112         OS << " [debug variable = " << DDI->getVariable()->getName() << "]";
113       }
114       else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
115         if (!Padded) {
116           OS.PadToColumn(50);
117           OS << ";";
118         }
119         OS << " [debug variable = " << DVI->getVariable()->getName() << "]";
120       }
121     }
122   }
123 };
124
125 struct LLVMDisDiagnosticHandler : public DiagnosticHandler {
126   char *Prefix;
127   LLVMDisDiagnosticHandler(char *PrefixPtr) : Prefix(PrefixPtr) {}
128   bool handleDiagnostics(const DiagnosticInfo &DI) override {
129     raw_ostream &OS = errs();
130     OS << Prefix << ": ";
131     switch (DI.getSeverity()) {
132       case DS_Error: OS << "error: "; break;
133       case DS_Warning: OS << "warning: "; break;
134       case DS_Remark: OS << "remark: "; break;
135       case DS_Note: OS << "note: "; break;
136     }
137
138     DiagnosticPrinterRawOStream DP(OS);
139     DI.print(DP);
140     OS << '\n';
141
142     if (DI.getSeverity() == DS_Error)
143       exit(1);
144     return true;
145   }
146 };
147 } // end anon namespace
148
149 static ExitOnError ExitOnErr;
150
151 static std::unique_ptr<Module> openInputFile(LLVMContext &Context) {
152   std::unique_ptr<MemoryBuffer> MB =
153       ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
154   std::unique_ptr<Module> M = ExitOnErr(getOwningLazyBitcodeModule(
155       std::move(MB), Context,
156       /*ShouldLazyLoadMetadata=*/true, SetImporting));
157   if (MaterializeMetadata)
158     ExitOnErr(M->materializeMetadata());
159   else
160     ExitOnErr(M->materializeAll());
161   return M;
162 }
163
164 int main(int argc, char **argv) {
165   // Print a stack trace if we signal out.
166   sys::PrintStackTraceOnErrorSignal(argv[0]);
167   PrettyStackTraceProgram X(argc, argv);
168
169   ExitOnErr.setBanner(std::string(argv[0]) + ": error: ");
170
171   LLVMContext Context;
172   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
173   Context.setDiagnosticHandler(
174       llvm::make_unique<LLVMDisDiagnosticHandler>(argv[0]));
175   cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
176
177   std::unique_ptr<Module> M = openInputFile(Context);
178
179   // Just use stdout.  We won't actually print anything on it.
180   if (DontPrint)
181     OutputFilename = "-";
182
183   if (OutputFilename.empty()) { // Unspecified output, infer it.
184     if (InputFilename == "-") {
185       OutputFilename = "-";
186     } else {
187       StringRef IFN = InputFilename;
188       OutputFilename = (IFN.endswith(".bc") ? IFN.drop_back(3) : IFN).str();
189       OutputFilename += ".ll";
190     }
191   }
192
193   std::error_code EC;
194   std::unique_ptr<ToolOutputFile> Out(
195       new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
196   if (EC) {
197     errs() << EC.message() << '\n';
198     return 1;
199   }
200
201   std::unique_ptr<AssemblyAnnotationWriter> Annotator;
202   if (ShowAnnotations)
203     Annotator.reset(new CommentWriter());
204
205   // All that llvm-dis does is write the assembly to a file.
206   if (!DontPrint)
207     M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);
208
209   // Declare success.
210   Out->keep();
211
212   return 0;
213 }