Skip to main content

rucc_ir/
opcode.rs

1//! The instruction set.
2//!
3//! Design: `spec/08-ir.md` section 8.3.
4//!
5//! The set is small enough to enumerate and it is closed. Adding an opcode is a spec change,
6//! because the verifier, the printer, the parser, the rewrite rules and the lowering all have
7//! to learn it, and an opcode that only half of them know about is a silent miscompilation
8//! waiting for the right input.
9//!
10//! Two things are deliberately absent. There is no `getelementptr`: pointer arithmetic is
11//! [`Opcode::PtrAdd`] over a byte offset the frontend computed, because C never needs the
12//! multi-index form and its absence removes a well known source of complexity. And there is no
13//! `phi`: values arriving at a block are the block's parameters, passed by the branch, so
14//! there is no operand list positionally tied to a predecessor list kept somewhere else.
15
16use std::fmt;
17
18/// One instruction of the IR.
19///
20/// The names are the textual form exactly, so [`Opcode::name`] and [`Opcode::from_name`] are
21/// what the printer and the parser use, and neither carries a table of its own that could
22/// drift from this one.
23///
24/// The enum is not `non_exhaustive`, deliberately. The set is closed, so a pass that matches
25/// on every opcode should stop compiling when one is added rather than fall into a wildcard
26/// arm that quietly does the wrong thing.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
28pub enum Opcode {
29    // Constants. A constant is an instruction rather than an operand kind, so that every
30    // operand is a value and every value has one definition, which is what makes the
31    // dominance check in the verifier a single rule rather than a rule with exceptions.
32    /// An integer constant, `iconst.i32 7`.
33    IConst,
34    /// A floating point constant, `fconst.f64 0x1.8p+1`.
35    FConst,
36    /// A vector constant with every lane the same, `splat.i8x16 0`.
37    Splat,
38    /// The address of a global or a function, `global_addr @counter`.
39    GlobalAddr,
40    /// The address of a block in this function, `block_addr block3`.
41    ///
42    /// The one instruction that names a block without being a branch, which is what GNU's
43    /// `&&label` is. Where it goes is [`Opcode::IndirectBr`], and the two are only useful
44    /// together: an address on its own is a number that nothing can do anything with.
45    BlockAddr,
46
47    // Arithmetic.
48    /// Integer addition.
49    Add,
50    /// Integer subtraction.
51    Sub,
52    /// Integer multiplication.
53    Mul,
54    /// Signed division.
55    SDiv,
56    /// Unsigned division.
57    UDiv,
58    /// Signed remainder, with the sign of the dividend.
59    SRem,
60    /// Unsigned remainder.
61    URem,
62    /// Bitwise and.
63    And,
64    /// Bitwise or.
65    Or,
66    /// Bitwise exclusive or.
67    Xor,
68    /// Shift left.
69    Shl,
70    /// Logical shift right, shifting in zeroes.
71    LShr,
72    /// Arithmetic shift right, shifting in the sign bit.
73    AShr,
74    /// Floating point addition.
75    FAdd,
76    /// Floating point subtraction.
77    FSub,
78    /// Floating point multiplication.
79    FMul,
80    /// Floating point division.
81    FDiv,
82    /// Floating point remainder.
83    FRem,
84    /// Floating point negation, which flips the sign bit and is not `0 - x`.
85    FNeg,
86    /// Fused multiply-add, rounded once.
87    Fma,
88
89    // Comparison.
90    /// Integer comparison, producing `i1` or a vector of `i1`.
91    ICmp,
92    /// Floating point comparison, producing `i1` or a vector of `i1`.
93    FCmp,
94
95    // Selection.
96    /// One of two values, chosen by a bit. `select c, a, b` is `a` when `c` is one.
97    ///
98    /// This is what control flow becomes when it stops being control flow.
99    /// `spec/optimizer/22-phiopt-and-if-conversion.md` section 22.2 makes it the lowering target
100    /// for a diamond whose two arms compute a value, and the reason it is an opcode rather than a
101    /// pattern is that it is the form the rule set is written against: `select(c, a, a) -> a` and
102    /// `select(c, 1, 0) -> zext(c)` are ordinary rules once the shape has a name.
103    ///
104    /// Both arms are evaluated, which is the whole point and also the whole danger. Whatever
105    /// produces one of these owes the argument that evaluating the arm that is not chosen is
106    /// harmless, and section 22.6 is the list of ways that argument goes wrong.
107    Select,
108
109    // Conversion.
110    /// Narrows an integer, discarding the high bits.
111    Trunc,
112    /// Widens an integer, copying the sign bit.
113    SExt,
114    /// Widens an integer, filling with zeroes.
115    ZExt,
116    /// Narrows a floating point value.
117    FPTrunc,
118    /// Widens a floating point value.
119    FPExt,
120    /// Floating point to signed integer.
121    FPToSI,
122    /// Floating point to unsigned integer.
123    FPToUI,
124    /// Signed integer to floating point.
125    SIToFP,
126    /// Unsigned integer to floating point.
127    UIToFP,
128    /// An address to an integer of the same width.
129    PtrToInt,
130    /// An integer to an address.
131    IntToPtr,
132    /// A reinterpretation of the same bits at the same width.
133    Bitcast,
134
135    // Memory.
136    /// Memory as the function found it, which is where a memory SSA chain starts.
137    ///
138    /// It produces one `mem` and takes nothing, and it belongs at the top of the entry block.
139    /// GCC calls the same thing the default definition of `.MEM` and LLVM calls it
140    /// `liveOnEntry`. It exists as an instruction rather than as a parameter of the entry block
141    /// because the entry block's parameters are the function's parameters and the verifier
142    /// checks them against the signature, and memory is not an argument anybody passed.
143    MemEntry,
144    /// A stack slot. In the entry block, or marked dynamic for a variable length array.
145    Alloca,
146    /// A read.
147    Load,
148    /// A write, producing no value.
149    Store,
150    /// Address arithmetic: an address and a byte offset.
151    PtrAdd,
152    /// A copy of a known size between addresses that do not overlap.
153    Memcpy,
154    /// A copy of a known size between addresses that may overlap.
155    Memmove,
156    /// A fill of a known size with one byte.
157    Memset,
158    /// An atomic read.
159    AtomicLoad,
160    /// An atomic write.
161    AtomicStore,
162    /// An atomic read-modify-write, carrying which operation in [`RmwOp`](crate::RmwOp).
163    AtomicRmw,
164    /// An atomic compare and exchange, producing the old value and whether it succeeded.
165    Cmpxchg,
166    /// A memory barrier.
167    Fence,
168
169    // Memory safety. Design: `spec/safe-memory/06-instrumentation.md` section 6.2.2. None of
170    // these is emitted unless `-fsafety` asked for it, and a function compiled without it
171    // contains not one of them.
172    /// The capability of a pointer value, taken from the pointer's provenance.
173    CapOf,
174    /// The capability in the auxiliary slot beside a stored pointer, read back.
175    ///
176    /// A pointer written to memory and read again has to bring its capability with it, and where
177    /// the capability lives is document 05's question rather than this one's. What this says is
178    /// that a capability comes back from an address, which is enough for every pass above.
179    CapLoad,
180    /// The other half of [`Opcode::CapLoad`], writing one into the slot beside a pointer.
181    CapStore,
182    /// The capability that permits nothing, which is what a null pointer has.
183    CapNull,
184    /// A capability narrowed to a sub-object of what it covered.
185    ///
186    /// Only under `-fsafety-subobject`. Narrowing is what catches an overflow from one member of
187    /// a struct into the next, and it is separate because C code that walks off the end of a
188    /// member on purpose exists and a project has to be able to say so.
189    CapNarrow,
190    /// The capability for an address that arrived from outside, recovered from the planes.
191    CapRecover,
192    /// How many bytes from an address on the capability covers, asking for no more than a limit.
193    ///
194    /// Three operands, the capability, the address and how many bytes the asker wants, and one
195    /// integer result that is never more than that limit. It is what
196    /// `spec/safe-memory/07-check-elimination.md` section 7.4 needs to split a loop: the checked
197    /// part and the unchecked part are divided at `min(n, extent / sizeof(T))`, and the extent is
198    /// the half of that a compiler cannot work out on its own.
199    ///
200    /// The limit is an operand because under milestone S1 answering means walking the lifetime
201    /// plane, and a walk that stops at the number of bytes the loop was going to read anyway is
202    /// bounded by the work the loop is already doing. An answer smaller than the truth costs
203    /// iterations in the checked half and is never wrong, which is what makes stopping early
204    /// allowed. Once a capability carries its own bounds, which is milestone S2, this is a
205    /// subtraction on the capability and the limit is one `min`.
206    CapExtent,
207    /// How many bytes below an address on the capability covers, asking for no more than a limit.
208    ///
209    /// The mirror of [`Opcode::CapExtent`], with the same three operands and the same kind of
210    /// answer. What it counts is the bytes ending at the address rather than the bytes starting
211    /// there, so an answer of `n` says that `[addr - n, addr)` belongs to one thing. The address
212    /// itself is one past what is asked about, which is what a walk from high to low needs: the
213    /// question is about where the walk ends up, and where it ends up is below where it began.
214    ///
215    /// The ownership asked about is the byte below the address rather than the byte at it, since
216    /// the address may be one past the end of the object and the object is what the question is
217    /// about. Everything else, the limit operand and why an answer short of the truth is allowed,
218    /// is [`Opcode::CapExtent`]'s.
219    CapExtentBack,
220    /// An access is within its capability's bounds, aligned, and permitted.
221    ///
222    /// The size and the alignment are the access's, and they are in the memory payload rather
223    /// than in operands because they are what the front end knew and not what the program
224    /// computed.
225    ///
226    /// A third operand overrides how many bytes are asked about, and it exists for the one check
227    /// the front end did not write. `spec/safe-memory/07-check-elimination.md` section 7.4 replaces
228    /// the checks in a loop that runs `n` times with one check over `n * sizeof(T)` bytes, and that
229    /// is a length the program computes rather than one anybody knew when the access was parsed. The
230    /// payload still holds the alignment and the type information of the access the check came from,
231    /// and its size becomes the size of one of them rather than the size of the question.
232    CheckBounds,
233    /// The capability's provenance is still live.
234    CheckLive,
235    /// The access agrees with the type plane, which is the effective type rule of C 6.5.
236    CheckType,
237    /// The bytes the access reads have been written.
238    CheckInit,
239    /// A pointer derived from another stays inside the capability the first one had.
240    ///
241    /// Three operands, because the answer is about the new pointer and the question is about
242    /// the old one's capability.
243    CheckDeriv,
244    /// The metadata this access is about to consult has not been changed under it.
245    ///
246    /// Judgement J9, which document 09 section 9.5 specifies and which document 04 section 4.5
247    /// keeps out of J1 for the reason the `restrict` checks are kept out: it is a statement about
248    /// two operations rather than about one. The payload holds the size of the access, because the
249    /// question is whether any granule of the range this touches carries a write by another thread.
250    CheckRace,
251    /// This read did not reach a byte another `restrict` pointer of the same block wrote.
252    ///
253    /// Judgement J8, which document 09 section 9.6 specifies and which document 04 section 4.6
254    /// keeps out of J1 because it is a statement about a pair of accesses rather than about one.
255    /// The payload holds the size of the access and the two numbers saying which pointer it went
256    /// through, and those are the same two [`crate::Restrict`] carries on the access itself.
257    ///
258    /// Read and write are two opcodes rather than one with a flag on it, because every bit of
259    /// [`crate::Flags`] is spoken for and because the operand would then be a constant the program
260    /// does not compute, which is the thing [`Opcode::CheckBounds`] says belongs in the payload.
261    CheckRestrictRead,
262    /// The same about a write, which is the half of the pair that makes the other half a violation.
263    ///
264    /// Two accesses that both only read are not a violation of anything, so what the scope records
265    /// is which of them wrote and the check refuses a pair only when at least one did.
266    CheckRestrictWrite,
267    /// A storage instance begins here, over a range, with a class.
268    ///
269    /// Judgement J4. This is the `alloca` for an automatic instance and the allocator's report
270    /// for an allocated one, and the range is a pointer and a length in registers rather than a
271    /// payload, because the length of a variable length array is not known when the instruction
272    /// is written down.
273    MetaBegin,
274    /// A storage instance ends here, which is judgement J5.
275    ///
276    /// Every capability for it fails from this point on and keeps failing after the address is
277    /// handed out again, which is what makes the check a use after free check rather than a use
278    /// after reallocation one.
279    MetaEnd,
280    /// The effective type of a range is now this one.
281    MetaType,
282    /// The effective types of a range are now the ones the range it was copied from had.
283    ///
284    /// Three operands, because a copy has two ranges and one length: the destination, the source,
285    /// and how many bytes moved. A `memcpy` does not store through a type, so there is no type to
286    /// name here and naming one would be wrong: C 6.5 says the copied bytes keep the effective type
287    /// they had, whatever that was, and the only place that is written down is the plane over the
288    /// source.
289    MetaTypeCopy,
290    /// The bytes of a range are now initialized.
291    MetaInit,
292    /// The bytes of a range are now initialized wherever the range they were copied from was.
293    ///
294    /// Three operands, for the reason [`Opcode::MetaTypeCopy`] has three. A copy does not write
295    /// values of its own, so whether a destination byte holds anything is whether the byte it came
296    /// from did, and the only place that is written down is the plane over the source. That is what
297    /// makes a structure filled member by member and then copied whole still have padding nothing
298    /// wrote, which is the infoleak the plane is for.
299    MetaInitCopy,
300    /// This thread wrote a range, at whatever step of its own counting it has reached.
301    ///
302    /// The epoch plane's only write, from `spec/safe-memory/09-type-init-and-races.md` section 9.5.
303    /// Two operands like the other plane writes, and the range is a pointer shaped slot rather than
304    /// whatever the access covered: the plane holds one stamp per eight bytes because that is what
305    /// a pointer comes in, and a granule two threads share is one holding no pointer.
306    ///
307    /// It carries no thread and no count. Which thread is running and how far it has counted are
308    /// both facts about the moment the program reaches this, so the runtime reads them and nothing
309    /// here could name them.
310    MetaEpoch,
311    /// A range leaves the monitor's authority, or comes back, which is judgement J7.
312    MetaTransfer,
313    /// A declared exemption starts here, with the reason it was declared.
314    ///
315    /// Not an optimization hint. Everything between this and its `safe_region_end` is code the
316    /// monitor is told not to judge, so the reason it carries is a trust set entry, and
317    /// `spec/safe-memory/10-boundaries.md` section 10.2 counts them per build precisely so that
318    /// a reviewer can read what a binary's guarantee rests on.
319    SafeRegionBegin,
320    /// The end of the region the last `safe_region_begin` opened.
321    SafeRegionEnd,
322    /// A block that declares `restrict` pointers begins here, over a slot to keep its record in.
323    ///
324    /// The operand is the storage the record lives in, which is the block's own stack slot, and the
325    /// payload says how large it is. The clique the block was given is [`crate::Restrict::clique`]
326    /// of the payload and how many pointers it declares is [`crate::Restrict::base`], which is the
327    /// one place that field counts bases rather than naming one.
328    ///
329    /// A marker rather than something the front end could fold into the accesses, because the
330    /// promise is about the block's dynamic extent: a function called twice has made the promise
331    /// twice, and what the second call reached says nothing about the first.
332    RestrictEnter,
333    /// The block the last `restrict_enter` opened ends here.
334    ///
335    /// The operand is the same slot, so that the record can be unlinked from whatever encloses it
336    /// without the runtime having to keep a list of its own.
337    RestrictLeave,
338
339    // Control. Every one of these is a terminator.
340    /// An unconditional branch, `jump block1(%a, %b)`.
341    Jump,
342    /// A two-way branch on an `i1`.
343    BrIf,
344    /// A multi-way branch on an integer, with a default.
345    Switch,
346    /// A branch to an address, `indirect_br %0, block1, block2`.
347    ///
348    /// The targets are every block control can arrive at, which is what makes the edges of a
349    /// computed `goto` ordinary edges: nothing else in the compiler has to know that the
350    /// address decides which one it is. A target that is not listed is a branch that does not
351    /// happen, so a frontend that leaves one out has made a promise on the program's behalf.
352    IndirectBr,
353    /// A return, with the values the signature says.
354    Return,
355    /// A place control cannot reach, which the frontend emits after a `noreturn` call.
356    Unreachable,
357
358    // Calls.
359    /// A call to a named function.
360    Call,
361    /// A call through an address, carrying the signature it is called with.
362    CallIndirect,
363    /// A call in tail position that reuses the frame, which is a terminator.
364    TailCall,
365
366    // Intrinsics, which is the closed part. The open part is `TargetIntrinsic`.
367    /// Count leading zeroes.
368    Ctlz,
369    /// Count trailing zeroes.
370    Cttz,
371    /// Count set bits.
372    Ctpop,
373    /// Reverse the bytes.
374    Bswap,
375    /// Reverse the bits.
376    Bitreverse,
377    /// Signed addition, producing the result and whether it overflowed.
378    SAddOverflow,
379    /// Unsigned addition, producing the result and whether it overflowed.
380    UAddOverflow,
381    /// Signed subtraction, producing the result and whether it overflowed.
382    SSubOverflow,
383    /// Unsigned subtraction, producing the result and whether it overflowed.
384    USubOverflow,
385    /// Signed multiplication, producing the result and whether it overflowed.
386    SMulOverflow,
387    /// Unsigned multiplication, producing the result and whether it overflowed.
388    UMulOverflow,
389    /// `__builtin_expect`, which is the value with a hint attached.
390    Expect,
391    /// `__builtin_unreachable` as a hint on a path, distinct from the terminator.
392    UnreachableHint,
393    /// `__builtin_prefetch`.
394    Prefetch,
395    /// `__builtin_frame_address`.
396    FrameAddress,
397    /// `__builtin_return_address`.
398    ReturnAddress,
399    /// The start of a variable argument list.
400    VaStart,
401    /// One argument off a variable argument list, which moves the list on as it reads it. Two
402    /// of these on one list are two arguments and never one argument read twice, so whatever
403    /// decides which instructions may be folded together has to leave these alone.
404    VaArg,
405    /// One argument off a variable argument list, when that argument is an object rather than a
406    /// value, which is what a `struct` or a `union` read out of one is.
407    ///
408    /// It answers the address of the object rather than the object, because an aggregate is not
409    /// a value and there is nothing for one result to be. Where the object arrives in registers
410    /// there is no address until something makes one, so what this asks of a target is a place
411    /// to put the registers and the address of that place, which is the copy every psABI's own
412    /// description of the algorithm makes. It moves the list on for the reason [`Opcode::VaArg`]
413    /// does.
414    VaObject,
415    /// The end of a variable argument list.
416    VaEnd,
417    /// A copy of a variable argument list.
418    VaCopy,
419    /// The stack pointer, saved before a variable length array.
420    StackSave,
421    /// The stack pointer, restored after one.
422    StackRestore,
423    /// The marker a `setjmp` leaves, which pins everything live across it.
424    SetjmpMarker,
425    /// The marker a `longjmp` leaves.
426    LongjmpMarker,
427    /// A target-specific intrinsic, named rather than enumerated, for the vector builtins.
428    TargetIntrinsic,
429
430    /// Inline assembly. A terminator when it has labels, which is `asm goto`.
431    InlineAsm,
432}
433
434impl Opcode {
435    /// The textual form, which is also what the parser reads.
436    #[must_use]
437    pub const fn name(self) -> &'static str {
438        match self {
439            Self::IConst => "iconst",
440            Self::FConst => "fconst",
441            Self::Splat => "splat",
442            Self::GlobalAddr => "global_addr",
443            Self::BlockAddr => "block_addr",
444            Self::Add => "add",
445            Self::Sub => "sub",
446            Self::Mul => "mul",
447            Self::SDiv => "sdiv",
448            Self::UDiv => "udiv",
449            Self::SRem => "srem",
450            Self::URem => "urem",
451            Self::And => "and",
452            Self::Or => "or",
453            Self::Xor => "xor",
454            Self::Shl => "shl",
455            Self::LShr => "lshr",
456            Self::AShr => "ashr",
457            Self::FAdd => "fadd",
458            Self::FSub => "fsub",
459            Self::FMul => "fmul",
460            Self::FDiv => "fdiv",
461            Self::FRem => "frem",
462            Self::FNeg => "fneg",
463            Self::Fma => "fma",
464            Self::ICmp => "icmp",
465            Self::FCmp => "fcmp",
466            Self::Select => "select",
467            Self::Trunc => "trunc",
468            Self::SExt => "sext",
469            Self::ZExt => "zext",
470            Self::FPTrunc => "fptrunc",
471            Self::FPExt => "fpext",
472            Self::FPToSI => "fptosi",
473            Self::FPToUI => "fptoui",
474            Self::SIToFP => "sitofp",
475            Self::UIToFP => "uitofp",
476            Self::PtrToInt => "ptrtoint",
477            Self::IntToPtr => "inttoptr",
478            Self::Bitcast => "bitcast",
479            Self::MemEntry => "mem_entry",
480            Self::Alloca => "alloca",
481            Self::Load => "load",
482            Self::Store => "store",
483            Self::PtrAdd => "ptr_add",
484            Self::Memcpy => "memcpy",
485            Self::Memmove => "memmove",
486            Self::Memset => "memset",
487            Self::AtomicLoad => "atomic_load",
488            Self::AtomicStore => "atomic_store",
489            Self::AtomicRmw => "atomic_rmw",
490            Self::Cmpxchg => "cmpxchg",
491            Self::Fence => "fence",
492            Self::CapOf => "cap_of",
493            Self::CapLoad => "cap_load",
494            Self::CapStore => "cap_store",
495            Self::CapNull => "cap_null",
496            Self::CapNarrow => "cap_narrow",
497            Self::CapRecover => "cap_recover",
498            Self::CapExtent => "cap_extent",
499            Self::CapExtentBack => "cap_extent_back",
500            Self::CheckBounds => "check_bounds",
501            Self::CheckLive => "check_live",
502            Self::CheckType => "check_type",
503            Self::CheckInit => "check_init",
504            Self::CheckDeriv => "check_deriv",
505            Self::CheckRace => "check_race",
506            Self::CheckRestrictRead => "check_restrict_read",
507            Self::CheckRestrictWrite => "check_restrict_write",
508            Self::MetaBegin => "meta_begin",
509            Self::MetaEnd => "meta_end",
510            Self::MetaType => "meta_type",
511            Self::MetaTypeCopy => "meta_type_copy",
512            Self::MetaInit => "meta_init",
513            Self::MetaInitCopy => "meta_init_copy",
514            Self::MetaEpoch => "meta_epoch",
515            Self::MetaTransfer => "meta_transfer",
516            Self::SafeRegionBegin => "safe_region_begin",
517            Self::SafeRegionEnd => "safe_region_end",
518            Self::RestrictEnter => "restrict_enter",
519            Self::RestrictLeave => "restrict_leave",
520            Self::Jump => "jump",
521            Self::BrIf => "br_if",
522            Self::Switch => "switch",
523            Self::IndirectBr => "indirect_br",
524            Self::Return => "return",
525            Self::Unreachable => "unreachable",
526            Self::Call => "call",
527            Self::CallIndirect => "call_indirect",
528            Self::TailCall => "tail_call",
529            Self::Ctlz => "ctlz",
530            Self::Cttz => "cttz",
531            Self::Ctpop => "ctpop",
532            Self::Bswap => "bswap",
533            Self::Bitreverse => "bitreverse",
534            Self::SAddOverflow => "sadd_overflow",
535            Self::UAddOverflow => "uadd_overflow",
536            Self::SSubOverflow => "ssub_overflow",
537            Self::USubOverflow => "usub_overflow",
538            Self::SMulOverflow => "smul_overflow",
539            Self::UMulOverflow => "umul_overflow",
540            Self::Expect => "expect",
541            Self::UnreachableHint => "unreachable_hint",
542            Self::Prefetch => "prefetch",
543            Self::FrameAddress => "frame_address",
544            Self::ReturnAddress => "return_address",
545            Self::VaStart => "va_start",
546            Self::VaArg => "va_arg",
547            Self::VaObject => "va_object",
548            Self::VaEnd => "va_end",
549            Self::VaCopy => "va_copy",
550            Self::StackSave => "stacksave",
551            Self::StackRestore => "stackrestore",
552            Self::SetjmpMarker => "setjmp_marker",
553            Self::LongjmpMarker => "longjmp_marker",
554            Self::TargetIntrinsic => "target_intrinsic",
555            Self::InlineAsm => "inline_asm",
556        }
557    }
558
559    /// Every opcode, in the order they are declared.
560    ///
561    /// The parser walks this rather than holding a second table, because a second table is a
562    /// table that can disagree with the first one.
563    pub fn all() -> impl Iterator<Item = Self> {
564        ALL.iter().copied()
565    }
566
567    /// The opcode with that name, if there is one.
568    #[must_use]
569    pub fn from_name(name: &str) -> Option<Self> {
570        ALL.iter().copied().find(|op| op.name() == name)
571    }
572
573    /// Whether this ends a block.
574    ///
575    /// [`Opcode::InlineAsm`] is not here and is the one instruction whose answer depends on
576    /// the instruction rather than on the opcode: `asm goto` has successors and everything
577    /// else does not. Ask the instruction, not the opcode.
578    #[must_use]
579    pub const fn is_terminator(self) -> bool {
580        matches!(
581            self,
582            Self::Jump
583                | Self::BrIf
584                | Self::Switch
585                | Self::IndirectBr
586                | Self::Return
587                | Self::Unreachable
588                | Self::TailCall
589        )
590    }
591
592    /// Whether the operands can be swapped without changing the result.
593    ///
594    /// The floating point cases are commutative even under the strictest rounding, because
595    /// swapping the operands of an addition does not change which of them is a NaN, and the
596    /// sign of a NaN result is not something we promise anything about either way.
597    #[must_use]
598    pub const fn is_commutative(self) -> bool {
599        matches!(
600            self,
601            Self::Add
602                | Self::Mul
603                | Self::And
604                | Self::Or
605                | Self::Xor
606                | Self::FAdd
607                | Self::FMul
608                | Self::SAddOverflow
609                | Self::UAddOverflow
610                | Self::SMulOverflow
611                | Self::UMulOverflow
612        )
613    }
614
615    /// Whether this reads or writes memory, or has an effect the optimizer has to preserve.
616    ///
617    /// An instruction that answers no can be deleted when nothing uses its result, moved
618    /// across a call, and merged with another one computing the same thing. Everything else
619    /// has to be argued about individually, so the conservative answer is the true one here
620    /// and the list of exceptions is the part that is checked.
621    #[must_use]
622    pub const fn has_effects(self) -> bool {
623        !matches!(
624            self,
625            Self::IConst
626                | Self::FConst
627                | Self::Splat
628                | Self::GlobalAddr
629                | Self::BlockAddr
630                | Self::Add
631                | Self::Sub
632                | Self::Mul
633                | Self::SDiv
634                | Self::UDiv
635                | Self::SRem
636                | Self::URem
637                | Self::And
638                | Self::Or
639                | Self::Xor
640                | Self::Shl
641                | Self::LShr
642                | Self::AShr
643                | Self::FAdd
644                | Self::FSub
645                | Self::FMul
646                | Self::FDiv
647                | Self::FRem
648                | Self::FNeg
649                | Self::Fma
650                | Self::ICmp
651                | Self::FCmp
652                | Self::Select
653                | Self::Trunc
654                | Self::SExt
655                | Self::ZExt
656                | Self::FPTrunc
657                | Self::FPExt
658                | Self::FPToSI
659                | Self::FPToUI
660                | Self::SIToFP
661                | Self::UIToFP
662                | Self::PtrToInt
663                | Self::IntToPtr
664                | Self::Bitcast
665                | Self::PtrAdd
666                | Self::Ctlz
667                | Self::Cttz
668                | Self::Ctpop
669                | Self::Bswap
670                | Self::Bitreverse
671                | Self::SAddOverflow
672                | Self::UAddOverflow
673                | Self::SSubOverflow
674                | Self::USubOverflow
675                | Self::SMulOverflow
676                | Self::UMulOverflow
677                | Self::Expect
678                | Self::FrameAddress
679                | Self::ReturnAddress
680                | Self::MemEntry
681                // Three of the capability instructions are arithmetic on a pointer's
682                // provenance and touch nothing. The other three do: `cap_load` and
683                // `cap_store` are an access, and `cap_recover` reads the planes.
684                | Self::CapOf
685                | Self::CapNull
686                | Self::CapNarrow
687        )
688    }
689
690    /// Whether an instruction with this opcode touches memory.
691    ///
692    /// This is what decides whether it takes a memory operand once memory SSA is built, per
693    /// document 09 of `spec/optimizer`. It is written as the exceptions to touching memory
694    /// rather than as a list of what does, for the reason document 08.6 gives about the escape
695    /// analysis: an opcode added later has to end up on the conservative side by default, and a
696    /// list of what touches memory would silently leave a new one out.
697    ///
698    /// `mem_entry` answers no. It produces memory rather than touching it, which is the whole
699    /// of what it is for.
700    #[must_use]
701    pub const fn touches_memory(self) -> bool {
702        if !self.has_effects() {
703            return false;
704        }
705        !matches!(
706            self,
707            // Fresh storage nothing could have been reading, and the pointer that names it.
708            Self::Alloca
709                // The stack pointer, which is a register and not memory. Putting it back is a
710                // different matter and is below, because it takes storage away.
711                | Self::StackSave
712                // Control, which goes somewhere rather than touching anything. A tail call is
713                // not here, because it is a call.
714                | Self::Jump
715                | Self::BrIf
716                | Self::Switch
717                | Self::IndirectBr
718                | Self::Return
719                | Self::Unreachable
720                | Self::UnreachableHint
721        )
722    }
723
724    /// Whether an instruction with this opcode writes memory, and so produces a new version of
725    /// it rather than only reading the version it was given.
726    ///
727    /// Everything that touches memory writes it except the ones that plainly do not. A `fence`
728    /// writes nothing and is still a write here, because document 09.5 says an atomic or a
729    /// barrier is a definition nothing walks past, and giving it one is how that is expressed
730    /// in a representation whose only ordering is the memory chain.
731    ///
732    /// The checks read the planes and change nothing, which
733    /// `spec/safe-memory/06-instrumentation.md` section 6.2.4 states as the word `readonly`. A
734    /// check that trapped is a program that stopped and there is no version of memory after it
735    /// for anything to observe, so the trap costs nothing here. What it does cost is that a
736    /// check may not be moved across a plane write, and that is the memory chain saying so
737    /// rather than this.
738    #[must_use]
739    pub const fn writes_memory(self) -> bool {
740        self.touches_memory()
741            && !matches!(
742                self,
743                Self::Load
744                    | Self::AtomicLoad
745                    | Self::Prefetch
746                    | Self::CapLoad
747                    | Self::CapRecover
748                    | Self::CapExtent
749                    | Self::CapExtentBack
750                    | Self::CheckBounds
751                    | Self::CheckLive
752                    | Self::CheckType
753                    | Self::CheckInit
754                    | Self::CheckDeriv
755                    | Self::CheckRace
756            )
757    }
758
759    /// How many values this produces, for the opcodes where the count is fixed.
760    ///
761    /// `None` means the count comes from somewhere else: a call takes it from its signature,
762    /// and inline assembly takes it from its output constraints. A tail call is not one of
763    /// them, because whatever it returns goes straight out of the function and there is no
764    /// instruction after it to use anything.
765    #[must_use]
766    pub const fn results(self) -> Option<u8> {
767        match self {
768            Self::Call | Self::CallIndirect | Self::InlineAsm => None,
769            Self::Cmpxchg
770            | Self::SAddOverflow
771            | Self::UAddOverflow
772            | Self::SSubOverflow
773            | Self::USubOverflow
774            | Self::SMulOverflow
775            | Self::UMulOverflow => Some(2),
776            Self::Store
777            | Self::Memcpy
778            | Self::Memmove
779            | Self::Memset
780            | Self::AtomicStore
781            | Self::Fence
782            | Self::Prefetch
783            | Self::VaStart
784            | Self::VaEnd
785            | Self::VaCopy
786            | Self::StackRestore
787            | Self::UnreachableHint
788            | Self::SetjmpMarker
789            | Self::LongjmpMarker
790            | Self::CapStore
791            | Self::CheckBounds
792            | Self::CheckLive
793            | Self::CheckType
794            | Self::CheckInit
795            | Self::CheckDeriv
796            | Self::CheckRace
797            | Self::CheckRestrictRead
798            | Self::CheckRestrictWrite
799            | Self::MetaBegin
800            | Self::MetaEnd
801            | Self::MetaType
802            | Self::MetaTypeCopy
803            | Self::MetaInit
804            | Self::MetaInitCopy
805            | Self::MetaEpoch
806            | Self::MetaTransfer
807            | Self::SafeRegionBegin
808            | Self::SafeRegionEnd
809            | Self::RestrictEnter
810            | Self::RestrictLeave => Some(0),
811            _ if self.is_terminator() => Some(0),
812            _ => Some(1),
813        }
814    }
815
816    /// Whether an instruction with this opcode produces a capability.
817    ///
818    /// Five of the eight `cap` instructions. The other three consume one instead: `cap_store`
819    /// writes it beside a pointer, and `cap_extent` and `cap_extent_back` ask it a question about
820    /// itself and answer with a number. The reason this is a question about the opcode rather than
821    /// about the
822    /// result type is that the verifier asks it the other way round: it walks the results looking
823    /// for a `cap` and needs to know whether the instruction under it was entitled to make one.
824    #[must_use]
825    pub const fn makes_capability(self) -> bool {
826        matches!(
827            self,
828            Self::CapOf | Self::CapLoad | Self::CapNull | Self::CapNarrow | Self::CapRecover
829        )
830    }
831
832    /// Which payload an instruction with this opcode carries.
833    ///
834    /// The printer reads the payload it finds and does not need this. The parser has only the
835    /// opcode when it reaches the operands, so this is where the two of them agree on what
836    /// comes after them. An instruction carrying a payload of some other kind prints as text
837    /// the parser cannot read back, which is why the verifier checks it against
838    /// [`Extra::kind`](crate::Extra::kind) rather than leaving it to be found later.
839    #[must_use]
840    pub const fn extra_kind(self) -> ExtraKind {
841        match self {
842            Self::IConst | Self::FConst | Self::Splat => ExtraKind::Imm,
843            Self::GlobalAddr | Self::TargetIntrinsic => ExtraKind::Symbol,
844            Self::ICmp => ExtraKind::IntPred,
845            Self::FCmp => ExtraKind::FloatPred,
846            Self::Alloca
847            | Self::Load
848            | Self::Store
849            | Self::Memcpy
850            | Self::Memmove
851            | Self::Memset
852            | Self::AtomicLoad
853            | Self::AtomicStore
854            | Self::Cmpxchg
855            // Four of the checks are about a run of bytes and the payload is where the size
856            // of that run is, along with the alignment `check_bounds` wants and the aliasing
857            // node `check_type` compares against. The other two ask a question about a
858            // pointer and not about a range, so they carry nothing.
859            | Self::CheckBounds
860            | Self::CheckType
861            | Self::CheckInit
862            | Self::CheckRace
863            // The two `restrict` checks and the marker that opens their scope. The first two carry
864            // the size of the access and the two numbers saying which pointer it went through, and
865            // the third carries the size of the slot and the numbers describing the scope itself.
866            | Self::CheckRestrictRead
867            | Self::CheckRestrictWrite
868            | Self::RestrictEnter => ExtraKind::Mem,
869            // The plane writes. What each one needs beyond the range is different, and the range
870            // itself is operands, since the length of a variable length array is a value.
871            Self::MetaBegin => ExtraKind::Class,
872            Self::MetaTransfer => ExtraKind::Owner,
873            Self::MetaType => ExtraKind::Node,
874            Self::SafeRegionBegin => ExtraKind::Reason,
875            Self::VaObject => ExtraKind::VaObject,
876            Self::AtomicRmw => ExtraKind::Rmw,
877            Self::Fence => ExtraKind::Order,
878            Self::Jump | Self::BrIf | Self::BlockAddr | Self::IndirectBr => ExtraKind::Targets,
879            Self::Switch => ExtraKind::Switch,
880            Self::Call | Self::CallIndirect | Self::TailCall => ExtraKind::Call,
881            Self::InlineAsm => ExtraKind::Asm,
882            _ => ExtraKind::None,
883        }
884    }
885}
886
887/// Which of [`Extra`](crate::Extra)'s shapes an instruction carries.
888///
889/// The same list of names, without any of the payloads, so that a question about an opcode can
890/// be answered without an instruction to look at.
891#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
892pub enum ExtraKind {
893    /// Nothing.
894    None,
895    /// A constant.
896    Imm,
897    /// A name.
898    Symbol,
899    /// An integer comparison predicate.
900    IntPred,
901    /// A floating point comparison predicate.
902    FloatPred,
903    /// An access.
904    Mem,
905    /// An atomic read-modify-write.
906    Rmw,
907    /// A barrier's ordering.
908    Order,
909    /// Branch targets.
910    Targets,
911    /// A call.
912    Call,
913    /// A `switch`.
914    Switch,
915    /// Inline assembly.
916    Asm,
917    /// An object read off a variable argument list.
918    VaObject,
919    /// What kind of storage an instance is.
920    Class,
921    /// Who a range of memory went to.
922    Owner,
923    /// A metadata node.
924    Node,
925    /// Why a declared exemption is there.
926    Reason,
927}
928
929impl ExtraKind {
930    /// What it is, in words, for a message that names two of them and has to read as English.
931    #[must_use]
932    pub const fn name(self) -> &'static str {
933        match self {
934            Self::None => "nothing",
935            Self::Imm => "a constant",
936            Self::Symbol => "a name",
937            Self::IntPred => "an integer comparison",
938            Self::FloatPred => "a floating point comparison",
939            Self::Mem => "an access",
940            Self::Rmw => "a read-modify-write",
941            Self::Order => "an ordering",
942            Self::Targets => "branch targets",
943            Self::Call => "a call",
944            Self::Switch => "a switch",
945            Self::Asm => "inline assembly",
946            Self::VaObject => "an object off a variable argument list",
947            Self::Class => "a storage class",
948            Self::Owner => "an owner",
949            Self::Node => "a metadata node",
950            Self::Reason => "a reason",
951        }
952    }
953}
954
955impl fmt::Display for Opcode {
956    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957        f.write_str(self.name())
958    }
959}
960
961/// Every opcode, which is what [`Opcode::all`] hands out.
962///
963/// This is written out rather than derived, and the test below is what keeps it complete: it
964/// checks the count against [`Opcode::InlineAsm`], the last variant, so a new opcode that is
965/// not added here fails the build rather than going quietly missing from the parser.
966static ALL: &[Opcode] = &[
967    Opcode::IConst,
968    Opcode::FConst,
969    Opcode::Splat,
970    Opcode::GlobalAddr,
971    Opcode::BlockAddr,
972    Opcode::Add,
973    Opcode::Sub,
974    Opcode::Mul,
975    Opcode::SDiv,
976    Opcode::UDiv,
977    Opcode::SRem,
978    Opcode::URem,
979    Opcode::And,
980    Opcode::Or,
981    Opcode::Xor,
982    Opcode::Shl,
983    Opcode::LShr,
984    Opcode::AShr,
985    Opcode::FAdd,
986    Opcode::FSub,
987    Opcode::FMul,
988    Opcode::FDiv,
989    Opcode::FRem,
990    Opcode::FNeg,
991    Opcode::Fma,
992    Opcode::ICmp,
993    Opcode::FCmp,
994    Opcode::Select,
995    Opcode::Trunc,
996    Opcode::SExt,
997    Opcode::ZExt,
998    Opcode::FPTrunc,
999    Opcode::FPExt,
1000    Opcode::FPToSI,
1001    Opcode::FPToUI,
1002    Opcode::SIToFP,
1003    Opcode::UIToFP,
1004    Opcode::PtrToInt,
1005    Opcode::IntToPtr,
1006    Opcode::Bitcast,
1007    Opcode::MemEntry,
1008    Opcode::Alloca,
1009    Opcode::Load,
1010    Opcode::Store,
1011    Opcode::PtrAdd,
1012    Opcode::Memcpy,
1013    Opcode::Memmove,
1014    Opcode::Memset,
1015    Opcode::AtomicLoad,
1016    Opcode::AtomicStore,
1017    Opcode::AtomicRmw,
1018    Opcode::Cmpxchg,
1019    Opcode::Fence,
1020    Opcode::CapOf,
1021    Opcode::CapLoad,
1022    Opcode::CapStore,
1023    Opcode::CapNull,
1024    Opcode::CapNarrow,
1025    Opcode::CapRecover,
1026    Opcode::CapExtent,
1027    Opcode::CapExtentBack,
1028    Opcode::CheckBounds,
1029    Opcode::CheckLive,
1030    Opcode::CheckType,
1031    Opcode::CheckInit,
1032    Opcode::CheckDeriv,
1033    Opcode::CheckRace,
1034    Opcode::CheckRestrictRead,
1035    Opcode::CheckRestrictWrite,
1036    Opcode::MetaBegin,
1037    Opcode::MetaEnd,
1038    Opcode::MetaType,
1039    Opcode::MetaTypeCopy,
1040    Opcode::MetaInit,
1041    Opcode::MetaInitCopy,
1042    Opcode::MetaEpoch,
1043    Opcode::MetaTransfer,
1044    Opcode::SafeRegionBegin,
1045    Opcode::SafeRegionEnd,
1046    Opcode::RestrictEnter,
1047    Opcode::RestrictLeave,
1048    Opcode::Jump,
1049    Opcode::BrIf,
1050    Opcode::Switch,
1051    Opcode::IndirectBr,
1052    Opcode::Return,
1053    Opcode::Unreachable,
1054    Opcode::Call,
1055    Opcode::CallIndirect,
1056    Opcode::TailCall,
1057    Opcode::Ctlz,
1058    Opcode::Cttz,
1059    Opcode::Ctpop,
1060    Opcode::Bswap,
1061    Opcode::Bitreverse,
1062    Opcode::SAddOverflow,
1063    Opcode::UAddOverflow,
1064    Opcode::SSubOverflow,
1065    Opcode::USubOverflow,
1066    Opcode::SMulOverflow,
1067    Opcode::UMulOverflow,
1068    Opcode::Expect,
1069    Opcode::UnreachableHint,
1070    Opcode::Prefetch,
1071    Opcode::FrameAddress,
1072    Opcode::ReturnAddress,
1073    Opcode::VaStart,
1074    Opcode::VaArg,
1075    Opcode::VaObject,
1076    Opcode::VaEnd,
1077    Opcode::VaCopy,
1078    Opcode::StackSave,
1079    Opcode::StackRestore,
1080    Opcode::SetjmpMarker,
1081    Opcode::LongjmpMarker,
1082    Opcode::TargetIntrinsic,
1083    Opcode::InlineAsm,
1084];
1085
1086/// The ten integer comparisons.
1087///
1088/// Signedness is on the predicate rather than on the type, for the same reason it is on
1089/// `sdiv` and `udiv`: the type space is halved and the operation says what it means.
1090#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1091pub enum IntPred {
1092    /// Equal.
1093    Eq,
1094    /// Not equal.
1095    Ne,
1096    /// Signed less than.
1097    Slt,
1098    /// Signed less than or equal.
1099    Sle,
1100    /// Signed greater than.
1101    Sgt,
1102    /// Signed greater than or equal.
1103    Sge,
1104    /// Unsigned less than.
1105    Ult,
1106    /// Unsigned less than or equal.
1107    Ule,
1108    /// Unsigned greater than.
1109    Ugt,
1110    /// Unsigned greater than or equal.
1111    Uge,
1112}
1113
1114impl IntPred {
1115    /// The textual form.
1116    #[must_use]
1117    pub const fn name(self) -> &'static str {
1118        match self {
1119            Self::Eq => "eq",
1120            Self::Ne => "ne",
1121            Self::Slt => "slt",
1122            Self::Sle => "sle",
1123            Self::Sgt => "sgt",
1124            Self::Sge => "sge",
1125            Self::Ult => "ult",
1126            Self::Ule => "ule",
1127            Self::Ugt => "ugt",
1128            Self::Uge => "uge",
1129        }
1130    }
1131
1132    /// The predicate with that name, if there is one.
1133    #[must_use]
1134    pub fn from_name(name: &str) -> Option<Self> {
1135        Self::all().find(|pred| pred.name() == name)
1136    }
1137
1138    /// Every predicate.
1139    pub fn all() -> impl Iterator<Item = Self> {
1140        [
1141            Self::Eq,
1142            Self::Ne,
1143            Self::Slt,
1144            Self::Sle,
1145            Self::Sgt,
1146            Self::Sge,
1147            Self::Ult,
1148            Self::Ule,
1149            Self::Ugt,
1150            Self::Uge,
1151        ]
1152        .into_iter()
1153    }
1154
1155    /// The predicate that holds exactly when this one does not.
1156    #[must_use]
1157    pub const fn inverse(self) -> Self {
1158        match self {
1159            Self::Eq => Self::Ne,
1160            Self::Ne => Self::Eq,
1161            Self::Slt => Self::Sge,
1162            Self::Sge => Self::Slt,
1163            Self::Sle => Self::Sgt,
1164            Self::Sgt => Self::Sle,
1165            Self::Ult => Self::Uge,
1166            Self::Uge => Self::Ult,
1167            Self::Ule => Self::Ugt,
1168            Self::Ugt => Self::Ule,
1169        }
1170    }
1171
1172    /// The predicate that holds when the operands are given the other way round.
1173    #[must_use]
1174    pub const fn swapped(self) -> Self {
1175        match self {
1176            Self::Eq => Self::Eq,
1177            Self::Ne => Self::Ne,
1178            Self::Slt => Self::Sgt,
1179            Self::Sgt => Self::Slt,
1180            Self::Sle => Self::Sge,
1181            Self::Sge => Self::Sle,
1182            Self::Ult => Self::Ugt,
1183            Self::Ugt => Self::Ult,
1184            Self::Ule => Self::Uge,
1185            Self::Uge => Self::Ule,
1186        }
1187    }
1188
1189    /// Whether this reads its operands as signed. Equality reads them as neither.
1190    #[must_use]
1191    pub const fn is_signed(self) -> bool {
1192        matches!(self, Self::Slt | Self::Sle | Self::Sgt | Self::Sge)
1193    }
1194}
1195
1196impl fmt::Display for IntPred {
1197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1198        f.write_str(self.name())
1199    }
1200}
1201
1202/// The floating point comparisons, ordered and unordered.
1203///
1204/// An ordered predicate is false if either operand is a NaN, and an unordered one is true. C's
1205/// `<` is `olt` and C's `!=` is `une`, which is the whole of why both families are here.
1206#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1207pub enum FloatPred {
1208    /// Always false.
1209    False,
1210    /// Ordered and equal.
1211    Oeq,
1212    /// Ordered and greater than.
1213    Ogt,
1214    /// Ordered and greater than or equal.
1215    Oge,
1216    /// Ordered and less than.
1217    Olt,
1218    /// Ordered and less than or equal.
1219    Ole,
1220    /// Ordered and not equal.
1221    One,
1222    /// Ordered, which is to say neither operand is a NaN.
1223    Ord,
1224    /// Unordered, which is to say one of them is.
1225    Uno,
1226    /// Unordered or equal.
1227    Ueq,
1228    /// Unordered or greater than.
1229    Ugt,
1230    /// Unordered or greater than or equal.
1231    Uge,
1232    /// Unordered or less than.
1233    Ult,
1234    /// Unordered or less than or equal.
1235    Ule,
1236    /// Unordered or not equal.
1237    Une,
1238    /// Always true.
1239    True,
1240}
1241
1242impl FloatPred {
1243    /// The textual form.
1244    #[must_use]
1245    pub const fn name(self) -> &'static str {
1246        match self {
1247            Self::False => "false",
1248            Self::Oeq => "oeq",
1249            Self::Ogt => "ogt",
1250            Self::Oge => "oge",
1251            Self::Olt => "olt",
1252            Self::Ole => "ole",
1253            Self::One => "one",
1254            Self::Ord => "ord",
1255            Self::Uno => "uno",
1256            Self::Ueq => "ueq",
1257            Self::Ugt => "ugt",
1258            Self::Uge => "uge",
1259            Self::Ult => "ult",
1260            Self::Ule => "ule",
1261            Self::Une => "une",
1262            Self::True => "true",
1263        }
1264    }
1265
1266    /// The predicate with that name, if there is one.
1267    #[must_use]
1268    pub fn from_name(name: &str) -> Option<Self> {
1269        Self::all().find(|pred| pred.name() == name)
1270    }
1271
1272    /// Every predicate.
1273    pub fn all() -> impl Iterator<Item = Self> {
1274        [
1275            Self::False,
1276            Self::Oeq,
1277            Self::Ogt,
1278            Self::Oge,
1279            Self::Olt,
1280            Self::Ole,
1281            Self::One,
1282            Self::Ord,
1283            Self::Uno,
1284            Self::Ueq,
1285            Self::Ugt,
1286            Self::Uge,
1287            Self::Ult,
1288            Self::Ule,
1289            Self::Une,
1290            Self::True,
1291        ]
1292        .into_iter()
1293    }
1294
1295    /// The predicate that holds exactly when this one does not.
1296    #[must_use]
1297    pub const fn inverse(self) -> Self {
1298        match self {
1299            Self::False => Self::True,
1300            Self::Oeq => Self::Une,
1301            Self::Ogt => Self::Ule,
1302            Self::Oge => Self::Ult,
1303            Self::Olt => Self::Uge,
1304            Self::Ole => Self::Ugt,
1305            Self::One => Self::Ueq,
1306            Self::Ord => Self::Uno,
1307            Self::Uno => Self::Ord,
1308            Self::Ueq => Self::One,
1309            Self::Ugt => Self::Ole,
1310            Self::Uge => Self::Olt,
1311            Self::Ult => Self::Oge,
1312            Self::Ule => Self::Ogt,
1313            Self::Une => Self::Oeq,
1314            Self::True => Self::False,
1315        }
1316    }
1317
1318    /// The predicate that holds when the operands are given the other way round.
1319    #[must_use]
1320    pub const fn swapped(self) -> Self {
1321        match self {
1322            Self::Ogt => Self::Olt,
1323            Self::Olt => Self::Ogt,
1324            Self::Oge => Self::Ole,
1325            Self::Ole => Self::Oge,
1326            Self::Ugt => Self::Ult,
1327            Self::Ult => Self::Ugt,
1328            Self::Uge => Self::Ule,
1329            Self::Ule => Self::Uge,
1330            same => same,
1331        }
1332    }
1333
1334    /// Whether this is false when either operand is a NaN.
1335    ///
1336    /// [`FloatPred::False`] and [`FloatPred::True`] are neither ordered nor unordered, since
1337    /// they do not look at their operands at all, and both answer no here.
1338    #[must_use]
1339    pub const fn is_ordered(self) -> bool {
1340        matches!(
1341            self,
1342            Self::Oeq | Self::Ogt | Self::Oge | Self::Olt | Self::Ole | Self::One | Self::Ord
1343        )
1344    }
1345}
1346
1347impl fmt::Display for FloatPred {
1348    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1349        f.write_str(self.name())
1350    }
1351}
1352
1353#[cfg(test)]
1354mod tests {
1355    use super::*;
1356
1357    #[test]
1358    fn every_opcode_is_in_the_table() {
1359        // `InlineAsm` is the last variant, so its discriminant plus one is how many there are.
1360        // A new opcode declared after it moves this number, and a new opcode declared before
1361        // it and not added to `ALL` moves the length, so either mistake fails here.
1362        assert_eq!(ALL.len(), Opcode::InlineAsm as usize + 1);
1363        for (position, &op) in ALL.iter().enumerate() {
1364            assert_eq!(op as usize, position, "{op} is out of order in ALL");
1365        }
1366    }
1367
1368    #[test]
1369    fn every_opcode_name_is_one_word_the_reader_can_take() {
1370        // The textual form keeps the dot for the type suffix and the flags, so an opcode with a
1371        // dot in it reads back as a shorter opcode with a suffix that is not a type. The safety
1372        // instructions are spelled `cap_of` and not `cap.of` for this reason, and the
1373        // specification says so at `spec/safe-memory/06-instrumentation.md` section 6.2.2.
1374        for opcode in Opcode::all() {
1375            let name = opcode.name();
1376            assert!(!name.is_empty(), "an opcode with no name");
1377            assert!(
1378                name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'),
1379                "{name} is not one word"
1380            );
1381        }
1382    }
1383
1384    #[test]
1385    fn every_opcode_has_its_own_name_and_finds_it_again() {
1386        let mut names: Vec<&str> = Opcode::all().map(Opcode::name).collect();
1387        let total = names.len();
1388        names.sort_unstable();
1389        names.dedup();
1390        assert_eq!(names.len(), total, "two opcodes share a name");
1391        for op in Opcode::all() {
1392            assert_eq!(Opcode::from_name(op.name()), Some(op));
1393        }
1394        assert_eq!(Opcode::from_name("phi"), None);
1395        assert_eq!(Opcode::from_name("getelementptr"), None);
1396        assert_eq!(Opcode::from_name(""), None);
1397    }
1398
1399    #[test]
1400    fn the_terminators_are_the_ones_control_leaves_by() {
1401        let terminators: Vec<&str> =
1402            Opcode::all().filter(|op| op.is_terminator()).map(Opcode::name).collect();
1403        assert_eq!(
1404            terminators,
1405            ["jump", "br_if", "switch", "indirect_br", "return", "unreachable", "tail_call"]
1406        );
1407    }
1408
1409    #[test]
1410    fn a_terminator_produces_nothing() {
1411        for op in Opcode::all().filter(|op| op.is_terminator()) {
1412            assert_eq!(op.results(), Some(0), "{op}");
1413        }
1414    }
1415
1416    #[test]
1417    fn the_pair_producing_opcodes_are_the_ones_with_a_flag_beside_the_value() {
1418        let pairs: Vec<&str> =
1419            Opcode::all().filter(|op| op.results() == Some(2)).map(Opcode::name).collect();
1420        assert_eq!(
1421            pairs,
1422            [
1423                "cmpxchg",
1424                "sadd_overflow",
1425                "uadd_overflow",
1426                "ssub_overflow",
1427                "usub_overflow",
1428                "smul_overflow",
1429                "umul_overflow"
1430            ]
1431        );
1432    }
1433
1434    #[test]
1435    fn the_capability_instructions_are_the_ones_that_make_a_capability() {
1436        let makers: Vec<Opcode> = Opcode::all().filter(|op| op.makes_capability()).collect();
1437        assert_eq!(
1438            makers,
1439            vec![
1440                Opcode::CapOf,
1441                Opcode::CapLoad,
1442                Opcode::CapNull,
1443                Opcode::CapNarrow,
1444                Opcode::CapRecover
1445            ]
1446        );
1447        // The other three read a capability rather than making one. `cap_store` writes it out and
1448        // produces nothing at all, and the two extent queries answer with a number.
1449        assert!(!Opcode::CapStore.makes_capability());
1450        assert_eq!(Opcode::CapStore.results(), Some(0));
1451        assert!(!Opcode::CapExtent.makes_capability());
1452        assert_eq!(Opcode::CapExtent.results(), Some(1));
1453        assert!(!Opcode::CapExtentBack.makes_capability());
1454        assert_eq!(Opcode::CapExtentBack.results(), Some(1));
1455        for opcode in makers {
1456            assert_eq!(opcode.results(), Some(1), "{}", opcode.name());
1457        }
1458    }
1459
1460    #[test]
1461    fn a_check_reads_the_planes_and_writes_nothing() {
1462        let checks = [
1463            Opcode::CheckBounds,
1464            Opcode::CheckLive,
1465            Opcode::CheckType,
1466            Opcode::CheckInit,
1467            Opcode::CheckDeriv,
1468            Opcode::CheckRace,
1469        ];
1470        for opcode in checks {
1471            let name = opcode.name();
1472            // It traps, so it stays where it was put and nothing deletes it for having no
1473            // result. It reads a plane, so it takes a memory operand. It writes nothing, so
1474            // the access after it reads the version the check was given.
1475            assert!(opcode.has_effects(), "{name}");
1476            assert!(opcode.touches_memory(), "{name}");
1477            assert!(!opcode.writes_memory(), "{name}");
1478            assert_eq!(opcode.results(), Some(0), "{name}");
1479        }
1480    }
1481
1482    #[test]
1483    fn a_restrict_check_writes_memory_because_it_records_what_it_saw() {
1484        // The one place the sentence above does not hold. Every other check reads a plane and
1485        // leaves it alone, so the optimizer may hoist one out of a loop or keep the later of two
1486        // identical ones. These record the range they were asked about into the block's own slot,
1487        // so a check that ran twice saw two accesses and a check that was hoisted saw one, and
1488        // either rewrite changes what the next one answers. Saying they write memory is how the
1489        // memory chain refuses both.
1490        let recording = [
1491            Opcode::CheckRestrictRead,
1492            Opcode::CheckRestrictWrite,
1493            Opcode::RestrictEnter,
1494            Opcode::RestrictLeave,
1495        ];
1496        for opcode in recording {
1497            let name = opcode.name();
1498            assert!(opcode.has_effects(), "{name}");
1499            assert!(opcode.touches_memory(), "{name}");
1500            assert!(opcode.writes_memory(), "{name}");
1501            assert_eq!(opcode.results(), Some(0), "{name}");
1502        }
1503    }
1504
1505    #[test]
1506    fn the_capability_instructions_that_touch_memory_are_the_five_that_have_to() {
1507        // `cap_load` and `cap_store` are an access to the slot beside a pointer, and `cap_recover`
1508        // and the two extent queries read the planes. The other three are arithmetic on a
1509        // provenance the program already had, so the optimizer may treat them as it treats
1510        // `ptr_add`.
1511        assert!(!Opcode::CapOf.has_effects());
1512        assert!(!Opcode::CapNull.has_effects());
1513        assert!(!Opcode::CapNarrow.has_effects());
1514        assert!(Opcode::CapLoad.touches_memory() && !Opcode::CapLoad.writes_memory());
1515        assert!(Opcode::CapRecover.touches_memory() && !Opcode::CapRecover.writes_memory());
1516        assert!(Opcode::CapExtent.touches_memory() && !Opcode::CapExtent.writes_memory());
1517        assert!(Opcode::CapExtentBack.touches_memory() && !Opcode::CapExtentBack.writes_memory());
1518        assert!(Opcode::CapStore.writes_memory());
1519    }
1520
1521    #[test]
1522    fn memory_has_effects_and_arithmetic_does_not() {
1523        for op in [Opcode::Load, Opcode::Store, Opcode::Call, Opcode::Alloca, Opcode::Fence] {
1524            assert!(op.has_effects(), "{op}");
1525        }
1526        for op in [Opcode::Add, Opcode::FDiv, Opcode::ICmp, Opcode::PtrAdd, Opcode::IConst] {
1527            assert!(!op.has_effects(), "{op}");
1528        }
1529    }
1530
1531    #[test]
1532    fn commuting_is_only_claimed_where_it_holds() {
1533        assert!(Opcode::Add.is_commutative());
1534        assert!(Opcode::FAdd.is_commutative());
1535        assert!(!Opcode::Sub.is_commutative());
1536        assert!(!Opcode::FDiv.is_commutative());
1537        assert!(!Opcode::Shl.is_commutative());
1538    }
1539
1540    #[test]
1541    fn an_integer_predicate_inverts_and_swaps_back_to_itself() {
1542        for pred in IntPred::all() {
1543            assert_eq!(pred.inverse().inverse(), pred);
1544            assert_eq!(pred.swapped().swapped(), pred);
1545            assert_eq!(IntPred::from_name(pred.name()), Some(pred));
1546        }
1547        assert_eq!(IntPred::Slt.inverse(), IntPred::Sge);
1548        assert_eq!(IntPred::Slt.swapped(), IntPred::Sgt);
1549        assert_eq!(IntPred::from_name("lt"), None);
1550    }
1551
1552    #[test]
1553    fn a_floating_predicate_inverts_across_the_ordered_line() {
1554        for pred in FloatPred::all() {
1555            assert_eq!(pred.inverse().inverse(), pred);
1556            assert_eq!(pred.swapped().swapped(), pred);
1557            assert_eq!(FloatPred::from_name(pred.name()), Some(pred));
1558        }
1559        // Inverting has to cross the line, because the negation of an ordered comparison is
1560        // true when an operand is a NaN. This is where `!(a < b)` stops being `a >= b`. The
1561        // two constants are outside it: neither of them looks at its operands.
1562        for pred in FloatPred::all().filter(|p| !matches!(p, FloatPred::False | FloatPred::True)) {
1563            assert_ne!(pred.is_ordered(), pred.inverse().is_ordered(), "{pred}");
1564        }
1565        assert_eq!(FloatPred::Olt.inverse(), FloatPred::Uge);
1566        assert_eq!(FloatPred::Olt.swapped(), FloatPred::Ogt);
1567    }
1568
1569    #[test]
1570    fn swapping_a_predicate_keeps_it_ordered_or_unordered() {
1571        for pred in FloatPred::all() {
1572            assert_eq!(pred.is_ordered(), pred.swapped().is_ordered(), "{pred}");
1573        }
1574        for pred in IntPred::all() {
1575            assert_eq!(pred.is_signed(), pred.swapped().is_signed(), "{pred}");
1576        }
1577    }
1578
1579    #[test]
1580    fn no_two_predicates_share_a_name_within_their_family() {
1581        for names in [
1582            IntPred::all().map(IntPred::name).collect::<Vec<_>>(),
1583            FloatPred::all().map(FloatPred::name).collect::<Vec<_>>(),
1584        ] {
1585            let total = names.len();
1586            let mut names = names;
1587            names.sort_unstable();
1588            names.dedup();
1589            assert_eq!(names.len(), total);
1590        }
1591    }
1592}