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