1 //===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "Disassembler.h"
11 #include "llvm-c/Disassembler.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCDisassembler.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCInstPrinter.h"
17 #include "llvm/MC/MCInstrInfo.h"
18 #include "llvm/MC/MCRegisterInfo.h"
19 #include "llvm/MC/MCRelocationInfo.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/MCSymbolizer.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/MemoryObject.h"
25 #include "llvm/Support/TargetRegistry.h"
29 // LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
30 // disassembly is supported by passing a block of information in the DisInfo
31 // parameter and specifying the TagType and callback functions as described in
32 // the header llvm-c/Disassembler.h . The pointer to the block and the
33 // functions can all be passed as NULL. If successful, this returns a
34 // disassembler context. If not, it returns NULL.
37 LLVMCreateDisasmCPUFeatures(const char *Triple, const char *CPU,
38 const char *Features, void *DisInfo, int TagType,
39 LLVMOpInfoCallback GetOpInfo,
40 LLVMSymbolLookupCallback SymbolLookUp) {
43 const Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
47 const MCRegisterInfo *MRI = TheTarget->createMCRegInfo(Triple);
51 // Get the assembler info needed to setup the MCContext.
52 const MCAsmInfo *MAI = TheTarget->createMCAsmInfo(*MRI, Triple);
56 const MCInstrInfo *MII = TheTarget->createMCInstrInfo();
60 const MCSubtargetInfo *STI = TheTarget->createMCSubtargetInfo(Triple, CPU,
65 // Set up the MCContext for creating symbols and MCExpr's.
66 MCContext *Ctx = new MCContext(MAI, MRI, nullptr);
70 // Set up disassembler.
71 MCDisassembler *DisAsm = TheTarget->createMCDisassembler(*STI, *Ctx);
75 std::unique_ptr<MCRelocationInfo> RelInfo(
76 TheTarget->createMCRelocationInfo(Triple, *Ctx));
80 std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
81 Triple, GetOpInfo, SymbolLookUp, DisInfo, Ctx, RelInfo.release()));
82 DisAsm->setSymbolizer(std::move(Symbolizer));
84 // Set up the instruction printer.
85 int AsmPrinterVariant = MAI->getAssemblerDialect();
86 MCInstPrinter *IP = TheTarget->createMCInstPrinter(AsmPrinterVariant,
87 *MAI, *MII, *MRI, *STI);
91 LLVMDisasmContext *DC = new LLVMDisasmContext(Triple, DisInfo, TagType,
92 GetOpInfo, SymbolLookUp,
94 STI, MII, Ctx, DisAsm, IP);
102 LLVMDisasmContextRef LLVMCreateDisasmCPU(const char *Triple, const char *CPU,
103 void *DisInfo, int TagType,
104 LLVMOpInfoCallback GetOpInfo,
105 LLVMSymbolLookupCallback SymbolLookUp){
106 return LLVMCreateDisasmCPUFeatures(Triple, CPU, "", DisInfo, TagType,
107 GetOpInfo, SymbolLookUp);
110 LLVMDisasmContextRef LLVMCreateDisasm(const char *Triple, void *DisInfo,
111 int TagType, LLVMOpInfoCallback GetOpInfo,
112 LLVMSymbolLookupCallback SymbolLookUp) {
113 return LLVMCreateDisasmCPUFeatures(Triple, "", "", DisInfo, TagType,
114 GetOpInfo, SymbolLookUp);
118 // LLVMDisasmDispose() disposes of the disassembler specified by the context.
120 void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
121 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
127 // The memory object created by LLVMDisasmInstruction().
129 class DisasmMemoryObject : public MemoryObject {
134 DisasmMemoryObject(uint8_t *bytes, uint64_t size, uint64_t basePC) :
135 Bytes(bytes), Size(size), BasePC(basePC) {}
137 uint64_t getBase() const override { return BasePC; }
138 uint64_t getExtent() const override { return Size; }
140 int readByte(uint64_t Addr, uint8_t *Byte) const override {
141 if (Addr - BasePC >= Size)
143 *Byte = Bytes[Addr - BasePC];
147 } // end anonymous namespace
149 /// \brief Emits the comments that are stored in \p DC comment stream.
150 /// Each comment in the comment stream must end with a newline.
151 static void emitComments(LLVMDisasmContext *DC,
152 formatted_raw_ostream &FormattedOS) {
153 // Flush the stream before taking its content.
154 DC->CommentStream.flush();
155 StringRef Comments = DC->CommentsToEmit.str();
156 // Get the default information for printing a comment.
157 const MCAsmInfo *MAI = DC->getAsmInfo();
158 const char *CommentBegin = MAI->getCommentString();
159 unsigned CommentColumn = MAI->getCommentColumn();
161 while (!Comments.empty()) {
164 // Emit a line of comments.
165 FormattedOS.PadToColumn(CommentColumn);
166 size_t Position = Comments.find('\n');
167 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
168 // Move after the newline character.
169 Comments = Comments.substr(Position+1);
174 // Tell the comment stream that the vector changed underneath it.
175 DC->CommentsToEmit.clear();
176 DC->CommentStream.resync();
179 /// \brief Gets latency information for \p Inst form the itinerary
180 /// scheduling model, based on \p DC information.
181 /// \return The maximum expected latency over all the operands or -1
182 /// if no information are available.
183 static int getItineraryLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
184 const int NoInformationAvailable = -1;
186 // Check if we have a CPU to get the itinerary information.
187 if (DC->getCPU().empty())
188 return NoInformationAvailable;
190 // Get itinerary information.
191 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
192 InstrItineraryData IID = STI->getInstrItineraryForCPU(DC->getCPU());
193 // Get the scheduling class of the requested instruction.
194 const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
195 unsigned SCClass = Desc.getSchedClass();
198 for (unsigned OpIdx = 0, OpIdxEnd = Inst.getNumOperands(); OpIdx != OpIdxEnd;
200 Latency = std::max(Latency, IID.getOperandCycle(SCClass, OpIdx));
205 /// \brief Gets latency information for \p Inst, based on \p DC information.
206 /// \return The maximum expected latency over all the definitions or -1
207 /// if no information are available.
208 static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
209 // Try to compute scheduling information.
210 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
211 const MCSchedModel SCModel = STI->getSchedModel();
212 const int NoInformationAvailable = -1;
214 // Check if we have a scheduling model for instructions.
215 if (!SCModel.hasInstrSchedModel())
216 // Try to fall back to the itinerary model if the scheduling model doesn't
217 // have a scheduling table. Note the default does not have a table.
218 return getItineraryLatency(DC, Inst);
220 // Get the scheduling class of the requested instruction.
221 const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
222 unsigned SCClass = Desc.getSchedClass();
223 const MCSchedClassDesc *SCDesc = SCModel.getSchedClassDesc(SCClass);
224 // Resolving the variant SchedClass requires an MI to pass to
225 // SubTargetInfo::resolveSchedClass.
226 if (!SCDesc || !SCDesc->isValid() || SCDesc->isVariant())
227 return NoInformationAvailable;
229 // Compute output latency.
231 for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
232 DefIdx != DefEnd; ++DefIdx) {
233 // Lookup the definition's write latency in SubtargetInfo.
234 const MCWriteLatencyEntry *WLEntry = STI->getWriteLatencyEntry(SCDesc,
236 Latency = std::max(Latency, WLEntry->Cycles);
243 /// \brief Emits latency information in DC->CommentStream for \p Inst, based
244 /// on the information available in \p DC.
245 static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
246 int Latency = getLatency(DC, Inst);
248 // Report only interesting latency.
252 DC->CommentStream << "Latency: " << Latency << '\n';
256 // LLVMDisasmInstruction() disassembles a single instruction using the
257 // disassembler context specified in the parameter DC. The bytes of the
258 // instruction are specified in the parameter Bytes, and contains at least
259 // BytesSize number of bytes. The instruction is at the address specified by
260 // the PC parameter. If a valid instruction can be disassembled its string is
261 // returned indirectly in OutString which whos size is specified in the
262 // parameter OutStringSize. This function returns the number of bytes in the
263 // instruction or zero if there was no valid instruction. If this function
264 // returns zero the caller will have to pick how many bytes they want to step
265 // over by printing a .byte, .long etc. to continue.
267 size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
268 uint64_t BytesSize, uint64_t PC, char *OutString,
269 size_t OutStringSize){
270 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
271 // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
272 DisasmMemoryObject MemoryObject(Bytes, BytesSize, PC);
276 const MCDisassembler *DisAsm = DC->getDisAsm();
277 MCInstPrinter *IP = DC->getIP();
278 MCDisassembler::DecodeStatus S;
279 SmallVector<char, 64> InsnStr;
280 raw_svector_ostream Annotations(InsnStr);
281 S = DisAsm->getInstruction(Inst, Size, MemoryObject, PC,
282 /*REMOVE*/ nulls(), Annotations);
284 case MCDisassembler::Fail:
285 case MCDisassembler::SoftFail:
286 // FIXME: Do something different for soft failure modes?
289 case MCDisassembler::Success: {
291 StringRef AnnotationsStr = Annotations.str();
293 SmallVector<char, 64> InsnStr;
294 raw_svector_ostream OS(InsnStr);
295 formatted_raw_ostream FormattedOS(OS);
296 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
298 if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
299 emitLatency(DC, Inst);
301 emitComments(DC, FormattedOS);
304 assert(OutStringSize != 0 && "Output buffer cannot be zero size");
305 size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
306 std::memcpy(OutString, InsnStr.data(), OutputSize);
307 OutString[OutputSize] = '\0'; // Terminate string.
312 llvm_unreachable("Invalid DecodeStatus!");
316 // LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
317 // can set all the Options and 0 otherwise.
319 int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
320 if (Options & LLVMDisassembler_Option_UseMarkup){
321 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
322 MCInstPrinter *IP = DC->getIP();
324 DC->addOptions(LLVMDisassembler_Option_UseMarkup);
325 Options &= ~LLVMDisassembler_Option_UseMarkup;
327 if (Options & LLVMDisassembler_Option_PrintImmHex){
328 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
329 MCInstPrinter *IP = DC->getIP();
330 IP->setPrintImmHex(1);
331 DC->addOptions(LLVMDisassembler_Option_PrintImmHex);
332 Options &= ~LLVMDisassembler_Option_PrintImmHex;
334 if (Options & LLVMDisassembler_Option_AsmPrinterVariant){
335 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
336 // Try to set up the new instruction printer.
337 const MCAsmInfo *MAI = DC->getAsmInfo();
338 const MCInstrInfo *MII = DC->getInstrInfo();
339 const MCRegisterInfo *MRI = DC->getRegisterInfo();
340 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
341 int AsmPrinterVariant = MAI->getAssemblerDialect();
342 AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
343 MCInstPrinter *IP = DC->getTarget()->createMCInstPrinter(
344 AsmPrinterVariant, *MAI, *MII, *MRI, *STI);
347 DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
348 Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
351 if (Options & LLVMDisassembler_Option_SetInstrComments) {
352 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
353 MCInstPrinter *IP = DC->getIP();
354 IP->setCommentStream(DC->CommentStream);
355 DC->addOptions(LLVMDisassembler_Option_SetInstrComments);
356 Options &= ~LLVMDisassembler_Option_SetInstrComments;
358 if (Options & LLVMDisassembler_Option_PrintLatency) {
359 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
360 DC->addOptions(LLVMDisassembler_Option_PrintLatency);
361 Options &= ~LLVMDisassembler_Option_PrintLatency;
363 return (Options == 0);