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