LLVM 19.0.0git
Go to the documentation of this file.
1//===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
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
9#include "Disassembler.h"
10#include "llvm-c/Disassembler.h"
11#include "llvm/ADT/ArrayRef.h"
13#include "llvm/MC/MCAsmInfo.h"
14#include "llvm/MC/MCContext.h"
18#include "llvm/MC/MCInst.h"
20#include "llvm/MC/MCInstrDesc.h"
21#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCSchedule.h"
32#include <cassert>
33#include <cstring>
35using namespace llvm;
37// LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
38// disassembly is supported by passing a block of information in the DisInfo
39// parameter and specifying the TagType and callback functions as described in
40// the header llvm-c/Disassembler.h . The pointer to the block and the
41// functions can all be passed as NULL. If successful, this returns a
42// disassembler context. If not, it returns NULL.
45LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
46 const char *Features, void *DisInfo, int TagType,
47 LLVMOpInfoCallback GetOpInfo,
48 LLVMSymbolLookupCallback SymbolLookUp) {
49 // Get the target.
50 std::string Error;
51 const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error);
52 if (!TheTarget)
53 return nullptr;
55 std::unique_ptr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
56 if (!MRI)
57 return nullptr;
59 MCTargetOptions MCOptions;
60 // Get the assembler info needed to setup the MCContext.
61 std::unique_ptr<const MCAsmInfo> MAI(
62 TheTarget->createMCAsmInfo(*MRI, TT, MCOptions));
63 if (!MAI)
64 return nullptr;
66 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
67 if (!MII)
68 return nullptr;
70 std::unique_ptr<const MCSubtargetInfo> STI(
71 TheTarget->createMCSubtargetInfo(TT, CPU, Features));
72 if (!STI)
73 return nullptr;
75 // Set up the MCContext for creating symbols and MCExpr's.
76 std::unique_ptr<MCContext> Ctx(
77 new MCContext(Triple(TT), MAI.get(), MRI.get(), STI.get()));
78 if (!Ctx)
79 return nullptr;
81 // Set up disassembler.
82 std::unique_ptr<MCDisassembler> DisAsm(
83 TheTarget->createMCDisassembler(*STI, *Ctx));
84 if (!DisAsm)
85 return nullptr;
87 std::unique_ptr<MCRelocationInfo> RelInfo(
88 TheTarget->createMCRelocationInfo(TT, *Ctx));
89 if (!RelInfo)
90 return nullptr;
92 std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
93 TT, GetOpInfo, SymbolLookUp, DisInfo, Ctx.get(), std::move(RelInfo)));
94 DisAsm->setSymbolizer(std::move(Symbolizer));
96 // Set up the instruction printer.
97 int AsmPrinterVariant = MAI->getAssemblerDialect();
98 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
99 Triple(TT), AsmPrinterVariant, *MAI, *MII, *MRI));
100 if (!IP)
101 return nullptr;
104 TT, DisInfo, TagType, GetOpInfo, SymbolLookUp, TheTarget, std::move(MAI),
105 std::move(MRI), std::move(STI), std::move(MII), std::move(Ctx),
106 std::move(DisAsm), std::move(IP));
107 if (!DC)
108 return nullptr;
110 DC->setCPU(CPU);
111 return DC;
115LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType,
116 LLVMOpInfoCallback GetOpInfo,
117 LLVMSymbolLookupCallback SymbolLookUp) {
118 return LLVMCreateDisasmCPUFeatures(TT, CPU, "", DisInfo, TagType, GetOpInfo,
119 SymbolLookUp);
122LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
123 int TagType, LLVMOpInfoCallback GetOpInfo,
124 LLVMSymbolLookupCallback SymbolLookUp) {
125 return LLVMCreateDisasmCPUFeatures(TT, "", "", DisInfo, TagType, GetOpInfo,
126 SymbolLookUp);
130// LLVMDisasmDispose() disposes of the disassembler specified by the context.
133 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
134 delete DC;
137/// Emits the comments that are stored in \p DC comment stream.
138/// Each comment in the comment stream must end with a newline.
140 formatted_raw_ostream &FormattedOS) {
141 // Flush the stream before taking its content.
142 StringRef Comments = DC->CommentsToEmit.str();
143 // Get the default information for printing a comment.
144 const MCAsmInfo *MAI = DC->getAsmInfo();
145 StringRef CommentBegin = MAI->getCommentString();
146 unsigned CommentColumn = MAI->getCommentColumn();
147 bool IsFirst = true;
148 while (!Comments.empty()) {
149 if (!IsFirst)
150 FormattedOS << '\n';
151 // Emit a line of comments.
152 FormattedOS.PadToColumn(CommentColumn);
153 size_t Position = Comments.find('\n');
154 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
155 // Move after the newline character.
156 Comments = Comments.substr(Position+1);
157 IsFirst = false;
158 }
159 FormattedOS.flush();
161 // Tell the comment stream that the vector changed underneath it.
162 DC->CommentsToEmit.clear();
165/// Gets latency information for \p Inst from the itinerary
166/// scheduling model, based on \p DC information.
167/// \return The maximum expected latency over all the operands or -1
168/// if no information is available.
169static int getItineraryLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
170 const int NoInformationAvailable = -1;
172 // Check if we have a CPU to get the itinerary information.
173 if (DC->getCPU().empty())
174 return NoInformationAvailable;
176 // Get itinerary information.
177 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
179 // Get the scheduling class of the requested instruction.
180 const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
181 unsigned SCClass = Desc.getSchedClass();
183 unsigned Latency = 0;
185 for (unsigned Idx = 0, IdxEnd = Inst.getNumOperands(); Idx != IdxEnd; ++Idx)
186 if (std::optional<unsigned> OperCycle = IID.getOperandCycle(SCClass, Idx))
187 Latency = std::max(Latency, *OperCycle);
189 return (int)Latency;
192/// Gets latency information for \p Inst, based on \p DC information.
193/// \return The maximum expected latency over all the definitions or -1
194/// if no information is available.
195static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
196 // Try to compute scheduling information.
197 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
198 const MCSchedModel SCModel = STI->getSchedModel();
199 const int NoInformationAvailable = -1;
201 // Check if we have a scheduling model for instructions.
202 if (!SCModel.hasInstrSchedModel())
203 // Try to fall back to the itinerary model if the scheduling model doesn't
204 // have a scheduling table. Note the default does not have a table.
205 return getItineraryLatency(DC, Inst);
207 // Get the scheduling class of the requested instruction.
208 const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
209 unsigned SCClass = Desc.getSchedClass();
210 const MCSchedClassDesc *SCDesc = SCModel.getSchedClassDesc(SCClass);
211 // Resolving the variant SchedClass requires an MI to pass to
212 // SubTargetInfo::resolveSchedClass.
213 if (!SCDesc || !SCDesc->isValid() || SCDesc->isVariant())
214 return NoInformationAvailable;
216 // Compute output latency.
217 int16_t Latency = 0;
218 for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
219 DefIdx != DefEnd; ++DefIdx) {
220 // Lookup the definition's write latency in SubtargetInfo.
221 const MCWriteLatencyEntry *WLEntry = STI->getWriteLatencyEntry(SCDesc,
222 DefIdx);
223 Latency = std::max(Latency, WLEntry->Cycles);
224 }
226 return Latency;
229/// Emits latency information in DC->CommentStream for \p Inst, based
230/// on the information available in \p DC.
231static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
232 int Latency = getLatency(DC, Inst);
234 // Report only interesting latencies.
235 if (Latency < 2)
236 return;
238 DC->CommentStream << "Latency: " << Latency << '\n';
242// LLVMDisasmInstruction() disassembles a single instruction using the
243// disassembler context specified in the parameter DC. The bytes of the
244// instruction are specified in the parameter Bytes, and contains at least
245// BytesSize number of bytes. The instruction is at the address specified by
246// the PC parameter. If a valid instruction can be disassembled its string is
247// returned indirectly in OutString which whos size is specified in the
248// parameter OutStringSize. This function returns the number of bytes in the
249// instruction or zero if there was no valid instruction. If this function
250// returns zero the caller will have to pick how many bytes they want to step
251// over by printing a .byte, .long etc. to continue.
254 uint64_t BytesSize, uint64_t PC, char *OutString,
255 size_t OutStringSize){
256 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
257 // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
258 ArrayRef<uint8_t> Data(Bytes, BytesSize);
261 MCInst Inst;
262 const MCDisassembler *DisAsm = DC->getDisAsm();
263 MCInstPrinter *IP = DC->getIP();
265 SmallVector<char, 64> InsnStr;
267 S = DisAsm->getInstruction(Inst, Size, Data, PC, Annotations);
268 switch (S) {
271 // FIXME: Do something different for soft failure modes?
272 return 0;
275 StringRef AnnotationsStr = Annotations.str();
277 SmallVector<char, 64> InsnStr;
278 raw_svector_ostream OS(InsnStr);
279 formatted_raw_ostream FormattedOS(OS);
280 IP->printInst(&Inst, PC, AnnotationsStr, *DC->getSubtargetInfo(),
281 FormattedOS);
284 emitLatency(DC, Inst);
286 emitComments(DC, FormattedOS);
288 assert(OutStringSize != 0 && "Output buffer cannot be zero size");
289 size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
290 std::memcpy(OutString, InsnStr.data(), OutputSize);
291 OutString[OutputSize] = '\0'; // Terminate string.
293 return Size;
294 }
295 }
296 llvm_unreachable("Invalid DecodeStatus!");
300// LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
301// can set all the Options and 0 otherwise.
305 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
306 MCInstPrinter *IP = DC->getIP();
307 IP->setUseMarkup(true);
309 Options &= ~LLVMDisassembler_Option_UseMarkup;
310 }
312 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
313 MCInstPrinter *IP = DC->getIP();
314 IP->setPrintImmHex(true);
316 Options &= ~LLVMDisassembler_Option_PrintImmHex;
317 }
319 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
320 // Try to set up the new instruction printer.
321 const MCAsmInfo *MAI = DC->getAsmInfo();
322 const MCInstrInfo *MII = DC->getInstrInfo();
323 const MCRegisterInfo *MRI = DC->getRegisterInfo();
324 int AsmPrinterVariant = MAI->getAssemblerDialect();
325 AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
327 Triple(DC->getTripleName()), AsmPrinterVariant, *MAI, *MII, *MRI);
328 if (IP) {
329 DC->setIP(IP);
331 Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
332 }
333 }
335 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
336 MCInstPrinter *IP = DC->getIP();
339 Options &= ~LLVMDisassembler_Option_SetInstrComments;
340 }
342 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
344 Options &= ~LLVMDisassembler_Option_PrintLatency;
345 }
346 return (Options == 0);
unsigned const MachineRegisterInfo * MRI
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static void emitComments(LLVMDisasmContext *DC, formatted_raw_ostream &FormattedOS)
Emits the comments that are stored in DC comment stream.
static int getItineraryLatency(LLVMDisasmContext *DC, const MCInst &Inst)
Gets latency information for Inst from the itinerary scheduling model, based on DC information.
static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst)
Gets latency information for Inst, based on DC information.
static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst)
Emits latency information in DC->CommentStream for Inst, based on the information available in DC.
uint64_t Size
static LVOptions Options
Definition: LVOptions.cpp:25
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallVector class.
Annotations lets you mark points and ranges inside source code, for tests:
Definition: Annotations.h:53
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Itinerary data supplied by a subtarget to be used by a target.
std::optional< unsigned > getOperandCycle(unsigned ItinClassIndx, unsigned OperandIdx) const
Return the cycle for the given class and operand.
const MCDisassembler * getDisAsm() const
Definition: Disassembler.h:109
void setCPU(const char *CPU)
Definition: Disassembler.h:119
void addOptions(uint64_t Options)
Definition: Disassembler.h:117
raw_svector_ostream CommentStream
Definition: Disassembler.h:83
void setIP(MCInstPrinter *NewIP)
Definition: Disassembler.h:115
const MCSubtargetInfo * getSubtargetInfo() const
Definition: Disassembler.h:113
const MCAsmInfo * getAsmInfo() const
Definition: Disassembler.h:110
uint64_t getOptions() const
Definition: Disassembler.h:116
const MCRegisterInfo * getRegisterInfo() const
Definition: Disassembler.h:112
SmallString< 128 > CommentsToEmit
Definition: Disassembler.h:82
MCInstPrinter * getIP()
Definition: Disassembler.h:114
StringRef getCPU() const
Definition: Disassembler.h:118
const MCInstrInfo * getInstrInfo() const
Definition: Disassembler.h:111
const Target * getTarget() const
Definition: Disassembler.h:108
const std::string & getTripleName() const
Definition: Disassembler.h:101
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:676
StringRef getCommentString() const
Definition: MCAsmInfo.h:645
unsigned getCommentColumn() const
This indicates the column (zero-based) at which asm comments should be printed.
Definition: MCAsmInfo.h:643
Context object for machine code objects.
Definition: MCContext.h:83
Superclass for all disassemblers.
Ternary decode status.
virtual DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size, ArrayRef< uint8_t > Bytes, uint64_t Address, raw_ostream &CStream) const =0
Returns the disassembly of a single instruction.
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:45
void setCommentStream(raw_ostream &OS)
Specify a stream to emit comments to.
void setPrintImmHex(bool Value)
void setUseMarkup(bool Value)
virtual void printInst(const MCInst *MI, uint64_t Address, StringRef Annot, const MCSubtargetInfo &STI, raw_ostream &OS)=0
Print the specified MCInst to the specified raw_ostream.
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
unsigned getNumOperands() const
Definition: MCInst.h:208
unsigned getOpcode() const
Definition: MCInst.h:198
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:26
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition: MCInstrInfo.h:63
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Generic base class for all target subtargets.
const MCWriteLatencyEntry * getWriteLatencyEntry(const MCSchedClassDesc *SC, unsigned DefIdx) const
InstrItineraryData getInstrItineraryForCPU(StringRef CPU) const
Get scheduling itinerary of a CPU.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:254
size_t size() const
Definition: SmallVector.h:91
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:299
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:564
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:290
Target - Wrapper for Target specific information.
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
MCSymbolizer * createMCSymbolizer(StringRef TT, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp, void *DisInfo, MCContext *Ctx, std::unique_ptr< MCRelocationInfo > &&RelInfo) const
createMCSymbolizer - Create a target specific MCSymbolizer.
MCRelocationInfo * createMCRelocationInfo(StringRef TT, MCContext &Ctx) const
createMCRelocationInfo - Create a target specific MCRelocationInfo.
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
MCDisassembler * createMCDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx) const
MCAsmInfo * createMCAsmInfo(const MCRegisterInfo &MRI, StringRef TheTriple, const MCTargetOptions &Options) const
createMCAsmInfo - Create a MCAsmInfo implementation for the specified target triple.
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
formatted_raw_ostream & PadToColumn(unsigned NewCol)
PadToColumn - Align the output to some column number.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
const char *(* LLVMSymbolLookupCallback)(void *DisInfo, uint64_t ReferenceValue, uint64_t *ReferenceType, uint64_t ReferencePC, const char **ReferenceName)
The type for the symbol lookup function.
LLVMDisasmContextRef LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU, const char *Features, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp)
Create a disassembler for the TripleName, a specific CPU and specific feature string.
void LLVMDisasmDispose(LLVMDisasmContextRef DCR)
Dispose of a disassembler context.
#define LLVMDisassembler_Option_PrintImmHex
Definition: Disassembler.h:77
#define LLVMDisassembler_Option_UseMarkup
Definition: Disassembler.h:75
size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes, uint64_t BytesSize, uint64_t PC, char *OutString, size_t OutStringSize)
Disassemble a single instruction using the disassembler context specified in the parameter DC.
#define LLVMDisassembler_Option_PrintLatency
Definition: Disassembler.h:83
#define LLVMDisassembler_Option_SetInstrComments
Definition: Disassembler.h:81
LLVMDisasmContextRef LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp)
Create a disassembler for the TripleName and a specific CPU.
int(* LLVMOpInfoCallback)(void *DisInfo, uint64_t PC, uint64_t Offset, uint64_t OpSize, uint64_t InstSize, int TagType, void *TagBuf)
The type for the operand information call back function.
LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp)
Create a disassembler for the TripleName.
int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options)
Set the disassembler's options.
#define LLVMDisassembler_Option_AsmPrinterVariant
Definition: Disassembler.h:79
void * LLVMDisasmContextRef
An opaque reference to a disassembler context.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Description of the encoding of one expression Op.
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition: MCSchedule.h:118
bool isValid() const
Definition: MCSchedule.h:136
bool isVariant() const
Definition: MCSchedule.h:139
uint16_t NumWriteLatencyEntries
Definition: MCSchedule.h:132
Machine model for scheduling, bundling, and heuristics.
Definition: MCSchedule.h:253
const MCSchedClassDesc * getSchedClassDesc(unsigned SchedClassIdx) const
Definition: MCSchedule.h:360
bool hasInstrSchedModel() const
Does this machine model include instruction-level scheduling.
Definition: MCSchedule.h:334
Specify the latency in cpu cycles for a particular scheduling class and def index.
Definition: MCSchedule.h:86
static const Target * lookupTarget(StringRef Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.