rucc_ir/inst.rs
1//! What one instruction is, and what a value is.
2//!
3//! Design: `spec/08-ir.md` sections 8.1 and 8.3.
4//!
5//! An instruction is an [`Opcode`], a set of [`Flags`], a run of value operands, and whatever
6//! else that opcode needs, which is [`Extra`]. Everything that fits in eight bytes is in the
7//! [`Extra`] itself and everything larger is an index into a side table, so the instruction
8//! stays small enough that walking a function is walking one dense array.
9//!
10//! A value is the result of an instruction or a parameter of a block, and it is nothing else.
11//! There is no constant operand kind: a constant is an [`Opcode::IConst`] with a result like
12//! any other instruction. That is what makes the dominance rule in the verifier a single rule
13//! with no exceptions, and it costs nothing, because a constant with no uses is deleted by the
14//! same pass that deletes anything else with no uses.
15
16use rucc_base::{Idx, IdxRange, Symbol};
17
18use rucc_target::Slot;
19
20use crate::{
21 ExtraKind, Flags, FloatPred, IntPred, MemOrder, Opcode, Owner, PrefetchHint, RmwOp,
22 StorageClass, Type,
23};
24
25/// One value: the result of an instruction, or a parameter of a block.
26pub type Value = Idx<ValueData>;
27/// One instruction, in the function that owns it.
28pub type Inst = Idx<InstData>;
29/// One basic block, in the function that owns it.
30pub type Block = Idx<BlockData>;
31
32/// The table of references to values, which is what an operand list is a run of.
33#[derive(Debug)]
34pub struct ValueRef;
35/// A run of value operands.
36pub type ValueList = IdxRange<ValueRef>;
37/// A run of branch targets, which is what a terminator's successors are.
38pub type BlockCallList = IdxRange<BlockCall>;
39/// A run of immediates, which is what a `switch` holds its case values in.
40pub type ImmList = IdxRange<Imm>;
41/// A run of ABI attributes, which is what a call says about the arguments its signature does
42/// not name.
43pub type AbiList = IdxRange<Abi>;
44/// A run of eightbytes, which is how an object read off a variable argument list travelled.
45pub type SlotList = IdxRange<Slot>;
46
47/// A constant, in the immediate table.
48///
49/// The bits and nothing else. An integer is stored two's complement in as many of the low bits
50/// as its type is wide, and a floating point value is stored as its bit pattern, so the same
51/// table holds both and the type on the result says how to read it. That keeps a bit-preserving
52/// answer for a NaN payload, which a value of a Rust floating type would not.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54pub struct Imm(u128);
55
56impl Imm {
57 /// The bits, as they are stored.
58 #[must_use]
59 pub const fn bits(self) -> u128 {
60 self.0
61 }
62
63 /// An immediate holding these bits.
64 #[must_use]
65 pub const fn from_bits(bits: u128) -> Self {
66 Self(bits)
67 }
68
69 /// An integer, with the bits above `ty` cleared.
70 ///
71 /// A value is stored in exactly the width its type has, so two immediates are equal when
72 /// they are the same value, which is what lets an equality on the table stand in for an
73 /// equality on the numbers.
74 ///
75 /// # Panics
76 ///
77 /// Panics if `ty` is not an integer type.
78 #[must_use]
79 pub fn int(value: i128, ty: Type) -> Self {
80 assert!(ty.is_int(), "an integer immediate needs an integer type");
81 Self(value as u128 & mask(ty.bits()))
82 }
83
84 /// The value read as unsigned.
85 #[must_use]
86 pub const fn unsigned(self) -> u128 {
87 self.0
88 }
89
90 /// The value read as signed, with the sign bit of `ty` extended.
91 ///
92 /// # Panics
93 ///
94 /// Panics if `ty` is not an integer type.
95 #[must_use]
96 pub fn signed(self, ty: Type) -> i128 {
97 assert!(ty.is_int(), "an integer immediate needs an integer type");
98 let spare = 128 - ty.bits();
99 // Shifting left and then arithmetic right is the branch-free way to sign extend from
100 // an arbitrary width, and it is correct for a width of 128 because the shift is zero.
101 ((self.0 << spare) as i128) >> spare
102 }
103}
104
105/// The low `bits` bits set, and a width of 128 meaning all of them.
106fn mask(bits: u32) -> u128 {
107 if bits >= 128 { u128::MAX } else { (1u128 << bits) - 1 }
108}
109
110/// How often an arm of a branch is the one taken, where something knows.
111///
112/// Parts out of [`Hint::SCALE`], and nothing at all for an arm nobody has said anything about,
113/// which is almost every arm of almost every branch. A hint is what somebody claimed and not what
114/// a heuristic guessed: `__builtin_expect` writes one, a profile will write one, and the ten
115/// static predictors in `rucc_opt::predict` write none, because a guess that was written down
116/// would be indistinguishable afterwards from a fact.
117///
118/// The scale is ten thousandths because that is the scale `rucc_opt::Probability` and
119/// `rucc_mir::Weight` are in, and a number that changed scale on its way through the compiler is a
120/// number somebody will eventually divide twice.
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
122pub struct Hint(Option<u16>);
123
124impl Hint {
125 /// What a hint is out of.
126 pub const SCALE: u32 = 10_000;
127
128 /// Nothing said about this arm, which is what every arm starts as.
129 pub const NONE: Self = Self(None);
130
131 /// This arm is taken `parts` times in [`Hint::SCALE`].
132 ///
133 /// More than the scale is certainty rather than a mistake worth refusing, because the callers
134 /// that can produce one are doing arithmetic whose answer is certainty, so it is clamped.
135 #[must_use]
136 pub fn parts(parts: u32) -> Self {
137 Self(Some(u16::try_from(parts.min(Self::SCALE)).unwrap_or(u16::MAX)))
138 }
139
140 /// The number, or nothing where nothing was said.
141 #[must_use]
142 pub fn taken(self) -> Option<u32> {
143 self.0.map(u32::from)
144 }
145
146 /// The hint the other arm of a two armed branch carries, so that the two sum to certainty.
147 #[must_use]
148 pub fn complement(self) -> Self {
149 match self.0 {
150 Some(parts) => Self::parts(Self::SCALE - u32::from(parts)),
151 None => Self::NONE,
152 }
153 }
154}
155
156/// A branch target, and the values passed to it.
157///
158/// This is the whole reason there are no phi nodes. The arguments are here, in the branch,
159/// beside the block they go to, so removing a predecessor is one edit in one place and there
160/// is no second list anywhere that has to be kept in step with this one.
161///
162/// The hint is here for the same reason and not on the instruction: a branch has as many arms as
163/// it has block calls, and a weight held anywhere else would be a second list to keep in step with
164/// this one.
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub struct BlockCall {
167 /// Where control goes.
168 pub block: Block,
169 /// What is passed, one for each of the block's parameters.
170 pub args: ValueList,
171 /// How often this arm is the one taken, where something said so.
172 pub hint: Hint,
173}
174
175impl BlockCall {
176 /// An arm going to a block with arguments and nothing said about how often it is taken.
177 #[must_use]
178 pub const fn new(block: Block, args: ValueList) -> Self {
179 Self { block, args, hint: Hint::NONE }
180 }
181
182 /// An arm going to a block that takes no arguments.
183 #[must_use]
184 pub const fn to(block: Block) -> Self {
185 Self::new(block, ValueList::EMPTY)
186 }
187}
188
189/// What defines a value.
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum Def {
192 /// The result of an instruction, at this position among its results.
193 Result {
194 /// The instruction.
195 inst: Inst,
196 /// Which of its results this is.
197 index: u8,
198 },
199 /// A parameter of a block, at this position among its parameters.
200 Param {
201 /// The block.
202 block: Block,
203 /// Which of its parameters this is.
204 index: u32,
205 },
206}
207
208/// One value.
209#[derive(Clone, Copy, Debug, PartialEq, Eq)]
210pub struct ValueData {
211 /// Its type.
212 pub ty: Type,
213 /// Where it comes from.
214 pub def: Def,
215}
216
217/// What an access does beyond naming an address.
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219pub struct MemInfo {
220 /// How many bytes the access covers, for the ones whose size is not their result type.
221 ///
222 /// A `load` takes its size from the type it produces. An `alloca` and a `memset` do not,
223 /// and this is where theirs is.
224 pub size: u64,
225 /// The alignment the access is known to have, in bytes.
226 pub align: u32,
227 /// How strongly it is ordered, with [`MemOrder::NotAtomic`] for an ordinary access.
228 pub order: MemOrder,
229 /// The type-based aliasing node, if the front end knew one.
230 pub tbaa: Option<Meta>,
231 /// How many bytes of its record this access owns, counting the padding after it.
232 ///
233 /// Zero for an access that is not a member of a record, and zero when the front end was not
234 /// asked to work it out. What it is for is the init plane of
235 /// `spec/safe-memory/09-type-init-and-races.md` section 9.3: under `-fsafety-init=nopadding`
236 /// a store through a member records the padding after the member as written too, so that a
237 /// record filled a member at a time comes out whole and the ordinary reads of it, which are a
238 /// `memcmp` or a hash or a `write` of the record, are not refused.
239 ///
240 /// Only the init plane reads it. A bounds check over these bytes would be asking about bytes
241 /// the access does not touch, and a type plane write over them would be saying the padding
242 /// holds a value of the member's type, which it does not.
243 pub owns: u32,
244 /// Which `restrict` scope the access is in and which pointer it went through.
245 pub restrict: Restrict,
246}
247
248/// Which `restrict` scope an access is in, and which pointer inside that scope it went through.
249///
250/// Two small numbers, which is the whole of the mechanism. GCC spells them
251/// `MR_DEPENDENCE_CLIQUE` and `MR_DEPENDENCE_BASE` at `gcc/tree-ssa-alias.cc:2503` and the rule
252/// is one line: same clique and different base means the two accesses cannot touch the same
253/// byte, because that is exactly what `restrict` promises. A clique is one scope, numbered as
254/// lowering enters it, and a base is one `restrict` pointer declared inside it. Clique zero
255/// means nothing is known, which is what every access that is not under a `restrict` gets.
256///
257/// This is spec 9.4's scope tree rather than a blanket assumption, and it costs four bytes that
258/// were padding in [`MemInfo`] already.
259#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
260pub struct Restrict {
261 /// The scope, with zero meaning no information.
262 pub clique: u16,
263 /// The pointer within that scope, which only means anything when the clique is not zero.
264 pub base: u16,
265}
266
267impl Restrict {
268 /// No information, which is what an access outside any `restrict` scope carries.
269 pub const NONE: Self = Self { clique: 0, base: 0 };
270
271 /// Whether `restrict` says these two accesses cannot touch the same byte.
272 ///
273 /// Only accesses. GCC's PR71062 is what happens when this answer is used to fold a
274 /// comparison of the two pointers: `restrict` constrains what is read and written through a
275 /// pointer and says nothing about what the pointer's value is, so two pointers that may not
276 /// be used to reach the same object can still compare equal. A rule that folds `p == q` to
277 /// false on the strength of this is wrong.
278 #[must_use]
279 pub const fn disjoint(self, other: Self) -> bool {
280 self.clique != 0 && self.clique == other.clique && self.base != other.base
281 }
282}
283
284/// A metadata node, in the module's table.
285pub type Meta = Idx<MetaNode>;
286
287/// A node of the metadata graph.
288///
289/// Two kinds share the one table and the one numbering, because both of them are the compiler's
290/// interned type universe seen from a different side and a reader chasing a `!3` should not have
291/// to know which table it came out of.
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub enum MetaNode {
294 /// What aliasing needs: a type, and where it sits in the tree of types.
295 Tbaa(TbaaNode),
296 /// What the type plane needs: one entry in the vocabulary its bytes are written in.
297 Plane(PlaneNode),
298}
299
300impl MetaNode {
301 /// The aliasing node this is, or `None` when it is a plane entry.
302 #[must_use]
303 pub const fn tbaa(self) -> Option<TbaaNode> {
304 match self {
305 Self::Tbaa(node) => Some(node),
306 Self::Plane(_) => None,
307 }
308 }
309
310 /// The plane entry this is, or `None` when it is an aliasing node.
311 #[must_use]
312 pub const fn plane(self) -> Option<PlaneNode> {
313 match self {
314 Self::Plane(node) => Some(node),
315 Self::Tbaa(_) => None,
316 }
317 }
318
319 /// The node one level up, which a plane entry never has.
320 ///
321 /// The tree is the aliasing tree and a plane entry is not in it. A plane entry that names a
322 /// type points at a node of that tree, and that is a reference and not a parent: the walk
323 /// that answers an aliasing query has no business leaving the tree it is walking.
324 #[must_use]
325 pub const fn parent(self) -> Option<Meta> {
326 match self {
327 Self::Tbaa(node) => node.parent,
328 Self::Plane(_) => None,
329 }
330 }
331
332 /// The node it points at, which is the parent of an aliasing node and the type of a plane
333 /// entry, and is what has to come earlier in the table than the node itself.
334 #[must_use]
335 pub const fn points_at(self) -> Option<Meta> {
336 match self {
337 Self::Tbaa(node) => node.parent,
338 Self::Plane(PlaneNode::Type(node)) => Some(node),
339 Self::Plane(_) => None,
340 }
341 }
342}
343
344/// A node of the type based aliasing tree.
345///
346/// The tree this forms is checked by the verifier, since a cycle in it would make the aliasing
347/// query that walks it not terminate, and the place to find that out is here and not there.
348#[derive(Clone, Copy, Debug, PartialEq, Eq)]
349pub struct TbaaNode {
350 /// What this node is called, which is what the printer writes and the parser reads.
351 pub name: Symbol,
352 /// The node one level up, with the root having none.
353 pub parent: Option<Meta>,
354 /// The offset within the parent, for a member of a struct type.
355 pub offset: u64,
356}
357
358/// One entry in the type plane's vocabulary, per `spec/safe-memory/09-type-init-and-races.md`
359/// section 9.1.
360///
361/// The plane maps every byte to one of these, so this is what a `meta_type` writes and what a
362/// `check_type` is asking about. Three of the four are the distinguished values that document
363/// says the plane has beyond the types themselves, and they are why the plane needs a node kind
364/// of its own rather than pointing straight at an aliasing node: there is no aliasing node for
365/// "nobody has stored here yet".
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367pub enum PlaneNode {
368 /// A type, named by the aliasing node that is that type.
369 ///
370 /// The same node the front end already interned, so the plane's vocabulary is exactly the
371 /// compiler's and a report can name a type in the spelling the source used.
372 Type(Meta),
373 /// Bytes nothing has stored through, or stored from an untyped source.
374 ///
375 /// Compatible with every access, because storage with no declared type takes its effective
376 /// type from the store, which is C's rule and is also the only choice that does not fire at
377 /// every boundary with uninstrumented code.
378 NoType,
379 /// Bytes stored through a character type, which is compatible with every access.
380 ///
381 /// This is what makes the byte-wise copy idiom work. C 6.5 says a character access is
382 /// always permitted and that a store through a character lvalue does not set an effective
383 /// type, so the plane says `character` over those bytes and the later read of the field
384 /// still passes.
385 Character,
386 /// Byte `k` of a pointer shaped word.
387 ///
388 /// A pointer is not one type over its bytes, it is a word whose bytes are only meaningful
389 /// together, so reading four bytes out of the middle of one is a different thing from
390 /// reading four bytes of an `int` and the plane has to be able to say which byte it is.
391 PointerSlot(u8),
392}
393
394/// What a call needs beyond its arguments.
395#[derive(Clone, Copy, Debug, PartialEq, Eq)]
396pub struct CallInfo {
397 /// The name, for a direct call. `None` for a call through an address, where the address is
398 /// the first operand.
399 pub callee: Option<Symbol>,
400 /// The signature it is called with, which is where the ABI attributes are.
401 pub signature: Sig,
402 /// What the ABI asks of the arguments the signature does not name, one entry for each of
403 /// them.
404 ///
405 /// Only a variadic call has any, because only a variadic call passes an argument no
406 /// parameter stands for, and it is empty when every one of them travels as the value in
407 /// hand, which is nearly always. A structure the classification puts in the argument area
408 /// is the case it exists for: the bytes travel and there is no parameter to hang the
409 /// [`Abi::ByVal`] on, so it hangs here instead.
410 pub varargs: AbiList,
411}
412
413/// A signature, in the function's table.
414pub type Sig = Idx<Signature>;
415
416/// What a `switch` needs beyond the value it switches on.
417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
418pub struct SwitchInfo {
419 /// The targets, with the default first and one for each case after it.
420 pub targets: BlockCallList,
421 /// The case values, one for each target after the default.
422 pub cases: ImmList,
423}
424
425/// What an object read off a variable argument list is.
426///
427/// The access says how many bytes it is and what it is aligned to, which is the whole of what an
428/// object the convention put in the caller's argument area needs: it is there, and those two say
429/// where the argument behind it starts. An object that travelled in registers is not there at all.
430/// It is in the callee's own register save area, in as many places as it has eightbytes, and which
431/// register file each of those came from is not something the size and the alignment say. So the
432/// slots say it, and they are empty for the object that went in memory.
433///
434/// The classification is the front end's, because it is the one that still has the type. By the
435/// time an instruction reaches a backend the type is a size and an alignment, and the algorithm in
436/// section 3.5.7 of the psABI wants more than that.
437#[derive(Clone, Copy, Debug, PartialEq, Eq)]
438pub struct VaInfo {
439 /// The object, as any other access describes one.
440 pub mem: Idx<MemInfo>,
441 /// Where each of its eightbytes travelled, or nothing at all for one that travelled whole in
442 /// the caller's memory.
443 pub slots: SlotList,
444}
445
446/// What inline assembly needs.
447///
448/// The semantics belong to the inline assembly document. What is here is the shape: a
449/// template, the constraints, the clobbers, and the successors that make `asm goto` the one
450/// instruction whose being a terminator is a property of the instruction and not the opcode.
451#[derive(Clone, Copy, Debug, PartialEq, Eq)]
452pub struct AsmInfo {
453 /// The template string, as written.
454 pub template: Symbol,
455 /// The constraint list, as written.
456 pub constraints: Symbol,
457 /// The clobber list, as written.
458 pub clobbers: Symbol,
459 /// The labels, which are empty for everything except `asm goto`.
460 pub targets: BlockCallList,
461}
462
463/// Everything an instruction carries that is not a value operand.
464///
465/// Anything that fits in eight bytes is here and anything larger is an index into a side
466/// table, so that the common instructions, which are the arithmetic ones carrying nothing at
467/// all, do not pay for the rare ones.
468#[derive(Clone, Copy, Debug, PartialEq, Eq)]
469pub enum Extra {
470 /// Nothing, which is most instructions.
471 None,
472 /// A constant, for `iconst`, `fconst` and `splat`.
473 Imm(Idx<Imm>),
474 /// A name, for `global_addr` and for a target-specific intrinsic.
475 Symbol(Symbol),
476 /// Which comparison, for `icmp`.
477 IntPred(IntPred),
478 /// Which comparison, for `fcmp`.
479 FloatPred(FloatPred),
480 /// An access, for the loads, the stores, the copies and `alloca`.
481 Mem(Idx<MemInfo>),
482 /// An atomic read-modify-write, which is an access and which operation.
483 Rmw(RmwOp, Idx<MemInfo>),
484 /// A barrier's ordering, for `fence`.
485 Order(MemOrder),
486 /// What a `prefetch` is a hint about, which is a read or a write and how much locality.
487 Prefetch(PrefetchHint),
488 /// How many frames up to walk, for `frame_address` and `return_address`.
489 Depth(u32),
490 /// The targets of a branch, with the default first for a `switch`.
491 Targets(BlockCallList),
492 /// A call.
493 Call(Idx<CallInfo>),
494 /// A `switch`, which is targets and the values that select them.
495 Switch(Idx<SwitchInfo>),
496 /// Inline assembly.
497 Asm(Idx<AsmInfo>),
498 /// An object read off a variable argument list, which is an access and how it travelled.
499 VaObject(Idx<VaInfo>),
500 /// What kind of storage an instance is, for `meta_begin`.
501 Class(StorageClass),
502 /// Who a range went to, for `meta_transfer`.
503 Owner(Owner),
504 /// A metadata node, for `meta_type`, which is the one plane write that names a type.
505 Node(Meta),
506 /// Why an exemption was declared, for `safe_region_begin`.
507 Reason(Symbol),
508}
509
510impl Extra {
511 /// Which shape this is, without the payload.
512 ///
513 /// The verifier compares this with [`Opcode::extra_kind`], because an instruction carrying
514 /// the payload of some other opcode prints as text the parser cannot read back.
515 #[must_use]
516 pub const fn kind(self) -> ExtraKind {
517 match self {
518 Self::None => ExtraKind::None,
519 Self::Imm(_) => ExtraKind::Imm,
520 Self::Symbol(_) => ExtraKind::Symbol,
521 Self::IntPred(_) => ExtraKind::IntPred,
522 Self::FloatPred(_) => ExtraKind::FloatPred,
523 Self::Mem(_) => ExtraKind::Mem,
524 Self::Rmw(..) => ExtraKind::Rmw,
525 Self::Order(_) => ExtraKind::Order,
526 Self::Prefetch(_) => ExtraKind::Prefetch,
527 Self::Depth(_) => ExtraKind::Depth,
528 Self::Targets(_) => ExtraKind::Targets,
529 Self::Call(_) => ExtraKind::Call,
530 Self::Switch(_) => ExtraKind::Switch,
531 Self::Asm(_) => ExtraKind::Asm,
532 Self::VaObject(_) => ExtraKind::VaObject,
533 Self::Class(_) => ExtraKind::Class,
534 Self::Owner(_) => ExtraKind::Owner,
535 Self::Node(_) => ExtraKind::Node,
536 Self::Reason(_) => ExtraKind::Reason,
537 }
538 }
539}
540
541/// One instruction.
542///
543/// There is no result type here. Each result is a value in the function's value table and the
544/// type is on the value, which means a reader asking what an instruction produces asks the
545/// same question about `add` as about `call`, and there is no second copy of the type to
546/// disagree with the first.
547#[derive(Clone, Copy, Debug, PartialEq, Eq)]
548pub struct InstData {
549 /// Which instruction this is.
550 pub opcode: Opcode,
551 /// What the optimizer is licensed to assume about it.
552 pub flags: Flags,
553 /// How many values it produces.
554 pub results: u8,
555 /// The first of them, with the rest following it in the value table.
556 pub first_result: Option<Value>,
557 /// Its value operands.
558 pub args: ValueList,
559 /// Everything else it carries.
560 pub extra: Extra,
561}
562
563impl InstData {
564 /// An instruction with no operands, no flags, no results and nothing extra.
565 #[must_use]
566 pub const fn new(opcode: Opcode) -> Self {
567 Self {
568 opcode,
569 flags: Flags::NONE,
570 results: 0,
571 first_result: None,
572 args: ValueList::EMPTY,
573 extra: Extra::None,
574 }
575 }
576
577 /// The values it produces, in order.
578 pub fn results(&self) -> impl Iterator<Item = Value> + use<> {
579 let first = self.first_result.map_or(0, Idx::raw);
580 (0..u32::from(self.results)).map(move |offset| Value::new(first + offset))
581 }
582
583 /// The run of targets it branches to, which is empty when it does not branch.
584 ///
585 /// A `switch` keeps its targets in a side table, so this reads `Extra::Targets` only and
586 /// the function is what answers for the rest.
587 #[must_use]
588 pub fn targets(&self) -> BlockCallList {
589 match self.extra {
590 Extra::Targets(targets) => targets,
591 _ => BlockCallList::EMPTY,
592 }
593 }
594}
595
596/// How one parameter or one return value travels, beyond what its type says.
597///
598/// The IR's types are the machine's and not C's, so a `ptr` parameter says nothing about
599/// whether the pointer is the argument or whether the object it points at is, and an `i8` says
600/// nothing about which half of the register above it the callee may read. Both are the ABI's
601/// answer rather than the type's, which is why they are here and not on [`Type`].
602///
603/// A signature carrying one of these has already had the ABI applied to it. What the walk to
604/// the IR builds first is the C-level form, where every parameter is [`Abi::Plain`], and the
605/// classification in `rucc-target` is what turns one into the other.
606#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
607pub enum Abi {
608 /// The value itself, in the type it is written as.
609 #[default]
610 Plain,
611 /// An integer narrower than a register, with the bits above it its own sign.
612 ///
613 /// Which of these an ABI asks for is not a property of the value: `unsigned char` is
614 /// [`Abi::Sext`] on the Darwin ABIs and [`Abi::Zext`] elsewhere, and on SysV neither the
615 /// caller nor the callee may assume anything about those bits at all.
616 Sext,
617 /// An integer narrower than a register, with zeroes above it.
618 Zext,
619 /// The bytes of the object the pointer points at, in the argument area, with no address
620 /// travelling anywhere.
621 ///
622 /// The caller makes the copy the callee is free to write to, which is what makes this a C
623 /// call by value rather than a pointer the callee must not keep.
624 ByVal {
625 /// How many bytes travel.
626 size: u64,
627 /// What the copy is aligned to, which is the C alignment of the type and not the
628 /// pointer's.
629 align: u32,
630 },
631 /// Somewhere for the return value to go, whose address the caller passes as the first
632 /// argument because the value does not fit in the registers a return comes back in.
633 Sret {
634 /// How many bytes the callee writes.
635 size: u64,
636 /// What the space is aligned to.
637 align: u32,
638 },
639}
640
641impl Abi {
642 /// Whether this describes an object behind a pointer rather than the value in hand.
643 #[must_use]
644 pub const fn indirect(self) -> bool {
645 matches!(self, Self::ByVal { .. } | Self::Sret { .. })
646 }
647
648 /// The size and alignment of that object, for the two that have one.
649 #[must_use]
650 pub const fn object(self) -> Option<(u64, u32)> {
651 match self {
652 Self::ByVal { size, align } | Self::Sret { size, align } => Some((size, align)),
653 _ => None,
654 }
655 }
656}
657
658/// One parameter, or one return value: a type and how it travels.
659#[derive(Clone, Copy, Debug, PartialEq, Eq)]
660pub struct Param {
661 /// The type the IR sees, which for the indirect forms is `ptr`.
662 pub ty: Type,
663 /// What the ABI asks of it.
664 pub abi: Abi,
665}
666
667impl Param {
668 /// A parameter of this type, in its C-level form.
669 #[must_use]
670 pub const fn new(ty: Type) -> Self {
671 Self { ty, abi: Abi::Plain }
672 }
673
674 /// A parameter of this type travelling this way.
675 #[must_use]
676 pub const fn with_abi(ty: Type, abi: Abi) -> Self {
677 Self { ty, abi }
678 }
679}
680
681/// What a function takes and returns.
682///
683/// A signature is not a type. Nothing in the IR has a function type, because a `ptr` has no
684/// pointee and there is nothing else a function type could sit on. A `call_indirect` names the
685/// signature it is called with, and that is where the ABI attributes are read from.
686#[derive(Clone, Debug, PartialEq, Eq, Default)]
687pub struct Signature {
688 /// What it takes, in their C-level form until the ABI has been applied.
689 pub params: Vec<Param>,
690 /// What it returns, which is empty for a `void` function and for one whose return value
691 /// comes back through an [`Abi::Sret`] parameter.
692 pub returns: Vec<Param>,
693 /// Whether it takes arguments beyond the ones named.
694 pub variadic: bool,
695}
696
697impl Signature {
698 /// A signature taking and returning nothing.
699 #[must_use]
700 pub fn new() -> Self {
701 Self::default()
702 }
703
704 /// The same signature with these parameters, each in its C-level form.
705 #[must_use]
706 pub fn with_params(mut self, params: &[Type]) -> Self {
707 self.params = params.iter().copied().map(Param::new).collect();
708 self
709 }
710
711 /// The same signature returning these, each in its C-level form.
712 #[must_use]
713 pub fn with_returns(mut self, returns: &[Type]) -> Self {
714 self.returns = returns.iter().copied().map(Param::new).collect();
715 self
716 }
717
718 /// The same signature with one more parameter, travelling the way the ABI said.
719 #[must_use]
720 pub fn and_param(mut self, param: Param) -> Self {
721 self.params.push(param);
722 self
723 }
724
725 /// The same signature with one more return value, travelling the way the ABI said.
726 #[must_use]
727 pub fn and_return(mut self, param: Param) -> Self {
728 self.returns.push(param);
729 self
730 }
731
732 /// The types it takes, without what the ABI asks of them.
733 pub fn param_types(&self) -> impl Iterator<Item = Type> + use<'_> {
734 self.params.iter().map(|param| param.ty)
735 }
736
737 /// The types it returns.
738 pub fn return_types(&self) -> impl Iterator<Item = Type> + use<'_> {
739 self.returns.iter().map(|param| param.ty)
740 }
741
742 /// The same signature, variadic.
743 #[must_use]
744 pub fn variadic(mut self) -> Self {
745 self.variadic = true;
746 self
747 }
748}
749
750/// One basic block: parameters, then instructions, then exactly one terminator.
751///
752/// The instructions are a doubly linked list rather than a vector, so that inserting one in
753/// the middle of a block does not move the ones after it. An optimizer does that constantly,
754/// and a move would invalidate every [`Inst`] anybody was holding.
755#[derive(Clone, Debug, Default, PartialEq, Eq)]
756pub struct BlockData {
757 /// The values arriving here, which is what other IRs spell as phi nodes.
758 ///
759 /// A `Vec` and not a run in a pool, because SSA construction adds a parameter to a loop
760 /// header long after the blocks that come after it have been built, and a run in a pool
761 /// cannot grow in the middle.
762 pub params: Vec<Value>,
763 /// The first instruction, or `None` for a block nothing has been put in yet.
764 pub first: Option<Inst>,
765 /// The last instruction, which is the terminator once the block is finished.
766 pub last: Option<Inst>,
767 /// The block before this one in layout order.
768 pub prev: Option<Block>,
769 /// The block after it.
770 pub next: Option<Block>,
771}
772
773/// Where one instruction sits.
774#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
775pub struct InstLayout {
776 /// The block it is in, or `None` if it has been made and not yet inserted.
777 pub block: Option<Block>,
778 /// The instruction before it in that block.
779 pub prev: Option<Inst>,
780 /// The instruction after it.
781 pub next: Option<Inst>,
782}
783
784#[cfg(test)]
785mod tests {
786 use super::*;
787
788 #[test]
789 fn an_immediate_keeps_only_the_bits_its_type_has() {
790 let byte = Type::int(8);
791 assert_eq!(Imm::int(-1, byte).unsigned(), 0xff);
792 assert_eq!(Imm::int(-1, byte).signed(byte), -1);
793 assert_eq!(Imm::int(255, byte), Imm::int(-1, byte));
794 assert_eq!(Imm::int(127, byte).signed(byte), 127);
795 assert_eq!(Imm::int(128, byte).signed(byte), -128);
796 }
797
798 #[test]
799 fn a_widest_immediate_is_not_truncated() {
800 let word = Type::int(128);
801 assert_eq!(Imm::int(i128::MIN, word).signed(word), i128::MIN);
802 assert_eq!(Imm::int(i128::MAX, word).signed(word), i128::MAX);
803 assert_eq!(Imm::int(-1, word).unsigned(), u128::MAX);
804 }
805
806 #[test]
807 fn a_one_bit_immediate_is_a_bit() {
808 let bit = Type::I1;
809 assert_eq!(Imm::int(1, bit).unsigned(), 1);
810 assert_eq!(Imm::int(3, bit).unsigned(), 1);
811 assert_eq!(Imm::int(2, bit).unsigned(), 0);
812 // The one bit is the sign bit, so the only two values are zero and minus one.
813 assert_eq!(Imm::int(1, bit).signed(bit), -1);
814 }
815
816 #[test]
817 fn a_floating_immediate_keeps_its_bits() {
818 let bits = f64::NAN.to_bits() | 0x7;
819 assert_eq!(Imm::from_bits(u128::from(bits)).bits(), u128::from(bits));
820 }
821
822 #[test]
823 fn an_instruction_with_no_results_yields_none() {
824 let inst = InstData::new(Opcode::Store);
825 assert_eq!(inst.results().count(), 0);
826 }
827
828 #[test]
829 fn results_follow_the_first_one() {
830 let mut inst = InstData::new(Opcode::SAddOverflow);
831 inst.first_result = Some(Value::new(4));
832 inst.results = 2;
833 let got: Vec<u32> = inst.results().map(Idx::raw).collect();
834 assert_eq!(got, [4, 5]);
835 }
836
837 #[test]
838 fn a_jump_says_where_it_goes() {
839 let mut inst = InstData::new(Opcode::Jump);
840 inst.extra = Extra::Targets(BlockCallList::new(Idx::new(0), Idx::new(1)));
841 assert_eq!(inst.targets().len(), 1);
842 }
843
844 #[test]
845 fn a_signature_is_built_by_saying_what_it_takes_and_returns() {
846 let sig = Signature::new()
847 .with_params(&[Type::int(32), Type::PTR])
848 .with_returns(&[Type::int(32)])
849 .variadic();
850 assert_eq!(sig.param_types().collect::<Vec<_>>(), [Type::int(32), Type::PTR]);
851 assert_eq!(sig.return_types().collect::<Vec<_>>(), [Type::int(32)]);
852 assert!(sig.variadic);
853 assert_eq!(Signature::new(), Signature::default());
854 }
855
856 #[test]
857 fn a_parameter_says_how_it_travels_and_not_only_what_it_is() {
858 let object = Abi::ByVal { size: 24, align: 8 };
859 let sig = Signature::new()
860 .and_param(Param::with_abi(Type::PTR, Abi::Sret { size: 32, align: 16 }))
861 .and_param(Param::with_abi(Type::PTR, object))
862 .and_param(Param::with_abi(Type::int(8), Abi::Zext));
863 // The types alone say `ptr, ptr, i8`, which is three of the calls in any C program and
864 // none of them the same call.
865 assert_eq!(sig.param_types().collect::<Vec<_>>(), [Type::PTR, Type::PTR, Type::int(8)]);
866 assert_eq!(sig.params[1].abi.object(), Some((24, 8)));
867 assert!(sig.params[0].abi.indirect() && !sig.params[2].abi.indirect());
868 assert_eq!(Param::new(Type::PTR).abi, Abi::Plain);
869 assert_eq!(Abi::Plain.object(), None);
870 }
871
872 #[test]
873 fn an_instruction_stays_small() {
874 // Not a promise, a tripwire. Every function in the program is a run of these, and a
875 // change that doubles this should be a change somebody decided to make.
876 assert!(size_of::<InstData>() <= 32, "{}", size_of::<InstData>());
877 assert_eq!(size_of::<ValueData>(), 16);
878 assert_eq!(size_of::<Extra>(), 12);
879 }
880}