Home | History | Annotate | Download | only in llvm-dis
      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/ReaderWriter.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/DataStream.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 ShowAnnotations("show-annotations",
     55                 cl::desc("Add informational comments to the .ll file"));
     56 
     57 static cl::opt<bool> PreserveAssemblyUseListOrder(
     58     "preserve-ll-uselistorder",
     59     cl::desc("Preserve use-list order when writing LLVM assembly."),
     60     cl::init(false), cl::Hidden);
     61 
     62 namespace {
     63 
     64 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
     65   OS << DL.getLine() << ":" << DL.getCol();
     66   if (MDLocation *IDL = DL.getInlinedAt()) {
     67     OS << "@";
     68     printDebugLoc(IDL, OS);
     69   }
     70 }
     71 class CommentWriter : public AssemblyAnnotationWriter {
     72 public:
     73   void emitFunctionAnnot(const Function *F,
     74                          formatted_raw_ostream &OS) override {
     75     OS << "; [#uses=" << F->getNumUses() << ']';  // Output # uses
     76     OS << '\n';
     77   }
     78   void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
     79     bool Padded = false;
     80     if (!V.getType()->isVoidTy()) {
     81       OS.PadToColumn(50);
     82       Padded = true;
     83       OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]";  // Output # uses and type
     84     }
     85     if (const Instruction *I = dyn_cast<Instruction>(&V)) {
     86       if (const DebugLoc &DL = I->getDebugLoc()) {
     87         if (!Padded) {
     88           OS.PadToColumn(50);
     89           Padded = true;
     90           OS << ";";
     91         }
     92         OS << " [debug line = ";
     93         printDebugLoc(DL,OS);
     94         OS << "]";
     95       }
     96       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
     97         DIVariable Var(DDI->getVariable());
     98         if (!Padded) {
     99           OS.PadToColumn(50);
    100           OS << ";";
    101         }
    102         OS << " [debug variable = " << Var->getName() << "]";
    103       }
    104       else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
    105         DIVariable Var(DVI->getVariable());
    106         if (!Padded) {
    107           OS.PadToColumn(50);
    108           OS << ";";
    109         }
    110         OS << " [debug variable = " << Var->getName() << "]";
    111       }
    112     }
    113   }
    114 };
    115 
    116 } // end anon namespace
    117 
    118 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
    119   raw_ostream &OS = errs();
    120   OS << (char *)Context << ": ";
    121   switch (DI.getSeverity()) {
    122   case DS_Error: OS << "error: "; break;
    123   case DS_Warning: OS << "warning: "; break;
    124   case DS_Remark: OS << "remark: "; break;
    125   case DS_Note: OS << "note: "; break;
    126   }
    127 
    128   DiagnosticPrinterRawOStream DP(OS);
    129   DI.print(DP);
    130   OS << '\n';
    131 
    132   if (DI.getSeverity() == DS_Error)
    133     exit(1);
    134 }
    135 
    136 int main(int argc, char **argv) {
    137   // Print a stack trace if we signal out.
    138   sys::PrintStackTraceOnErrorSignal();
    139   PrettyStackTraceProgram X(argc, argv);
    140 
    141   LLVMContext &Context = getGlobalContext();
    142   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
    143 
    144   Context.setDiagnosticHandler(diagnosticHandler, argv[0]);
    145 
    146   cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
    147 
    148   std::string ErrorMessage;
    149   std::unique_ptr<Module> M;
    150 
    151   // Use the bitcode streaming interface
    152   DataStreamer *Streamer = getDataFileStreamer(InputFilename, &ErrorMessage);
    153   if (Streamer) {
    154     std::string DisplayFilename;
    155     if (InputFilename == "-")
    156       DisplayFilename = "<stdin>";
    157     else
    158       DisplayFilename = InputFilename;
    159     ErrorOr<std::unique_ptr<Module>> MOrErr =
    160         getStreamedBitcodeModule(DisplayFilename, Streamer, Context);
    161     M = std::move(*MOrErr);
    162     M->materializeAllPermanently();
    163   }
    164 
    165   // Just use stdout.  We won't actually print anything on it.
    166   if (DontPrint)
    167     OutputFilename = "-";
    168 
    169   if (OutputFilename.empty()) { // Unspecified output, infer it.
    170     if (InputFilename == "-") {
    171       OutputFilename = "-";
    172     } else {
    173       const std::string &IFN = InputFilename;
    174       int Len = IFN.length();
    175       // If the source ends in .bc, strip it off.
    176       if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c')
    177         OutputFilename = std::string(IFN.begin(), IFN.end()-3)+".ll";
    178       else
    179         OutputFilename = IFN+".ll";
    180     }
    181   }
    182 
    183   std::error_code EC;
    184   std::unique_ptr<tool_output_file> Out(
    185       new tool_output_file(OutputFilename, EC, sys::fs::F_None));
    186   if (EC) {
    187     errs() << EC.message() << '\n';
    188     return 1;
    189   }
    190 
    191   std::unique_ptr<AssemblyAnnotationWriter> Annotator;
    192   if (ShowAnnotations)
    193     Annotator.reset(new CommentWriter());
    194 
    195   // All that llvm-dis does is write the assembly to a file.
    196   if (!DontPrint)
    197     M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);
    198 
    199   // Declare success.
    200   Out->keep();
    201 
    202   return 0;
    203 }
    204