rustc_middle/mir/syntax.rs
1//! This defines the syntax of MIR, i.e., the set of available MIR operations, and other definitions
2//! closely related to MIR semantics.
3//! This is in a dedicated file so that changes to this file can be reviewed more carefully.
4//! The intention is that this file only contains datatype declarations, no code.
5
6use rustc_abi::{FieldIdx, VariantIdx};
7use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, Mutability};
8use rustc_data_structures::packed::Pu128;
9use rustc_hir::CoroutineKind;
10use rustc_hir::def_id::DefId;
11use rustc_index::IndexVec;
12use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
13use rustc_span::def_id::LocalDefId;
14use rustc_span::source_map::Spanned;
15use rustc_span::{Span, Symbol};
16use rustc_target::asm::InlineAsmRegOrRegClass;
17use smallvec::SmallVec;
18
19use super::{BasicBlock, Const, Local, UserTypeProjection};
20use crate::mir::coverage::CoverageKind;
21use crate::ty::adjustment::PointerCoercion;
22use crate::ty::{self, GenericArgsRef, List, Region, Ty, UserTypeAnnotationIndex};
23
24/// Represents the "flavors" of MIR.
25///
26/// The MIR pipeline is structured into a few major dialects, with one or more phases within each
27/// dialect. A MIR flavor is identified by a dialect-phase pair. A single `MirPhase` value
28/// specifies such a pair. All flavors of MIR use the same data structure to represent the program.
29///
30/// Different MIR dialects have different semantics. (The differences between dialects are small,
31/// but they do exist.) The progression from one MIR dialect to the next is technically a lowering
32/// from one IR to another. In other words, a single well-formed [`Body`](crate::mir::Body) might
33/// have different semantic meaning and different behavior at runtime in the different dialects.
34/// The specific differences between dialects are described on the variants below.
35///
36/// Phases exist only to place restrictions on what language constructs are permitted in
37/// well-formed MIR, and subsequent phases mostly increase those restrictions. I.e. to convert MIR
38/// from one phase to the next might require removing/replacing certain MIR constructs.
39///
40/// When adding dialects or phases, remember to update [`MirPhase::index`].
41#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
42#[derive(HashStable)]
43pub enum MirPhase {
44 /// The "built MIR" dialect, as generated by MIR building.
45 ///
46 /// The only things that operate on this dialect are unsafeck, the various MIR lints, and const
47 /// qualifs.
48 ///
49 /// This dialect has just the one (implicit) phase, which places few restrictions on what MIR
50 /// constructs are allowed.
51 Built,
52
53 /// The "analysis MIR" dialect, used for borrowck and friends.
54 ///
55 /// The only semantic difference between built MIR and analysis MIR relates to constant
56 /// promotion. In built MIR, sequences of statements that would generally be subject to
57 /// constant promotion are semantically constants, while in analysis MIR all constants are
58 /// explicit.
59 ///
60 /// The result of const promotion is available from the `mir_promoted` and `promoted_mir`
61 /// queries.
62 ///
63 /// The phases of this dialect are described in `AnalysisPhase`.
64 Analysis(AnalysisPhase),
65
66 /// The "runtime MIR" dialect, used for CTFE, optimizations, and codegen.
67 ///
68 /// The semantic differences between analysis MIR and runtime MIR are as follows.
69 ///
70 /// - Drops: In analysis MIR, `Drop` terminators represent *conditional* drops; roughly
71 /// speaking, if dataflow analysis determines that the place being dropped is uninitialized,
72 /// the drop will not be executed. The exact semantics of this aren't written down anywhere,
73 /// which means they are essentially "what drop elaboration does." In runtime MIR, the drops
74 /// are unconditional; when a `Drop` terminator is reached, if the type has drop glue that
75 /// drop glue is always executed. This may be UB if the underlying place is not initialized.
76 /// - Packed drops: Places might in general be misaligned - in most cases this is UB, the
77 /// exception is fields of packed structs. In analysis MIR, `Drop(P)` for a `P` that might be
78 /// misaligned for this reason implicitly moves `P` to a temporary before dropping. Runtime
79 /// MIR has no such rules, and dropping a misaligned place is simply UB.
80 /// - Async drops: after drop elaboration some drops may become async (`drop`, `async_fut` fields).
81 /// StateTransform pass will expand those async drops or reset to sync.
82 /// - Unwinding: in analysis MIR, unwinding from a function which may not unwind aborts. In
83 /// runtime MIR, this is UB.
84 /// - Retags: If `-Zmir-emit-retag` is enabled, analysis MIR has "implicit" retags in the same
85 /// way that Rust itself has them. Where exactly these are is generally subject to change,
86 /// and so we don't document this here. Runtime MIR has most retags explicit (though implicit
87 /// retags can still occur at `Rvalue::{Ref,AddrOf}`).
88 /// - Coroutine bodies: In analysis MIR, locals may actually be behind a pointer that user code
89 /// has access to. This occurs in coroutine bodies. Such locals do not behave like other
90 /// locals, because they e.g. may be aliased in surprising ways. Runtime MIR has no such
91 /// special locals. All coroutine bodies are lowered and so all places that look like locals
92 /// really are locals.
93 ///
94 /// Also note that the lint pass which reports eg `200_u8 + 200_u8` as an error is run as a part
95 /// of analysis to runtime MIR lowering. To ensure lints are reported reliably, this means that
96 /// transformations that can suppress such errors should not run on analysis MIR.
97 ///
98 /// The phases of this dialect are described in `RuntimePhase`.
99 Runtime(RuntimePhase),
100}
101
102/// See [`MirPhase::Analysis`].
103#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
104#[derive(HashStable)]
105pub enum AnalysisPhase {
106 Initial = 0,
107 /// Beginning in this phase, the following variants are disallowed:
108 /// * [`TerminatorKind::FalseUnwind`]
109 /// * [`TerminatorKind::FalseEdge`]
110 /// * [`StatementKind::FakeRead`]
111 /// * [`StatementKind::AscribeUserType`]
112 /// * [`StatementKind::Coverage`] with [`CoverageKind::BlockMarker`] or
113 /// [`CoverageKind::SpanMarker`]
114 /// * [`Rvalue::Ref`] with `BorrowKind::Fake`
115 /// * [`CastKind::PointerCoercion`] with any of the following:
116 /// * [`PointerCoercion::ArrayToPointer`]
117 /// * [`PointerCoercion::MutToConstPointer`]
118 ///
119 /// Furthermore, `Deref` projections must be the first projection within any place (if they
120 /// appear at all)
121 PostCleanup = 1,
122}
123
124/// See [`MirPhase::Runtime`].
125#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
126#[derive(HashStable)]
127pub enum RuntimePhase {
128 /// In addition to the semantic changes, beginning with this phase, the following variants are
129 /// disallowed:
130 /// * [`TerminatorKind::Yield`]
131 /// * [`TerminatorKind::CoroutineDrop`]
132 /// * [`Rvalue::Aggregate`] for any `AggregateKind` except `Array`
133 /// * [`Rvalue::CopyForDeref`]
134 /// * [`PlaceElem::OpaqueCast`]
135 /// * [`LocalInfo::DerefTemp`](super::LocalInfo::DerefTemp)
136 ///
137 /// And the following variants are allowed:
138 /// * [`StatementKind::Retag`]
139 /// * [`StatementKind::SetDiscriminant`]
140 ///
141 /// Furthermore, `Copy` operands are allowed for non-`Copy` types.
142 Initial = 0,
143 /// Beginning with this phase, the following variant is disallowed:
144 /// * [`ProjectionElem::Deref`] of `Box`
145 PostCleanup = 1,
146 Optimized = 2,
147}
148
149///////////////////////////////////////////////////////////////////////////
150// Borrow kinds
151
152#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
153#[derive(Hash, HashStable)]
154pub enum BorrowKind {
155 /// Data must be immutable and is aliasable.
156 Shared,
157
158 /// An immutable, aliasable borrow that is discarded after borrow-checking. Can behave either
159 /// like a normal shared borrow or like a special shallow borrow (see [`FakeBorrowKind`]).
160 ///
161 /// This is used when lowering index expressions and matches. This is used to prevent code like
162 /// the following from compiling:
163 /// ```compile_fail,E0510
164 /// let mut x: &[_] = &[[0, 1]];
165 /// let y: &[_] = &[];
166 /// let _ = x[0][{x = y; 1}];
167 /// ```
168 /// ```compile_fail,E0510
169 /// let mut x = &Some(0);
170 /// match *x {
171 /// None => (),
172 /// Some(_) if { x = &None; false } => (),
173 /// Some(_) => (),
174 /// }
175 /// ```
176 /// We can also report errors with this kind of borrow differently.
177 Fake(FakeBorrowKind),
178
179 /// Data is mutable and not aliasable.
180 Mut { kind: MutBorrowKind },
181}
182
183#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
184#[derive(Hash, HashStable)]
185pub enum RawPtrKind {
186 Mut,
187 Const,
188 /// Creates a raw pointer to a place that will only be used to access its metadata,
189 /// not the data behind the pointer. Note that this limitation is *not* enforced
190 /// by the validator.
191 ///
192 /// The borrow checker allows overlap of these raw pointers with references to the
193 /// data. This is sound even if the pointer is "misused" since any such use is anyway
194 /// unsafe. In terms of the operational semantics (i.e., Miri), this is equivalent
195 /// to `RawPtrKind::Mut`, but will never incur a retag.
196 FakeForPtrMetadata,
197}
198
199#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
200#[derive(Hash, HashStable)]
201pub enum MutBorrowKind {
202 Default,
203 /// This borrow arose from method-call auto-ref. (i.e., `adjustment::Adjust::Borrow`)
204 TwoPhaseBorrow,
205 /// Data must be immutable but not aliasable. This kind of borrow
206 /// cannot currently be expressed by the user and is used only in
207 /// implicit closure bindings. It is needed when the closure is
208 /// borrowing or mutating a mutable referent, e.g.:
209 /// ```
210 /// let mut z = 3;
211 /// let x: &mut isize = &mut z;
212 /// let y = || *x += 5;
213 /// ```
214 /// If we were to try to translate this closure into a more explicit
215 /// form, we'd encounter an error with the code as written:
216 /// ```compile_fail,E0594
217 /// struct Env<'a> { x: &'a &'a mut isize }
218 /// let mut z = 3;
219 /// let x: &mut isize = &mut z;
220 /// let y = (&mut Env { x: &x }, fn_ptr); // Closure is pair of env and fn
221 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
222 /// ```
223 /// This is then illegal because you cannot mutate an `&mut` found
224 /// in an aliasable location. To solve, you'd have to translate with
225 /// an `&mut` borrow:
226 /// ```compile_fail,E0596
227 /// struct Env<'a> { x: &'a mut &'a mut isize }
228 /// let mut z = 3;
229 /// let x: &mut isize = &mut z;
230 /// let y = (&mut Env { x: &mut x }, fn_ptr); // changed from &x to &mut x
231 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
232 /// ```
233 /// Now the assignment to `**env.x` is legal, but creating a
234 /// mutable pointer to `x` is not because `x` is not mutable. We
235 /// could fix this by declaring `x` as `let mut x`. This is ok in
236 /// user code, if awkward, but extra weird for closures, since the
237 /// borrow is hidden.
238 ///
239 /// So we introduce a `ClosureCapture` borrow -- user will not have to mark the variable
240 /// containing the mutable reference as `mut`, as they didn't ever
241 /// intend to mutate the mutable reference itself. We still mutable capture it in order to
242 /// mutate the pointed value through it (but not mutating the reference itself).
243 ///
244 /// This solves the problem. For simplicity, we don't give users the way to express this
245 /// borrow, it's just used when translating closures.
246 ClosureCapture,
247}
248
249#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
250#[derive(Hash, HashStable)]
251pub enum FakeBorrowKind {
252 /// A shared shallow borrow. The immediately borrowed place must be immutable, but projections
253 /// from it don't need to be. For example, a shallow borrow of `a.b` doesn't conflict with a
254 /// mutable borrow of `a.b.c`.
255 ///
256 /// This is used when lowering matches: when matching on a place we want to ensure that place
257 /// have the same value from the start of the match until an arm is selected. This prevents this
258 /// code from compiling:
259 /// ```compile_fail,E0510
260 /// let mut x = &Some(0);
261 /// match *x {
262 /// None => (),
263 /// Some(_) if { x = &None; false } => (),
264 /// Some(_) => (),
265 /// }
266 /// ```
267 /// This can't be a shared borrow because mutably borrowing `(*x as Some).0` should not checking
268 /// the discriminant or accessing other variants, because the mutating `(*x as Some).0` can't
269 /// affect the discriminant of `x`. E.g. the following is allowed:
270 /// ```rust
271 /// let mut x = Some(0);
272 /// match x {
273 /// Some(_)
274 /// if {
275 /// if let Some(ref mut y) = x {
276 /// *y += 1;
277 /// };
278 /// true
279 /// } => {}
280 /// _ => {}
281 /// }
282 /// ```
283 Shallow,
284 /// A shared (deep) borrow. Data must be immutable and is aliasable.
285 ///
286 /// This is used when lowering deref patterns, where shallow borrows wouldn't prevent something
287 /// like:
288 /// ```compile_fail
289 /// let mut b = Box::new(false);
290 /// match b {
291 /// deref!(true) => {} // not reached because `*b == false`
292 /// _ if { *b = true; false } => {} // not reached because the guard is `false`
293 /// deref!(false) => {} // not reached because the guard changed it
294 /// // UB because we reached the unreachable.
295 /// }
296 /// ```
297 Deep,
298}
299
300///////////////////////////////////////////////////////////////////////////
301// Statements
302
303/// The various kinds of statements that can appear in MIR.
304///
305/// Not all of these are allowed at every [`MirPhase`]. Check the documentation there to see which
306/// ones you do not have to worry about. The MIR validator will generally enforce such restrictions,
307/// causing an ICE if they are violated.
308#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
309#[derive(TypeFoldable, TypeVisitable)]
310pub enum StatementKind<'tcx> {
311 /// Assign statements roughly correspond to an assignment in Rust proper (`x = ...`) except
312 /// without the possibility of dropping the previous value (that must be done separately, if at
313 /// all). The *exact* way this works is undecided. It probably does something like evaluating
314 /// the LHS to a place and the RHS to a value, and then storing the value to the place. Various
315 /// parts of this may do type specific things that are more complicated than simply copying
316 /// bytes.
317 ///
318 /// **Needs clarification**: The implication of the above idea would be that assignment implies
319 /// that the resulting value is initialized. I believe we could commit to this separately from
320 /// committing to whatever part of the memory model we would need to decide on to make the above
321 /// paragraph precise. Do we want to?
322 ///
323 /// Assignments in which the types of the place and rvalue differ are not well-formed.
324 ///
325 /// **Needs clarification**: Do we ever want to worry about non-free (in the body) lifetimes for
326 /// the typing requirement in post drop-elaboration MIR? I think probably not - I'm not sure we
327 /// could meaningfully require this anyway. How about free lifetimes? Is ignoring this
328 /// interesting for optimizations? Do we want to allow such optimizations?
329 ///
330 /// **Needs clarification**: We currently require that the LHS place not overlap with any place
331 /// read as part of computation of the RHS for some rvalues. This requirement is under
332 /// discussion in [#68364]. Specifically, overlap is permitted only for assignments of a type
333 /// with `BackendRepr::Scalar | BackendRepr::ScalarPair` where all the scalar fields are
334 /// [`Scalar::Initialized`][rustc_abi::Scalar::Initialized]. As a part of this discussion, it is
335 /// also unclear in what order the components are evaluated.
336 ///
337 /// [#68364]: https://github.com/rust-lang/rust/issues/68364
338 ///
339 /// See [`Rvalue`] documentation for details on each of those.
340 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
341
342 /// When executed at runtime, this is a nop.
343 ///
344 /// During static analysis, a fake read:
345 /// - requires that the value being read is initialized (or, in the case
346 /// of closures, that it was fully initialized at some point in the past)
347 /// - constitutes a use of a value for the purposes of NLL (i.e. if the
348 /// value being fake-read is a reference, the lifetime of that reference
349 /// will be extended to cover the `FakeRead`)
350 /// - but, unlike an actual read, does *not* invalidate any exclusive
351 /// borrows.
352 ///
353 /// See [`FakeReadCause`] for more details on the situations in which a
354 /// `FakeRead` is emitted.
355 ///
356 /// Disallowed after drop elaboration.
357 FakeRead(Box<(FakeReadCause, Place<'tcx>)>),
358
359 /// Write the discriminant for a variant to the enum Place.
360 ///
361 /// This is permitted for both coroutines and ADTs. This does not necessarily write to the
362 /// entire place; instead, it writes to the minimum set of bytes as required by the layout for
363 /// the type.
364 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
365
366 /// `StorageLive` and `StorageDead` statements mark the live range of a local.
367 ///
368 /// At any point during the execution of a function, each local is either allocated or
369 /// unallocated. Except as noted below, all locals except function parameters are initially
370 /// unallocated. `StorageLive` statements cause memory to be allocated for the local while
371 /// `StorageDead` statements cause the memory to be freed. In other words,
372 /// `StorageLive`/`StorageDead` act like the heap operations `allocate`/`deallocate`, but for
373 /// stack-allocated local variables. Using a local in any way (not only reading/writing from it)
374 /// while it is unallocated is UB.
375 ///
376 /// Some locals have no `StorageLive` or `StorageDead` statements within the entire MIR body.
377 /// These locals are implicitly allocated for the full duration of the function. There is a
378 /// convenience method at `rustc_mir_dataflow::storage::always_storage_live_locals` for
379 /// computing these locals.
380 ///
381 /// If the local is already allocated, calling `StorageLive` again will implicitly free the
382 /// local and then allocate fresh uninitialized memory. If a local is already deallocated,
383 /// calling `StorageDead` again is a NOP.
384 StorageLive(Local),
385
386 /// See `StorageLive` above.
387 StorageDead(Local),
388
389 /// Retag references in the given place, ensuring they got fresh tags.
390 ///
391 /// This is part of the Stacked Borrows model. These statements are currently only interpreted
392 /// by miri and only generated when `-Z mir-emit-retag` is passed. See
393 /// <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/> for
394 /// more details.
395 ///
396 /// For code that is not specific to stacked borrows, you should consider retags to read and
397 /// modify the place in an opaque way.
398 ///
399 /// Only `RetagKind::Default` and `RetagKind::FnEntry` are permitted.
400 Retag(RetagKind, Box<Place<'tcx>>),
401
402 /// This statement exists to preserve a trace of a scrutinee matched against a wildcard binding.
403 /// This is especially useful for `let _ = PLACE;` bindings that desugar to a single
404 /// `PlaceMention(PLACE)`.
405 ///
406 /// When executed at runtime, this computes the given place, but then discards
407 /// it without doing a load. `let _ = *ptr;` is fine even if the pointer is dangling.
408 PlaceMention(Box<Place<'tcx>>),
409
410 /// Encodes a user's type ascription. These need to be preserved
411 /// intact so that NLL can respect them. For example:
412 /// ```ignore (illustrative)
413 /// let a: T = y;
414 /// ```
415 /// The effect of this annotation is to relate the type `T_y` of the place `y`
416 /// to the user-given type `T`. The effect depends on the specified variance:
417 ///
418 /// - `Covariant` -- requires that `T_y <: T`
419 /// - `Contravariant` -- requires that `T_y :> T`
420 /// - `Invariant` -- requires that `T_y == T`
421 /// - `Bivariant` -- no effect
422 ///
423 /// When executed at runtime this is a nop.
424 ///
425 /// Disallowed after drop elaboration.
426 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
427
428 /// Carries control-flow-sensitive information injected by `-Cinstrument-coverage`,
429 /// such as where to generate physical coverage-counter-increments during codegen.
430 ///
431 /// Coverage statements are used in conjunction with the coverage mappings and other
432 /// information stored in the function's
433 /// [`mir::Body::function_coverage_info`](crate::mir::Body::function_coverage_info).
434 /// (For inlined MIR, take care to look up the *original function's* coverage info.)
435 ///
436 /// Interpreters and codegen backends that don't support coverage instrumentation
437 /// can usually treat this as a no-op.
438 Coverage(
439 // Coverage statements are unlikely to ever contain type information in
440 // the foreseeable future, so excluding them from TypeFoldable/TypeVisitable
441 // avoids some unhelpful derive boilerplate.
442 #[type_foldable(identity)]
443 #[type_visitable(ignore)]
444 CoverageKind,
445 ),
446
447 /// Denotes a call to an intrinsic that does not require an unwind path and always returns.
448 /// This avoids adding a new block and a terminator for simple intrinsics.
449 Intrinsic(Box<NonDivergingIntrinsic<'tcx>>),
450
451 /// Instructs the const eval interpreter to increment a counter; this counter is used to track
452 /// how many steps the interpreter has taken. It is used to prevent the user from writing const
453 /// code that runs for too long or infinitely. Other than in the const eval interpreter, this
454 /// is a no-op.
455 ConstEvalCounter,
456
457 /// No-op. Useful for deleting instructions without affecting statement indices.
458 Nop,
459
460 /// Marker statement indicating where `place` would be dropped.
461 /// This is semantically equivalent to `Nop`, so codegen and MIRI should interpret this
462 /// statement as such.
463 /// The only use case of this statement is for linting in MIR to detect temporary lifetime
464 /// changes.
465 BackwardIncompatibleDropHint {
466 /// Place to drop
467 place: Box<Place<'tcx>>,
468 /// Reason for backward incompatibility
469 reason: BackwardIncompatibleDropReason,
470 },
471}
472
473#[derive(
474 Clone,
475 TyEncodable,
476 TyDecodable,
477 Debug,
478 PartialEq,
479 Hash,
480 HashStable,
481 TypeFoldable,
482 TypeVisitable
483)]
484pub enum NonDivergingIntrinsic<'tcx> {
485 /// Denotes a call to the intrinsic function `assume`.
486 ///
487 /// The operand must be a boolean. Optimizers may use the value of the boolean to backtrack its
488 /// computation to infer information about other variables. So if the boolean came from a
489 /// `x < y` operation, subsequent operations on `x` and `y` could elide various bound checks.
490 /// If the argument is `false`, this operation is equivalent to `TerminatorKind::Unreachable`.
491 Assume(Operand<'tcx>),
492
493 /// Denotes a call to the intrinsic function `copy_nonoverlapping`.
494 ///
495 /// First, all three operands are evaluated. `src` and `dest` must each be a reference, pointer,
496 /// or `Box` pointing to the same type `T`. `count` must evaluate to a `usize`. Then, `src` and
497 /// `dest` are dereferenced, and `count * size_of::<T>()` bytes beginning with the first byte of
498 /// the `src` place are copied to the contiguous range of bytes beginning with the first byte
499 /// of `dest`.
500 ///
501 /// **Needs clarification**: In what order are operands computed and dereferenced? It should
502 /// probably match the order for assignment, but that is also undecided.
503 ///
504 /// **Needs clarification**: Is this typed or not, ie is there a typed load and store involved?
505 /// I vaguely remember Ralf saying somewhere that he thought it should not be.
506 CopyNonOverlapping(CopyNonOverlapping<'tcx>),
507}
508
509/// Describes what kind of retag is to be performed.
510#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
511#[rustc_pass_by_value]
512pub enum RetagKind {
513 /// The initial retag of arguments when entering a function.
514 FnEntry,
515 /// Retag preparing for a two-phase borrow.
516 TwoPhase,
517 /// Retagging raw pointers.
518 Raw,
519 /// A "normal" retag.
520 Default,
521}
522
523/// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
524#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
525pub enum FakeReadCause {
526 /// A fake read injected into a match guard to ensure that the discriminants
527 /// that are being matched on aren't modified while the match guard is being
528 /// evaluated.
529 ///
530 /// At the beginning of each match guard, a [fake borrow][FakeBorrowKind] is
531 /// inserted for each discriminant accessed in the entire `match` statement.
532 ///
533 /// Then, at the end of the match guard, a `FakeRead(ForMatchGuard)` is
534 /// inserted to keep the fake borrows alive until that point.
535 ///
536 /// This should ensure that you cannot change the variant for an enum while
537 /// you are in the midst of matching on it.
538 ForMatchGuard,
539
540 /// Fake read of the scrutinee of a `match` or destructuring `let`
541 /// (i.e. `let` with non-trivial pattern).
542 ///
543 /// In `match x { ... }`, we generate a `FakeRead(ForMatchedPlace, x)`
544 /// and insert it into the `otherwise_block` (which is supposed to be
545 /// unreachable for irrefutable pattern-matches like `match` or `let`).
546 ///
547 /// This is necessary because `let x: !; match x {}` doesn't generate any
548 /// actual read of x, so we need to generate a `FakeRead` to check that it
549 /// is initialized.
550 ///
551 /// If the `FakeRead(ForMatchedPlace)` is being performed with a closure
552 /// that doesn't capture the required upvars, the `FakeRead` within the
553 /// closure is omitted entirely.
554 ///
555 /// To make sure that this is still sound, if a closure matches against
556 /// a Place starting with an Upvar, we hoist the `FakeRead` to the
557 /// definition point of the closure.
558 ///
559 /// If the `FakeRead` comes from being hoisted out of a closure like this,
560 /// we record the `LocalDefId` of the closure. Otherwise, the `Option` will be `None`.
561 //
562 // We can use LocalDefId here since fake read statements are removed
563 // before codegen in the `CleanupNonCodegenStatements` pass.
564 ForMatchedPlace(Option<LocalDefId>),
565
566 /// A fake read injected into a match guard to ensure that the places
567 /// bound by the pattern are immutable for the duration of the match guard.
568 ///
569 /// Within a match guard, references are created for each place that the
570 /// pattern creates a binding for — this is known as the `RefWithinGuard`
571 /// version of the variables. To make sure that the references stay
572 /// alive until the end of the match guard, and properly prevent the
573 /// places in question from being modified, a `FakeRead(ForGuardBinding)`
574 /// is inserted at the end of the match guard.
575 ///
576 /// For details on how these references are created, see the extensive
577 /// documentation on `bind_matched_candidate_for_guard` in
578 /// `rustc_mir_build`.
579 ForGuardBinding,
580
581 /// Officially, the semantics of
582 ///
583 /// `let pattern = <expr>;`
584 ///
585 /// is that `<expr>` is evaluated into a temporary and then this temporary is
586 /// into the pattern.
587 ///
588 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
589 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
590 /// but in some cases it can affect the borrow checker, as in #53695.
591 ///
592 /// Therefore, we insert a `FakeRead(ForLet)` immediately after each `let`
593 /// with a trivial pattern.
594 ///
595 /// FIXME: `ExprUseVisitor` has an entirely different opinion on what `FakeRead(ForLet)`
596 /// is supposed to mean. If it was accurate to what MIR lowering does,
597 /// would it even make sense to hoist these out of closures like
598 /// `ForMatchedPlace`?
599 ForLet(Option<LocalDefId>),
600
601 /// Currently, index expressions overloaded through the `Index` trait
602 /// get lowered differently than index expressions with builtin semantics
603 /// for arrays and slices — the latter will emit code to perform
604 /// bound checks, and then return a MIR place that will only perform the
605 /// indexing "for real" when it gets incorporated into an instruction.
606 ///
607 /// This is observable in the fact that the following compiles:
608 ///
609 /// ```
610 /// fn f(x: &mut [&mut [u32]], i: usize) {
611 /// x[i][x[i].len() - 1] += 1;
612 /// }
613 /// ```
614 ///
615 /// However, we need to be careful to not let the user invalidate the
616 /// bound check with an expression like
617 ///
618 /// `(*x)[1][{ x = y; 4}]`
619 ///
620 /// Here, the first bounds check would be invalidated when we evaluate the
621 /// second index expression. To make sure that this doesn't happen, we
622 /// create a fake borrow of `x` and hold it while we evaluate the second
623 /// index.
624 ///
625 /// This borrow is kept alive by a `FakeRead(ForIndex)` at the end of its
626 /// scope.
627 ForIndex,
628}
629
630#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
631#[derive(TypeFoldable, TypeVisitable)]
632pub struct CopyNonOverlapping<'tcx> {
633 pub src: Operand<'tcx>,
634 pub dst: Operand<'tcx>,
635 /// Number of elements to copy from src to dest, not bytes.
636 pub count: Operand<'tcx>,
637}
638
639/// Represents how a [`TerminatorKind::Call`] was constructed.
640/// Used only for diagnostics.
641#[derive(Clone, Copy, TyEncodable, TyDecodable, Debug, PartialEq, Hash, HashStable)]
642#[derive(TypeFoldable, TypeVisitable)]
643pub enum CallSource {
644 /// This came from something such as `a > b` or `a + b`. In THIR, if `from_hir_call`
645 /// is false then this is the desugaring.
646 OverloadedOperator,
647 /// This was from comparison generated by a match, used by const-eval for better errors
648 /// when the comparison cannot be done in compile time.
649 ///
650 /// (see <https://github.com/rust-lang/rust/issues/90237>)
651 MatchCmp,
652 /// Other types of desugaring that did not come from the HIR, but we don't care about
653 /// for diagnostics (yet).
654 Misc,
655 /// Use of value, generating a clone function call
656 Use,
657 /// Normal function call, no special source
658 Normal,
659}
660
661#[derive(Clone, Copy, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
662#[derive(TypeFoldable, TypeVisitable)]
663/// The macro that an inline assembly block was created by
664pub enum InlineAsmMacro {
665 /// The `asm!` macro
666 Asm,
667 /// The `naked_asm!` macro
668 NakedAsm,
669}
670
671///////////////////////////////////////////////////////////////////////////
672// Terminators
673
674/// The various kinds of terminators, representing ways of exiting from a basic block.
675///
676/// A note on unwinding: Panics may occur during the execution of some terminators. Depending on the
677/// `-C panic` flag, this may either cause the program to abort or the call stack to unwind. Such
678/// terminators have a `unwind: UnwindAction` field on them. If stack unwinding occurs, then
679/// once the current function is reached, an action will be taken based on the `unwind` field.
680/// If the action is `Cleanup`, then the execution continues at the given basic block. If the
681/// action is `Continue` then no cleanup is performed, and the stack continues unwinding.
682///
683/// The basic block pointed to by a `Cleanup` unwind action must have its `cleanup` flag set.
684/// `cleanup` basic blocks have a couple restrictions:
685/// 1. All `unwind` fields in them must be `UnwindAction::Terminate` or `UnwindAction::Unreachable`.
686/// 2. `Return` terminators are not allowed in them. `Terminate` and `Resume` terminators are.
687/// 3. All other basic blocks (in the current body) that are reachable from `cleanup` basic blocks
688/// must also be `cleanup`. This is a part of the type system and checked statically, so it is
689/// still an error to have such an edge in the CFG even if it's known that it won't be taken at
690/// runtime.
691/// 4. The control flow between cleanup blocks must look like an upside down tree. Roughly
692/// speaking, this means that control flow that looks like a V is allowed, while control flow
693/// that looks like a W is not. This is necessary to ensure that landing pad information can be
694/// correctly codegened on MSVC. More precisely:
695///
696/// Begin with the standard control flow graph `G`. Modify `G` as follows: for any two cleanup
697/// vertices `u` and `v` such that `u` dominates `v`, contract `u` and `v` into a single vertex,
698/// deleting self edges and duplicate edges in the process. Now remove all vertices from `G`
699/// that are not cleanup vertices or are not reachable. The resulting graph must be an inverted
700/// tree, that is each vertex may have at most one successor and there may be no cycles.
701#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
702pub enum TerminatorKind<'tcx> {
703 /// Block has one successor; we continue execution there.
704 Goto { target: BasicBlock },
705
706 /// Switches based on the computed value.
707 ///
708 /// First, evaluates the `discr` operand. The type of the operand must be a signed or unsigned
709 /// integer, char, or bool, and must match the given type. Then, if the list of switch targets
710 /// contains the computed value, continues execution at the associated basic block. Otherwise,
711 /// continues execution at the "otherwise" basic block.
712 ///
713 /// Target values may not appear more than once.
714 SwitchInt {
715 /// The discriminant value being tested.
716 discr: Operand<'tcx>,
717 targets: SwitchTargets,
718 },
719
720 /// Indicates that the landing pad is finished and that the process should continue unwinding.
721 ///
722 /// Like a return, this marks the end of this invocation of the function.
723 ///
724 /// Only permitted in cleanup blocks. `Resume` is not permitted with `-C unwind=abort` after
725 /// deaggregation runs.
726 UnwindResume,
727
728 /// Indicates that the landing pad is finished and that the process should terminate.
729 ///
730 /// Used to prevent unwinding for foreign items or with `-C unwind=abort`. Only permitted in
731 /// cleanup blocks.
732 UnwindTerminate(UnwindTerminateReason),
733
734 /// Returns from the function.
735 ///
736 /// Like function calls, the exact semantics of returns in Rust are unclear. Returning very
737 /// likely at least assigns the value currently in the return place (`_0`) to the place
738 /// specified in the associated `Call` terminator in the calling function, as if assigned via
739 /// `dest = move _0`. It might additionally do other things, like have side-effects in the
740 /// aliasing model.
741 ///
742 /// If the body is a coroutine body, this has slightly different semantics; it instead causes a
743 /// `CoroutineState::Returned(_0)` to be created (as if by an `Aggregate` rvalue) and assigned
744 /// to the return place.
745 Return,
746
747 /// Indicates a terminator that can never be reached.
748 ///
749 /// Executing this terminator is UB.
750 Unreachable,
751
752 /// The behavior of this statement differs significantly before and after drop elaboration.
753 ///
754 /// After drop elaboration: `Drop` terminators are a complete nop for types that have no drop
755 /// glue. For other types, `Drop` terminators behave exactly like a call to
756 /// `core::mem::drop_in_place` with a pointer to the given place.
757 ///
758 /// `Drop` before drop elaboration is a *conditional* execution of the drop glue. Specifically,
759 /// the `Drop` will be executed if...
760 ///
761 /// **Needs clarification**: End of that sentence. This in effect should document the exact
762 /// behavior of drop elaboration. The following sounds vaguely right, but I'm not quite sure:
763 ///
764 /// > The drop glue is executed if, among all statements executed within this `Body`, an assignment to
765 /// > the place or one of its "parents" occurred more recently than a move out of it. This does not
766 /// > consider indirect assignments.
767 ///
768 /// The `replace` flag indicates whether this terminator was created as part of an assignment.
769 /// This should only be used for diagnostic purposes, and does not have any operational
770 /// meaning.
771 ///
772 /// Async drop processing:
773 /// In compiler/rustc_mir_build/src/build/scope.rs we detect possible async drop:
774 /// drop of object with `needs_async_drop`.
775 /// Async drop later, in StateTransform pass, may be expanded into additional yield-point
776 /// for poll-loop of async drop future.
777 /// So we need prepared 'drop' target block in the similar way as for `Yield` terminator
778 /// (see `drops.build_mir::<CoroutineDrop>` in scopes.rs).
779 /// In compiler/rustc_mir_transform/src/elaborate_drops.rs for object implementing `AsyncDrop` trait
780 /// we need to prepare async drop feature - resolve `AsyncDrop::drop` and codegen call.
781 /// `async_fut` is set to the corresponding local.
782 /// For coroutine drop we don't need this logic because coroutine drop works with the same
783 /// layout object as coroutine itself. So `async_fut` will be `None` for coroutine drop.
784 /// Both `drop` and `async_fut` fields are only used in compiler/rustc_mir_transform/src/coroutine.rs,
785 /// StateTransform pass. In `expand_async_drops` async drops are expanded
786 /// into one or two yield points with poll ready/pending switch.
787 /// When a coroutine has any internal async drop, the coroutine drop function will be async
788 /// (generated by `create_coroutine_drop_shim_async`, not `create_coroutine_drop_shim`).
789 Drop {
790 place: Place<'tcx>,
791 target: BasicBlock,
792 unwind: UnwindAction,
793 replace: bool,
794 /// Cleanup to be done if the coroutine is dropped at this suspend point (for async drop).
795 drop: Option<BasicBlock>,
796 /// Prepared async future local (for async drop)
797 async_fut: Option<Local>,
798 },
799
800 /// Roughly speaking, evaluates the `func` operand and the arguments, and starts execution of
801 /// the referred to function. The operand types must match the argument types of the function.
802 /// The return place type must match the return type. The type of the `func` operand must be
803 /// callable, meaning either a function pointer, a function type, or a closure type.
804 ///
805 /// **Needs clarification**: The exact semantics of this. Current backends rely on `move`
806 /// operands not aliasing the return place. It is unclear how this is justified in MIR, see
807 /// [#71117].
808 ///
809 /// [#71117]: https://github.com/rust-lang/rust/issues/71117
810 Call {
811 /// The function that’s being called.
812 func: Operand<'tcx>,
813 /// Arguments the function is called with.
814 /// These are owned by the callee, which is free to modify them.
815 /// This allows the memory occupied by "by-value" arguments to be
816 /// reused across function calls without duplicating the contents.
817 /// The span for each arg is also included
818 /// (e.g. `a` and `b` in `x.foo(a, b)`).
819 args: Box<[Spanned<Operand<'tcx>>]>,
820 /// Where the returned value will be written
821 destination: Place<'tcx>,
822 /// Where to go after this call returns. If none, the call necessarily diverges.
823 target: Option<BasicBlock>,
824 /// Action to be taken if the call unwinds.
825 unwind: UnwindAction,
826 /// Where this call came from in HIR/THIR.
827 call_source: CallSource,
828 /// This `Span` is the span of the function, without the dot and receiver
829 /// e.g. `foo(a, b)` in `x.foo(a, b)`
830 fn_span: Span,
831 },
832
833 /// Tail call.
834 ///
835 /// Roughly speaking this is a chimera of [`Call`] and [`Return`], with some caveats.
836 /// Semantically tail calls consists of two actions:
837 /// - pop of the current stack frame
838 /// - a call to the `func`, with the return address of the **current** caller
839 /// - so that a `return` inside `func` returns to the caller of the caller
840 /// of the function that is currently being executed
841 ///
842 /// Note that in difference with [`Call`] this is missing
843 /// - `destination` (because it's always the return place)
844 /// - `target` (because it's always taken from the current stack frame)
845 /// - `unwind` (because it's always taken from the current stack frame)
846 ///
847 /// [`Call`]: TerminatorKind::Call
848 /// [`Return`]: TerminatorKind::Return
849 TailCall {
850 /// The function that’s being called.
851 func: Operand<'tcx>,
852 /// Arguments the function is called with.
853 /// These are owned by the callee, which is free to modify them.
854 /// This allows the memory occupied by "by-value" arguments to be
855 /// reused across function calls without duplicating the contents.
856 args: Box<[Spanned<Operand<'tcx>>]>,
857 // FIXME(explicit_tail_calls): should we have the span for `become`? is this span accurate? do we need it?
858 /// This `Span` is the span of the function, without the dot and receiver
859 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
860 fn_span: Span,
861 },
862
863 /// Evaluates the operand, which must have type `bool`. If it is not equal to `expected`,
864 /// initiates a panic. Initiating a panic corresponds to a `Call` terminator with some
865 /// unspecified constant as the function to call, all the operands stored in the `AssertMessage`
866 /// as parameters, and `None` for the destination. Keep in mind that the `cleanup` path is not
867 /// necessarily executed even in the case of a panic, for example in `-C panic=abort`. If the
868 /// assertion does not fail, execution continues at the specified basic block.
869 ///
870 /// When overflow checking is disabled and this is run-time MIR (as opposed to compile-time MIR
871 /// that is used for CTFE), the following variants of this terminator behave as `goto target`:
872 /// - `OverflowNeg(..)`,
873 /// - `Overflow(op, ..)` if op is add, sub, mul, shl, shr, but NOT div or rem.
874 Assert {
875 cond: Operand<'tcx>,
876 expected: bool,
877 msg: Box<AssertMessage<'tcx>>,
878 target: BasicBlock,
879 unwind: UnwindAction,
880 },
881
882 /// Marks a suspend point.
883 ///
884 /// Like `Return` terminators in coroutine bodies, this computes `value` and then a
885 /// `CoroutineState::Yielded(value)` as if by `Aggregate` rvalue. That value is then assigned to
886 /// the return place of the function calling this one, and execution continues in the calling
887 /// function. When next invoked with the same first argument, execution of this function
888 /// continues at the `resume` basic block, with the second argument written to the `resume_arg`
889 /// place. If the coroutine is dropped before then, the `drop` basic block is invoked.
890 ///
891 /// Note that coroutines can be (unstably) cloned under certain conditions, which means that
892 /// this terminator can **return multiple times**! MIR optimizations that reorder code into
893 /// different basic blocks needs to be aware of that.
894 /// See <https://github.com/rust-lang/rust/issues/95360>.
895 ///
896 /// Not permitted in bodies that are not coroutine bodies, or after coroutine lowering.
897 ///
898 /// **Needs clarification**: What about the evaluation order of the `resume_arg` and `value`?
899 Yield {
900 /// The value to return.
901 value: Operand<'tcx>,
902 /// Where to resume to.
903 resume: BasicBlock,
904 /// The place to store the resume argument in.
905 resume_arg: Place<'tcx>,
906 /// Cleanup to be done if the coroutine is dropped at this suspend point.
907 drop: Option<BasicBlock>,
908 },
909
910 /// Indicates the end of dropping a coroutine.
911 ///
912 /// Semantically just a `return` (from the coroutines drop glue). Only permitted in the same situations
913 /// as `yield`.
914 ///
915 /// **Needs clarification**: Is that even correct? The coroutine drop code is always confusing
916 /// to me, because it's not even really in the current body.
917 ///
918 /// **Needs clarification**: Are there type system constraints on these terminators? Should
919 /// there be a "block type" like `cleanup` blocks for them?
920 CoroutineDrop,
921
922 /// A block where control flow only ever takes one real path, but borrowck needs to be more
923 /// conservative.
924 ///
925 /// At runtime this is semantically just a goto.
926 ///
927 /// Disallowed after drop elaboration.
928 FalseEdge {
929 /// The target normal control flow will take.
930 real_target: BasicBlock,
931 /// A block control flow could conceptually jump to, but won't in
932 /// practice.
933 imaginary_target: BasicBlock,
934 },
935
936 /// A terminator for blocks that only take one path in reality, but where we reserve the right
937 /// to unwind in borrowck, even if it won't happen in practice. This can arise in infinite loops
938 /// with no function calls for example.
939 ///
940 /// At runtime this is semantically just a goto.
941 ///
942 /// Disallowed after drop elaboration.
943 FalseUnwind {
944 /// The target normal control flow will take.
945 real_target: BasicBlock,
946 /// The imaginary cleanup block link. This particular path will never be taken
947 /// in practice, but in order to avoid fragility we want to always
948 /// consider it in borrowck. We don't want to accept programs which
949 /// pass borrowck only when `panic=abort` or some assertions are disabled
950 /// due to release vs. debug mode builds.
951 unwind: UnwindAction,
952 },
953
954 /// Block ends with an inline assembly block. This is a terminator since
955 /// inline assembly is allowed to diverge.
956 InlineAsm {
957 /// Macro used to create this inline asm: one of `asm!` or `naked_asm!`
958 asm_macro: InlineAsmMacro,
959
960 /// The template for the inline assembly, with placeholders.
961 #[type_foldable(identity)]
962 #[type_visitable(ignore)]
963 template: &'tcx [InlineAsmTemplatePiece],
964
965 /// The operands for the inline assembly, as `Operand`s or `Place`s.
966 operands: Box<[InlineAsmOperand<'tcx>]>,
967
968 /// Miscellaneous options for the inline assembly.
969 options: InlineAsmOptions,
970
971 /// Source spans for each line of the inline assembly code. These are
972 /// used to map assembler errors back to the line in the source code.
973 #[type_foldable(identity)]
974 #[type_visitable(ignore)]
975 line_spans: &'tcx [Span],
976
977 /// Valid targets for the inline assembly.
978 /// The first element is the fallthrough destination, unless
979 /// asm_macro == InlineAsmMacro::NakedAsm or InlineAsmOptions::NORETURN is set.
980 targets: Box<[BasicBlock]>,
981
982 /// Action to be taken if the inline assembly unwinds. This is present
983 /// if and only if InlineAsmOptions::MAY_UNWIND is set.
984 unwind: UnwindAction,
985 },
986}
987
988#[derive(
989 Clone,
990 Debug,
991 TyEncodable,
992 TyDecodable,
993 Hash,
994 HashStable,
995 PartialEq,
996 TypeFoldable,
997 TypeVisitable
998)]
999pub enum BackwardIncompatibleDropReason {
1000 Edition2024,
1001}
1002
1003#[derive(Debug, Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
1004pub struct SwitchTargets {
1005 /// Possible values. For each value, the location to branch to is found in
1006 /// the corresponding element in the `targets` vector.
1007 pub(super) values: SmallVec<[Pu128; 1]>,
1008
1009 /// Possible branch targets. The last element of this vector is used for
1010 /// the "otherwise" branch, so `targets.len() == values.len() + 1` always
1011 /// holds.
1012 //
1013 // Note: This invariant is non-obvious and easy to violate. This would be a
1014 // more rigorous representation:
1015 //
1016 // normal: SmallVec<[(Pu128, BasicBlock); 1]>,
1017 // otherwise: BasicBlock,
1018 //
1019 // But it's important to have the targets in a sliceable type, because
1020 // target slices show up elsewhere. E.g. `TerminatorKind::InlineAsm` has a
1021 // boxed slice, and `TerminatorKind::FalseEdge` has a single target that
1022 // can be converted to a slice with `slice::from_ref`.
1023 //
1024 // Why does this matter? In functions like `TerminatorKind::successors` we
1025 // return `impl Iterator` and a non-slice-of-targets representation here
1026 // causes problems because multiple different concrete iterator types would
1027 // be involved and we would need a boxed trait object, which requires an
1028 // allocation, which is expensive if done frequently.
1029 pub(super) targets: SmallVec<[BasicBlock; 2]>,
1030}
1031
1032/// Action to be taken when a stack unwind happens.
1033#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1034#[derive(TypeFoldable, TypeVisitable)]
1035pub enum UnwindAction {
1036 /// No action is to be taken. Continue unwinding.
1037 ///
1038 /// This is similar to `Cleanup(bb)` where `bb` does nothing but `Resume`, but they are not
1039 /// equivalent, as presence of `Cleanup(_)` will make a frame non-POF.
1040 Continue,
1041 /// Triggers undefined behavior if unwind happens.
1042 Unreachable,
1043 /// Terminates the execution if unwind happens.
1044 ///
1045 /// Depending on the platform and situation this may cause a non-unwindable panic or abort.
1046 Terminate(UnwindTerminateReason),
1047 /// Cleanups to be done.
1048 Cleanup(BasicBlock),
1049}
1050
1051/// The reason we are terminating the process during unwinding.
1052#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1053#[derive(TypeFoldable, TypeVisitable)]
1054pub enum UnwindTerminateReason {
1055 /// Unwinding is just not possible given the ABI of this function.
1056 Abi,
1057 /// We were already cleaning up for an ongoing unwind, and a *second*, *nested* unwind was
1058 /// triggered by the drop glue.
1059 InCleanup,
1060}
1061
1062/// Information about an assertion failure.
1063#[derive(Clone, Hash, HashStable, PartialEq, Debug)]
1064#[derive(TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
1065pub enum AssertKind<O> {
1066 BoundsCheck { len: O, index: O },
1067 Overflow(BinOp, O, O),
1068 OverflowNeg(O),
1069 DivisionByZero(O),
1070 RemainderByZero(O),
1071 ResumedAfterReturn(CoroutineKind),
1072 ResumedAfterPanic(CoroutineKind),
1073 ResumedAfterDrop(CoroutineKind),
1074 MisalignedPointerDereference { required: O, found: O },
1075 NullPointerDereference,
1076 InvalidEnumConstruction(O),
1077}
1078
1079#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
1080#[derive(TypeFoldable, TypeVisitable)]
1081pub enum InlineAsmOperand<'tcx> {
1082 In {
1083 reg: InlineAsmRegOrRegClass,
1084 value: Operand<'tcx>,
1085 },
1086 Out {
1087 reg: InlineAsmRegOrRegClass,
1088 late: bool,
1089 place: Option<Place<'tcx>>,
1090 },
1091 InOut {
1092 reg: InlineAsmRegOrRegClass,
1093 late: bool,
1094 in_value: Operand<'tcx>,
1095 out_place: Option<Place<'tcx>>,
1096 },
1097 Const {
1098 value: Box<ConstOperand<'tcx>>,
1099 },
1100 SymFn {
1101 value: Box<ConstOperand<'tcx>>,
1102 },
1103 SymStatic {
1104 def_id: DefId,
1105 },
1106 Label {
1107 /// This represents the index into the `targets` array in `TerminatorKind::InlineAsm`.
1108 target_index: usize,
1109 },
1110}
1111
1112/// Type for MIR `Assert` terminator error messages.
1113pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1114
1115///////////////////////////////////////////////////////////////////////////
1116// Places
1117
1118/// Places roughly correspond to a "location in memory." Places in MIR are the same mathematical
1119/// object as places in Rust. This of course means that what exactly they are is undecided and part
1120/// of the Rust memory model. However, they will likely contain at least the following pieces of
1121/// information in some form:
1122///
1123/// 1. The address in memory that the place refers to.
1124/// 2. The provenance with which the place is being accessed.
1125/// 3. The type of the place and an optional variant index. See [`PlaceTy`][super::PlaceTy].
1126/// 4. Optionally, some metadata. This exists if and only if the type of the place is not `Sized`.
1127///
1128/// We'll give a description below of how all pieces of the place except for the provenance are
1129/// calculated. We cannot give a description of the provenance, because that is part of the
1130/// undecided aliasing model - we only include it here at all to acknowledge its existence.
1131///
1132/// Each local naturally corresponds to the place `Place { local, projection: [] }`. This place has
1133/// the address of the local's allocation and the type of the local.
1134///
1135/// For places that are not locals, ie they have a non-empty list of projections, we define the
1136/// values as a function of the parent place, that is the place with its last [`ProjectionElem`]
1137/// stripped. The way this is computed of course depends on the kind of that last projection
1138/// element:
1139///
1140/// - [`Downcast`](ProjectionElem::Downcast): This projection sets the place's variant index to the
1141/// given one, and makes no other changes. A `Downcast` projection must always be followed
1142/// immediately by a `Field` projection.
1143/// - [`Field`](ProjectionElem::Field): `Field` projections take their parent place and create a
1144/// place referring to one of the fields of the type. The resulting address is the parent
1145/// address, plus the offset of the field. The type becomes the type of the field. If the parent
1146/// was unsized and so had metadata associated with it, then the metadata is retained if the
1147/// field is unsized and thrown out if it is sized.
1148///
1149/// These projections are only legal for tuples, ADTs, closures, and coroutines. If the ADT or
1150/// coroutine has more than one variant, the parent place's variant index must be set, indicating
1151/// which variant is being used. If it has just one variant, the variant index may or may not be
1152/// included - the single possible variant is inferred if it is not included.
1153/// - [`OpaqueCast`](ProjectionElem::OpaqueCast): This projection changes the place's type to the
1154/// given one, and makes no other changes. A `OpaqueCast` projection on any type other than an
1155/// opaque type from the current crate is not well-formed.
1156/// - [`ConstantIndex`](ProjectionElem::ConstantIndex): Computes an offset in units of `T` into the
1157/// place as described in the documentation for the `ProjectionElem`. The resulting address is
1158/// the parent's address plus that offset, and the type is `T`. This is only legal if the parent
1159/// place has type `[T; N]` or `[T]` (*not* `&[T]`). Since such a `T` is always sized, any
1160/// resulting metadata is thrown out.
1161/// - [`Subslice`](ProjectionElem::Subslice): This projection calculates an offset and a new
1162/// address in a similar manner as `ConstantIndex`. It is also only legal on `[T; N]` and `[T]`.
1163/// However, this yields a `Place` of type `[T]`, and additionally sets the metadata to be the
1164/// length of the subslice.
1165/// - [`Index`](ProjectionElem::Index): Like `ConstantIndex`, only legal on `[T; N]` or `[T]`.
1166/// However, `Index` additionally takes a local from which the value of the index is computed at
1167/// runtime. Computing the value of the index involves interpreting the `Local` as a
1168/// `Place { local, projection: [] }`, and then computing its value as if done via
1169/// [`Operand::Copy`]. The array/slice is then indexed with the resulting value. The local must
1170/// have type `usize`.
1171/// - [`Deref`](ProjectionElem::Deref): Derefs are the last type of projection, and the most
1172/// complicated. They are only legal on parent places that are references, pointers, or `Box`. A
1173/// `Deref` projection begins by loading a value from the parent place, as if by
1174/// [`Operand::Copy`]. It then dereferences the resulting pointer, creating a place of the
1175/// pointee's type. The resulting address is the address that was stored in the pointer. If the
1176/// pointee type is unsized, the pointer additionally stored the value of the metadata.
1177///
1178/// The "validity invariant" of places is the same as that of raw pointers, meaning that e.g.
1179/// `*ptr` on a dangling or unaligned pointer is never UB. (Later doing a load/store on that place
1180/// or turning it into a reference can be UB though!) The only ways for a place computation can
1181/// cause UB are:
1182/// - On a `Deref` projection, we do an actual load of the inner place, with all the usual
1183/// consequences (the inner place must be based on an aligned pointer, it must point to allocated
1184/// memory, the aliasig model must allow reads, this must not be a data race).
1185/// - For the projections that perform pointer arithmetic, the offset must in-bounds of an
1186/// allocation (i.e., the preconditions of `ptr::offset` must be met).
1187#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, HashStable, TypeFoldable, TypeVisitable)]
1188pub struct Place<'tcx> {
1189 pub local: Local,
1190
1191 /// projection out of a place (access a field, deref a pointer, etc)
1192 pub projection: &'tcx List<PlaceElem<'tcx>>,
1193}
1194
1195#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1196#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1197pub enum ProjectionElem<V, T> {
1198 Deref,
1199
1200 /// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
1201 /// rustc can identify that a field projection refers to either two different regions of memory
1202 /// or the same one between the base and the 'projection element'.
1203 /// Read more about projections in the [rustc-dev-guide][mir-datatypes]
1204 ///
1205 /// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
1206 Field(FieldIdx, T),
1207
1208 /// Index into a slice/array.
1209 ///
1210 /// Note that this does not also dereference, and so it does not exactly correspond to slice
1211 /// indexing in Rust. In other words, in the below Rust code:
1212 ///
1213 /// ```rust
1214 /// let x = &[1, 2, 3, 4];
1215 /// let i = 2;
1216 /// x[i];
1217 /// ```
1218 ///
1219 /// The `x[i]` is turned into a `Deref` followed by an `Index`, not just an `Index`. The same
1220 /// thing is true of the `ConstantIndex` and `Subslice` projections below.
1221 Index(V),
1222
1223 /// These indices are generated by slice patterns. Easiest to explain
1224 /// by example:
1225 ///
1226 /// ```ignore (illustrative)
1227 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1228 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1229 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1230 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1231 /// ```
1232 ConstantIndex {
1233 /// index or -index (in Python terms), depending on from_end
1234 offset: u64,
1235 /// The thing being indexed must be at least this long -- otherwise, the
1236 /// projection is UB.
1237 ///
1238 /// For arrays this is always the exact length.
1239 min_length: u64,
1240 /// Counting backwards from end? This is always false when indexing an
1241 /// array.
1242 from_end: bool,
1243 },
1244
1245 /// These indices are generated by slice patterns.
1246 ///
1247 /// If `from_end` is true `slice[from..slice.len() - to]`.
1248 /// Otherwise `array[from..to]`.
1249 Subslice {
1250 from: u64,
1251 to: u64,
1252 /// Whether `to` counts from the start or end of the array/slice.
1253 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1254 /// For `ProjectionKind`, this can also be `true` for arrays.
1255 from_end: bool,
1256 },
1257
1258 /// "Downcast" to a variant of an enum or a coroutine.
1259 ///
1260 /// The included Symbol is the name of the variant, used for printing MIR.
1261 ///
1262 /// This operation itself is never UB, all it does is change the type of the place.
1263 Downcast(Option<Symbol>, VariantIdx),
1264
1265 /// Like an explicit cast from an opaque type to a concrete type, but without
1266 /// requiring an intermediate variable.
1267 ///
1268 /// This is unused with `-Znext-solver`.
1269 OpaqueCast(T),
1270
1271 /// A transmute from an unsafe binder to the type that it wraps. This is a projection
1272 /// of a place, so it doesn't necessarily constitute a move out of the binder.
1273 UnwrapUnsafeBinder(T),
1274}
1275
1276/// Alias for projections as they appear in places, where the base is a place
1277/// and the index is a local.
1278pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1279
1280///////////////////////////////////////////////////////////////////////////
1281// Operands
1282
1283/// An operand in MIR represents a "value" in Rust, the definition of which is undecided and part of
1284/// the memory model. One proposal for a definition of values can be found [on UCG][value-def].
1285///
1286/// [value-def]: https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/value-domain.md
1287///
1288/// The most common way to create values is via loading a place. Loading a place is an operation
1289/// which reads the memory of the place and converts it to a value. This is a fundamentally *typed*
1290/// operation. The nature of the value produced depends on the type of the conversion. Furthermore,
1291/// there may be other effects: if the type has a validity constraint loading the place might be UB
1292/// if the validity constraint is not met.
1293///
1294/// **Needs clarification:** Is loading a place that has its variant index set well-formed? Miri
1295/// currently implements it, but it seems like this may be something to check against in the
1296/// validator.
1297#[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable, TypeVisitable)]
1298pub enum Operand<'tcx> {
1299 /// Creates a value by loading the given place.
1300 ///
1301 /// Before drop elaboration, the type of the place must be `Copy`. After drop elaboration there
1302 /// is no such requirement.
1303 Copy(Place<'tcx>),
1304
1305 /// Creates a value by performing loading the place, just like the `Copy` operand.
1306 ///
1307 /// This *may* additionally overwrite the place with `uninit` bytes, depending on how we decide
1308 /// in [UCG#188]. You should not emit MIR that may attempt a subsequent second load of this
1309 /// place without first re-initializing it.
1310 ///
1311 /// **Needs clarification:** The operational impact of `Move` is unclear. Currently (both in
1312 /// Miri and codegen) it has no effect at all unless it appears in an argument to `Call`; for
1313 /// `Call` it allows the argument to be passed to the callee "in-place", i.e. the callee might
1314 /// just get a reference to this place instead of a full copy. Miri implements this with a
1315 /// combination of aliasing model "protectors" and putting `uninit` into the place. Ralf
1316 /// proposes that we don't want these semantics for `Move` in regular assignments, because
1317 /// loading a place should not have side-effects, and the aliasing model "protectors" are
1318 /// inherently tied to a function call. Are these the semantics we want for MIR? Is this
1319 /// something we can even decide without knowing more about Rust's memory model?
1320 ///
1321 /// [UCG#188]: https://github.com/rust-lang/unsafe-code-guidelines/issues/188
1322 Move(Place<'tcx>),
1323
1324 /// Constants are already semantically values, and remain unchanged.
1325 Constant(Box<ConstOperand<'tcx>>),
1326}
1327
1328#[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
1329#[derive(TypeFoldable, TypeVisitable)]
1330pub struct ConstOperand<'tcx> {
1331 pub span: Span,
1332
1333 /// Optional user-given type: for something like
1334 /// `collect::<Vec<_>>`, this would be present and would
1335 /// indicate that `Vec<_>` was explicitly specified.
1336 ///
1337 /// Needed for NLL to impose user-given type constraints.
1338 pub user_ty: Option<UserTypeAnnotationIndex>,
1339
1340 pub const_: Const<'tcx>,
1341}
1342
1343///////////////////////////////////////////////////////////////////////////
1344// Rvalues
1345
1346/// The various kinds of rvalues that can appear in MIR.
1347///
1348/// Not all of these are allowed at every [`MirPhase`] - when this is the case, it's stated below.
1349///
1350/// Computing any rvalue begins by evaluating the places and operands in some order (**Needs
1351/// clarification**: Which order?). These are then used to produce a "value" - the same kind of
1352/// value that an [`Operand`] produces.
1353#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
1354pub enum Rvalue<'tcx> {
1355 /// Yields the operand unchanged
1356 Use(Operand<'tcx>),
1357
1358 /// Creates an array where each element is the value of the operand.
1359 ///
1360 /// Corresponds to source code like `[x; 32]`.
1361 Repeat(Operand<'tcx>, ty::Const<'tcx>),
1362
1363 /// Creates a reference of the indicated kind to the place.
1364 ///
1365 /// There is not much to document here, because besides the obvious parts the semantics of this
1366 /// are essentially entirely a part of the aliasing model. There are many UCG issues discussing
1367 /// exactly what the behavior of this operation should be.
1368 ///
1369 /// `Shallow` borrows are disallowed after drop lowering.
1370 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1371
1372 /// Creates a pointer/reference to the given thread local.
1373 ///
1374 /// The yielded type is a `*mut T` if the static is mutable, otherwise if the static is extern a
1375 /// `*const T`, and if neither of those apply a `&T`.
1376 ///
1377 /// **Note:** This is a runtime operation that actually executes code and is in this sense more
1378 /// like a function call. Also, eliminating dead stores of this rvalue causes `fn main() {}` to
1379 /// SIGILL for some reason that I (JakobDegen) never got a chance to look into.
1380 ///
1381 /// **Needs clarification**: Are there weird additional semantics here related to the runtime
1382 /// nature of this operation?
1383 ThreadLocalRef(DefId),
1384
1385 /// Creates a raw pointer with the indicated mutability to the place.
1386 ///
1387 /// This is generated by pointer casts like `&v as *const _` or raw borrow expressions like
1388 /// `&raw const v`.
1389 ///
1390 /// Like with references, the semantics of this operation are heavily dependent on the aliasing
1391 /// model.
1392 RawPtr(RawPtrKind, Place<'tcx>),
1393
1394 /// Performs essentially all of the casts that can be performed via `as`.
1395 ///
1396 /// This allows for casts from/to a variety of types.
1397 ///
1398 /// **FIXME**: Document exactly which `CastKind`s allow which types of casts.
1399 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1400
1401 /// * `Offset` has the same semantics as [`offset`](pointer::offset), except that the second
1402 /// parameter may be a `usize` as well.
1403 /// * The comparison operations accept `bool`s, `char`s, signed or unsigned integers, floats,
1404 /// raw pointers, or function pointers and return a `bool`. The types of the operands must be
1405 /// matching, up to the usual caveat of the lifetimes in function pointers.
1406 /// * Left and right shift operations accept signed or unsigned integers not necessarily of the
1407 /// same type and return a value of the same type as their LHS. Like in Rust, the RHS is
1408 /// truncated as needed.
1409 /// * The `Bit*` operations accept signed integers, unsigned integers, or bools with matching
1410 /// types and return a value of that type.
1411 /// * The `FooWithOverflow` are like the `Foo`, but returning `(T, bool)` instead of just `T`,
1412 /// where the `bool` is true if the result is not equal to the infinite-precision result.
1413 /// * The remaining operations accept signed integers, unsigned integers, or floats with
1414 /// matching types and return a value of that type.
1415 BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
1416
1417 /// Computes a value as described by the operation.
1418 NullaryOp(NullOp<'tcx>, Ty<'tcx>),
1419
1420 /// Exactly like `BinaryOp`, but less operands.
1421 ///
1422 /// Also does two's-complement arithmetic. Negation requires a signed integer or a float;
1423 /// bitwise not requires a signed integer, unsigned integer, or bool. Both operation kinds
1424 /// return a value with the same type as their operand.
1425 UnaryOp(UnOp, Operand<'tcx>),
1426
1427 /// Computes the discriminant of the place, returning it as an integer of type
1428 /// [`discriminant_ty`]. Returns zero for types without discriminant.
1429 ///
1430 /// The validity requirements for the underlying value are undecided for this rvalue, see
1431 /// [#91095]. Note too that the value of the discriminant is not the same thing as the
1432 /// variant index; use [`discriminant_for_variant`] to convert.
1433 ///
1434 /// [`discriminant_ty`]: crate::ty::Ty::discriminant_ty
1435 /// [#91095]: https://github.com/rust-lang/rust/issues/91095
1436 /// [`discriminant_for_variant`]: crate::ty::Ty::discriminant_for_variant
1437 Discriminant(Place<'tcx>),
1438
1439 /// Creates an aggregate value, like a tuple or struct.
1440 ///
1441 /// This is needed because dataflow analysis needs to distinguish
1442 /// `dest = Foo { x: ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case that `Foo`
1443 /// has a destructor.
1444 ///
1445 /// Disallowed after deaggregation for all aggregate kinds except `Array` and `Coroutine`. After
1446 /// coroutine lowering, `Coroutine` aggregate kinds are disallowed too.
1447 Aggregate(Box<AggregateKind<'tcx>>, IndexVec<FieldIdx, Operand<'tcx>>),
1448
1449 /// Transmutes a `*mut u8` into shallow-initialized `Box<T>`.
1450 ///
1451 /// This is different from a normal transmute because dataflow analysis will treat the box as
1452 /// initialized but its content as uninitialized. Like other pointer casts, this in general
1453 /// affects alias analysis.
1454 ShallowInitBox(Operand<'tcx>, Ty<'tcx>),
1455
1456 /// A CopyForDeref is equivalent to a read from a place at the
1457 /// codegen level, but is treated specially by drop elaboration. When such a read happens, it
1458 /// is guaranteed (via nature of the mir_opt `Derefer` in rustc_mir_transform/src/deref_separator)
1459 /// that the returned value is written into a `DerefTemp` local and that its only use is a deref operation,
1460 /// immediately followed by one or more projections. Drop elaboration treats this rvalue as if the
1461 /// read never happened and just projects further. This allows simplifying various MIR
1462 /// optimizations and codegen backends that previously had to handle deref operations anywhere
1463 /// in a place.
1464 ///
1465 /// Disallowed in runtime MIR and is replaced by normal copies.
1466 CopyForDeref(Place<'tcx>),
1467
1468 /// Wraps a value in an unsafe binder.
1469 WrapUnsafeBinder(Operand<'tcx>, Ty<'tcx>),
1470}
1471
1472#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1473pub enum CastKind {
1474 /// An exposing pointer to address cast. A cast between a pointer and an integer type, or
1475 /// between a function pointer and an integer type.
1476 /// See the docs on `expose_provenance` for more details.
1477 PointerExposeProvenance,
1478 /// An address-to-pointer cast that picks up an exposed provenance.
1479 /// See the docs on `with_exposed_provenance` for more details.
1480 PointerWithExposedProvenance,
1481 /// Pointer related casts that are done by coercions. Note that reference-to-raw-ptr casts are
1482 /// translated into `&raw mut/const *r`, i.e., they are not actually casts.
1483 ///
1484 /// The following are allowed in [`AnalysisPhase::Initial`] as they're needed for borrowck,
1485 /// but after that are forbidden (including in all phases of runtime MIR):
1486 /// * [`PointerCoercion::ArrayToPointer`]
1487 /// * [`PointerCoercion::MutToConstPointer`]
1488 ///
1489 /// Both are runtime nops, so should be [`CastKind::PtrToPtr`] instead in runtime MIR.
1490 PointerCoercion(PointerCoercion, CoercionSource),
1491 IntToInt,
1492 FloatToInt,
1493 FloatToFloat,
1494 IntToFloat,
1495 PtrToPtr,
1496 FnPtrToPtr,
1497 /// Reinterpret the bits of the input as a different type.
1498 ///
1499 /// MIR is well-formed if the input and output types have different sizes,
1500 /// but running a transmute between differently-sized types is UB.
1501 Transmute,
1502
1503 /// A `Subtype` cast is applied to any `StatementKind::Assign` where
1504 /// type of lvalue doesn't match the type of rvalue, the primary goal is making subtyping
1505 /// explicit during optimizations and codegen.
1506 ///
1507 /// This cast doesn't impact the runtime behavior of the program except for potentially changing
1508 /// some type metadata of the interpreter or codegen backend.
1509 ///
1510 /// This goal is achieved with mir_transform pass `Subtyper`, which runs right after
1511 /// borrowchecker, as we only care about subtyping that can affect trait selection and
1512 /// `TypeId`.
1513 Subtype,
1514}
1515
1516/// Represents how a [`CastKind::PointerCoercion`] was constructed.
1517/// Used only for diagnostics.
1518#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1519pub enum CoercionSource {
1520 /// The coercion was manually written by the user with an `as` cast.
1521 AsCast,
1522 /// The coercion was automatically inserted by the compiler.
1523 Implicit,
1524}
1525
1526#[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1527#[derive(TypeFoldable, TypeVisitable)]
1528pub enum AggregateKind<'tcx> {
1529 /// The type is of the element
1530 Array(Ty<'tcx>),
1531 Tuple,
1532
1533 /// The second field is the variant index. It's equal to 0 for struct
1534 /// and union expressions. The last field is the
1535 /// active field number and is present only for union expressions
1536 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
1537 /// active field index would identity the field `c`
1538 Adt(DefId, VariantIdx, GenericArgsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<FieldIdx>),
1539
1540 Closure(DefId, GenericArgsRef<'tcx>),
1541 Coroutine(DefId, GenericArgsRef<'tcx>),
1542 CoroutineClosure(DefId, GenericArgsRef<'tcx>),
1543
1544 /// Construct a raw pointer from the data pointer and metadata.
1545 ///
1546 /// The `Ty` here is the type of the *pointee*, not the pointer itself.
1547 /// The `Mutability` indicates whether this produces a `*const` or `*mut`.
1548 ///
1549 /// The [`Rvalue::Aggregate`] operands for thus must be
1550 ///
1551 /// 0. A raw pointer of matching mutability with any [`core::ptr::Thin`] pointee
1552 /// 1. A value of the appropriate [`core::ptr::Pointee::Metadata`] type
1553 ///
1554 /// *Both* operands must always be included, even the unit value if this is
1555 /// creating a thin pointer. If you're just converting between thin pointers,
1556 /// you may want an [`Rvalue::Cast`] with [`CastKind::PtrToPtr`] instead.
1557 RawPtr(Ty<'tcx>, Mutability),
1558}
1559
1560#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1561pub enum NullOp<'tcx> {
1562 /// Returns the size of a value of that type
1563 SizeOf,
1564 /// Returns the minimum alignment of a type
1565 AlignOf,
1566 /// Returns the offset of a field
1567 OffsetOf(&'tcx List<(VariantIdx, FieldIdx)>),
1568 /// Returns whether we should perform some UB-checking at runtime.
1569 /// See the `ub_checks` intrinsic docs for details.
1570 UbChecks,
1571 /// Returns whether we should perform contract-checking at runtime.
1572 /// See the `contract_checks` intrinsic docs for details.
1573 ContractChecks,
1574}
1575
1576#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1577#[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
1578pub enum UnOp {
1579 /// The `!` operator for logical inversion
1580 Not,
1581 /// The `-` operator for negation
1582 Neg,
1583 /// Gets the metadata `M` from a `*const`/`*mut`/`&`/`&mut` to
1584 /// `impl Pointee<Metadata = M>`.
1585 ///
1586 /// For example, this will give a `()` from `*const i32`, a `usize` from
1587 /// `&mut [u8]`, or a `ptr::DynMetadata<dyn Foo>` (internally a pointer)
1588 /// from a `*mut dyn Foo`.
1589 ///
1590 /// Allowed only in [`MirPhase::Runtime`]; earlier it's an intrinsic.
1591 PtrMetadata,
1592}
1593
1594#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1595#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1596pub enum BinOp {
1597 /// The `+` operator (addition)
1598 Add,
1599 /// Like `Add`, but with UB on overflow. (Integers only.)
1600 AddUnchecked,
1601 /// Like `Add`, but returns `(T, bool)` of both the wrapped result
1602 /// and a bool indicating whether it overflowed.
1603 AddWithOverflow,
1604 /// The `-` operator (subtraction)
1605 Sub,
1606 /// Like `Sub`, but with UB on overflow. (Integers only.)
1607 SubUnchecked,
1608 /// Like `Sub`, but returns `(T, bool)` of both the wrapped result
1609 /// and a bool indicating whether it overflowed.
1610 SubWithOverflow,
1611 /// The `*` operator (multiplication)
1612 Mul,
1613 /// Like `Mul`, but with UB on overflow. (Integers only.)
1614 MulUnchecked,
1615 /// Like `Mul`, but returns `(T, bool)` of both the wrapped result
1616 /// and a bool indicating whether it overflowed.
1617 MulWithOverflow,
1618 /// The `/` operator (division)
1619 ///
1620 /// For integer types, division by zero is UB, as is `MIN / -1` for signed.
1621 /// The compiler should have inserted checks prior to this.
1622 ///
1623 /// Floating-point division by zero is safe, and does not need guards.
1624 Div,
1625 /// The `%` operator (modulus)
1626 ///
1627 /// For integer types, using zero as the modulus (second operand) is UB,
1628 /// as is `MIN % -1` for signed.
1629 /// The compiler should have inserted checks prior to this.
1630 ///
1631 /// Floating-point remainder by zero is safe, and does not need guards.
1632 Rem,
1633 /// The `^` operator (bitwise xor)
1634 BitXor,
1635 /// The `&` operator (bitwise and)
1636 BitAnd,
1637 /// The `|` operator (bitwise or)
1638 BitOr,
1639 /// The `<<` operator (shift left)
1640 ///
1641 /// The offset is given by `RHS.rem_euclid(LHS::BITS)`.
1642 /// In other words, it is (uniquely) determined as follows:
1643 /// - it is "equal modulo LHS::BITS" to the RHS
1644 /// - it is in the range `0..LHS::BITS`
1645 Shl,
1646 /// Like `Shl`, but is UB if the RHS >= LHS::BITS or RHS < 0
1647 ShlUnchecked,
1648 /// The `>>` operator (shift right)
1649 ///
1650 /// The offset is given by `RHS.rem_euclid(LHS::BITS)`.
1651 /// In other words, it is (uniquely) determined as follows:
1652 /// - it is "equal modulo LHS::BITS" to the RHS
1653 /// - it is in the range `0..LHS::BITS`
1654 ///
1655 /// This is an arithmetic shift if the LHS is signed
1656 /// and a logical shift if the LHS is unsigned.
1657 Shr,
1658 /// Like `Shl`, but is UB if the RHS >= LHS::BITS or RHS < 0
1659 ShrUnchecked,
1660 /// The `==` operator (equality)
1661 Eq,
1662 /// The `<` operator (less than)
1663 Lt,
1664 /// The `<=` operator (less than or equal to)
1665 Le,
1666 /// The `!=` operator (not equal to)
1667 Ne,
1668 /// The `>=` operator (greater than or equal to)
1669 Ge,
1670 /// The `>` operator (greater than)
1671 Gt,
1672 /// The `<=>` operator (three-way comparison, like `Ord::cmp`)
1673 ///
1674 /// This is supported only on the integer types and `char`, always returning
1675 /// [`rustc_hir::LangItem::OrderingEnum`] (aka [`std::cmp::Ordering`]).
1676 ///
1677 /// [`Rvalue::BinaryOp`]`(BinOp::Cmp, A, B)` returns
1678 /// - `Ordering::Less` (`-1_i8`, as a Scalar) if `A < B`
1679 /// - `Ordering::Equal` (`0_i8`, as a Scalar) if `A == B`
1680 /// - `Ordering::Greater` (`+1_i8`, as a Scalar) if `A > B`
1681 Cmp,
1682 /// The `ptr.offset` operator
1683 Offset,
1684}
1685
1686// Assignment operators, e.g. `+=`. See comments on the corresponding variants
1687// in `BinOp` for details.
1688#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1689pub enum AssignOp {
1690 AddAssign,
1691 SubAssign,
1692 MulAssign,
1693 DivAssign,
1694 RemAssign,
1695 BitXorAssign,
1696 BitAndAssign,
1697 BitOrAssign,
1698 ShlAssign,
1699 ShrAssign,
1700}
1701
1702// Sometimes `BinOp` and `AssignOp` need the same treatment. The operations
1703// covered by `AssignOp` are a subset of those covered by `BinOp`, so it makes
1704// sense to convert `AssignOp` to `BinOp`.
1705impl From<AssignOp> for BinOp {
1706 fn from(op: AssignOp) -> BinOp {
1707 match op {
1708 AssignOp::AddAssign => BinOp::Add,
1709 AssignOp::SubAssign => BinOp::Sub,
1710 AssignOp::MulAssign => BinOp::Mul,
1711 AssignOp::DivAssign => BinOp::Div,
1712 AssignOp::RemAssign => BinOp::Rem,
1713 AssignOp::BitXorAssign => BinOp::BitXor,
1714 AssignOp::BitAndAssign => BinOp::BitAnd,
1715 AssignOp::BitOrAssign => BinOp::BitOr,
1716 AssignOp::ShlAssign => BinOp::Shl,
1717 AssignOp::ShrAssign => BinOp::Shr,
1718 }
1719 }
1720}
1721
1722// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1723#[cfg(target_pointer_width = "64")]
1724mod size_asserts {
1725 use rustc_data_structures::static_assert_size;
1726
1727 use super::*;
1728 // tidy-alphabetical-start
1729 static_assert_size!(AggregateKind<'_>, 32);
1730 static_assert_size!(Operand<'_>, 24);
1731 static_assert_size!(Place<'_>, 16);
1732 static_assert_size!(PlaceElem<'_>, 24);
1733 static_assert_size!(Rvalue<'_>, 40);
1734 static_assert_size!(StatementKind<'_>, 16);
1735 static_assert_size!(TerminatorKind<'_>, 80);
1736 // tidy-alphabetical-end
1737}