Disassembler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. //===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
  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. #include "Disassembler.h"
  9. #include "llvm-c/Disassembler.h"
  10. #include "llvm/ADT/ArrayRef.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/Triple.h"
  13. #include "llvm/MC/MCAsmInfo.h"
  14. #include "llvm/MC/MCContext.h"
  15. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  16. #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
  17. #include "llvm/MC/MCDisassembler/MCSymbolizer.h"
  18. #include "llvm/MC/MCInst.h"
  19. #include "llvm/MC/MCInstPrinter.h"
  20. #include "llvm/MC/MCInstrDesc.h"
  21. #include "llvm/MC/MCInstrInfo.h"
  22. #include "llvm/MC/MCInstrItineraries.h"
  23. #include "llvm/MC/MCRegisterInfo.h"
  24. #include "llvm/MC/MCSchedule.h"
  25. #include "llvm/MC/MCSubtargetInfo.h"
  26. #include "llvm/MC/MCTargetOptions.h"
  27. #include "llvm/MC/TargetRegistry.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/FormattedStream.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <cassert>
  32. #include <cstring>
  33. using namespace llvm;
  34. // LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
  35. // disassembly is supported by passing a block of information in the DisInfo
  36. // parameter and specifying the TagType and callback functions as described in
  37. // the header llvm-c/Disassembler.h . The pointer to the block and the
  38. // functions can all be passed as NULL. If successful, this returns a
  39. // disassembler context. If not, it returns NULL.
  40. //
  41. LLVMDisasmContextRef
  42. LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
  43. const char *Features, void *DisInfo, int TagType,
  44. LLVMOpInfoCallback GetOpInfo,
  45. LLVMSymbolLookupCallback SymbolLookUp) {
  46. // Get the target.
  47. std::string Error;
  48. const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error);
  49. if (!TheTarget)
  50. return nullptr;
  51. std::unique_ptr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
  52. if (!MRI)
  53. return nullptr;
  54. MCTargetOptions MCOptions;
  55. // Get the assembler info needed to setup the MCContext.
  56. std::unique_ptr<const MCAsmInfo> MAI(
  57. TheTarget->createMCAsmInfo(*MRI, TT, MCOptions));
  58. if (!MAI)
  59. return nullptr;
  60. std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  61. if (!MII)
  62. return nullptr;
  63. std::unique_ptr<const MCSubtargetInfo> STI(
  64. TheTarget->createMCSubtargetInfo(TT, CPU, Features));
  65. if (!STI)
  66. return nullptr;
  67. // Set up the MCContext for creating symbols and MCExpr's.
  68. std::unique_ptr<MCContext> Ctx(
  69. new MCContext(Triple(TT), MAI.get(), MRI.get(), STI.get()));
  70. if (!Ctx)
  71. return nullptr;
  72. // Set up disassembler.
  73. std::unique_ptr<MCDisassembler> DisAsm(
  74. TheTarget->createMCDisassembler(*STI, *Ctx));
  75. if (!DisAsm)
  76. return nullptr;
  77. std::unique_ptr<MCRelocationInfo> RelInfo(
  78. TheTarget->createMCRelocationInfo(TT, *Ctx));
  79. if (!RelInfo)
  80. return nullptr;
  81. std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
  82. TT, GetOpInfo, SymbolLookUp, DisInfo, Ctx.get(), std::move(RelInfo)));
  83. DisAsm->setSymbolizer(std::move(Symbolizer));
  84. // Set up the instruction printer.
  85. int AsmPrinterVariant = MAI->getAssemblerDialect();
  86. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  87. Triple(TT), AsmPrinterVariant, *MAI, *MII, *MRI));
  88. if (!IP)
  89. return nullptr;
  90. LLVMDisasmContext *DC = new LLVMDisasmContext(
  91. TT, DisInfo, TagType, GetOpInfo, SymbolLookUp, TheTarget, std::move(MAI),
  92. std::move(MRI), std::move(STI), std::move(MII), std::move(Ctx),
  93. std::move(DisAsm), std::move(IP));
  94. if (!DC)
  95. return nullptr;
  96. DC->setCPU(CPU);
  97. return DC;
  98. }
  99. LLVMDisasmContextRef
  100. LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType,
  101. LLVMOpInfoCallback GetOpInfo,
  102. LLVMSymbolLookupCallback SymbolLookUp) {
  103. return LLVMCreateDisasmCPUFeatures(TT, CPU, "", DisInfo, TagType, GetOpInfo,
  104. SymbolLookUp);
  105. }
  106. LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
  107. int TagType, LLVMOpInfoCallback GetOpInfo,
  108. LLVMSymbolLookupCallback SymbolLookUp) {
  109. return LLVMCreateDisasmCPUFeatures(TT, "", "", DisInfo, TagType, GetOpInfo,
  110. SymbolLookUp);
  111. }
  112. //
  113. // LLVMDisasmDispose() disposes of the disassembler specified by the context.
  114. //
  115. void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
  116. LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
  117. delete DC;
  118. }
  119. /// Emits the comments that are stored in \p DC comment stream.
  120. /// Each comment in the comment stream must end with a newline.
  121. static void emitComments(LLVMDisasmContext *DC,
  122. formatted_raw_ostream &FormattedOS) {
  123. // Flush the stream before taking its content.
  124. StringRef Comments = DC->CommentsToEmit.str();
  125. // Get the default information for printing a comment.
  126. const MCAsmInfo *MAI = DC->getAsmInfo();
  127. StringRef CommentBegin = MAI->getCommentString();
  128. unsigned CommentColumn = MAI->getCommentColumn();
  129. bool IsFirst = true;
  130. while (!Comments.empty()) {
  131. if (!IsFirst)
  132. FormattedOS << '\n';
  133. // Emit a line of comments.
  134. FormattedOS.PadToColumn(CommentColumn);
  135. size_t Position = Comments.find('\n');
  136. FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
  137. // Move after the newline character.
  138. Comments = Comments.substr(Position+1);
  139. IsFirst = false;
  140. }
  141. FormattedOS.flush();
  142. // Tell the comment stream that the vector changed underneath it.
  143. DC->CommentsToEmit.clear();
  144. }
  145. /// Gets latency information for \p Inst from the itinerary
  146. /// scheduling model, based on \p DC information.
  147. /// \return The maximum expected latency over all the operands or -1
  148. /// if no information is available.
  149. static int getItineraryLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
  150. const int NoInformationAvailable = -1;
  151. // Check if we have a CPU to get the itinerary information.
  152. if (DC->getCPU().empty())
  153. return NoInformationAvailable;
  154. // Get itinerary information.
  155. const MCSubtargetInfo *STI = DC->getSubtargetInfo();
  156. InstrItineraryData IID = STI->getInstrItineraryForCPU(DC->getCPU());
  157. // Get the scheduling class of the requested instruction.
  158. const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
  159. unsigned SCClass = Desc.getSchedClass();
  160. int Latency = 0;
  161. for (unsigned OpIdx = 0, OpIdxEnd = Inst.getNumOperands(); OpIdx != OpIdxEnd;
  162. ++OpIdx)
  163. Latency = std::max(Latency, IID.getOperandCycle(SCClass, OpIdx));
  164. return Latency;
  165. }
  166. /// Gets latency information for \p Inst, based on \p DC information.
  167. /// \return The maximum expected latency over all the definitions or -1
  168. /// if no information is available.
  169. static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
  170. // Try to compute scheduling information.
  171. const MCSubtargetInfo *STI = DC->getSubtargetInfo();
  172. const MCSchedModel SCModel = STI->getSchedModel();
  173. const int NoInformationAvailable = -1;
  174. // Check if we have a scheduling model for instructions.
  175. if (!SCModel.hasInstrSchedModel())
  176. // Try to fall back to the itinerary model if the scheduling model doesn't
  177. // have a scheduling table. Note the default does not have a table.
  178. return getItineraryLatency(DC, Inst);
  179. // Get the scheduling class of the requested instruction.
  180. const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
  181. unsigned SCClass = Desc.getSchedClass();
  182. const MCSchedClassDesc *SCDesc = SCModel.getSchedClassDesc(SCClass);
  183. // Resolving the variant SchedClass requires an MI to pass to
  184. // SubTargetInfo::resolveSchedClass.
  185. if (!SCDesc || !SCDesc->isValid() || SCDesc->isVariant())
  186. return NoInformationAvailable;
  187. // Compute output latency.
  188. int16_t Latency = 0;
  189. for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
  190. DefIdx != DefEnd; ++DefIdx) {
  191. // Lookup the definition's write latency in SubtargetInfo.
  192. const MCWriteLatencyEntry *WLEntry = STI->getWriteLatencyEntry(SCDesc,
  193. DefIdx);
  194. Latency = std::max(Latency, WLEntry->Cycles);
  195. }
  196. return Latency;
  197. }
  198. /// Emits latency information in DC->CommentStream for \p Inst, based
  199. /// on the information available in \p DC.
  200. static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
  201. int Latency = getLatency(DC, Inst);
  202. // Report only interesting latencies.
  203. if (Latency < 2)
  204. return;
  205. DC->CommentStream << "Latency: " << Latency << '\n';
  206. }
  207. //
  208. // LLVMDisasmInstruction() disassembles a single instruction using the
  209. // disassembler context specified in the parameter DC. The bytes of the
  210. // instruction are specified in the parameter Bytes, and contains at least
  211. // BytesSize number of bytes. The instruction is at the address specified by
  212. // the PC parameter. If a valid instruction can be disassembled its string is
  213. // returned indirectly in OutString which whos size is specified in the
  214. // parameter OutStringSize. This function returns the number of bytes in the
  215. // instruction or zero if there was no valid instruction. If this function
  216. // returns zero the caller will have to pick how many bytes they want to step
  217. // over by printing a .byte, .long etc. to continue.
  218. //
  219. size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
  220. uint64_t BytesSize, uint64_t PC, char *OutString,
  221. size_t OutStringSize){
  222. LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
  223. // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
  224. ArrayRef<uint8_t> Data(Bytes, BytesSize);
  225. uint64_t Size;
  226. MCInst Inst;
  227. const MCDisassembler *DisAsm = DC->getDisAsm();
  228. MCInstPrinter *IP = DC->getIP();
  229. MCDisassembler::DecodeStatus S;
  230. SmallVector<char, 64> InsnStr;
  231. raw_svector_ostream Annotations(InsnStr);
  232. S = DisAsm->getInstruction(Inst, Size, Data, PC, Annotations);
  233. switch (S) {
  234. case MCDisassembler::Fail:
  235. case MCDisassembler::SoftFail:
  236. // FIXME: Do something different for soft failure modes?
  237. return 0;
  238. case MCDisassembler::Success: {
  239. StringRef AnnotationsStr = Annotations.str();
  240. SmallVector<char, 64> InsnStr;
  241. raw_svector_ostream OS(InsnStr);
  242. formatted_raw_ostream FormattedOS(OS);
  243. IP->printInst(&Inst, PC, AnnotationsStr, *DC->getSubtargetInfo(),
  244. FormattedOS);
  245. if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
  246. emitLatency(DC, Inst);
  247. emitComments(DC, FormattedOS);
  248. assert(OutStringSize != 0 && "Output buffer cannot be zero size");
  249. size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
  250. std::memcpy(OutString, InsnStr.data(), OutputSize);
  251. OutString[OutputSize] = '\0'; // Terminate string.
  252. return Size;
  253. }
  254. }
  255. llvm_unreachable("Invalid DecodeStatus!");
  256. }
  257. //
  258. // LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
  259. // can set all the Options and 0 otherwise.
  260. //
  261. int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
  262. if (Options & LLVMDisassembler_Option_UseMarkup){
  263. LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
  264. MCInstPrinter *IP = DC->getIP();
  265. IP->setUseMarkup(true);
  266. DC->addOptions(LLVMDisassembler_Option_UseMarkup);
  267. Options &= ~LLVMDisassembler_Option_UseMarkup;
  268. }
  269. if (Options & LLVMDisassembler_Option_PrintImmHex){
  270. LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
  271. MCInstPrinter *IP = DC->getIP();
  272. IP->setPrintImmHex(true);
  273. DC->addOptions(LLVMDisassembler_Option_PrintImmHex);
  274. Options &= ~LLVMDisassembler_Option_PrintImmHex;
  275. }
  276. if (Options & LLVMDisassembler_Option_AsmPrinterVariant){
  277. LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
  278. // Try to set up the new instruction printer.
  279. const MCAsmInfo *MAI = DC->getAsmInfo();
  280. const MCInstrInfo *MII = DC->getInstrInfo();
  281. const MCRegisterInfo *MRI = DC->getRegisterInfo();
  282. int AsmPrinterVariant = MAI->getAssemblerDialect();
  283. AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
  284. MCInstPrinter *IP = DC->getTarget()->createMCInstPrinter(
  285. Triple(DC->getTripleName()), AsmPrinterVariant, *MAI, *MII, *MRI);
  286. if (IP) {
  287. DC->setIP(IP);
  288. DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
  289. Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
  290. }
  291. }
  292. if (Options & LLVMDisassembler_Option_SetInstrComments) {
  293. LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
  294. MCInstPrinter *IP = DC->getIP();
  295. IP->setCommentStream(DC->CommentStream);
  296. DC->addOptions(LLVMDisassembler_Option_SetInstrComments);
  297. Options &= ~LLVMDisassembler_Option_SetInstrComments;
  298. }
  299. if (Options & LLVMDisassembler_Option_PrintLatency) {
  300. LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
  301. DC->addOptions(LLVMDisassembler_Option_PrintLatency);
  302. Options &= ~LLVMDisassembler_Option_PrintLatency;
  303. }
  304. return (Options == 0);
  305. }