bb2d707b404f62fa25b08dd3d9cf59ef6148a756
[oota-llvm.git] / lib / MC / MCDisassembler / Disassembler.cpp
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/StringRefMemoryObject.h"
25 #include "llvm/Support/TargetRegistry.h"
26
27 using namespace llvm;
28
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.
35 //
36 LLVMDisasmContextRef
37 LLVMCreateDisasmCPUFeatures(const char *Triple, const char *CPU,
38                             const char *Features, void *DisInfo, int TagType,
39                             LLVMOpInfoCallback GetOpInfo,
40                             LLVMSymbolLookupCallback SymbolLookUp) {
41   // Get the target.
42   std::string Error;
43   const Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
44   if (!TheTarget)
45     return nullptr;
46
47   const MCRegisterInfo *MRI = TheTarget->createMCRegInfo(Triple);
48   if (!MRI)
49     return nullptr;
50
51   // Get the assembler info needed to setup the MCContext.
52   const MCAsmInfo *MAI = TheTarget->createMCAsmInfo(*MRI, Triple);
53   if (!MAI)
54     return nullptr;
55
56   const MCInstrInfo *MII = TheTarget->createMCInstrInfo();
57   if (!MII)
58     return nullptr;
59
60   const MCSubtargetInfo *STI = TheTarget->createMCSubtargetInfo(Triple, CPU,
61                                                                 Features);
62   if (!STI)
63     return nullptr;
64
65   // Set up the MCContext for creating symbols and MCExpr's.
66   MCContext *Ctx = new MCContext(MAI, MRI, nullptr);
67   if (!Ctx)
68     return nullptr;
69
70   // Set up disassembler.
71   MCDisassembler *DisAsm = TheTarget->createMCDisassembler(*STI, *Ctx);
72   if (!DisAsm)
73     return nullptr;
74
75   std::unique_ptr<MCRelocationInfo> RelInfo(
76       TheTarget->createMCRelocationInfo(Triple, *Ctx));
77   if (!RelInfo)
78     return nullptr;
79
80   std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
81       Triple, GetOpInfo, SymbolLookUp, DisInfo, Ctx, RelInfo.release()));
82   DisAsm->setSymbolizer(std::move(Symbolizer));
83
84   // Set up the instruction printer.
85   int AsmPrinterVariant = MAI->getAssemblerDialect();
86   MCInstPrinter *IP = TheTarget->createMCInstPrinter(AsmPrinterVariant,
87                                                      *MAI, *MII, *MRI, *STI);
88   if (!IP)
89     return nullptr;
90
91   LLVMDisasmContext *DC = new LLVMDisasmContext(Triple, DisInfo, TagType,
92                                                 GetOpInfo, SymbolLookUp,
93                                                 TheTarget, MAI, MRI,
94                                                 STI, MII, Ctx, DisAsm, IP);
95   if (!DC)
96     return nullptr;
97
98   DC->setCPU(CPU);
99   return DC;
100 }
101
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);
108 }
109
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);
115 }
116
117 //
118 // LLVMDisasmDispose() disposes of the disassembler specified by the context.
119 //
120 void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
121   LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
122   delete DC;
123 }
124
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();
136   bool IsFirst = true;
137   while (!Comments.empty()) {
138     if (!IsFirst)
139       FormattedOS << '\n';
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);
146     IsFirst = false;
147   }
148   FormattedOS.flush();
149
150   // Tell the comment stream that the vector changed underneath it.
151   DC->CommentsToEmit.clear();
152   DC->CommentStream.resync();
153 }
154
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;
161
162   // Check if we have a CPU to get the itinerary information.
163   if (DC->getCPU().empty())
164     return NoInformationAvailable;
165
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();
172
173   int Latency = 0;
174   for (unsigned OpIdx = 0, OpIdxEnd = Inst.getNumOperands(); OpIdx != OpIdxEnd;
175        ++OpIdx)
176     Latency = std::max(Latency, IID.getOperandCycle(SCClass, OpIdx));
177
178   return Latency;
179 }
180
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;
189
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);
195
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;
204
205   // Compute output latency.
206   int Latency = 0;
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,
211                                                                    DefIdx);
212     Latency = std::max(Latency, WLEntry->Cycles);
213   }
214
215   return Latency;
216 }
217
218
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);
223
224   // Report only interesting latency.
225   if (Latency < 2)
226     return;
227
228   DC->CommentStream << "Latency: " << Latency << '\n';
229 }
230
231 //
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.
242 //
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);
249
250   uint64_t Size;
251   MCInst Inst;
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);
259   switch (S) {
260   case MCDisassembler::Fail:
261   case MCDisassembler::SoftFail:
262     // FIXME: Do something different for soft failure modes?
263     return 0;
264
265   case MCDisassembler::Success: {
266     Annotations.flush();
267     StringRef AnnotationsStr = Annotations.str();
268
269     SmallVector<char, 64> InsnStr;
270     raw_svector_ostream OS(InsnStr);
271     formatted_raw_ostream FormattedOS(OS);
272     IP->printInst(&Inst, FormattedOS, AnnotationsStr);
273
274     if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
275       emitLatency(DC, Inst);
276
277     emitComments(DC, FormattedOS);
278     OS.flush();
279
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.
284
285     return Size;
286   }
287   }
288   llvm_unreachable("Invalid DecodeStatus!");
289 }
290
291 //
292 // LLVMSetDisasmOptions() sets the disassembler's options.  It returns 1 if it
293 // can set all the Options and 0 otherwise.
294 //
295 int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
296   if (Options & LLVMDisassembler_Option_UseMarkup){
297       LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
298       MCInstPrinter *IP = DC->getIP();
299       IP->setUseMarkup(1);
300       DC->addOptions(LLVMDisassembler_Option_UseMarkup);
301       Options &= ~LLVMDisassembler_Option_UseMarkup;
302   }
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;
309   }
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);
321       if (IP) {
322         DC->setIP(IP);
323         DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
324         Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
325       }
326   }
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;
333   }
334   if (Options & LLVMDisassembler_Option_PrintLatency) {
335     LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
336     DC->addOptions(LLVMDisassembler_Option_PrintLatency);
337     Options &= ~LLVMDisassembler_Option_PrintLatency;
338   }
339   return (Options == 0);
340 }