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 between addresses that do not overlap, of the payload's size or of a third operand.
153 Memcpy,
154 /// A copy between addresses that may overlap, of the payload's size or of a third operand.
155 Memmove,
156 /// A fill with one byte, of the payload's size or of a third operand.
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 ///
174 /// One operand, the pointer, and one capability out. This is the general question and the other
175 /// producers are all the special cases of it that have a cheap answer, which is why it is the
176 /// one that always works and the one to reach for last. A pointer whose provenance the compiler
177 /// still holds should have got its capability from wherever that provenance came from: from the
178 /// allocation site, from the aux slot beside it in memory, from the frame its caller wrote, or
179 /// from the derivation that narrowed it. One of these is what is left when none of those did.
180 ///
181 /// So it has two lowerings and which one it gets is not a property of the instruction. A pointer
182 /// the lowering can trace back to an allocation site gets the cheap answer, which is a subtract
183 /// and a load off the header the allocator wrote. Anything else gets the plane walk, which is
184 /// the expensive answer and the only one that is always available, and comes back marked as
185 /// recovered so the summary counts it as the weakening it is.
186 ///
187 /// An interior pointer is always the second of those, and that is the answer to the question
188 /// document 05 section 5.2.3 leaves open rather than a gap in it. The header is behind the
189 /// payload so that finding it is a subtract by a constant, which is true of a pointer to the
190 /// base of an object and false of a pointer to the middle of one, and the lowering asks for the
191 /// base by construction rather than by checking.
192 CapOf,
193 /// The capability in the auxiliary slot beside a stored pointer, read back.
194 ///
195 /// A pointer written to memory and read again has to bring its capability with it, and where
196 /// the capability lives is document 05's question rather than this one's. What this says is
197 /// that a capability comes back from an address.
198 ///
199 /// Three operands: the capability of the object the word is in, the address of the word, and
200 /// the pointer that was loaded from it. The first is what says where the slot is, since the
201 /// aux is in front of the object and the arithmetic is over the object's own base and extent,
202 /// and the third is what the slot's two numbers are relative to. Both of those are facts about
203 /// the representation document 05 section 5.2.2 chose, and an instrumented load has both
204 /// values in hand already, since the capability is the one its bounds check used and the
205 /// pointer is what the load produced.
206 CapLoad,
207 /// The other half of [`Opcode::CapLoad`], writing one into the slot beside a pointer.
208 ///
209 /// Four operands: the capability of the object the word is in, the address of the word, the
210 /// pointer being stored there, and that pointer's capability. The first three are the same
211 /// three [`Opcode::CapLoad`] takes and for the same reasons, and the fourth is what is being
212 /// written down.
213 CapStore,
214 /// The slots beside a run of copied words, carried over from the run they were copied from.
215 ///
216 /// Three operands, for the reason [`Opcode::MetaTypeCopy`] has three: the destination, the
217 /// source, and how many bytes moved. A copy of a structure moves whatever pointers are in it
218 /// and the capability of each of those lives in the slot beside it, so a copy that moved the
219 /// bytes and left the slots alone would leave every pointer in the destination described by
220 /// whatever was there before, which is nothing at best and another instance's answer at worst.
221 ///
222 /// No capability operand, for the reason the other two copies name no node. What each
223 /// destination slot ends up saying is whatever the slot beside the word it came from said, and
224 /// the only place that is written down is the aux over the source.
225 CapCopy,
226 /// The capability that permits nothing, which is what a null pointer has.
227 CapNull,
228 /// A capability narrowed to a sub-object of what it covered.
229 ///
230 /// Only under `-fsafety-subobject`. Narrowing is what catches an overflow from one member of
231 /// a struct into the next, and it is separate because C code that walks off the end of a
232 /// member on purpose exists and a project has to be able to say so.
233 CapNarrow,
234 /// The capability for an address that arrived from outside, recovered from the planes.
235 CapRecover,
236 /// How many bytes from an address on the capability covers, asking for no more than a limit.
237 ///
238 /// Three operands, the capability, the address and how many bytes the asker wants, and one
239 /// integer result that is never more than that limit. It is what
240 /// `spec/safe-memory/07-check-elimination.md` section 7.4 needs to split a loop: the checked
241 /// part and the unchecked part are divided at `min(n, extent / sizeof(T))`, and the extent is
242 /// the half of that a compiler cannot work out on its own.
243 ///
244 /// The limit is an operand because under milestone S1 answering means walking the lifetime
245 /// plane, and a walk that stops at the number of bytes the loop was going to read anyway is
246 /// bounded by the work the loop is already doing. An answer smaller than the truth costs
247 /// iterations in the checked half and is never wrong, which is what makes stopping early
248 /// allowed. Once a capability carries its own bounds, which is milestone S2, this is a
249 /// subtraction on the capability and the limit is one `min`.
250 CapExtent,
251 /// How many bytes below an address on the capability covers, asking for no more than a limit.
252 ///
253 /// The mirror of [`Opcode::CapExtent`], with the same three operands and the same kind of
254 /// answer. What it counts is the bytes ending at the address rather than the bytes starting
255 /// there, so an answer of `n` says that `[addr - n, addr)` belongs to one thing. The address
256 /// itself is one past what is asked about, which is what a walk from high to low needs: the
257 /// question is about where the walk ends up, and where it ends up is below where it began.
258 ///
259 /// The ownership asked about is the byte below the address rather than the byte at it, since
260 /// the address may be one past the end of the object and the object is what the question is
261 /// about. Everything else, the limit operand and why an answer short of the truth is allowed,
262 /// is [`Opcode::CapExtent`]'s.
263 CapExtentBack,
264 /// The capabilities of a call's pointer arguments, handed over beside the arguments.
265 ///
266 /// Document 05 section 5.3 is the whole of why this is an instruction of its own rather than
267 /// more operands on the call. An instrumented function's calling convention is unchanged, so a
268 /// pointer argument goes in the register it always went in and `sizeof(void *)` is still eight,
269 /// which is what lets an object this compiler built link against one nobody instrumented. The
270 /// capability therefore travels out of band, in a small per thread frame the caller writes and
271 /// the callee reads, indexed by argument position.
272 ///
273 /// One operand per pointer argument, in the order the call passes them, and no operand for the
274 /// arguments that are not pointers. A call handing over more pointers than the frame has room
275 /// for describes the ones that fit and the callee recovers the rest, which is a weakening the
276 /// summary counts rather than a refusal. How many fit is the runtime's number and
277 /// `rucc_safety::frame` is where the compiler keeps it, so nothing here is a bound on the
278 /// operand count.
279 ///
280 /// It goes immediately in front of the call it is about, which is how the two are tied
281 /// together, the same way [`Opcode::MetaRelease`] is tied to the atomic it goes in front of.
282 CapPublish,
283 /// There is no frame for this call, which is what a callee that might not be instrumented gets.
284 ///
285 /// The other half of [`Opcode::CapPublish`] and not the absence of one. Publishing to a callee
286 /// that never reads the frame leaves it in place for whatever that callee calls back into, and
287 /// a callback entered from uninstrumented code holding somebody else's capabilities is worse
288 /// than one entered holding none. So a call the compiler cannot say reads frames says there is
289 /// nothing rather than saying nothing at all, and document 10 section 10.8's callback recovers
290 /// its arguments the way an entry from outside always does.
291 CapClear,
292 /// The capability of a pointer parameter, out of the frame the caller published.
293 ///
294 /// The reading end of [`Opcode::CapPublish`], in the callee rather than in the caller. Two
295 /// operands, the parameter itself and which position it is in the call, and one capability out.
296 ///
297 /// The parameter is an operand because it is the answer when there is no frame. A function
298 /// entered from code this build never compiled finds nothing published, and so does one whose
299 /// caller could not vouch for it and said `cap_clear`, and in both cases the capability has to be
300 /// worked out from the pointer the way [`Opcode::CapRecover`] does. That is the expensive answer
301 /// the frame exists to avoid, it is available whatever the caller did, and it is counted as the
302 /// weakening it is.
303 ///
304 /// The position is an operand rather than a payload for the same reason [`Opcode::CapNarrow`]'s
305 /// offset and length are: it is a number the runtime is handed. A position the frame does not
306 /// reach is not an error either, since it is the recovery again, so nothing here has to know how
307 /// many capabilities a frame holds.
308 CapArg,
309 /// The capability of the pointer this function is returning, left where its caller reads.
310 ///
311 /// One operand, the capability, and it goes immediately in front of the `ret` it is about, which
312 /// is the tie [`Opcode::CapPublish`] has with its call. A function that returns from several
313 /// places has one of these in front of each of them, because what is being said is about the
314 /// value leaving by that particular one.
315 ///
316 /// This is the only thing in the design that writes into a frame somebody else made. It is
317 /// allowed to because the frame is the caller's stack and the caller is waiting for this
318 /// function to return, and it is needed because a returned pointer is the one value that crosses
319 /// a call in the other direction.
320 CapYield,
321 /// The capability of the pointer a call gave back, out of the frame the call was published with.
322 ///
323 /// The reading end of [`Opcode::CapYield`], in the caller. One operand, the pointer that came
324 /// back, and one capability out. The operand is there for the reason [`Opcode::CapArg`]'s is: a
325 /// callee that wrote nothing leaves the bottom capability where the caller put it, and the
326 /// bottom one is the signal to work the answer out from the pointer instead.
327 ///
328 /// It goes immediately after the call it is about, and that call has to be one a `cap_publish`
329 /// goes in front of. A call that says there is no frame has no frame for a callee to have
330 /// written into, so there would be nothing for this to read.
331 CapResult,
332 /// An access is within its capability's bounds, aligned, and permitted.
333 ///
334 /// The size and the alignment are the access's, and they are in the memory payload rather
335 /// than in operands because they are what the front end knew and not what the program
336 /// computed.
337 ///
338 /// A third operand overrides how many bytes are asked about, and it exists for the one check
339 /// the front end did not write. `spec/safe-memory/07-check-elimination.md` section 7.4 replaces
340 /// the checks in a loop that runs `n` times with one check over `n * sizeof(T)` bytes, and that
341 /// is a length the program computes rather than one anybody knew when the access was parsed. The
342 /// payload still holds the alignment and the type information of the access the check came from,
343 /// and its size becomes the size of one of them rather than the size of the question.
344 CheckBounds,
345 /// The capability's provenance is still live.
346 CheckLive,
347 /// The access agrees with the type plane, which is the effective type rule of C 6.5.
348 ///
349 /// A third operand overrides how many bytes are asked about, as on [`Opcode::CheckBounds`] and
350 /// for the same reason. Agreeing with a type is a property of a range that holds of every
351 /// subrange of it, so one check over a loop's whole walk says what the loop's checks were going
352 /// to say, which is `spec/safe-memory/07-check-elimination.md` section 7.4's transformation
353 /// applied to this plane rather than to the bounds. The plane entry stays in the payload, since
354 /// the checks a hoisted one stands for all asked at the same type or it would not have been
355 /// written.
356 CheckType,
357 /// The bytes the access reads have been written.
358 ///
359 /// A third operand overrides how many bytes are asked about, as on [`Opcode::CheckType`].
360 CheckInit,
361 /// A pointer derived from another stays inside the capability the first one had.
362 ///
363 /// Three operands, because the answer is about the new pointer and the question is about
364 /// the old one's capability.
365 CheckDeriv,
366 /// The metadata this access is about to consult has not been changed under it.
367 ///
368 /// Judgement J9, which document 09 section 9.5 specifies and which document 04 section 4.5
369 /// keeps out of J1 for the reason the `restrict` checks are kept out: it is a statement about
370 /// two operations rather than about one. The payload holds the size of the access, because the
371 /// question is whether any granule of the range this touches carries a write by another thread.
372 CheckRace,
373 /// This read did not reach a byte another `restrict` pointer of the same block wrote.
374 ///
375 /// Judgement J8, which document 09 section 9.6 specifies and which document 04 section 4.6
376 /// keeps out of J1 because it is a statement about a pair of accesses rather than about one.
377 /// The payload holds the size of the access and the two numbers saying which pointer it went
378 /// through, and those are the same two [`crate::Restrict`] carries on the access itself.
379 ///
380 /// Read and write are two opcodes rather than one with a flag on it, because every bit of
381 /// [`crate::Flags`] is spoken for and because the operand would then be a constant the program
382 /// does not compute, which is the thing [`Opcode::CheckBounds`] says belongs in the payload.
383 CheckRestrictRead,
384 /// The same about a write, which is the half of the pair that makes the other half a violation.
385 ///
386 /// Two accesses that both only read are not a violation of anything, so what the scope records
387 /// is which of them wrote and the check refuses a pair only when at least one did.
388 CheckRestrictWrite,
389 /// The capability this free goes through still names the instance that owns the address.
390 ///
391 /// Judgement J6, and the same two operands [`Opcode::CheckLive`] has for the same reason: a
392 /// capability and the pointer it is about, with no payload, because how many bytes are at the
393 /// address is not something a free asks. What separates it from the lifetime check is where it
394 /// goes and what it is about. This one sits in front of a call that ends a storage instance
395 /// rather than in front of an access, and the question it decides is whether the pointer being
396 /// handed over still names the instance it was made for.
397 ///
398 /// It exists because that question has no other way of being asked. `free` takes an address and
399 /// nothing else, so a second free of a block the allocator has already handed back out looks
400 /// like an ordinary free to the allocator and releases somebody else's live object.
401 /// tamnd/rucc#492 is that, and the version the capability carries is what tells the two apart.
402 ///
403 /// Nothing discharges one. A bounds fact says nothing about it and a lifetime fact about an
404 /// access says nothing about a free, so it stays where the pass put it and the cost is one
405 /// check per free rather than one per access.
406 CheckFree,
407 /// A storage instance begins here, over a range, with a class.
408 ///
409 /// Judgement J4. This is the `alloca` for an automatic instance and the allocator's report
410 /// for an allocated one, and the range is a pointer and a length in registers rather than a
411 /// payload, because the length of a variable length array is not known when the instruction
412 /// is written down.
413 MetaBegin,
414 /// A storage instance ends here, which is judgement J5.
415 ///
416 /// Every capability for it fails from this point on and keeps failing after the address is
417 /// handed out again, which is what makes the check a use after free check rather than a use
418 /// after reallocation one.
419 MetaEnd,
420 /// The effective type of a range is now this one.
421 MetaType,
422 /// The effective types of a range are now the ones the range it was copied from had.
423 ///
424 /// Three operands, because a copy has two ranges and one length: the destination, the source,
425 /// and how many bytes moved. A `memcpy` does not store through a type, so there is no type to
426 /// name here and naming one would be wrong: C 6.5 says the copied bytes keep the effective type
427 /// they had, whatever that was, and the only place that is written down is the plane over the
428 /// source.
429 MetaTypeCopy,
430 /// The bytes of a range are now initialized.
431 MetaInit,
432 /// The bytes of a range are now initialized wherever the range they were copied from was.
433 ///
434 /// Three operands, for the reason [`Opcode::MetaTypeCopy`] has three. A copy does not write
435 /// values of its own, so whether a destination byte holds anything is whether the byte it came
436 /// from did, and the only place that is written down is the plane over the source. That is what
437 /// makes a structure filled member by member and then copied whole still have padding nothing
438 /// wrote, which is the infoleak the plane is for.
439 MetaInitCopy,
440 /// This thread wrote a range, at whatever step of its own counting it has reached.
441 ///
442 /// The epoch plane's only write, from `spec/safe-memory/09-type-init-and-races.md` section 9.5.
443 /// Two operands like the other plane writes, and the range is a pointer shaped slot rather than
444 /// whatever the access covered: the plane holds one stamp per eight bytes because that is what
445 /// a pointer comes in, and a granule two threads share is one holding no pointer.
446 ///
447 /// It carries no thread and no count. Which thread is running and how far it has counted are
448 /// both facts about the moment the program reaches this, so the runtime reads them and nothing
449 /// here could name them.
450 MetaEpoch,
451 /// Everything this thread has done so far is published at the atomic object named here.
452 ///
453 /// One half of a synchronization edge in the sense of section 9.5, and the half that goes in
454 /// front of the atomic that carries it. The operand is the object's address, because that is
455 /// the key whoever takes the other end will look the clock up under, and there is no payload:
456 /// which thread is publishing and how far it has counted are facts about the moment the program
457 /// reaches this, the same way they are for [`Opcode::MetaEpoch`].
458 ///
459 /// This exists because an atomic is not a call. Every other edge the monitor knows about is a
460 /// `pthread` function and is interposed, and a C11 release store is a machine instruction with
461 /// nothing to interpose, so the compiler is the only thing that can say the edge was there.
462 MetaRelease,
463 /// Everything published at the atomic object named here is now ordered before this thread.
464 ///
465 /// The other half of [`Opcode::MetaRelease`], and it goes after the atomic rather than in front
466 /// of it, because the ordering it takes is the ordering the atomic just read.
467 ///
468 /// A missing edge is the one kind of missing instrumentation in the whole safety pass that
469 /// costs a false report rather than a missed one: two threads that really were ordered by an
470 /// edge nobody recorded look concurrent, and a race is reported against a program doing nothing
471 /// wrong. That is why the edges go in before the race check is ever on by default.
472 MetaAcquire,
473 /// Everything this thread has done so far is published at no object in particular.
474 ///
475 /// What a release fence is, and the reason it cannot reuse [`Opcode::MetaRelease`]: a fence
476 /// orders against every other thread rather than against one object, so there is no address to
477 /// key it on and it takes no operands at all. The relaxed atomic that usually sits beside it in
478 /// the source is not the key either, because the fence orders everything, not that one word.
479 ///
480 /// The runtime pays for that with one cell shared by every fence in the program, which orders
481 /// more pairs of threads than the program really ordered. That direction is safe. A thread put
482 /// further ahead than it needed to be reports fewer races, never a wrong one.
483 MetaFenceRelease,
484 /// Everything published at any release fence is now ordered before this thread.
485 ///
486 /// The other half of [`Opcode::MetaFenceRelease`], after the fence rather than in front of it,
487 /// for the same reason [`Opcode::MetaAcquire`] goes after its atomic.
488 MetaFenceAcquire,
489 /// A range leaves the monitor's authority, or comes back, which is judgement J7.
490 MetaTransfer,
491 /// A declared exemption starts here, with the reason it was declared.
492 ///
493 /// Not an optimization hint. Everything between this and its `safe_region_end` is code the
494 /// monitor is told not to judge, so the reason it carries is a trust set entry, and
495 /// `spec/safe-memory/10-boundaries.md` section 10.2 counts them per build precisely so that
496 /// a reviewer can read what a binary's guarantee rests on.
497 SafeRegionBegin,
498 /// The end of the region the last `safe_region_begin` opened.
499 SafeRegionEnd,
500 /// A block that declares `restrict` pointers begins here, over a slot to keep its record in.
501 ///
502 /// The operand is the storage the record lives in, which is the block's own stack slot, and the
503 /// payload says how large it is. The clique the block was given is [`crate::Restrict::clique`]
504 /// of the payload and how many pointers it declares is [`crate::Restrict::base`], which is the
505 /// one place that field counts bases rather than naming one.
506 ///
507 /// A marker rather than something the front end could fold into the accesses, because the
508 /// promise is about the block's dynamic extent: a function called twice has made the promise
509 /// twice, and what the second call reached says nothing about the first.
510 RestrictEnter,
511 /// The block the last `restrict_enter` opened ends here.
512 ///
513 /// The operand is the same slot, so that the record can be unlinked from whatever encloses it
514 /// without the runtime having to keep a list of its own.
515 RestrictLeave,
516
517 // Control. Every one of these is a terminator.
518 /// An unconditional branch, `jump block1(%a, %b)`.
519 Jump,
520 /// A two-way branch on an `i1`.
521 BrIf,
522 /// A multi-way branch on an integer, with a default.
523 Switch,
524 /// A branch to an address, `indirect_br %0, block1, block2`.
525 ///
526 /// The targets are every block control can arrive at, which is what makes the edges of a
527 /// computed `goto` ordinary edges: nothing else in the compiler has to know that the
528 /// address decides which one it is. A target that is not listed is a branch that does not
529 /// happen, so a frontend that leaves one out has made a promise on the program's behalf.
530 IndirectBr,
531 /// A return, with the values the signature says.
532 Return,
533 /// A place control cannot reach, which the frontend emits after a `noreturn` call.
534 Unreachable,
535
536 // Calls.
537 /// A call to a named function.
538 Call,
539 /// A call through an address, carrying the signature it is called with.
540 CallIndirect,
541 /// A call in tail position that reuses the frame, which is a terminator.
542 TailCall,
543
544 // Intrinsics, which is the closed part. The open part is `TargetIntrinsic`.
545 /// Count leading zeroes.
546 Ctlz,
547 /// Count trailing zeroes.
548 Cttz,
549 /// Count set bits.
550 Ctpop,
551 /// Reverse the bytes.
552 Bswap,
553 /// Reverse the bits.
554 Bitreverse,
555 /// Signed addition, producing the result and whether it overflowed.
556 SAddOverflow,
557 /// Unsigned addition, producing the result and whether it overflowed.
558 UAddOverflow,
559 /// Signed subtraction, producing the result and whether it overflowed.
560 SSubOverflow,
561 /// Unsigned subtraction, producing the result and whether it overflowed.
562 USubOverflow,
563 /// Signed multiplication, producing the result and whether it overflowed.
564 SMulOverflow,
565 /// Unsigned multiplication, producing the result and whether it overflowed.
566 UMulOverflow,
567 /// `__builtin_expect`, which is the value with a hint attached.
568 Expect,
569 /// `__builtin_unreachable` as a hint on a path, distinct from the terminator.
570 UnreachableHint,
571 /// `__builtin_trap`, which stops the program where it stands.
572 ///
573 /// Not a terminator, for the reason `unreachable_hint` is not one: what ends a block here is
574 /// control going somewhere, and this goes nowhere at all. The block it is in goes on being
575 /// lowered and whatever follows it is written and never run, which costs a few bytes nothing
576 /// reaches and keeps every pass that walks a block from needing a second shape for it.
577 Trap,
578 /// `__builtin_prefetch`.
579 Prefetch,
580 /// `__builtin_frame_address`.
581 FrameAddress,
582 /// `__builtin_return_address`.
583 ReturnAddress,
584 /// `__builtin_thread_pointer`, the address of the storage the running thread has.
585 ///
586 /// It takes nothing and answers a pointer. Unlike the two above it there is no walk to do and
587 /// no frame to have kept: the machine holds the address in a place of its own, so this is one
588 /// instruction on every target that has the builtin at all.
589 ThreadPointer,
590 /// `__builtin_object_size` where the front end could not see the object, which is how many
591 /// bytes there are from the address to the end of whatever it points into.
592 ///
593 /// One operand, the address, and the question as a number from zero to three beside it: the
594 /// low bit asks about the closest member rather than the whole object and the high bit asks
595 /// for the smallest answer rather than the largest. It never reaches the back end:
596 /// `rucc_opt::objsize` answers every one before any other pass runs, from the allocations and
597 /// the arithmetic the address was built out of, and says it does not know where it cannot
598 /// see, which is the largest number there is for the first two questions and zero for the
599 /// other two.
600 ObjectSize,
601 /// What is in a machine register, for `register long x asm ("rbx");`.
602 ///
603 /// The GNU extension that puts an object in a named register rather than in the frame. The
604 /// name of the register is the payload and the result is whatever that register holds where
605 /// this stands, which is the value the object starts with. A garbage collector written in C
606 /// reads the callee saved registers this way, because a root that is only in one of those is
607 /// a root no walk of the stack finds.
608 ///
609 /// It is not pure. Two of these on the same register in one function are two different
610 /// answers, since anything in between may have written the register, so neither may be moved
611 /// to where the other is and neither may be dropped for the other.
612 RegisterValue,
613 /// The start of a variable argument list.
614 VaStart,
615 /// One argument off a variable argument list, which moves the list on as it reads it. Two
616 /// of these on one list are two arguments and never one argument read twice, so whatever
617 /// decides which instructions may be folded together has to leave these alone.
618 VaArg,
619 /// One argument off a variable argument list, when that argument is an object rather than a
620 /// value, which is what a `struct` or a `union` read out of one is.
621 ///
622 /// It answers the address of the object rather than the object, because an aggregate is not
623 /// a value and there is nothing for one result to be. Where the object arrives in registers
624 /// there is no address until something makes one, so what this asks of a target is a place
625 /// to put the registers and the address of that place, which is the copy every psABI's own
626 /// description of the algorithm makes. It moves the list on for the reason [`Opcode::VaArg`]
627 /// does.
628 VaObject,
629 /// The end of a variable argument list.
630 VaEnd,
631 /// A copy of a variable argument list.
632 VaCopy,
633 /// The stack pointer, saved before a variable length array.
634 StackSave,
635 /// The stack pointer, restored after one.
636 StackRestore,
637 /// The marker a `setjmp` leaves, which pins everything live across it.
638 ///
639 /// One operand, the buffer, and one result, which is the `int` the save answers with: zero
640 /// where control went past it and one where control came back to it. That is the one
641 /// instruction here whose value depends on how control reached it, and it is one instruction
642 /// rather than a branch and a block because the edge a `longjmp` travels is not in this
643 /// function's control flow graph. It is written into the buffer and taken at run time, so a
644 /// pass that walked the edges would find a block nothing reaches and take it away.
645 SetjmpMarker,
646 /// The marker a `longjmp` leaves.
647 ///
648 /// One operand, the buffer, and no result, and not a terminator either, for the reason above:
649 /// where control goes is not a block of this function. What follows it is written and never
650 /// reached.
651 LongjmpMarker,
652 /// A target-specific intrinsic, named rather than enumerated, for the vector builtins.
653 TargetIntrinsic,
654
655 /// Inline assembly. A terminator when it has labels, which is `asm goto`.
656 InlineAsm,
657}
658
659impl Opcode {
660 /// The textual form, which is also what the parser reads.
661 #[must_use]
662 pub const fn name(self) -> &'static str {
663 match self {
664 Self::IConst => "iconst",
665 Self::FConst => "fconst",
666 Self::Splat => "splat",
667 Self::GlobalAddr => "global_addr",
668 Self::BlockAddr => "block_addr",
669 Self::Add => "add",
670 Self::Sub => "sub",
671 Self::Mul => "mul",
672 Self::SDiv => "sdiv",
673 Self::UDiv => "udiv",
674 Self::SRem => "srem",
675 Self::URem => "urem",
676 Self::And => "and",
677 Self::Or => "or",
678 Self::Xor => "xor",
679 Self::Shl => "shl",
680 Self::LShr => "lshr",
681 Self::AShr => "ashr",
682 Self::FAdd => "fadd",
683 Self::FSub => "fsub",
684 Self::FMul => "fmul",
685 Self::FDiv => "fdiv",
686 Self::FRem => "frem",
687 Self::FNeg => "fneg",
688 Self::Fma => "fma",
689 Self::ICmp => "icmp",
690 Self::FCmp => "fcmp",
691 Self::Select => "select",
692 Self::Trunc => "trunc",
693 Self::SExt => "sext",
694 Self::ZExt => "zext",
695 Self::FPTrunc => "fptrunc",
696 Self::FPExt => "fpext",
697 Self::FPToSI => "fptosi",
698 Self::FPToUI => "fptoui",
699 Self::SIToFP => "sitofp",
700 Self::UIToFP => "uitofp",
701 Self::PtrToInt => "ptrtoint",
702 Self::IntToPtr => "inttoptr",
703 Self::Bitcast => "bitcast",
704 Self::MemEntry => "mem_entry",
705 Self::Alloca => "alloca",
706 Self::Load => "load",
707 Self::Store => "store",
708 Self::PtrAdd => "ptr_add",
709 Self::Memcpy => "memcpy",
710 Self::Memmove => "memmove",
711 Self::Memset => "memset",
712 Self::AtomicLoad => "atomic_load",
713 Self::AtomicStore => "atomic_store",
714 Self::AtomicRmw => "atomic_rmw",
715 Self::Cmpxchg => "cmpxchg",
716 Self::Fence => "fence",
717 Self::CapOf => "cap_of",
718 Self::CapLoad => "cap_load",
719 Self::CapStore => "cap_store",
720 Self::CapCopy => "cap_copy",
721 Self::CapNull => "cap_null",
722 Self::CapNarrow => "cap_narrow",
723 Self::CapRecover => "cap_recover",
724 Self::CapExtent => "cap_extent",
725 Self::CapExtentBack => "cap_extent_back",
726 Self::CapPublish => "cap_publish",
727 Self::CapClear => "cap_clear",
728 Self::CapArg => "cap_arg",
729 Self::CapYield => "cap_yield",
730 Self::CapResult => "cap_result",
731 Self::CheckBounds => "check_bounds",
732 Self::CheckLive => "check_live",
733 Self::CheckType => "check_type",
734 Self::CheckInit => "check_init",
735 Self::CheckDeriv => "check_deriv",
736 Self::CheckRace => "check_race",
737 Self::CheckRestrictRead => "check_restrict_read",
738 Self::CheckRestrictWrite => "check_restrict_write",
739 Self::CheckFree => "check_free",
740 Self::MetaBegin => "meta_begin",
741 Self::MetaEnd => "meta_end",
742 Self::MetaType => "meta_type",
743 Self::MetaTypeCopy => "meta_type_copy",
744 Self::MetaInit => "meta_init",
745 Self::MetaInitCopy => "meta_init_copy",
746 Self::MetaEpoch => "meta_epoch",
747 Self::MetaRelease => "meta_release",
748 Self::MetaAcquire => "meta_acquire",
749 Self::MetaFenceRelease => "meta_fence_release",
750 Self::MetaFenceAcquire => "meta_fence_acquire",
751 Self::MetaTransfer => "meta_transfer",
752 Self::SafeRegionBegin => "safe_region_begin",
753 Self::SafeRegionEnd => "safe_region_end",
754 Self::RestrictEnter => "restrict_enter",
755 Self::RestrictLeave => "restrict_leave",
756 Self::Jump => "jump",
757 Self::BrIf => "br_if",
758 Self::Switch => "switch",
759 Self::IndirectBr => "indirect_br",
760 Self::Return => "return",
761 Self::Unreachable => "unreachable",
762 Self::Call => "call",
763 Self::CallIndirect => "call_indirect",
764 Self::TailCall => "tail_call",
765 Self::Ctlz => "ctlz",
766 Self::Cttz => "cttz",
767 Self::Ctpop => "ctpop",
768 Self::Bswap => "bswap",
769 Self::Bitreverse => "bitreverse",
770 Self::SAddOverflow => "sadd_overflow",
771 Self::UAddOverflow => "uadd_overflow",
772 Self::SSubOverflow => "ssub_overflow",
773 Self::USubOverflow => "usub_overflow",
774 Self::SMulOverflow => "smul_overflow",
775 Self::UMulOverflow => "umul_overflow",
776 Self::Expect => "expect",
777 Self::UnreachableHint => "unreachable_hint",
778 Self::Trap => "trap",
779 Self::Prefetch => "prefetch",
780 Self::FrameAddress => "frame_address",
781 Self::ReturnAddress => "return_address",
782 Self::ThreadPointer => "thread_pointer",
783 Self::ObjectSize => "object_size",
784 Self::RegisterValue => "register_value",
785 Self::VaStart => "va_start",
786 Self::VaArg => "va_arg",
787 Self::VaObject => "va_object",
788 Self::VaEnd => "va_end",
789 Self::VaCopy => "va_copy",
790 Self::StackSave => "stacksave",
791 Self::StackRestore => "stackrestore",
792 Self::SetjmpMarker => "setjmp_marker",
793 Self::LongjmpMarker => "longjmp_marker",
794 Self::TargetIntrinsic => "target_intrinsic",
795 Self::InlineAsm => "inline_asm",
796 }
797 }
798
799 /// Every opcode, in the order they are declared.
800 ///
801 /// The parser walks this rather than holding a second table, because a second table is a
802 /// table that can disagree with the first one.
803 pub fn all() -> impl Iterator<Item = Self> {
804 ALL.iter().copied()
805 }
806
807 /// The opcode with that name, if there is one.
808 #[must_use]
809 pub fn from_name(name: &str) -> Option<Self> {
810 ALL.iter().copied().find(|op| op.name() == name)
811 }
812
813 /// Whether this ends a block.
814 ///
815 /// [`Opcode::InlineAsm`] is not here and is the one instruction whose answer depends on
816 /// the instruction rather than on the opcode: `asm goto` has successors and everything
817 /// else does not. Ask the instruction, not the opcode.
818 #[must_use]
819 pub const fn is_terminator(self) -> bool {
820 matches!(
821 self,
822 Self::Jump
823 | Self::BrIf
824 | Self::Switch
825 | Self::IndirectBr
826 | Self::Return
827 | Self::Unreachable
828 | Self::TailCall
829 )
830 }
831
832 /// Whether the operands can be swapped without changing the result.
833 ///
834 /// The floating point cases are commutative even under the strictest rounding, because
835 /// swapping the operands of an addition does not change which of them is a NaN, and the
836 /// sign of a NaN result is not something we promise anything about either way.
837 #[must_use]
838 pub const fn is_commutative(self) -> bool {
839 matches!(
840 self,
841 Self::Add
842 | Self::Mul
843 | Self::And
844 | Self::Or
845 | Self::Xor
846 | Self::FAdd
847 | Self::FMul
848 | Self::SAddOverflow
849 | Self::UAddOverflow
850 | Self::SMulOverflow
851 | Self::UMulOverflow
852 )
853 }
854
855 /// Whether this reads or writes memory, or has an effect the optimizer has to preserve.
856 ///
857 /// An instruction that answers no can be deleted when nothing uses its result, moved
858 /// across a call, and merged with another one computing the same thing. Everything else
859 /// has to be argued about individually, so the conservative answer is the true one here
860 /// and the list of exceptions is the part that is checked.
861 #[must_use]
862 pub const fn has_effects(self) -> bool {
863 !matches!(
864 self,
865 Self::IConst
866 | Self::FConst
867 | Self::Splat
868 | Self::GlobalAddr
869 | Self::BlockAddr
870 | Self::Add
871 | Self::Sub
872 | Self::Mul
873 | Self::SDiv
874 | Self::UDiv
875 | Self::SRem
876 | Self::URem
877 | Self::And
878 | Self::Or
879 | Self::Xor
880 | Self::Shl
881 | Self::LShr
882 | Self::AShr
883 | Self::FAdd
884 | Self::FSub
885 | Self::FMul
886 | Self::FDiv
887 | Self::FRem
888 | Self::FNeg
889 | Self::Fma
890 | Self::ICmp
891 | Self::FCmp
892 | Self::Select
893 | Self::Trunc
894 | Self::SExt
895 | Self::ZExt
896 | Self::FPTrunc
897 | Self::FPExt
898 | Self::FPToSI
899 | Self::FPToUI
900 | Self::SIToFP
901 | Self::UIToFP
902 | Self::PtrToInt
903 | Self::IntToPtr
904 | Self::Bitcast
905 | Self::PtrAdd
906 | Self::Ctlz
907 | Self::Cttz
908 | Self::Ctpop
909 | Self::Bswap
910 | Self::Bitreverse
911 | Self::SAddOverflow
912 | Self::UAddOverflow
913 | Self::SSubOverflow
914 | Self::USubOverflow
915 | Self::SMulOverflow
916 | Self::UMulOverflow
917 | Self::Expect
918 | Self::FrameAddress
919 | Self::ReturnAddress
920 // The same address for as long as the thread runs, and a thread cannot change
921 // which one it is part way through a function, so two of these in one function
922 // are the same value and either may be moved to where the other is.
923 | Self::ThreadPointer
924 // A question about an address that reads nothing: the answer is a fact about where
925 // the address came from, which is the same fact wherever the question is asked.
926 | Self::ObjectSize
927 | Self::MemEntry
928 // Three of the capability instructions are arithmetic on a pointer's
929 // provenance and touch nothing. The other four do: `cap_load`, `cap_store` and
930 // `cap_copy` are an access, and `cap_recover` reads the planes.
931 | Self::CapOf
932 | Self::CapNull
933 | Self::CapNarrow
934 )
935 }
936
937 /// Whether an instruction with this opcode touches memory.
938 ///
939 /// This is what decides whether it takes a memory operand once memory SSA is built, per
940 /// document 09 of `spec/optimizer`. It is written as the exceptions to touching memory
941 /// rather than as a list of what does, for the reason document 08.6 gives about the escape
942 /// analysis: an opcode added later has to end up on the conservative side by default, and a
943 /// list of what touches memory would silently leave a new one out.
944 ///
945 /// `mem_entry` answers no. It produces memory rather than touching it, which is the whole
946 /// of what it is for.
947 #[must_use]
948 pub const fn touches_memory(self) -> bool {
949 if !self.has_effects() {
950 return false;
951 }
952 !matches!(
953 self,
954 // Fresh storage nothing could have been reading, and the pointer that names it.
955 Self::Alloca
956 // The stack pointer, which is a register and not memory. Putting it back is a
957 // different matter and is below, because it takes storage away.
958 | Self::StackSave
959 // Control, which goes somewhere rather than touching anything. A tail call is
960 // not here, because it is a call.
961 | Self::Jump
962 | Self::BrIf
963 | Self::Switch
964 | Self::IndirectBr
965 | Self::Return
966 | Self::Unreachable
967 | Self::UnreachableHint
968 )
969 }
970
971 /// Whether an instruction with this opcode writes memory, and so produces a new version of
972 /// it rather than only reading the version it was given.
973 ///
974 /// Everything that touches memory writes it except the ones that plainly do not. A `fence`
975 /// writes nothing and is still a write here, because document 09.5 says an atomic or a
976 /// barrier is a definition nothing walks past, and giving it one is how that is expressed
977 /// in a representation whose only ordering is the memory chain.
978 ///
979 /// The checks read the planes and change nothing, which
980 /// `spec/safe-memory/06-instrumentation.md` section 6.2.4 states as the word `readonly`. A
981 /// check that trapped is a program that stopped and there is no version of memory after it
982 /// for anything to observe, so the trap costs nothing here. What it does cost is that a
983 /// check may not be moved across a plane write, and that is the memory chain saying so
984 /// rather than this.
985 #[must_use]
986 pub const fn writes_memory(self) -> bool {
987 self.touches_memory()
988 && !matches!(
989 self,
990 Self::Load
991 | Self::AtomicLoad
992 | Self::Prefetch
993 | Self::CapLoad
994 | Self::CapRecover
995 | Self::CapArg
996 | Self::CapResult
997 | Self::CapExtent
998 | Self::CapExtentBack
999 | Self::CheckBounds
1000 | Self::CheckLive
1001 | Self::CheckType
1002 | Self::CheckInit
1003 | Self::CheckDeriv
1004 | Self::CheckRace
1005 | Self::CheckFree
1006 )
1007 }
1008
1009 /// Whether the only memory this touches is the safety planes.
1010 ///
1011 /// The planes are storage the runtime keeps for itself, one entry per range of program bytes,
1012 /// laid out by `spec/safe-memory/05-representation.md` section 5.2. What matters here is that
1013 /// no name in the program reaches one. A plane write and a program store can never be the same
1014 /// byte, and neither can a plane read and a program load, so an alias oracle that knows this
1015 /// answers no to every pair with one of each.
1016 ///
1017 /// The aux plane sits in the same allocation as the object rather than in a map of its own, so
1018 /// an address far enough outside an object does land in somebody's plane. That is an access
1019 /// outside the bounds of the thing it was derived from, which is the access every check in this
1020 /// list exists to refuse, and it is undefined before it is refused. An optimizer is entitled to
1021 /// the assumption that the program does not make one, and this is that assumption and not a
1022 /// second one.
1023 ///
1024 /// Nothing above can work that out by looking at the access, which is why this is here. The
1025 /// address operand of one of these is a locator and not the memory it touches: `meta_init %p`
1026 /// writes the entry the plane keeps for `%p` and does not write `%p`, so an oracle reading the
1027 /// operand the ordinary way sees a write to exactly the bytes a load of `%p` wants.
1028 ///
1029 /// A list of what does rather than the exceptions to it, which is the other way round from
1030 /// [`Opcode::touches_memory`] and for the same reason: an opcode added later and left out of
1031 /// this one is an opcode the oracle says nothing about, which costs a missed optimization,
1032 /// and an opcode added later that lands in here without anybody reading what it does would be
1033 /// a wrong answer about memory in the safety pass of all places.
1034 ///
1035 /// Two families are deliberately not here even though their names look like they belong. The
1036 /// `restrict` markers take the block's own stack slot as an operand and write their record into
1037 /// it. The synchronization edges say something about the ordering of program memory rather than
1038 /// only about a plane, and a wrong answer there is a false report rather than a missed one.
1039 ///
1040 /// The capability instructions are mostly out and not all of them, so the line between them is
1041 /// worth saying plainly: it is whether every pointer the instruction takes is a locator.
1042 /// `cap_load`, `cap_store` and `cap_recover` each have one that is not, because the point of
1043 /// the aux pair is that a pointer written into a slot comes back out of one, so an address
1044 /// handed to any of those has gone somewhere a later instruction can get it from. `cap_copy`
1045 /// has no such operand. Its three are a destination, a source and a length, it writes nothing
1046 /// but the slots over the destination and reads nothing but the slots over the source, and a
1047 /// slot holds a displacement from the pointer beside it rather than an address, so a run of
1048 /// slots that ends up saying what another run said has moved no address anywhere the copy of
1049 /// the words themselves did not move it already.
1050 #[must_use]
1051 pub const fn touches_only_planes(self) -> bool {
1052 matches!(
1053 self,
1054 Self::CheckBounds
1055 | Self::CheckLive
1056 | Self::CheckType
1057 | Self::CheckInit
1058 | Self::CheckDeriv
1059 | Self::CheckRace
1060 | Self::CheckFree
1061 | Self::CapExtent
1062 | Self::CapExtentBack
1063 | Self::CapCopy
1064 | Self::MetaBegin
1065 | Self::MetaEnd
1066 | Self::MetaType
1067 | Self::MetaTypeCopy
1068 | Self::MetaInit
1069 | Self::MetaInitCopy
1070 | Self::MetaEpoch
1071 | Self::MetaTransfer
1072 )
1073 }
1074
1075 /// Whether this marks one end of a jump along an edge this function's control flow graph does
1076 /// not have.
1077 ///
1078 /// The two `setjmp` markers and nothing else. It exists because an alias oracle that reasons
1079 /// about a call reasons from what the call was handed, and neither of these was handed
1080 /// anything. Control arrives at the instruction after a `setjmp_marker` from wherever the
1081 /// matching `longjmp` sits, so the memory there is a join of the chain that flows into the
1082 /// marker and the memory at every one of those points, and a `longjmp_marker` is the other end
1083 /// of that join and so reads everything the landing will look at. An object whose address never
1084 /// left this function is as exposed to both as anything else, because the jump comes back into
1085 /// this frame and the program reads the frame's own slots afterwards. The only answer about a
1086 /// reference across one of these that cannot be wrong is that it may be touched.
1087 #[must_use]
1088 pub const fn is_jump_marker(self) -> bool {
1089 matches!(self, Self::SetjmpMarker | Self::LongjmpMarker)
1090 }
1091
1092 /// How many values this produces, for the opcodes where the count is fixed.
1093 ///
1094 /// `None` means the count comes from somewhere else: a call takes it from its signature,
1095 /// and inline assembly takes it from its output constraints. A tail call is not one of
1096 /// them, because whatever it returns goes straight out of the function and there is no
1097 /// instruction after it to use anything.
1098 #[must_use]
1099 pub const fn results(self) -> Option<u8> {
1100 match self {
1101 Self::Call | Self::CallIndirect | Self::InlineAsm => None,
1102 Self::Cmpxchg
1103 | Self::SAddOverflow
1104 | Self::UAddOverflow
1105 | Self::SSubOverflow
1106 | Self::USubOverflow
1107 | Self::SMulOverflow
1108 | Self::UMulOverflow => Some(2),
1109 Self::Store
1110 | Self::Memcpy
1111 | Self::Memmove
1112 | Self::Memset
1113 | Self::AtomicStore
1114 | Self::Fence
1115 | Self::Prefetch
1116 | Self::VaStart
1117 | Self::VaEnd
1118 | Self::VaCopy
1119 | Self::StackRestore
1120 | Self::UnreachableHint
1121 | Self::Trap
1122 | Self::LongjmpMarker
1123 | Self::CapStore
1124 | Self::CapCopy
1125 | Self::CapPublish
1126 | Self::CapClear
1127 | Self::CapYield
1128 | Self::CheckBounds
1129 | Self::CheckLive
1130 | Self::CheckType
1131 | Self::CheckInit
1132 | Self::CheckDeriv
1133 | Self::CheckRace
1134 | Self::CheckRestrictRead
1135 | Self::CheckRestrictWrite
1136 | Self::CheckFree
1137 | Self::MetaBegin
1138 | Self::MetaEnd
1139 | Self::MetaType
1140 | Self::MetaTypeCopy
1141 | Self::MetaInit
1142 | Self::MetaInitCopy
1143 | Self::MetaEpoch
1144 | Self::MetaRelease
1145 | Self::MetaAcquire
1146 | Self::MetaFenceRelease
1147 | Self::MetaFenceAcquire
1148 | Self::MetaTransfer
1149 | Self::SafeRegionBegin
1150 | Self::SafeRegionEnd
1151 | Self::RestrictEnter
1152 | Self::RestrictLeave => Some(0),
1153 _ if self.is_terminator() => Some(0),
1154 _ => Some(1),
1155 }
1156 }
1157
1158 /// Whether an instruction with this opcode produces a capability.
1159 ///
1160 /// Seven of the fourteen `cap` instructions. The other seven consume one instead, or none at
1161 /// all: `cap_store` writes one beside a pointer, `cap_copy` moves a run of them from beside one
1162 /// set of words to beside another, `cap_extent` and `cap_extent_back` ask one a
1163 /// question about itself and answer with a number, `cap_publish` hands a call's worth of them
1164 /// to a callee, `cap_yield` leaves one where the caller of this function will look for it, and
1165 /// `cap_clear` takes no operands because saying there is no frame is not a statement about any
1166 /// capability. The reason this is a question about the opcode rather than
1167 /// about the result type is that the verifier asks it the other way round: it walks the results
1168 /// looking for a `cap` and needs to know whether the instruction under it was entitled to make
1169 /// one.
1170 #[must_use]
1171 pub const fn makes_capability(self) -> bool {
1172 matches!(
1173 self,
1174 Self::CapOf
1175 | Self::CapLoad
1176 | Self::CapNull
1177 | Self::CapNarrow
1178 | Self::CapRecover
1179 | Self::CapArg
1180 | Self::CapResult
1181 )
1182 }
1183
1184 /// Which operand of a capability producer names the pointer the capability is about.
1185 ///
1186 /// Five of the seven [`Opcode::makes_capability`] lists, and they all mean the same thing by it:
1187 /// the capability describes the object that pointer is in. Where they differ is only in how the
1188 /// answer was arrived at, which is a walk of the lifetime plane for `cap_recover`, a read of the
1189 /// slot beside the word for `cap_load`, a read of the caller's frame for `cap_arg`, a read of
1190 /// the frame the caller published for `cap_result`, and whatever the back end has at hand for
1191 /// `cap_of`.
1192 ///
1193 /// That is worth stating as one question because the optimizer asks it. A rule that discharges a
1194 /// check by knowing which pointer the check's capability is about has no business caring which
1195 /// producer supplied it, and while `cap_of` was the only one anything emitted, asking for the
1196 /// opcode by name and taking operand zero was the same question. It stopped being the same
1197 /// question when tamnd/rucc#1241 started emitting the cheap producers, and a rule that still
1198 /// asked by name would quietly discharge less the better the code got.
1199 ///
1200 /// The two that answer nothing are the two that are not about a pointer at all. A `cap_narrow`
1201 /// is about another capability and a `cap_null` is about nothing by construction.
1202 ///
1203 /// `cap_result` was in that group and did not belong there. The reasoning was that it is about a
1204 /// pointer the callee returned, which sounds like a value this function has only as the call's
1205 /// own result, and the opcode carries that pointer as operand zero for the same reason
1206 /// `cap_arg` carries one: a callee that wrote nothing leaves the bottom capability in the slot,
1207 /// and the pointer is what the runtime falls back to working the answer out from. So the
1208 /// operand was there the whole time and this said there was none. It is the same mistake the
1209 /// paragraph above is about, made once more in the place that exists to stop it, which is
1210 /// exactly how much care this question wants: every producer that names a pointer has to be
1211 /// here, and the way to tell is to read the opcode's operands rather than its purpose.
1212 #[must_use]
1213 pub const fn capability_names(self) -> Option<usize> {
1214 match self {
1215 Self::CapOf | Self::CapRecover | Self::CapArg | Self::CapResult => Some(0),
1216 // The third, because the first two are the container's capability and the address of
1217 // the word, and the pointer this one is about is the value that came out of the word.
1218 Self::CapLoad => Some(2),
1219 _ => None,
1220 }
1221 }
1222
1223 /// Which payload an instruction with this opcode carries.
1224 ///
1225 /// The printer reads the payload it finds and does not need this. The parser has only the
1226 /// opcode when it reaches the operands, so this is where the two of them agree on what
1227 /// comes after them. An instruction carrying a payload of some other kind prints as text
1228 /// the parser cannot read back, which is why the verifier checks it against
1229 /// [`Extra::kind`](crate::Extra::kind) rather than leaving it to be found later.
1230 #[must_use]
1231 pub const fn extra_kind(self) -> ExtraKind {
1232 match self {
1233 Self::IConst | Self::FConst | Self::Splat => ExtraKind::Imm,
1234 Self::GlobalAddr | Self::TargetIntrinsic | Self::RegisterValue => ExtraKind::Symbol,
1235 Self::ICmp => ExtraKind::IntPred,
1236 Self::FCmp => ExtraKind::FloatPred,
1237 Self::Alloca
1238 | Self::Load
1239 | Self::Store
1240 | Self::Memcpy
1241 | Self::Memmove
1242 | Self::Memset
1243 | Self::AtomicLoad
1244 | Self::AtomicStore
1245 | Self::Cmpxchg
1246 // Four of the checks are about a run of bytes and the payload is where the size
1247 // of that run is, along with the alignment `check_bounds` wants and the aliasing
1248 // node `check_type` compares against. The other two ask a question about a
1249 // pointer and not about a range, so they carry nothing.
1250 | Self::CheckBounds
1251 | Self::CheckType
1252 | Self::CheckInit
1253 | Self::CheckRace
1254 // The two `restrict` checks and the marker that opens their scope. The first two carry
1255 // the size of the access and the two numbers saying which pointer it went through, and
1256 // the third carries the size of the slot and the numbers describing the scope itself.
1257 | Self::CheckRestrictRead
1258 | Self::CheckRestrictWrite
1259 | Self::RestrictEnter => ExtraKind::Mem,
1260 // The plane writes. What each one needs beyond the range is different, and the range
1261 // itself is operands, since the length of a variable length array is a value.
1262 Self::MetaBegin => ExtraKind::Class,
1263 Self::MetaTransfer => ExtraKind::Owner,
1264 Self::MetaType => ExtraKind::Node,
1265 Self::SafeRegionBegin => ExtraKind::Reason,
1266 Self::VaObject => ExtraKind::VaObject,
1267 Self::AtomicRmw => ExtraKind::Rmw,
1268 Self::Fence => ExtraKind::Order,
1269 Self::Prefetch => ExtraKind::Prefetch,
1270 Self::ObjectSize => ExtraKind::Question,
1271 // How far up the chain of frames to walk, which is a number written in the instruction
1272 // and never a value. The builtins these came from take a constant and nothing else, for
1273 // the reason `prefetch` takes one: the instructions this becomes are a walk of that
1274 // length, and a length not known until the program runs has nothing to walk.
1275 Self::FrameAddress | Self::ReturnAddress => ExtraKind::Depth,
1276 Self::Jump | Self::BrIf | Self::BlockAddr | Self::IndirectBr => ExtraKind::Targets,
1277 Self::Switch => ExtraKind::Switch,
1278 Self::Call | Self::CallIndirect | Self::TailCall => ExtraKind::Call,
1279 Self::InlineAsm => ExtraKind::Asm,
1280 _ => ExtraKind::None,
1281 }
1282 }
1283}
1284
1285/// Which of [`Extra`](crate::Extra)'s shapes an instruction carries.
1286///
1287/// The same list of names, without any of the payloads, so that a question about an opcode can
1288/// be answered without an instruction to look at.
1289#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1290pub enum ExtraKind {
1291 /// Nothing.
1292 None,
1293 /// A constant.
1294 Imm,
1295 /// A name.
1296 Symbol,
1297 /// An integer comparison predicate.
1298 IntPred,
1299 /// A floating point comparison predicate.
1300 FloatPred,
1301 /// An access.
1302 Mem,
1303 /// An atomic read-modify-write.
1304 Rmw,
1305 /// A barrier's ordering.
1306 Order,
1307 /// What a prefetch is a hint about.
1308 Prefetch,
1309 /// How many frames up to walk.
1310 Depth,
1311 /// Which of the four object size questions.
1312 Question,
1313 /// Branch targets.
1314 Targets,
1315 /// A call.
1316 Call,
1317 /// A `switch`.
1318 Switch,
1319 /// Inline assembly.
1320 Asm,
1321 /// An object read off a variable argument list.
1322 VaObject,
1323 /// What kind of storage an instance is.
1324 Class,
1325 /// Who a range of memory went to.
1326 Owner,
1327 /// A metadata node.
1328 Node,
1329 /// Why a declared exemption is there.
1330 Reason,
1331}
1332
1333impl ExtraKind {
1334 /// What it is, in words, for a message that names two of them and has to read as English.
1335 #[must_use]
1336 pub const fn name(self) -> &'static str {
1337 match self {
1338 Self::None => "nothing",
1339 Self::Imm => "a constant",
1340 Self::Symbol => "a name",
1341 Self::IntPred => "an integer comparison",
1342 Self::FloatPred => "a floating point comparison",
1343 Self::Mem => "an access",
1344 Self::Rmw => "a read-modify-write",
1345 Self::Order => "an ordering",
1346 Self::Prefetch => "a prefetch hint",
1347 Self::Depth => "a depth",
1348 Self::Question => "an object size question",
1349 Self::Targets => "branch targets",
1350 Self::Call => "a call",
1351 Self::Switch => "a switch",
1352 Self::Asm => "inline assembly",
1353 Self::VaObject => "an object off a variable argument list",
1354 Self::Class => "a storage class",
1355 Self::Owner => "an owner",
1356 Self::Node => "a metadata node",
1357 Self::Reason => "a reason",
1358 }
1359 }
1360}
1361
1362impl fmt::Display for Opcode {
1363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1364 f.write_str(self.name())
1365 }
1366}
1367
1368/// Every opcode, which is what [`Opcode::all`] hands out.
1369///
1370/// This is written out rather than derived, and the test below is what keeps it complete: it
1371/// checks the count against [`Opcode::InlineAsm`], the last variant, so a new opcode that is
1372/// not added here fails the build rather than going quietly missing from the parser.
1373static ALL: &[Opcode] = &[
1374 Opcode::IConst,
1375 Opcode::FConst,
1376 Opcode::Splat,
1377 Opcode::GlobalAddr,
1378 Opcode::BlockAddr,
1379 Opcode::Add,
1380 Opcode::Sub,
1381 Opcode::Mul,
1382 Opcode::SDiv,
1383 Opcode::UDiv,
1384 Opcode::SRem,
1385 Opcode::URem,
1386 Opcode::And,
1387 Opcode::Or,
1388 Opcode::Xor,
1389 Opcode::Shl,
1390 Opcode::LShr,
1391 Opcode::AShr,
1392 Opcode::FAdd,
1393 Opcode::FSub,
1394 Opcode::FMul,
1395 Opcode::FDiv,
1396 Opcode::FRem,
1397 Opcode::FNeg,
1398 Opcode::Fma,
1399 Opcode::ICmp,
1400 Opcode::FCmp,
1401 Opcode::Select,
1402 Opcode::Trunc,
1403 Opcode::SExt,
1404 Opcode::ZExt,
1405 Opcode::FPTrunc,
1406 Opcode::FPExt,
1407 Opcode::FPToSI,
1408 Opcode::FPToUI,
1409 Opcode::SIToFP,
1410 Opcode::UIToFP,
1411 Opcode::PtrToInt,
1412 Opcode::IntToPtr,
1413 Opcode::Bitcast,
1414 Opcode::MemEntry,
1415 Opcode::Alloca,
1416 Opcode::Load,
1417 Opcode::Store,
1418 Opcode::PtrAdd,
1419 Opcode::Memcpy,
1420 Opcode::Memmove,
1421 Opcode::Memset,
1422 Opcode::AtomicLoad,
1423 Opcode::AtomicStore,
1424 Opcode::AtomicRmw,
1425 Opcode::Cmpxchg,
1426 Opcode::Fence,
1427 Opcode::CapOf,
1428 Opcode::CapLoad,
1429 Opcode::CapStore,
1430 Opcode::CapCopy,
1431 Opcode::CapNull,
1432 Opcode::CapNarrow,
1433 Opcode::CapRecover,
1434 Opcode::CapExtent,
1435 Opcode::CapExtentBack,
1436 Opcode::CapPublish,
1437 Opcode::CapClear,
1438 Opcode::CapArg,
1439 Opcode::CapYield,
1440 Opcode::CapResult,
1441 Opcode::CheckBounds,
1442 Opcode::CheckLive,
1443 Opcode::CheckType,
1444 Opcode::CheckInit,
1445 Opcode::CheckDeriv,
1446 Opcode::CheckRace,
1447 Opcode::CheckRestrictRead,
1448 Opcode::CheckRestrictWrite,
1449 Opcode::CheckFree,
1450 Opcode::MetaBegin,
1451 Opcode::MetaEnd,
1452 Opcode::MetaType,
1453 Opcode::MetaTypeCopy,
1454 Opcode::MetaInit,
1455 Opcode::MetaInitCopy,
1456 Opcode::MetaEpoch,
1457 Opcode::MetaRelease,
1458 Opcode::MetaAcquire,
1459 Opcode::MetaFenceRelease,
1460 Opcode::MetaFenceAcquire,
1461 Opcode::MetaTransfer,
1462 Opcode::SafeRegionBegin,
1463 Opcode::SafeRegionEnd,
1464 Opcode::RestrictEnter,
1465 Opcode::RestrictLeave,
1466 Opcode::Jump,
1467 Opcode::BrIf,
1468 Opcode::Switch,
1469 Opcode::IndirectBr,
1470 Opcode::Return,
1471 Opcode::Unreachable,
1472 Opcode::Call,
1473 Opcode::CallIndirect,
1474 Opcode::TailCall,
1475 Opcode::Ctlz,
1476 Opcode::Cttz,
1477 Opcode::Ctpop,
1478 Opcode::Bswap,
1479 Opcode::Bitreverse,
1480 Opcode::SAddOverflow,
1481 Opcode::UAddOverflow,
1482 Opcode::SSubOverflow,
1483 Opcode::USubOverflow,
1484 Opcode::SMulOverflow,
1485 Opcode::UMulOverflow,
1486 Opcode::Expect,
1487 Opcode::UnreachableHint,
1488 Opcode::Trap,
1489 Opcode::Prefetch,
1490 Opcode::FrameAddress,
1491 Opcode::ReturnAddress,
1492 Opcode::ThreadPointer,
1493 Opcode::ObjectSize,
1494 Opcode::RegisterValue,
1495 Opcode::VaStart,
1496 Opcode::VaArg,
1497 Opcode::VaObject,
1498 Opcode::VaEnd,
1499 Opcode::VaCopy,
1500 Opcode::StackSave,
1501 Opcode::StackRestore,
1502 Opcode::SetjmpMarker,
1503 Opcode::LongjmpMarker,
1504 Opcode::TargetIntrinsic,
1505 Opcode::InlineAsm,
1506];
1507
1508/// The ten integer comparisons.
1509///
1510/// Signedness is on the predicate rather than on the type, for the same reason it is on
1511/// `sdiv` and `udiv`: the type space is halved and the operation says what it means.
1512#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1513pub enum IntPred {
1514 /// Equal.
1515 Eq,
1516 /// Not equal.
1517 Ne,
1518 /// Signed less than.
1519 Slt,
1520 /// Signed less than or equal.
1521 Sle,
1522 /// Signed greater than.
1523 Sgt,
1524 /// Signed greater than or equal.
1525 Sge,
1526 /// Unsigned less than.
1527 Ult,
1528 /// Unsigned less than or equal.
1529 Ule,
1530 /// Unsigned greater than.
1531 Ugt,
1532 /// Unsigned greater than or equal.
1533 Uge,
1534}
1535
1536impl IntPred {
1537 /// The textual form.
1538 #[must_use]
1539 pub const fn name(self) -> &'static str {
1540 match self {
1541 Self::Eq => "eq",
1542 Self::Ne => "ne",
1543 Self::Slt => "slt",
1544 Self::Sle => "sle",
1545 Self::Sgt => "sgt",
1546 Self::Sge => "sge",
1547 Self::Ult => "ult",
1548 Self::Ule => "ule",
1549 Self::Ugt => "ugt",
1550 Self::Uge => "uge",
1551 }
1552 }
1553
1554 /// The predicate with that name, if there is one.
1555 #[must_use]
1556 pub fn from_name(name: &str) -> Option<Self> {
1557 Self::all().find(|pred| pred.name() == name)
1558 }
1559
1560 /// Every predicate.
1561 pub fn all() -> impl Iterator<Item = Self> {
1562 [
1563 Self::Eq,
1564 Self::Ne,
1565 Self::Slt,
1566 Self::Sle,
1567 Self::Sgt,
1568 Self::Sge,
1569 Self::Ult,
1570 Self::Ule,
1571 Self::Ugt,
1572 Self::Uge,
1573 ]
1574 .into_iter()
1575 }
1576
1577 /// The predicate that holds exactly when this one does not.
1578 #[must_use]
1579 pub const fn inverse(self) -> Self {
1580 match self {
1581 Self::Eq => Self::Ne,
1582 Self::Ne => Self::Eq,
1583 Self::Slt => Self::Sge,
1584 Self::Sge => Self::Slt,
1585 Self::Sle => Self::Sgt,
1586 Self::Sgt => Self::Sle,
1587 Self::Ult => Self::Uge,
1588 Self::Uge => Self::Ult,
1589 Self::Ule => Self::Ugt,
1590 Self::Ugt => Self::Ule,
1591 }
1592 }
1593
1594 /// The predicate that holds when the operands are given the other way round.
1595 #[must_use]
1596 pub const fn swapped(self) -> Self {
1597 match self {
1598 Self::Eq => Self::Eq,
1599 Self::Ne => Self::Ne,
1600 Self::Slt => Self::Sgt,
1601 Self::Sgt => Self::Slt,
1602 Self::Sle => Self::Sge,
1603 Self::Sge => Self::Sle,
1604 Self::Ult => Self::Ugt,
1605 Self::Ugt => Self::Ult,
1606 Self::Ule => Self::Uge,
1607 Self::Uge => Self::Ule,
1608 }
1609 }
1610
1611 /// Whether this reads its operands as signed. Equality reads them as neither.
1612 #[must_use]
1613 pub const fn is_signed(self) -> bool {
1614 matches!(self, Self::Slt | Self::Sle | Self::Sgt | Self::Sge)
1615 }
1616
1617 /// The predicate that asks the same question with the bits read as unsigned.
1618 ///
1619 /// Each ordering has a counterpart the other way round and equality is the same question at
1620 /// both readings, so every predicate has one and nothing here is a refusal. What it is for is
1621 /// operands known not to be negative: the two readings agree on those, so a signed comparison
1622 /// of two of them is the unsigned comparison of them, and the unsigned one is the one that
1623 /// still holds when the same values are looked at in fewer bits.
1624 #[must_use]
1625 pub const fn unsigned(self) -> Self {
1626 match self {
1627 Self::Slt => Self::Ult,
1628 Self::Sle => Self::Ule,
1629 Self::Sgt => Self::Ugt,
1630 Self::Sge => Self::Uge,
1631 other => other,
1632 }
1633 }
1634}
1635
1636impl fmt::Display for IntPred {
1637 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1638 f.write_str(self.name())
1639 }
1640}
1641
1642/// The floating point comparisons, ordered and unordered.
1643///
1644/// An ordered predicate is false if either operand is a NaN, and an unordered one is true. C's
1645/// `<` is `olt` and C's `!=` is `une`, which is the whole of why both families are here.
1646#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1647pub enum FloatPred {
1648 /// Always false.
1649 False,
1650 /// Ordered and equal.
1651 Oeq,
1652 /// Ordered and greater than.
1653 Ogt,
1654 /// Ordered and greater than or equal.
1655 Oge,
1656 /// Ordered and less than.
1657 Olt,
1658 /// Ordered and less than or equal.
1659 Ole,
1660 /// Ordered and not equal.
1661 One,
1662 /// Ordered, which is to say neither operand is a NaN.
1663 Ord,
1664 /// Unordered, which is to say one of them is.
1665 Uno,
1666 /// Unordered or equal.
1667 Ueq,
1668 /// Unordered or greater than.
1669 Ugt,
1670 /// Unordered or greater than or equal.
1671 Uge,
1672 /// Unordered or less than.
1673 Ult,
1674 /// Unordered or less than or equal.
1675 Ule,
1676 /// Unordered or not equal.
1677 Une,
1678 /// Always true.
1679 True,
1680}
1681
1682impl FloatPred {
1683 /// The textual form.
1684 #[must_use]
1685 pub const fn name(self) -> &'static str {
1686 match self {
1687 Self::False => "false",
1688 Self::Oeq => "oeq",
1689 Self::Ogt => "ogt",
1690 Self::Oge => "oge",
1691 Self::Olt => "olt",
1692 Self::Ole => "ole",
1693 Self::One => "one",
1694 Self::Ord => "ord",
1695 Self::Uno => "uno",
1696 Self::Ueq => "ueq",
1697 Self::Ugt => "ugt",
1698 Self::Uge => "uge",
1699 Self::Ult => "ult",
1700 Self::Ule => "ule",
1701 Self::Une => "une",
1702 Self::True => "true",
1703 }
1704 }
1705
1706 /// The predicate with that name, if there is one.
1707 #[must_use]
1708 pub fn from_name(name: &str) -> Option<Self> {
1709 Self::all().find(|pred| pred.name() == name)
1710 }
1711
1712 /// Every predicate.
1713 pub fn all() -> impl Iterator<Item = Self> {
1714 [
1715 Self::False,
1716 Self::Oeq,
1717 Self::Ogt,
1718 Self::Oge,
1719 Self::Olt,
1720 Self::Ole,
1721 Self::One,
1722 Self::Ord,
1723 Self::Uno,
1724 Self::Ueq,
1725 Self::Ugt,
1726 Self::Uge,
1727 Self::Ult,
1728 Self::Ule,
1729 Self::Une,
1730 Self::True,
1731 ]
1732 .into_iter()
1733 }
1734
1735 /// The predicate that holds exactly when this one does not.
1736 #[must_use]
1737 pub const fn inverse(self) -> Self {
1738 match self {
1739 Self::False => Self::True,
1740 Self::Oeq => Self::Une,
1741 Self::Ogt => Self::Ule,
1742 Self::Oge => Self::Ult,
1743 Self::Olt => Self::Uge,
1744 Self::Ole => Self::Ugt,
1745 Self::One => Self::Ueq,
1746 Self::Ord => Self::Uno,
1747 Self::Uno => Self::Ord,
1748 Self::Ueq => Self::One,
1749 Self::Ugt => Self::Ole,
1750 Self::Uge => Self::Olt,
1751 Self::Ult => Self::Oge,
1752 Self::Ule => Self::Ogt,
1753 Self::Une => Self::Oeq,
1754 Self::True => Self::False,
1755 }
1756 }
1757
1758 /// The predicate that holds when the operands are given the other way round.
1759 #[must_use]
1760 pub const fn swapped(self) -> Self {
1761 match self {
1762 Self::Ogt => Self::Olt,
1763 Self::Olt => Self::Ogt,
1764 Self::Oge => Self::Ole,
1765 Self::Ole => Self::Oge,
1766 Self::Ugt => Self::Ult,
1767 Self::Ult => Self::Ugt,
1768 Self::Uge => Self::Ule,
1769 Self::Ule => Self::Uge,
1770 same => same,
1771 }
1772 }
1773
1774 /// Whether this is false when either operand is a NaN.
1775 ///
1776 /// [`FloatPred::False`] and [`FloatPred::True`] are neither ordered nor unordered, since
1777 /// they do not look at their operands at all, and both answer no here.
1778 #[must_use]
1779 pub const fn is_ordered(self) -> bool {
1780 matches!(
1781 self,
1782 Self::Oeq | Self::Ogt | Self::Oge | Self::Olt | Self::Ole | Self::One | Self::Ord
1783 )
1784 }
1785}
1786
1787impl fmt::Display for FloatPred {
1788 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1789 f.write_str(self.name())
1790 }
1791}
1792
1793#[cfg(test)]
1794mod tests {
1795 use super::*;
1796
1797 #[test]
1798 fn every_opcode_is_in_the_table() {
1799 // `InlineAsm` is the last variant, so its discriminant plus one is how many there are.
1800 // A new opcode declared after it moves this number, and a new opcode declared before
1801 // it and not added to `ALL` moves the length, so either mistake fails here.
1802 assert_eq!(ALL.len(), Opcode::InlineAsm as usize + 1);
1803 for (position, &op) in ALL.iter().enumerate() {
1804 assert_eq!(op as usize, position, "{op} is out of order in ALL");
1805 }
1806 }
1807
1808 #[test]
1809 fn every_opcode_name_is_one_word_the_reader_can_take() {
1810 // The textual form keeps the dot for the type suffix and the flags, so an opcode with a
1811 // dot in it reads back as a shorter opcode with a suffix that is not a type. The safety
1812 // instructions are spelled `cap_of` and not `cap.of` for this reason, and the
1813 // specification says so at `spec/safe-memory/06-instrumentation.md` section 6.2.2.
1814 for opcode in Opcode::all() {
1815 let name = opcode.name();
1816 assert!(!name.is_empty(), "an opcode with no name");
1817 assert!(
1818 name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'),
1819 "{name} is not one word"
1820 );
1821 }
1822 }
1823
1824 #[test]
1825 fn every_opcode_has_its_own_name_and_finds_it_again() {
1826 let mut names: Vec<&str> = Opcode::all().map(Opcode::name).collect();
1827 let total = names.len();
1828 names.sort_unstable();
1829 names.dedup();
1830 assert_eq!(names.len(), total, "two opcodes share a name");
1831 for op in Opcode::all() {
1832 assert_eq!(Opcode::from_name(op.name()), Some(op));
1833 }
1834 assert_eq!(Opcode::from_name("phi"), None);
1835 assert_eq!(Opcode::from_name("getelementptr"), None);
1836 assert_eq!(Opcode::from_name(""), None);
1837 }
1838
1839 #[test]
1840 fn the_terminators_are_the_ones_control_leaves_by() {
1841 let terminators: Vec<&str> =
1842 Opcode::all().filter(|op| op.is_terminator()).map(Opcode::name).collect();
1843 assert_eq!(
1844 terminators,
1845 ["jump", "br_if", "switch", "indirect_br", "return", "unreachable", "tail_call"]
1846 );
1847 }
1848
1849 #[test]
1850 fn a_terminator_produces_nothing() {
1851 for op in Opcode::all().filter(|op| op.is_terminator()) {
1852 assert_eq!(op.results(), Some(0), "{op}");
1853 }
1854 }
1855
1856 #[test]
1857 fn the_pair_producing_opcodes_are_the_ones_with_a_flag_beside_the_value() {
1858 let pairs: Vec<&str> =
1859 Opcode::all().filter(|op| op.results() == Some(2)).map(Opcode::name).collect();
1860 assert_eq!(
1861 pairs,
1862 [
1863 "cmpxchg",
1864 "sadd_overflow",
1865 "uadd_overflow",
1866 "ssub_overflow",
1867 "usub_overflow",
1868 "smul_overflow",
1869 "umul_overflow"
1870 ]
1871 );
1872 }
1873
1874 #[test]
1875 fn the_capability_instructions_are_the_ones_that_make_a_capability() {
1876 let makers: Vec<Opcode> = Opcode::all().filter(|op| op.makes_capability()).collect();
1877 assert_eq!(
1878 makers,
1879 vec![
1880 Opcode::CapOf,
1881 Opcode::CapLoad,
1882 Opcode::CapNull,
1883 Opcode::CapNarrow,
1884 Opcode::CapRecover,
1885 Opcode::CapArg,
1886 Opcode::CapResult
1887 ]
1888 );
1889 // The other three read a capability rather than making one. `cap_store` writes it out and
1890 // produces nothing at all, and the two extent queries answer with a number.
1891 assert!(!Opcode::CapStore.makes_capability());
1892 assert_eq!(Opcode::CapStore.results(), Some(0));
1893 assert!(!Opcode::CapExtent.makes_capability());
1894 assert_eq!(Opcode::CapExtent.results(), Some(1));
1895 assert!(!Opcode::CapExtentBack.makes_capability());
1896 assert_eq!(Opcode::CapExtentBack.results(), Some(1));
1897 for opcode in makers {
1898 assert_eq!(opcode.results(), Some(1), "{}", opcode.name());
1899 }
1900 }
1901
1902 #[test]
1903 fn a_producer_says_which_of_its_operands_is_the_pointer_it_is_about() {
1904 // Five of the seven, and the one that is not operand zero is the one whose first two
1905 // operands are the container and the word rather than the value that came out of it.
1906 assert_eq!(Opcode::CapOf.capability_names(), Some(0));
1907 assert_eq!(Opcode::CapRecover.capability_names(), Some(0));
1908 assert_eq!(Opcode::CapArg.capability_names(), Some(0));
1909 assert_eq!(Opcode::CapResult.capability_names(), Some(0));
1910 assert_eq!(Opcode::CapLoad.capability_names(), Some(2));
1911
1912 // The two that are about something other than a pointer this function has an operand for.
1913 assert_eq!(Opcode::CapNarrow.capability_names(), None);
1914 assert_eq!(Opcode::CapNull.capability_names(), None);
1915
1916 // Nothing that is not a producer answers, since the question is what a capability describes
1917 // and those have no capability to describe anything with.
1918 assert_eq!(Opcode::CapStore.capability_names(), None);
1919 assert_eq!(Opcode::Load.capability_names(), None);
1920 assert_eq!(Opcode::CheckLive.capability_names(), None);
1921 }
1922
1923 #[test]
1924 fn a_check_reads_the_planes_and_writes_nothing() {
1925 let checks = [
1926 Opcode::CheckBounds,
1927 Opcode::CheckLive,
1928 Opcode::CheckType,
1929 Opcode::CheckInit,
1930 Opcode::CheckDeriv,
1931 Opcode::CheckRace,
1932 Opcode::CheckFree,
1933 ];
1934 for opcode in checks {
1935 let name = opcode.name();
1936 // It traps, so it stays where it was put and nothing deletes it for having no
1937 // result. It reads a plane, so it takes a memory operand. It writes nothing, so
1938 // the access after it reads the version the check was given.
1939 assert!(opcode.has_effects(), "{name}");
1940 assert!(opcode.touches_memory(), "{name}");
1941 assert!(!opcode.writes_memory(), "{name}");
1942 assert_eq!(opcode.results(), Some(0), "{name}");
1943 }
1944 }
1945
1946 #[test]
1947 fn a_restrict_check_writes_memory_because_it_records_what_it_saw() {
1948 // The one place the sentence above does not hold. Every other check reads a plane and
1949 // leaves it alone, so the optimizer may hoist one out of a loop or keep the later of two
1950 // identical ones. These record the range they were asked about into the block's own slot,
1951 // so a check that ran twice saw two accesses and a check that was hoisted saw one, and
1952 // either rewrite changes what the next one answers. Saying they write memory is how the
1953 // memory chain refuses both.
1954 let recording = [
1955 Opcode::CheckRestrictRead,
1956 Opcode::CheckRestrictWrite,
1957 Opcode::RestrictEnter,
1958 Opcode::RestrictLeave,
1959 ];
1960 for opcode in recording {
1961 let name = opcode.name();
1962 assert!(opcode.has_effects(), "{name}");
1963 assert!(opcode.touches_memory(), "{name}");
1964 assert!(opcode.writes_memory(), "{name}");
1965 assert_eq!(opcode.results(), Some(0), "{name}");
1966 }
1967 }
1968
1969 #[test]
1970 fn the_capability_instructions_that_touch_memory_are_the_five_that_have_to() {
1971 // `cap_load` and `cap_store` are an access to the slot beside a pointer, and `cap_recover`
1972 // and the two extent queries read the planes. The other three are arithmetic on a
1973 // provenance the program already had, so the optimizer may treat them as it treats
1974 // `ptr_add`.
1975 assert!(!Opcode::CapOf.has_effects());
1976 assert!(!Opcode::CapNull.has_effects());
1977 assert!(!Opcode::CapNarrow.has_effects());
1978 assert!(Opcode::CapLoad.touches_memory() && !Opcode::CapLoad.writes_memory());
1979 assert!(Opcode::CapRecover.touches_memory() && !Opcode::CapRecover.writes_memory());
1980 assert!(Opcode::CapExtent.touches_memory() && !Opcode::CapExtent.writes_memory());
1981 assert!(Opcode::CapExtentBack.touches_memory() && !Opcode::CapExtentBack.writes_memory());
1982 assert!(Opcode::CapStore.writes_memory());
1983 }
1984
1985 #[test]
1986 fn what_only_touches_a_plane_touches_memory_and_is_not_an_access() {
1987 // Two halves. Everything in the list is on the memory chain, because an instruction the
1988 // chain does not carry is one the walk never sees and saying anything about it would be
1989 // saying it about nothing. And everything in the list comes from the safety lowering,
1990 // because the planes are the lowering's own storage and an opcode from somewhere else
1991 // claiming to touch only them is the claim being made about the wrong memory.
1992 for opcode in Opcode::all() {
1993 if !opcode.touches_only_planes() {
1994 continue;
1995 }
1996 let name = opcode.name();
1997 assert!(opcode.touches_memory(), "{name}");
1998 let instrumentation = name.starts_with("check_")
1999 || name.starts_with("meta_")
2000 || name.starts_with("cap_extent")
2001 || name == "cap_copy";
2002 assert!(instrumentation, "{name}");
2003 }
2004 for opcode in [Opcode::MetaInit, Opcode::MetaType, Opcode::CheckBounds, Opcode::CapExtent] {
2005 assert!(opcode.touches_only_planes(), "{opcode}");
2006 }
2007 }
2008
2009 #[test]
2010 fn what_goes_through_a_frame_slot_is_not_a_plane_access() {
2011 // What the list leaves out on purpose. The three capability instructions here each take a
2012 // pointer that is not a locator, since a pointer written into a slot is one a later
2013 // instruction reads back out, and the `restrict` markers write their record into the
2014 // block's own slot. The synchronization edges are left out for a different reason, which is
2015 // that they say something about the ordering of program memory and not only about a plane.
2016 let outside = [
2017 Opcode::CapLoad,
2018 Opcode::CapStore,
2019 Opcode::CapRecover,
2020 Opcode::CheckRestrictRead,
2021 Opcode::CheckRestrictWrite,
2022 Opcode::RestrictEnter,
2023 Opcode::RestrictLeave,
2024 Opcode::MetaRelease,
2025 Opcode::MetaAcquire,
2026 Opcode::MetaFenceRelease,
2027 Opcode::MetaFenceAcquire,
2028 ];
2029 for opcode in outside {
2030 assert!(!opcode.touches_only_planes(), "{opcode}");
2031 }
2032 // And nothing ordinary is in it either, since a store answering yes would be the whole
2033 // optimizer told that program memory is unreachable.
2034 for opcode in [Opcode::Load, Opcode::Store, Opcode::Call, Opcode::Memcpy, Opcode::Fence] {
2035 assert!(!opcode.touches_only_planes(), "{opcode}");
2036 }
2037 }
2038
2039 #[test]
2040 fn memory_has_effects_and_arithmetic_does_not() {
2041 for op in [Opcode::Load, Opcode::Store, Opcode::Call, Opcode::Alloca, Opcode::Fence] {
2042 assert!(op.has_effects(), "{op}");
2043 }
2044 for op in [Opcode::Add, Opcode::FDiv, Opcode::ICmp, Opcode::PtrAdd, Opcode::IConst] {
2045 assert!(!op.has_effects(), "{op}");
2046 }
2047 }
2048
2049 #[test]
2050 fn commuting_is_only_claimed_where_it_holds() {
2051 assert!(Opcode::Add.is_commutative());
2052 assert!(Opcode::FAdd.is_commutative());
2053 assert!(!Opcode::Sub.is_commutative());
2054 assert!(!Opcode::FDiv.is_commutative());
2055 assert!(!Opcode::Shl.is_commutative());
2056 }
2057
2058 #[test]
2059 fn an_integer_predicate_inverts_and_swaps_back_to_itself() {
2060 for pred in IntPred::all() {
2061 assert_eq!(pred.inverse().inverse(), pred);
2062 assert_eq!(pred.swapped().swapped(), pred);
2063 assert_eq!(IntPred::from_name(pred.name()), Some(pred));
2064 }
2065 assert_eq!(IntPred::Slt.inverse(), IntPred::Sge);
2066 assert_eq!(IntPred::Slt.swapped(), IntPred::Sgt);
2067 assert_eq!(IntPred::from_name("lt"), None);
2068 }
2069
2070 #[test]
2071 fn an_integer_predicate_has_an_unsigned_counterpart_that_asks_the_same_way_round() {
2072 for pred in IntPred::all() {
2073 let unsigned = pred.unsigned();
2074 assert!(!unsigned.is_signed(), "{pred}");
2075 assert_eq!(unsigned.unsigned(), unsigned, "{pred}");
2076 // The same way round, so inverting or swapping either first gives the same answer.
2077 assert_eq!(pred.inverse().unsigned(), unsigned.inverse(), "{pred}");
2078 assert_eq!(pred.swapped().unsigned(), unsigned.swapped(), "{pred}");
2079 }
2080 assert_eq!(IntPred::Slt.unsigned(), IntPred::Ult);
2081 assert_eq!(IntPred::Sge.unsigned(), IntPred::Uge);
2082 // Equality is the same question at both readings, so it is already its own counterpart.
2083 assert_eq!(IntPred::Eq.unsigned(), IntPred::Eq);
2084 assert_eq!(IntPred::Ne.unsigned(), IntPred::Ne);
2085 }
2086
2087 #[test]
2088 fn a_floating_predicate_inverts_across_the_ordered_line() {
2089 for pred in FloatPred::all() {
2090 assert_eq!(pred.inverse().inverse(), pred);
2091 assert_eq!(pred.swapped().swapped(), pred);
2092 assert_eq!(FloatPred::from_name(pred.name()), Some(pred));
2093 }
2094 // Inverting has to cross the line, because the negation of an ordered comparison is
2095 // true when an operand is a NaN. This is where `!(a < b)` stops being `a >= b`. The
2096 // two constants are outside it: neither of them looks at its operands.
2097 for pred in FloatPred::all().filter(|p| !matches!(p, FloatPred::False | FloatPred::True)) {
2098 assert_ne!(pred.is_ordered(), pred.inverse().is_ordered(), "{pred}");
2099 }
2100 assert_eq!(FloatPred::Olt.inverse(), FloatPred::Uge);
2101 assert_eq!(FloatPred::Olt.swapped(), FloatPred::Ogt);
2102 }
2103
2104 #[test]
2105 fn swapping_a_predicate_keeps_it_ordered_or_unordered() {
2106 for pred in FloatPred::all() {
2107 assert_eq!(pred.is_ordered(), pred.swapped().is_ordered(), "{pred}");
2108 }
2109 for pred in IntPred::all() {
2110 assert_eq!(pred.is_signed(), pred.swapped().is_signed(), "{pred}");
2111 }
2112 }
2113
2114 #[test]
2115 fn no_two_predicates_share_a_name_within_their_family() {
2116 for names in [
2117 IntPred::all().map(IntPred::name).collect::<Vec<_>>(),
2118 FloatPred::all().map(FloatPred::name).collect::<Vec<_>>(),
2119 ] {
2120 let total = names.len();
2121 let mut names = names;
2122 names.sort_unstable();
2123 names.dedup();
2124 assert_eq!(names.len(), total);
2125 }
2126 }
2127}