LLVM API Documentation

Disassembler.cpp
Go to the documentation of this file.
00001 //===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "Disassembler.h"
00011 #include "llvm-c/Disassembler.h"
00012 #include "llvm/MC/MCAsmInfo.h"
00013 #include "llvm/MC/MCContext.h"
00014 #include "llvm/MC/MCDisassembler.h"
00015 #include "llvm/MC/MCInst.h"
00016 #include "llvm/MC/MCInstPrinter.h"
00017 #include "llvm/MC/MCInstrInfo.h"
00018 #include "llvm/MC/MCRegisterInfo.h"
00019 #include "llvm/MC/MCRelocationInfo.h"
00020 #include "llvm/MC/MCSubtargetInfo.h"
00021 #include "llvm/MC/MCSymbolizer.h"
00022 #include "llvm/Support/ErrorHandling.h"
00023 #include "llvm/Support/FormattedStream.h"
00024 #include "llvm/Support/MemoryObject.h"
00025 #include "llvm/Support/TargetRegistry.h"
00026 
00027 using namespace llvm;
00028 
00029 // LLVMCreateDisasm() creates a disassembler for the TripleName.  Symbolic
00030 // disassembly is supported by passing a block of information in the DisInfo
00031 // parameter and specifying the TagType and callback functions as described in
00032 // the header llvm-c/Disassembler.h .  The pointer to the block and the 
00033 // functions can all be passed as NULL.  If successful, this returns a
00034 // disassembler context.  If not, it returns NULL.
00035 //
00036 LLVMDisasmContextRef LLVMCreateDisasmCPU(const char *Triple, const char *CPU,
00037                                          void *DisInfo, int TagType,
00038                                          LLVMOpInfoCallback GetOpInfo,
00039                                          LLVMSymbolLookupCallback SymbolLookUp){
00040   // Get the target.
00041   std::string Error;
00042   const Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
00043   if (!TheTarget)
00044     return nullptr;
00045 
00046   const MCRegisterInfo *MRI = TheTarget->createMCRegInfo(Triple);
00047   if (!MRI)
00048     return nullptr;
00049 
00050   // Get the assembler info needed to setup the MCContext.
00051   const MCAsmInfo *MAI = TheTarget->createMCAsmInfo(*MRI, Triple);
00052   if (!MAI)
00053     return nullptr;
00054 
00055   const MCInstrInfo *MII = TheTarget->createMCInstrInfo();
00056   if (!MII)
00057     return nullptr;
00058 
00059   // Package up features to be passed to target/subtarget
00060   std::string FeaturesStr;
00061 
00062   const MCSubtargetInfo *STI = TheTarget->createMCSubtargetInfo(Triple, CPU,
00063                                                                 FeaturesStr);
00064   if (!STI)
00065     return nullptr;
00066 
00067   // Set up the MCContext for creating symbols and MCExpr's.
00068   MCContext *Ctx = new MCContext(MAI, MRI, nullptr);
00069   if (!Ctx)
00070     return nullptr;
00071 
00072   // Set up disassembler.
00073   MCDisassembler *DisAsm = TheTarget->createMCDisassembler(*STI, *Ctx);
00074   if (!DisAsm)
00075     return nullptr;
00076 
00077   std::unique_ptr<MCRelocationInfo> RelInfo(
00078       TheTarget->createMCRelocationInfo(Triple, *Ctx));
00079   if (!RelInfo)
00080     return nullptr;
00081 
00082   std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
00083       Triple, GetOpInfo, SymbolLookUp, DisInfo, Ctx, RelInfo.release()));
00084   DisAsm->setSymbolizer(std::move(Symbolizer));
00085 
00086   // Set up the instruction printer.
00087   int AsmPrinterVariant = MAI->getAssemblerDialect();
00088   MCInstPrinter *IP = TheTarget->createMCInstPrinter(AsmPrinterVariant,
00089                                                      *MAI, *MII, *MRI, *STI);
00090   if (!IP)
00091     return nullptr;
00092 
00093   LLVMDisasmContext *DC = new LLVMDisasmContext(Triple, DisInfo, TagType,
00094                                                 GetOpInfo, SymbolLookUp,
00095                                                 TheTarget, MAI, MRI,
00096                                                 STI, MII, Ctx, DisAsm, IP);
00097   if (!DC)
00098     return nullptr;
00099 
00100   DC->setCPU(CPU);
00101   return DC;
00102 }
00103 
00104 LLVMDisasmContextRef LLVMCreateDisasm(const char *Triple, void *DisInfo,
00105                                       int TagType, LLVMOpInfoCallback GetOpInfo,
00106                                       LLVMSymbolLookupCallback SymbolLookUp) {
00107   return LLVMCreateDisasmCPU(Triple, "", DisInfo, TagType, GetOpInfo,
00108                              SymbolLookUp);
00109 }
00110 
00111 //
00112 // LLVMDisasmDispose() disposes of the disassembler specified by the context.
00113 //
00114 void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
00115   LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
00116   delete DC;
00117 }
00118 
00119 namespace {
00120 //
00121 // The memory object created by LLVMDisasmInstruction().
00122 //
00123 class DisasmMemoryObject : public MemoryObject {
00124   uint8_t *Bytes;
00125   uint64_t Size;
00126   uint64_t BasePC;
00127 public:
00128   DisasmMemoryObject(uint8_t *bytes, uint64_t size, uint64_t basePC) :
00129                      Bytes(bytes), Size(size), BasePC(basePC) {}
00130 
00131   uint64_t getBase() const override { return BasePC; }
00132   uint64_t getExtent() const override { return Size; }
00133 
00134   int readByte(uint64_t Addr, uint8_t *Byte) const override {
00135     if (Addr - BasePC >= Size)
00136       return -1;
00137     *Byte = Bytes[Addr - BasePC];
00138     return 0;
00139   }
00140 };
00141 } // end anonymous namespace
00142 
00143 /// \brief Emits the comments that are stored in \p DC comment stream.
00144 /// Each comment in the comment stream must end with a newline.
00145 static void emitComments(LLVMDisasmContext *DC,
00146                          formatted_raw_ostream &FormattedOS) {
00147   // Flush the stream before taking its content.
00148   DC->CommentStream.flush();
00149   StringRef Comments = DC->CommentsToEmit.str();
00150   // Get the default information for printing a comment.
00151   const MCAsmInfo *MAI = DC->getAsmInfo();
00152   const char *CommentBegin = MAI->getCommentString();
00153   unsigned CommentColumn = MAI->getCommentColumn();
00154   bool IsFirst = true;
00155   while (!Comments.empty()) {
00156     if (!IsFirst)
00157       FormattedOS << '\n';
00158     // Emit a line of comments.
00159     FormattedOS.PadToColumn(CommentColumn);
00160     size_t Position = Comments.find('\n');
00161     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
00162     // Move after the newline character.
00163     Comments = Comments.substr(Position+1);
00164     IsFirst = false;
00165   }
00166   FormattedOS.flush();
00167 
00168   // Tell the comment stream that the vector changed underneath it.
00169   DC->CommentsToEmit.clear();
00170   DC->CommentStream.resync();
00171 }
00172 
00173 /// \brief Gets latency information for \p Inst form the itinerary
00174 /// scheduling model, based on \p DC information.
00175 /// \return The maximum expected latency over all the operands or -1
00176 /// if no information are available.
00177 static int getItineraryLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
00178   const int NoInformationAvailable = -1;
00179 
00180   // Check if we have a CPU to get the itinerary information.
00181   if (DC->getCPU().empty())
00182     return NoInformationAvailable;
00183 
00184   // Get itinerary information.
00185   const MCSubtargetInfo *STI = DC->getSubtargetInfo();
00186   InstrItineraryData IID = STI->getInstrItineraryForCPU(DC->getCPU());
00187   // Get the scheduling class of the requested instruction.
00188   const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
00189   unsigned SCClass = Desc.getSchedClass();
00190 
00191   int Latency = 0;
00192   for (unsigned OpIdx = 0, OpIdxEnd = Inst.getNumOperands(); OpIdx != OpIdxEnd;
00193        ++OpIdx)
00194     Latency = std::max(Latency, IID.getOperandCycle(SCClass, OpIdx));
00195 
00196   return Latency;
00197 }
00198 
00199 /// \brief Gets latency information for \p Inst, based on \p DC information.
00200 /// \return The maximum expected latency over all the definitions or -1
00201 /// if no information are available.
00202 static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
00203   // Try to compute scheduling information.
00204   const MCSubtargetInfo *STI = DC->getSubtargetInfo();
00205   const MCSchedModel SCModel = STI->getSchedModel();
00206   const int NoInformationAvailable = -1;
00207 
00208   // Check if we have a scheduling model for instructions.
00209   if (!SCModel.hasInstrSchedModel())
00210     // Try to fall back to the itinerary model if the scheduling model doesn't
00211     // have a scheduling table.  Note the default does not have a table.
00212     return getItineraryLatency(DC, Inst);
00213 
00214   // Get the scheduling class of the requested instruction.
00215   const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
00216   unsigned SCClass = Desc.getSchedClass();
00217   const MCSchedClassDesc *SCDesc = SCModel.getSchedClassDesc(SCClass);
00218   // Resolving the variant SchedClass requires an MI to pass to
00219   // SubTargetInfo::resolveSchedClass.
00220   if (!SCDesc || !SCDesc->isValid() || SCDesc->isVariant())
00221     return NoInformationAvailable;
00222 
00223   // Compute output latency.
00224   int Latency = 0;
00225   for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
00226        DefIdx != DefEnd; ++DefIdx) {
00227     // Lookup the definition's write latency in SubtargetInfo.
00228     const MCWriteLatencyEntry *WLEntry = STI->getWriteLatencyEntry(SCDesc,
00229                                                                    DefIdx);
00230     Latency = std::max(Latency, WLEntry->Cycles);
00231   }
00232 
00233   return Latency;
00234 }
00235 
00236 
00237 /// \brief Emits latency information in DC->CommentStream for \p Inst, based
00238 /// on the information available in \p DC.
00239 static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
00240   int Latency = getLatency(DC, Inst);
00241 
00242   // Report only interesting latency.
00243   if (Latency < 2)
00244     return;
00245 
00246   DC->CommentStream << "Latency: " << Latency << '\n';
00247 }
00248 
00249 //
00250 // LLVMDisasmInstruction() disassembles a single instruction using the
00251 // disassembler context specified in the parameter DC.  The bytes of the
00252 // instruction are specified in the parameter Bytes, and contains at least
00253 // BytesSize number of bytes.  The instruction is at the address specified by
00254 // the PC parameter.  If a valid instruction can be disassembled its string is
00255 // returned indirectly in OutString which whos size is specified in the
00256 // parameter OutStringSize.  This function returns the number of bytes in the
00257 // instruction or zero if there was no valid instruction.  If this function
00258 // returns zero the caller will have to pick how many bytes they want to step
00259 // over by printing a .byte, .long etc. to continue.
00260 //
00261 size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
00262                              uint64_t BytesSize, uint64_t PC, char *OutString,
00263                              size_t OutStringSize){
00264   LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
00265   // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
00266   DisasmMemoryObject MemoryObject(Bytes, BytesSize, PC);
00267 
00268   uint64_t Size;
00269   MCInst Inst;
00270   const MCDisassembler *DisAsm = DC->getDisAsm();
00271   MCInstPrinter *IP = DC->getIP();
00272   MCDisassembler::DecodeStatus S;
00273   SmallVector<char, 64> InsnStr;
00274   raw_svector_ostream Annotations(InsnStr);
00275   S = DisAsm->getInstruction(Inst, Size, MemoryObject, PC,
00276                              /*REMOVE*/ nulls(), Annotations);
00277   switch (S) {
00278   case MCDisassembler::Fail:
00279   case MCDisassembler::SoftFail:
00280     // FIXME: Do something different for soft failure modes?
00281     return 0;
00282 
00283   case MCDisassembler::Success: {
00284     Annotations.flush();
00285     StringRef AnnotationsStr = Annotations.str();
00286 
00287     SmallVector<char, 64> InsnStr;
00288     raw_svector_ostream OS(InsnStr);
00289     formatted_raw_ostream FormattedOS(OS);
00290     IP->printInst(&Inst, FormattedOS, AnnotationsStr);
00291 
00292     if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
00293       emitLatency(DC, Inst);
00294 
00295     emitComments(DC, FormattedOS);
00296     OS.flush();
00297 
00298     assert(OutStringSize != 0 && "Output buffer cannot be zero size");
00299     size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
00300     std::memcpy(OutString, InsnStr.data(), OutputSize);
00301     OutString[OutputSize] = '\0'; // Terminate string.
00302 
00303     return Size;
00304   }
00305   }
00306   llvm_unreachable("Invalid DecodeStatus!");
00307 }
00308 
00309 //
00310 // LLVMSetDisasmOptions() sets the disassembler's options.  It returns 1 if it
00311 // can set all the Options and 0 otherwise.
00312 //
00313 int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
00314   if (Options & LLVMDisassembler_Option_UseMarkup){
00315       LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
00316       MCInstPrinter *IP = DC->getIP();
00317       IP->setUseMarkup(1);
00318       DC->addOptions(LLVMDisassembler_Option_UseMarkup);
00319       Options &= ~LLVMDisassembler_Option_UseMarkup;
00320   }
00321   if (Options & LLVMDisassembler_Option_PrintImmHex){
00322       LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
00323       MCInstPrinter *IP = DC->getIP();
00324       IP->setPrintImmHex(1);
00325       DC->addOptions(LLVMDisassembler_Option_PrintImmHex);
00326       Options &= ~LLVMDisassembler_Option_PrintImmHex;
00327   }
00328   if (Options & LLVMDisassembler_Option_AsmPrinterVariant){
00329       LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
00330       // Try to set up the new instruction printer.
00331       const MCAsmInfo *MAI = DC->getAsmInfo();
00332       const MCInstrInfo *MII = DC->getInstrInfo();
00333       const MCRegisterInfo *MRI = DC->getRegisterInfo();
00334       const MCSubtargetInfo *STI = DC->getSubtargetInfo();
00335       int AsmPrinterVariant = MAI->getAssemblerDialect();
00336       AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
00337       MCInstPrinter *IP = DC->getTarget()->createMCInstPrinter(
00338           AsmPrinterVariant, *MAI, *MII, *MRI, *STI);
00339       if (IP) {
00340         DC->setIP(IP);
00341         DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
00342         Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
00343       }
00344   }
00345   if (Options & LLVMDisassembler_Option_SetInstrComments) {
00346     LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
00347     MCInstPrinter *IP = DC->getIP();
00348     IP->setCommentStream(DC->CommentStream);
00349     DC->addOptions(LLVMDisassembler_Option_SetInstrComments);
00350     Options &= ~LLVMDisassembler_Option_SetInstrComments;
00351   }
00352   if (Options & LLVMDisassembler_Option_PrintLatency) {
00353     LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
00354     DC->addOptions(LLVMDisassembler_Option_PrintLatency);
00355     Options &= ~LLVMDisassembler_Option_PrintLatency;
00356   }
00357   return (Options == 0);
00358 }