Disassembler.cpp 13 KB

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