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/StringRefMemoryObject.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;
125 /// \brief Emits the comments that are stored in \p DC comment stream.
126 /// Each comment in the comment stream must end with a newline.
127 static void emitComments(LLVMDisasmContext *DC,
128 formatted_raw_ostream &FormattedOS) {
129 // Flush the stream before taking its content.
130 DC->CommentStream.flush();
131 StringRef Comments = DC->CommentsToEmit.str();
132 // Get the default information for printing a comment.
133 const MCAsmInfo *MAI = DC->getAsmInfo();
134 const char *CommentBegin = MAI->getCommentString();
135 unsigned CommentColumn = MAI->getCommentColumn();
137 while (!Comments.empty()) {
140 // Emit a line of comments.
141 FormattedOS.PadToColumn(CommentColumn);
142 size_t Position = Comments.find('\n');
143 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
144 // Move after the newline character.
145 Comments = Comments.substr(Position+1);
150 // Tell the comment stream that the vector changed underneath it.
151 DC->CommentsToEmit.clear();
152 DC->CommentStream.resync();
155 /// \brief Gets latency information for \p Inst form the itinerary
156 /// scheduling model, based on \p DC information.
157 /// \return The maximum expected latency over all the operands or -1
158 /// if no information are available.
159 static int getItineraryLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
160 const int NoInformationAvailable = -1;
162 // Check if we have a CPU to get the itinerary information.
163 if (DC->getCPU().empty())
164 return NoInformationAvailable;
166 // Get itinerary information.
167 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
168 InstrItineraryData IID = STI->getInstrItineraryForCPU(DC->getCPU());
169 // Get the scheduling class of the requested instruction.
170 const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
171 unsigned SCClass = Desc.getSchedClass();
174 for (unsigned OpIdx = 0, OpIdxEnd = Inst.getNumOperands(); OpIdx != OpIdxEnd;
176 Latency = std::max(Latency, IID.getOperandCycle(SCClass, OpIdx));
181 /// \brief Gets latency information for \p Inst, based on \p DC information.
182 /// \return The maximum expected latency over all the definitions or -1
183 /// if no information are available.
184 static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
185 // Try to compute scheduling information.
186 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
187 const MCSchedModel SCModel = STI->getSchedModel();
188 const int NoInformationAvailable = -1;
190 // Check if we have a scheduling model for instructions.
191 if (!SCModel.hasInstrSchedModel())
192 // Try to fall back to the itinerary model if the scheduling model doesn't
193 // have a scheduling table. Note the default does not have a table.
194 return getItineraryLatency(DC, Inst);
196 // Get the scheduling class of the requested instruction.
197 const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
198 unsigned SCClass = Desc.getSchedClass();
199 const MCSchedClassDesc *SCDesc = SCModel.getSchedClassDesc(SCClass);
200 // Resolving the variant SchedClass requires an MI to pass to
201 // SubTargetInfo::resolveSchedClass.
202 if (!SCDesc || !SCDesc->isValid() || SCDesc->isVariant())
203 return NoInformationAvailable;
205 // Compute output latency.
207 for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
208 DefIdx != DefEnd; ++DefIdx) {
209 // Lookup the definition's write latency in SubtargetInfo.
210 const MCWriteLatencyEntry *WLEntry = STI->getWriteLatencyEntry(SCDesc,
212 Latency = std::max(Latency, WLEntry->Cycles);
219 /// \brief Emits latency information in DC->CommentStream for \p Inst, based
220 /// on the information available in \p DC.
221 static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
222 int Latency = getLatency(DC, Inst);
224 // Report only interesting latency.
228 DC->CommentStream << "Latency: " << Latency << '\n';
232 // LLVMDisasmInstruction() disassembles a single instruction using the
233 // disassembler context specified in the parameter DC. The bytes of the
234 // instruction are specified in the parameter Bytes, and contains at least
235 // BytesSize number of bytes. The instruction is at the address specified by
236 // the PC parameter. If a valid instruction can be disassembled its string is
237 // returned indirectly in OutString which whos size is specified in the
238 // parameter OutStringSize. This function returns the number of bytes in the
239 // instruction or zero if there was no valid instruction. If this function
240 // returns zero the caller will have to pick how many bytes they want to step
241 // over by printing a .byte, .long etc. to continue.
243 size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
244 uint64_t BytesSize, uint64_t PC, char *OutString,
245 size_t OutStringSize){
246 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
247 // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
248 ArrayRef<uint8_t> Data(Bytes, BytesSize);
252 const MCDisassembler *DisAsm = DC->getDisAsm();
253 MCInstPrinter *IP = DC->getIP();
254 MCDisassembler::DecodeStatus S;
255 SmallVector<char, 64> InsnStr;
256 raw_svector_ostream Annotations(InsnStr);
257 S = DisAsm->getInstruction(Inst, Size, Data, 0,
258 /*REMOVE*/ nulls(), Annotations);
260 case MCDisassembler::Fail:
261 case MCDisassembler::SoftFail:
262 // FIXME: Do something different for soft failure modes?
265 case MCDisassembler::Success: {
267 StringRef AnnotationsStr = Annotations.str();
269 SmallVector<char, 64> InsnStr;
270 raw_svector_ostream OS(InsnStr);
271 formatted_raw_ostream FormattedOS(OS);
272 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
274 if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
275 emitLatency(DC, Inst);
277 emitComments(DC, FormattedOS);
280 assert(OutStringSize != 0 && "Output buffer cannot be zero size");
281 size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
282 std::memcpy(OutString, InsnStr.data(), OutputSize);
283 OutString[OutputSize] = '\0'; // Terminate string.
288 llvm_unreachable("Invalid DecodeStatus!");
292 // LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
293 // can set all the Options and 0 otherwise.
295 int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
296 if (Options & LLVMDisassembler_Option_UseMarkup){
297 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
298 MCInstPrinter *IP = DC->getIP();
300 DC->addOptions(LLVMDisassembler_Option_UseMarkup);
301 Options &= ~LLVMDisassembler_Option_UseMarkup;
303 if (Options & LLVMDisassembler_Option_PrintImmHex){
304 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
305 MCInstPrinter *IP = DC->getIP();
306 IP->setPrintImmHex(1);
307 DC->addOptions(LLVMDisassembler_Option_PrintImmHex);
308 Options &= ~LLVMDisassembler_Option_PrintImmHex;
310 if (Options & LLVMDisassembler_Option_AsmPrinterVariant){
311 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
312 // Try to set up the new instruction printer.
313 const MCAsmInfo *MAI = DC->getAsmInfo();
314 const MCInstrInfo *MII = DC->getInstrInfo();
315 const MCRegisterInfo *MRI = DC->getRegisterInfo();
316 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
317 int AsmPrinterVariant = MAI->getAssemblerDialect();
318 AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
319 MCInstPrinter *IP = DC->getTarget()->createMCInstPrinter(
320 AsmPrinterVariant, *MAI, *MII, *MRI, *STI);
323 DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
324 Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
327 if (Options & LLVMDisassembler_Option_SetInstrComments) {
328 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
329 MCInstPrinter *IP = DC->getIP();
330 IP->setCommentStream(DC->CommentStream);
331 DC->addOptions(LLVMDisassembler_Option_SetInstrComments);
332 Options &= ~LLVMDisassembler_Option_SetInstrComments;
334 if (Options & LLVMDisassembler_Option_PrintLatency) {
335 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
336 DC->addOptions(LLVMDisassembler_Option_PrintLatency);
337 Options &= ~LLVMDisassembler_Option_PrintLatency;
339 return (Options == 0);