forked from bytecodealliance/wasmtime
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathformat.rs
433 lines (390 loc) · 12.1 KB
/
format.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! A DSL for describing x64 instruction formats--the shape of the operands.
//!
//! Every instruction has a format that corresponds to its encoding's expected
//! operands. The format is what allows us to generate code that accepts
//! operands of the right type and check that the operands are used in the right
//! way.
//!
//! The entry point for this module is [`fmt`].
//!
//! ```
//! # use cranelift_assembler_x64_meta::dsl::{fmt, rw, r, Location::*};
//! let f = fmt("rm", [rw(r32), r(rm32)]);
//! assert_eq!(f.to_string(), "rm(r32[rw], rm32)")
//! ```
/// An abbreviated constructor for an instruction "format."
///
/// These model what the reference manual calls "instruction operand encodings,"
/// usually defined in a table after an instruction's opcodes.
pub fn fmt(name: impl Into<String>, operands: impl IntoIterator<Item = impl Into<Operand>>) -> Format {
Format {
name: name.into(),
operands: operands.into_iter().map(Into::into).collect(),
}
}
/// An abbreviated constructor for a "read-write" operand.
///
/// # Panics
///
/// This function panics if the location is an immediate (i.e., an immediate
/// cannot be written to).
#[must_use]
pub fn rw(location: Location) -> Operand {
assert!(!matches!(location.kind(), OperandKind::Imm(_)));
Operand {
location,
mutability: Mutability::ReadWrite,
extension: Extension::default(),
align: false,
}
}
/// An abbreviated constructor for a "read" operand.
#[must_use]
pub fn r(op: impl Into<Operand>) -> Operand {
let op = op.into();
assert!(op.mutability.is_read());
op
}
/// An abbreviated constructor for a memory operand that requires alignment.
pub fn align(location: Location) -> Operand {
assert!(location.uses_memory());
Operand {
location,
mutability: Mutability::Read,
extension: Extension::None,
align: true,
}
}
/// An abbreviated constructor for a "read" operand that is sign-extended to 64
/// bits (quadword).
///
/// # Panics
///
/// This function panics if the location size is too large to extend.
#[must_use]
pub fn sxq(location: Location) -> Operand {
assert!(location.bits() <= 64);
Operand {
location,
mutability: Mutability::Read,
extension: Extension::SignExtendQuad,
align: false,
}
}
/// An abbreviated constructor for a "read" operand that is sign-extended to 32
/// bits (longword).
///
/// # Panics
///
/// This function panics if the location size is too large to extend.
#[must_use]
pub fn sxl(location: Location) -> Operand {
assert!(location.bits() <= 32);
Operand {
location,
mutability: Mutability::Read,
extension: Extension::SignExtendLong,
align: false,
}
}
/// An abbreviated constructor for a "read" operand that is sign-extended to 16
/// bits (word).
///
/// # Panics
///
/// This function panics if the location size is too large to extend.
#[must_use]
pub fn sxw(location: Location) -> Operand {
assert!(location.bits() <= 16);
Operand {
location,
mutability: Mutability::Read,
extension: Extension::SignExtendWord,
align: false,
}
}
/// A format describes the operands for an instruction.
pub struct Format {
/// This name, when combined with the instruction mnemonic, uniquely
/// identifies an instruction. The reference manual uses this name in the
/// "Instruction Operand Encoding" table.
pub name: String,
/// These operands should match the "Instruction" column ing the reference
/// manual.
pub operands: Vec<Operand>,
}
impl Format {
/// Iterate over the operand locations.
pub fn locations(&self) -> impl Iterator<Item = &Location> + '_ {
self.operands.iter().map(|o| &o.location)
}
/// Return the location of the operand that uses memory, if any; return
/// `None` otherwise.
pub fn uses_memory(&self) -> Option<Location> {
debug_assert!(self.locations().copied().filter(Location::uses_memory).count() <= 1);
self.locations().copied().find(Location::uses_memory)
}
/// Return `true` if any of the operands accepts a variable register (i.e.,
/// not a fixed register, immediate); return `false` otherwise.
#[must_use]
pub fn uses_variable_register(&self) -> bool {
self.locations().any(Location::uses_variable_register)
}
/// Collect into operand kinds.
pub fn operands_by_kind(&self) -> Vec<OperandKind> {
self.locations().map(Location::kind).collect()
}
}
impl core::fmt::Display for Format {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let Format { name, operands } = self;
let operands = operands
.iter()
.map(|operand| format!("{operand}"))
.collect::<Vec<_>>()
.join(", ");
write!(f, "{name}({operands})")
}
}
/// An x64 operand.
///
/// This is designed to look and feel like the operands as expressed in Intel's
/// _Instruction Set Reference_.
///
/// ```
/// # use cranelift_assembler_x64_meta::dsl::{align, r, rw, sxq, Location::*};
/// assert_eq!(r(r8).to_string(), "r8");
/// assert_eq!(rw(rm16).to_string(), "rm16[rw]");
/// assert_eq!(sxq(imm32).to_string(), "imm32[sxq]");
/// assert_eq!(align(rm128).to_string(), "rm128[align]");
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Operand {
/// The location of the data: memory, register, immediate.
pub location: Location,
/// An operand can be read-only or read-write.
pub mutability: Mutability,
/// Some operands are sign- or zero-extended.
pub extension: Extension,
/// Some memory operands require alignment; `true` indicates that the memory
/// address used in the operand must align to the size of the operand (e.g.,
/// `m128` must be 16-byte aligned).
pub align: bool,
}
impl core::fmt::Display for Operand {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let Self { location, mutability, extension, align } = self;
write!(f, "{location}")?;
let mut flags = vec![];
if !matches!(mutability, Mutability::Read) {
flags.push(format!("{mutability}"));
}
if !matches!(extension, Extension::None) {
flags.push(format!("{extension}"));
}
if *align != false {
flags.push("align".to_owned());
}
if !flags.is_empty() {
write!(f, "[{}]", flags.join(","))?;
}
Ok(())
}
}
impl From<Location> for Operand {
fn from(location: Location) -> Self {
let mutability = Mutability::default();
let extension = Extension::default();
let align = false;
Self { location, mutability, extension, align }
}
}
/// An operand location, as expressed in Intel's _Instruction Set Reference_.
#[derive(Clone, Copy, Debug)]
#[allow(non_camel_case_types, reason = "makes DSL definitions easier to read")]
pub enum Location {
al,
ax,
eax,
rax,
cl,
imm8,
imm16,
imm32,
r8,
r16,
r32,
r64,
xmm,
rm8,
rm16,
rm32,
rm64,
rm128,
}
impl Location {
/// Return the number of bits accessed.
#[must_use]
pub fn bits(&self) -> u8 {
use Location::*;
match self {
al | cl | imm8 | r8 | rm8 => 8,
ax | imm16 | r16 | rm16 => 16,
eax | imm32 | r32 | rm32 => 32,
rax | r64 | rm64 => 64,
xmm | rm128 => 128,
}
}
/// Return the number of bytes accessed, for convenience.
#[must_use]
pub fn bytes(&self) -> u8 {
self.bits() / 8
}
/// Return `true` if the location accesses memory; `false` otherwise.
#[must_use]
pub fn uses_memory(&self) -> bool {
use Location::*;
match self {
al | cl | ax | eax | rax | imm8 | imm16 | imm32 | r8 | r16 | r32 | r64 | xmm => false,
rm8 | rm16 | rm32 | rm64 | rm128 => true,
}
}
/// Return `true` if the location accepts a variable register (i.e., not a
/// fixed register, immediate); return `false` otherwise.
#[must_use]
pub fn uses_variable_register(&self) -> bool {
use Location::*;
match self {
al | ax | eax | rax | cl | imm8 | imm16 | imm32 => false,
r8 | r16 | r32 | r64 | xmm | rm8 | rm16 | rm32 | rm64 | rm128 => true,
}
}
/// Convert the location to an [`OperandKind`].
#[must_use]
pub fn kind(&self) -> OperandKind {
use Location::*;
match self {
al | ax | eax | rax | cl => OperandKind::FixedReg(*self),
imm8 | imm16 | imm32 => OperandKind::Imm(*self),
r8 | r16 | r32 | r64 | xmm => OperandKind::Reg(*self),
rm8 | rm16 | rm32 | rm64 | rm128 => OperandKind::RegMem(*self),
}
}
}
impl core::fmt::Display for Location {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
use Location::*;
match self {
al => write!(f, "al"),
ax => write!(f, "ax"),
eax => write!(f, "eax"),
rax => write!(f, "rax"),
cl => write!(f, "cl"),
imm8 => write!(f, "imm8"),
imm16 => write!(f, "imm16"),
imm32 => write!(f, "imm32"),
r8 => write!(f, "r8"),
r16 => write!(f, "r16"),
r32 => write!(f, "r32"),
r64 => write!(f, "r64"),
xmm => write!(f, "xmm"),
rm8 => write!(f, "rm8"),
rm16 => write!(f, "rm16"),
rm32 => write!(f, "rm32"),
rm64 => write!(f, "rm64"),
rm128 => write!(f, "rm128"),
}
}
}
/// Organize the operand locations by kind.
///
/// ```
/// # use cranelift_assembler_x64_meta::dsl::{OperandKind, Location};
/// let k: OperandKind = Location::imm32.kind();
/// ```
#[derive(Clone, Copy, Debug)]
pub enum OperandKind {
FixedReg(Location),
Imm(Location),
Reg(Location),
RegMem(Location),
}
/// x64 operands can be mutable or not.
///
/// ```
/// # use cranelift_assembler_x64_meta::dsl::{r, rw, Location::r8, Mutability};
/// assert_eq!(r(r8).mutability, Mutability::Read);
/// assert_eq!(rw(r8).mutability, Mutability::ReadWrite);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Mutability {
Read,
ReadWrite,
}
impl Mutability {
/// Returns whether this represents a read of the operand in question.
///
/// Note that for read/write operands this returns `true`.
pub fn is_read(&self) -> bool {
match self {
Mutability::Read | Mutability::ReadWrite => true,
}
}
/// Returns whether this represents a write of the operand in question.
///
/// Note that for read/write operands this returns `true`.
pub fn is_write(&self) -> bool {
match self {
Mutability::Read => false,
Mutability::ReadWrite => true,
}
}
}
impl Default for Mutability {
fn default() -> Self {
Self::Read
}
}
impl core::fmt::Display for Mutability {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Read => write!(f, "r"),
Self::ReadWrite => write!(f, "rw"),
}
}
}
/// x64 operands may be sign- or zero-extended.
///
/// ```
/// # use cranelift_assembler_x64_meta::dsl::{Location::r8, sxw, Extension};
/// assert_eq!(sxw(r8).extension, Extension::SignExtendWord);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Extension {
None,
SignExtendQuad,
SignExtendLong,
SignExtendWord,
}
impl Extension {
/// Check if the extension is sign-extended.
#[must_use]
pub fn is_sign_extended(&self) -> bool {
matches!(self, Self::SignExtendQuad | Self::SignExtendLong | Self::SignExtendWord)
}
}
impl Default for Extension {
fn default() -> Self {
Self::None
}
}
impl core::fmt::Display for Extension {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Extension::None => write!(f, ""),
Extension::SignExtendQuad => write!(f, "sxq"),
Extension::SignExtendLong => write!(f, "sxl"),
Extension::SignExtendWord => write!(f, "sxw"),
}
}
}