LLVM 22.0.0git
Disassembler.cpp
Go to the documentation of this file.
1//===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
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/MCInstrInfo.h"
22#include "llvm/MC/MCSchedule.h"
30#include <cassert>
31#include <cstring>
32
33using namespace llvm;
34
35// LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
36// disassembly is supported by passing a block of information in the DisInfo
37// parameter and specifying the TagType and callback functions as described in
38// the header llvm-c/Disassembler.h . The pointer to the block and the
39// functions can all be passed as NULL. If successful, this returns a
40// disassembler context. If not, it returns NULL.
41//
43LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
44 const char *Features, void *DisInfo, int TagType,
45 LLVMOpInfoCallback GetOpInfo,
46 LLVMSymbolLookupCallback SymbolLookUp) {
47 // Get the target.
48 std::string Error;
49 const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error);
50 if (!TheTarget)
51 return nullptr;
52
53 std::unique_ptr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
54 if (!MRI)
55 return nullptr;
56
57 MCTargetOptions MCOptions;
58 // Get the assembler info needed to setup the MCContext.
59 std::unique_ptr<const MCAsmInfo> MAI(
60 TheTarget->createMCAsmInfo(*MRI, TT, MCOptions));
61 if (!MAI)
62 return nullptr;
63
64 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
65 if (!MII)
66 return nullptr;
67
68 std::unique_ptr<const MCSubtargetInfo> STI(
69 TheTarget->createMCSubtargetInfo(TT, CPU, Features));
70 if (!STI)
71 return nullptr;
72
73 // Set up the MCContext for creating symbols and MCExpr's.
74 std::unique_ptr<MCContext> Ctx(
75 new MCContext(Triple(TT), MAI.get(), MRI.get(), STI.get()));
76 if (!Ctx)
77 return nullptr;
78
79 // Set up disassembler.
80 std::unique_ptr<MCDisassembler> DisAsm(
81 TheTarget->createMCDisassembler(*STI, *Ctx));
82 if (!DisAsm)
83 return nullptr;
84
85 std::unique_ptr<MCRelocationInfo> RelInfo(
86 TheTarget->createMCRelocationInfo(TT, *Ctx));
87 if (!RelInfo)
88 return nullptr;
89
90 std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
91 TT, GetOpInfo, SymbolLookUp, DisInfo, Ctx.get(), std::move(RelInfo)));
92 DisAsm->setSymbolizer(std::move(Symbolizer));
93
94 // Set up the instruction printer.
95 int AsmPrinterVariant = MAI->getAssemblerDialect();
96 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
97 Triple(TT), AsmPrinterVariant, *MAI, *MII, *MRI));
98 if (!IP)
99 return nullptr;
100
102 TT, DisInfo, TagType, GetOpInfo, SymbolLookUp, TheTarget, std::move(MAI),
103 std::move(MRI), std::move(STI), std::move(MII), std::move(Ctx),
104 std::move(DisAsm), std::move(IP));
105 if (!DC)
106 return nullptr;
107
108 DC->setCPU(CPU);
109 return DC;
110}
111
113LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType,
114 LLVMOpInfoCallback GetOpInfo,
115 LLVMSymbolLookupCallback SymbolLookUp) {
116 return LLVMCreateDisasmCPUFeatures(TT, CPU, "", DisInfo, TagType, GetOpInfo,
117 SymbolLookUp);
118}
119
120LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
121 int TagType, LLVMOpInfoCallback GetOpInfo,
122 LLVMSymbolLookupCallback SymbolLookUp) {
123 return LLVMCreateDisasmCPUFeatures(TT, "", "", DisInfo, TagType, GetOpInfo,
124 SymbolLookUp);
125}
126
127//
128// LLVMDisasmDispose() disposes of the disassembler specified by the context.
129//
131 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
132 delete DC;
133}
134
135/// Emits the comments that are stored in \p DC comment stream.
136/// Each comment in the comment stream must end with a newline.
138 formatted_raw_ostream &FormattedOS) {
139 // Flush the stream before taking its content.
140 StringRef Comments = DC->CommentsToEmit.str();
141 // Get the default information for printing a comment.
142 const MCAsmInfo *MAI = DC->getAsmInfo();
143 StringRef CommentBegin = MAI->getCommentString();
144 unsigned CommentColumn = MAI->getCommentColumn();
145 bool IsFirst = true;
146 while (!Comments.empty()) {
147 if (!IsFirst)
148 FormattedOS << '\n';
149 // Emit a line of comments.
150 FormattedOS.PadToColumn(CommentColumn);
151 size_t Position = Comments.find('\n');
152 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
153 // Move after the newline character.
154 Comments = Comments.substr(Position+1);
155 IsFirst = false;
156 }
157 FormattedOS.flush();
158
159 // Tell the comment stream that the vector changed underneath it.
160 DC->CommentsToEmit.clear();
161}
162
163/// Emits latency information in DC->CommentStream for \p Inst, based
164/// on the information available in \p DC.
165static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
166 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
167 const MCInstrInfo *MCII = DC->getInstrInfo();
168 const MCSchedModel &SCModel = STI->getSchedModel();
169 int Latency = SCModel.computeInstrLatency(*STI, *MCII, Inst);
170
171 // Report only interesting latencies.
172 if (Latency < 2)
173 return;
174
175 DC->CommentStream << "Latency: " << Latency << '\n';
176}
177
178//
179// LLVMDisasmInstruction() disassembles a single instruction using the
180// disassembler context specified in the parameter DC. The bytes of the
181// instruction are specified in the parameter Bytes, and contains at least
182// BytesSize number of bytes. The instruction is at the address specified by
183// the PC parameter. If a valid instruction can be disassembled its string is
184// returned indirectly in OutString which whos size is specified in the
185// parameter OutStringSize. This function returns the number of bytes in the
186// instruction or zero if there was no valid instruction. If this function
187// returns zero the caller will have to pick how many bytes they want to step
188// over by printing a .byte, .long etc. to continue.
189//
191 uint64_t BytesSize, uint64_t PC, char *OutString,
192 size_t OutStringSize){
193 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
194 // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
195 ArrayRef<uint8_t> Data(Bytes, BytesSize);
196
198 MCInst Inst;
199 const MCDisassembler *DisAsm = DC->getDisAsm();
200 MCInstPrinter *IP = DC->getIP();
202 SmallVector<char, 64> InsnStr;
204 S = DisAsm->getInstruction(Inst, Size, Data, PC, Annotations);
205 switch (S) {
208 // FIXME: Do something different for soft failure modes?
209 return 0;
210
212 StringRef AnnotationsStr = Annotations.str();
213
214 SmallVector<char, 64> InsnStr;
215 raw_svector_ostream OS(InsnStr);
216 formatted_raw_ostream FormattedOS(OS);
217
219 FormattedOS.enable_colors(true);
220 IP->setUseColor(true);
221 }
222
223 IP->printInst(&Inst, PC, AnnotationsStr, *DC->getSubtargetInfo(),
224 FormattedOS);
225
227 emitLatency(DC, Inst);
228
229 emitComments(DC, FormattedOS);
230
231 assert(OutStringSize != 0 && "Output buffer cannot be zero size");
232 size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
233 std::memcpy(OutString, InsnStr.data(), OutputSize);
234 OutString[OutputSize] = '\0'; // Terminate string.
235
236 return Size;
237 }
238 }
239 llvm_unreachable("Invalid DecodeStatus!");
240}
241
242//
243// LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
244// can set all the Options and 0 otherwise.
245//
248 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
249 MCInstPrinter *IP = DC->getIP();
250 IP->setUseMarkup(true);
252 Options &= ~LLVMDisassembler_Option_UseMarkup;
253 }
255 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
256 MCInstPrinter *IP = DC->getIP();
257 IP->setPrintImmHex(true);
259 Options &= ~LLVMDisassembler_Option_PrintImmHex;
260 }
262 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
263 // Try to set up the new instruction printer.
264 const MCAsmInfo *MAI = DC->getAsmInfo();
265 const MCInstrInfo *MII = DC->getInstrInfo();
266 const MCRegisterInfo *MRI = DC->getRegisterInfo();
267 int AsmPrinterVariant = MAI->getAssemblerDialect();
268 AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
270 Triple(DC->getTripleName()), AsmPrinterVariant, *MAI, *MII, *MRI);
271 if (IP) {
272 DC->setIP(IP);
274 Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
275 }
276 }
278 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
279 MCInstPrinter *IP = DC->getIP();
282 Options &= ~LLVMDisassembler_Option_SetInstrComments;
283 }
285 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
287 Options &= ~LLVMDisassembler_Option_PrintLatency;
288 }
290 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
292 Options &= ~LLVMDisassembler_Option_Color;
293 }
294 return (Options == 0);
295}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static void emitComments(LLVMDisasmContext *DC, formatted_raw_ostream &FormattedOS)
Emits the comments that are stored in DC comment stream.
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
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:159
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 getTripleName() const
Definition: Disassembler.h:101
const MCInstrInfo * getInstrInfo() const
Definition: Disassembler.h:111
const Target * getTarget() const
Definition: Disassembler.h:108
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:64
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:560
StringRef getCommentString() const
Definition: MCAsmInfo.h:538
unsigned getCommentColumn() const
Definition: MCAsmInfo.h:535
Context object for machine code objects.
Definition: MCContext.h:83
Superclass for all disassemblers.
DecodeStatus
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:46
void setCommentStream(raw_ostream &OS)
Specify a stream to emit comments to.
void setUseColor(bool Value)
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:188
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:27
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Generic base class for all target subtargets.
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:79
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:287
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:581
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:301
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:47
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.
virtual void enable_colors(bool enable)
Definition: raw_ostream.h:356
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:692
const char *(* LLVMSymbolLookupCallback)(void *DisInfo, uint64_t ReferenceValue, uint64_t *ReferenceType, uint64_t ReferencePC, const char **ReferenceName)
The type for the symbol lookup function.
#define LLVMDisassembler_Option_PrintImmHex
Definition: Disassembler.h:76
#define LLVMDisassembler_Option_UseMarkup
Definition: Disassembler.h:74
void LLVMDisasmDispose(LLVMDisasmContextRef DCR)
Dispose of a disassembler context.
int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options)
Set the disassembler's options.
#define LLVMDisassembler_Option_PrintLatency
Definition: Disassembler.h:82
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.
#define LLVMDisassembler_Option_SetInstrComments
Definition: Disassembler.h:80
LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp)
Create a disassembler for the TripleName.
#define LLVMDisassembler_Option_Color
Definition: Disassembler.h:84
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.
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.
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.
#define LLVMDisassembler_Option_AsmPrinterVariant
Definition: Disassembler.h:78
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
Machine model for scheduling, bundling, and heuristics.
Definition: MCSchedule.h:258
static LLVM_ABI int computeInstrLatency(const MCSubtargetInfo &STI, const MCSchedClassDesc &SCDesc)
Returns the latency value for the scheduling class.
Definition: MCSchedule.cpp:43
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.