LLVM 22.0.0git
MCInstPrinter.cpp
Go to the documentation of this file.
1//===- MCInstPrinter.cpp - Convert an MCInst to target assembly syntax ----===//
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
10#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/MC/MCAsmInfo.h"
14#include "llvm/MC/MCInst.h"
15#include "llvm/MC/MCInstrInfo.h"
19#include "llvm/Support/Format.h"
21#include <cinttypes>
22#include <cstdint>
23
24using namespace llvm;
25
27 static const char HexRep[] = "0123456789abcdef";
28 ListSeparator LS(" ");
29 for (char Byte : Bytes)
30 OS << LS << HexRep[(Byte & 0xF0) >> 4] << HexRep[Byte & 0xF];
31}
32
34
35/// getOpcodeName - Return the name of the specified opcode enum (e.g.
36/// "MOV32ri") or empty if we can't resolve it.
38 return MII.getName(Opcode);
39}
40
42 llvm_unreachable("Target should implement this");
43}
44
46 if (!Annot.empty()) {
47 if (CommentStream) {
48 (*CommentStream) << Annot;
49 // By definition (see MCInstPrinter.h), CommentStream must end with
50 // a newline after each comment.
51 if (Annot.back() != '\n')
52 (*CommentStream) << '\n';
53 } else
54 OS << " " << MAI.getCommentString() << " " << Annot;
55 }
56}
57
58static bool matchAliasCondition(const MCInst &MI, const MCSubtargetInfo *STI,
59 const MCInstrInfo &MII,
60 const MCRegisterInfo &MRI, unsigned &OpIdx,
61 const AliasMatchingData &M,
62 const AliasPatternCond &C,
63 bool &OrPredicateResult) {
64 // Feature tests are special, they don't consume operands.
66 return STI->getFeatureBits().test(C.Value);
68 return !STI->getFeatureBits().test(C.Value);
69 // For feature tests where just one feature is required in a list, set the
70 // predicate result bit to whether the expression will return true, and only
71 // return the real result at the end of list marker.
72 if (C.Kind == AliasPatternCond::K_OrFeature) {
73 OrPredicateResult |= STI->getFeatureBits().test(C.Value);
74 return true;
75 }
77 OrPredicateResult |= !(STI->getFeatureBits().test(C.Value));
78 return true;
79 }
81 bool Res = OrPredicateResult;
82 OrPredicateResult = false;
83 return Res;
84 }
85
86 // Get and consume an operand.
87 const MCOperand &Opnd = MI.getOperand(OpIdx);
88 ++OpIdx;
89
90 // Check the specific condition for the operand.
91 switch (C.Kind) {
93 // Operand must be a specific immediate.
94 return Opnd.isImm() && Opnd.getImm() == int32_t(C.Value);
96 // Operand must be a specific register.
97 return Opnd.isReg() && Opnd.getReg() == C.Value;
99 // Operand must match the register of another operand.
100 return Opnd.isReg() && Opnd.getReg() == MI.getOperand(C.Value).getReg();
102 // Operand must be RegisterByHwMode. Value is RegClassByHwMode index.
103 unsigned HwModeId = STI->getHwMode(MCSubtargetInfo::HwMode_RegInfo);
104 int16_t RCID = MII.getRegClassByHwModeTable(HwModeId)[C.Value];
105 return Opnd.isReg() && MRI.getRegClass(RCID).contains(Opnd.getReg());
106 }
108 // Operand must be a register in this class. Value is a register class id.
109 return Opnd.isReg() && MRI.getRegClass(C.Value).contains(Opnd.getReg());
111 // Operand must match some custom criteria.
112 return M.ValidateMCOperand(Opnd, *STI, C.Value);
114 // Operand can be anything.
115 return true;
121 llvm_unreachable("handled earlier");
122 }
123 llvm_unreachable("invalid kind");
124}
125
127 const MCSubtargetInfo *STI,
128 const AliasMatchingData &M) {
129 // Binary search by opcode. Return false if there are no aliases for this
130 // opcode.
131 auto It = lower_bound(M.OpToPatterns, MI->getOpcode(),
132 [](const PatternsForOpcode &L, unsigned Opcode) {
133 return L.Opcode < Opcode;
134 });
135 if (It == M.OpToPatterns.end() || It->Opcode != MI->getOpcode())
136 return nullptr;
137
138 // Try all patterns for this opcode.
139 uint32_t AsmStrOffset = ~0U;
140 ArrayRef<AliasPattern> Patterns =
141 M.Patterns.slice(It->PatternStart, It->NumPatterns);
142 for (const AliasPattern &P : Patterns) {
143 // Check operand count first.
144 if (MI->getNumOperands() != P.NumOperands)
145 return nullptr;
146
147 // Test all conditions for this pattern.
149 M.PatternConds.slice(P.AliasCondStart, P.NumConds);
150 unsigned OpIdx = 0;
151 bool OrPredicateResult = false;
152 if (llvm::all_of(Conds, [&](const AliasPatternCond &C) {
153 return matchAliasCondition(*MI, STI, MII, MRI, OpIdx, M, C,
154 OrPredicateResult);
155 })) {
156 // If all conditions matched, use this asm string.
157 AsmStrOffset = P.AsmStrOffset;
158 break;
159 }
160 }
161
162 // If no alias matched, don't print an alias.
163 if (AsmStrOffset == ~0U)
164 return nullptr;
165
166 // Go to offset AsmStrOffset and use the null terminated string there. The
167 // offset should point to the beginning of an alias string, so it should
168 // either be zero or be preceded by a null byte.
169 assert(AsmStrOffset < M.AsmStrings.size() &&
170 (AsmStrOffset == 0 || M.AsmStrings[AsmStrOffset - 1] == '\0') &&
171 "bad asm string offset");
172 return M.AsmStrings.data() + AsmStrOffset;
173}
174
175// For asm-style hex (e.g. 0ffh) the first digit always has to be a number.
177{
178 while (Value)
179 {
180 uint64_t digit = (Value >> 60) & 0xf;
181 if (digit != 0)
182 return (digit >= 0xa);
183 Value <<= 4;
184 }
185 return false;
186}
187
189 return format("%" PRId64, Value);
190}
191
193 switch (PrintHexStyle) {
194 case HexStyle::C:
195 if (Value < 0) {
196 if (Value == std::numeric_limits<int64_t>::min())
197 return format<int64_t>("-0x8000000000000000", Value);
198 return format("-0x%" PRIx64, -Value);
199 }
200 return format("0x%" PRIx64, Value);
201 case HexStyle::Asm:
202 if (Value < 0) {
203 if (Value == std::numeric_limits<int64_t>::min())
204 return format<int64_t>("-8000000000000000h", Value);
206 return format("-0%" PRIx64 "h", -Value);
207 return format("-%" PRIx64 "h", -Value);
208 }
210 return format("0%" PRIx64 "h", Value);
211 return format("%" PRIx64 "h", Value);
212 }
213 llvm_unreachable("unsupported print style");
214}
215
217 switch(PrintHexStyle) {
218 case HexStyle::C:
219 return format("0x%" PRIx64, Value);
220 case HexStyle::Asm:
222 return format("0%" PRIx64 "h", Value);
223 else
224 return format("%" PRIx64 "h", Value);
225 }
226 llvm_unreachable("unsupported print style");
227}
228
232
234 Markup M, bool EnableMarkup,
235 bool EnableColor)
236 : IP(IP), OS(OS), EnableMarkup(EnableMarkup), EnableColor(EnableColor) {
237 if (EnableColor) {
239 switch (M) {
241 Color = raw_ostream::RED;
242 break;
243 case Markup::Register:
244 Color = raw_ostream::CYAN;
245 break;
246 case Markup::Target:
247 Color = raw_ostream::YELLOW;
248 break;
249 case Markup::Memory:
250 Color = raw_ostream::GREEN;
251 break;
252 }
253 IP.ColorStack.push_back(Color);
254 OS.changeColor(Color);
255 }
256
257 if (EnableMarkup) {
258 switch (M) {
260 OS << "<imm:";
261 break;
262 case Markup::Register:
263 OS << "<reg:";
264 break;
265 case Markup::Target:
266 OS << "<target:";
267 break;
268 case Markup::Memory:
269 OS << "<mem:";
270 break;
271 }
272 }
273}
274
276 if (EnableMarkup)
277 OS << '>';
278 if (!EnableColor)
279 return;
280 IP.ColorStack.pop_back();
281 OS << IP.ColorStack.back();
282}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
IRTranslator LLVM IR MI
static bool needsLeadingZero(uint64_t Value)
static bool matchAliasCondition(const MCInst &MI, const MCSubtargetInfo *STI, const MCInstrInfo &MII, const MCRegisterInfo &MRI, unsigned &OpIdx, const AliasMatchingData &M, const AliasPatternCond &C, bool &OrPredicateResult)
modulo schedule test
MachineInstr unsigned OpIdx
#define P(N)
This file contains some functions that are useful when dealing with strings.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:186
constexpr bool test(unsigned I) const
A helper class to return the specified delimiter string after the first invocation of operator String...
LLVM_CTOR_NODISCARD LLVM_ABI WithMarkup(MCInstPrinter &IP, raw_ostream &OS, Markup M, bool EnableMarkup, bool EnableColor)
WithMarkup markup(raw_ostream &OS, Markup M)
format_object< int64_t > formatHex(int64_t Value) const
bool getUseColor() const
const MCInstrInfo & MII
raw_ostream * CommentStream
A stream that comments can be emitted to if desired.
virtual ~MCInstPrinter()
StringRef getOpcodeName(unsigned Opcode) const
Return the name of the specified opcode enum (e.g.
format_object< int64_t > formatDec(int64_t Value) const
Utility functions to print decimal/hexadecimal values.
const MCRegisterInfo & MRI
void printAnnotation(raw_ostream &OS, StringRef Annot)
Utility function for printing annotations.
const MCAsmInfo & MAI
bool getUseMarkup() const
virtual void printRegName(raw_ostream &OS, MCRegister Reg)
Print the assembler register name.
const char * matchAliasPatterns(const MCInst *MI, const MCSubtargetInfo *STI, const AliasMatchingData &M)
Helper for matching MCInsts to alias patterns when printing instructions.
MCInstPrinter(const MCAsmInfo &mai, const MCInstrInfo &mii, const MCRegisterInfo &mri)
HexStyle::Style PrintHexStyle
Which style to use for printing hexadecimal values.
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
const int16_t * getRegClassByHwModeTable(unsigned ModeId) const
Definition MCInstrInfo.h:71
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
int64_t getImm() const
Definition MCInst.h:84
bool isImm() const
Definition MCInst.h:66
bool isReg() const
Definition MCInst.h:65
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:73
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Generic base class for all target subtargets.
const FeatureBitset & getFeatureBits() const
virtual unsigned getHwMode(enum HwModeType type=HwMode_Default) const
HwMode ID corresponding to the 'type' parameter is retrieved from the HwMode bit set of the current s...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
LLVM Value Representation.
Definition Value.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
static constexpr Colors GREEN
static constexpr Colors RED
static constexpr Colors YELLOW
static constexpr Colors CYAN
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
LLVM_ABI void dumpBytes(ArrayRef< uint8_t > Bytes, raw_ostream &OS)
Convert ‘Bytes’ to a hex string and output to ‘OS’.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2042
Tablegenerated data structures needed to match alias patterns.
Data for each alias pattern.
Map from opcode to pattern list by binary search.