rustc_mir_build/builder/expr/
into.rs

1//! See docs in build/expr/mod.rs
2
3use rustc_ast::{AsmMacro, InlineAsmOptions};
4use rustc_data_structures::fx::FxHashMap;
5use rustc_data_structures::stack::ensure_sufficient_stack;
6use rustc_hir as hir;
7use rustc_hir::lang_items::LangItem;
8use rustc_middle::mir::*;
9use rustc_middle::span_bug;
10use rustc_middle::thir::*;
11use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty};
12use rustc_span::DUMMY_SP;
13use rustc_span::source_map::Spanned;
14use rustc_trait_selection::infer::InferCtxtExt;
15use tracing::{debug, instrument};
16
17use crate::builder::expr::category::{Category, RvalueFunc};
18use crate::builder::matches::{DeclareLetBindings, HasMatchGuard};
19use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTemporary};
20use crate::errors::{LoopMatchArmWithGuard, LoopMatchUnsupportedType};
21
22impl<'a, 'tcx> Builder<'a, 'tcx> {
23    /// Compile `expr`, storing the result into `destination`, which
24    /// is assumed to be uninitialized.
25    #[instrument(level = "debug", skip(self))]
26    pub(crate) fn expr_into_dest(
27        &mut self,
28        destination: Place<'tcx>,
29        mut block: BasicBlock,
30        expr_id: ExprId,
31    ) -> BlockAnd<()> {
32        // since we frequently have to reference `self` from within a
33        // closure, where `self` would be shadowed, it's easier to
34        // just use the name `this` uniformly
35        let this = self;
36        let expr = &this.thir[expr_id];
37        let expr_span = expr.span;
38        let source_info = this.source_info(expr_span);
39
40        let expr_is_block_or_scope =
41            matches!(expr.kind, ExprKind::Block { .. } | ExprKind::Scope { .. });
42
43        if !expr_is_block_or_scope {
44            this.block_context.push(BlockFrame::SubExpr);
45        }
46
47        let block_and = match expr.kind {
48            ExprKind::Scope { region_scope, lint_level, value } => {
49                let region_scope = (region_scope, source_info);
50                ensure_sufficient_stack(|| {
51                    this.in_scope(region_scope, lint_level, |this| {
52                        this.expr_into_dest(destination, block, value)
53                    })
54                })
55            }
56            ExprKind::Block { block: ast_block } => {
57                this.ast_block(destination, block, ast_block, source_info)
58            }
59            ExprKind::Match { scrutinee, ref arms, .. } => this.match_expr(
60                destination,
61                block,
62                scrutinee,
63                arms,
64                expr_span,
65                this.thir[scrutinee].span,
66            ),
67            ExprKind::If { cond, then, else_opt, if_then_scope } => {
68                let then_span = this.thir[then].span;
69                let then_source_info = this.source_info(then_span);
70                let condition_scope = this.local_scope();
71
72                let then_and_else_blocks = this.in_scope(
73                    (if_then_scope, then_source_info),
74                    LintLevel::Inherited,
75                    |this| {
76                        // FIXME: Does this need extra logic to handle let-chains?
77                        let source_info = if this.is_let(cond) {
78                            let variable_scope =
79                                this.new_source_scope(then_span, LintLevel::Inherited);
80                            this.source_scope = variable_scope;
81                            SourceInfo { span: then_span, scope: variable_scope }
82                        } else {
83                            this.source_info(then_span)
84                        };
85
86                        // Lower the condition, and have it branch into `then` and `else` blocks.
87                        let (then_block, else_block) =
88                            this.in_if_then_scope(condition_scope, then_span, |this| {
89                                let then_blk = this
90                                    .then_else_break(
91                                        block,
92                                        cond,
93                                        Some(condition_scope), // Temp scope
94                                        source_info,
95                                        DeclareLetBindings::Yes, // Declare `let` bindings normally
96                                    )
97                                    .into_block();
98
99                                // Lower the `then` arm into its block.
100                                this.expr_into_dest(destination, then_blk, then)
101                            });
102
103                        // Pack `(then_block, else_block)` into `BlockAnd<BasicBlock>`.
104                        then_block.and(else_block)
105                    },
106                );
107
108                // Unpack `BlockAnd<BasicBlock>` into `(then_blk, else_blk)`.
109                let (then_blk, mut else_blk);
110                else_blk = unpack!(then_blk = then_and_else_blocks);
111
112                // If there is an `else` arm, lower it into `else_blk`.
113                if let Some(else_expr) = else_opt {
114                    else_blk = this.expr_into_dest(destination, else_blk, else_expr).into_block();
115                } else {
116                    // There is no `else` arm, so we know both arms have type `()`.
117                    // Generate the implicit `else {}` by assigning unit.
118                    let correct_si = this.source_info(expr_span.shrink_to_hi());
119                    this.cfg.push_assign_unit(else_blk, correct_si, destination, this.tcx);
120                }
121
122                // The `then` and `else` arms have been lowered into their respective
123                // blocks, so make both of them meet up in a new block.
124                let join_block = this.cfg.start_new_block();
125                this.cfg.goto(then_blk, source_info, join_block);
126                this.cfg.goto(else_blk, source_info, join_block);
127                join_block.unit()
128            }
129            ExprKind::Let { .. } => {
130                // After desugaring, `let` expressions should only appear inside `if`
131                // expressions or `match` guards, possibly nested within a let-chain.
132                // In both cases they are specifically handled by the lowerings of
133                // those expressions, so this case is currently unreachable.
134                span_bug!(expr_span, "unexpected let expression outside of if or match-guard");
135            }
136            ExprKind::NeverToAny { source } => {
137                let source_expr = &this.thir[source];
138                let is_call =
139                    matches!(source_expr.kind, ExprKind::Call { .. } | ExprKind::InlineAsm { .. });
140
141                // (#66975) Source could be a const of type `!`, so has to
142                // exist in the generated MIR.
143                unpack!(
144                    block =
145                        this.as_temp(block, this.local_temp_lifetime(), source, Mutability::Mut)
146                );
147
148                // This is an optimization. If the expression was a call then we already have an
149                // unreachable block. Don't bother to terminate it and create a new one.
150                if is_call {
151                    block.unit()
152                } else {
153                    this.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
154                    let end_block = this.cfg.start_new_block();
155                    end_block.unit()
156                }
157            }
158            ExprKind::LogicalOp { op, lhs, rhs } => {
159                let condition_scope = this.local_scope();
160                let source_info = this.source_info(expr.span);
161
162                // We first evaluate the left-hand side of the predicate ...
163                let (then_block, else_block) =
164                    this.in_if_then_scope(condition_scope, expr.span, |this| {
165                        this.then_else_break(
166                            block,
167                            lhs,
168                            Some(condition_scope), // Temp scope
169                            source_info,
170                            // This flag controls how inner `let` expressions are lowered,
171                            // but either way there shouldn't be any of those in here.
172                            DeclareLetBindings::LetNotPermitted,
173                        )
174                    });
175                let (short_circuit, continuation, constant) = match op {
176                    LogicalOp::And => (else_block, then_block, false),
177                    LogicalOp::Or => (then_block, else_block, true),
178                };
179                // At this point, the control flow splits into a short-circuiting path
180                // and a continuation path.
181                // - If the operator is `&&`, passing `lhs` leads to continuation of evaluation on `rhs`;
182                //   failing it leads to the short-circuting path which assigns `false` to the place.
183                // - If the operator is `||`, failing `lhs` leads to continuation of evaluation on `rhs`;
184                //   passing it leads to the short-circuting path which assigns `true` to the place.
185                this.cfg.push_assign_constant(
186                    short_circuit,
187                    source_info,
188                    destination,
189                    ConstOperand {
190                        span: expr.span,
191                        user_ty: None,
192                        const_: Const::from_bool(this.tcx, constant),
193                    },
194                );
195                let mut rhs_block =
196                    this.expr_into_dest(destination, continuation, rhs).into_block();
197                // Instrument the lowered RHS's value for condition coverage.
198                // (Does nothing if condition coverage is not enabled.)
199                this.visit_coverage_standalone_condition(rhs, destination, &mut rhs_block);
200
201                let target = this.cfg.start_new_block();
202                this.cfg.goto(rhs_block, source_info, target);
203                this.cfg.goto(short_circuit, source_info, target);
204                target.unit()
205            }
206            ExprKind::Loop { body } => {
207                // [block]
208                //    |
209                //   [loop_block] -> [body_block] -/eval. body/-> [body_block_end]
210                //    |        ^                                         |
211                // false link  |                                         |
212                //    |        +-----------------------------------------+
213                //    +-> [diverge_cleanup]
214                // The false link is required to make sure borrowck considers unwinds through the
215                // body, even when the exact code in the body cannot unwind
216
217                let loop_block = this.cfg.start_new_block();
218
219                // Start the loop.
220                this.cfg.goto(block, source_info, loop_block);
221
222                this.in_breakable_scope(Some(loop_block), destination, expr_span, move |this| {
223                    // conduct the test, if necessary
224                    let body_block = this.cfg.start_new_block();
225                    this.cfg.terminate(
226                        loop_block,
227                        source_info,
228                        TerminatorKind::FalseUnwind {
229                            real_target: body_block,
230                            unwind: UnwindAction::Continue,
231                        },
232                    );
233                    this.diverge_from(loop_block);
234
235                    // The “return” value of the loop body must always be a unit. We therefore
236                    // introduce a unit temporary as the destination for the loop body.
237                    let tmp = this.get_unit_temp();
238                    // Execute the body, branching back to the test.
239                    let body_block_end = this.expr_into_dest(tmp, body_block, body).into_block();
240                    this.cfg.goto(body_block_end, source_info, loop_block);
241
242                    // Loops are only exited by `break` expressions.
243                    None
244                })
245            }
246            ExprKind::LoopMatch {
247                state,
248                region_scope,
249                match_data: box LoopMatchMatchData { box ref arms, span: match_span, scrutinee },
250            } => {
251                // Intuitively, this is a combination of a loop containing a labeled block
252                // containing a match.
253                //
254                // The only new bit here is that the lowering of the match is wrapped in a
255                // `in_const_continuable_scope`, which makes the match arms and their target basic
256                // block available to the lowering of `#[const_continue]`.
257
258                fn is_supported_loop_match_type(ty: Ty<'_>) -> bool {
259                    match ty.kind() {
260                        ty::Uint(_) | ty::Int(_) | ty::Float(_) | ty::Bool | ty::Char => true,
261                        ty::Adt(adt_def, _) => match adt_def.adt_kind() {
262                            ty::AdtKind::Struct | ty::AdtKind::Union => false,
263                            ty::AdtKind::Enum => {
264                                adt_def.variants().iter().all(|v| v.fields.is_empty())
265                            }
266                        },
267                        _ => false,
268                    }
269                }
270
271                let state_ty = this.thir.exprs[state].ty;
272                if !is_supported_loop_match_type(state_ty) {
273                    let span = this.thir.exprs[state].span;
274                    this.tcx.dcx().emit_fatal(LoopMatchUnsupportedType { span, ty: state_ty })
275                }
276
277                let loop_block = this.cfg.start_new_block();
278
279                // Start the loop.
280                this.cfg.goto(block, source_info, loop_block);
281
282                this.in_breakable_scope(Some(loop_block), destination, expr_span, |this| {
283                    // Logic for `loop`.
284                    let mut body_block = this.cfg.start_new_block();
285                    this.cfg.terminate(
286                        loop_block,
287                        source_info,
288                        TerminatorKind::FalseUnwind {
289                            real_target: body_block,
290                            unwind: UnwindAction::Continue,
291                        },
292                    );
293                    this.diverge_from(loop_block);
294
295                    // Logic for `match`.
296                    let scrutinee_span = this.thir.exprs[scrutinee].span;
297                    let scrutinee_place_builder = unpack!(
298                        body_block = this.lower_scrutinee(body_block, scrutinee, scrutinee_span)
299                    );
300
301                    let match_start_span = match_span.shrink_to_lo().to(scrutinee_span);
302
303                    let mut patterns = Vec::with_capacity(arms.len());
304                    for &arm_id in arms.iter() {
305                        let arm = &this.thir[arm_id];
306
307                        if let Some(guard) = arm.guard {
308                            let span = this.thir.exprs[guard].span;
309                            this.tcx.dcx().emit_fatal(LoopMatchArmWithGuard { span })
310                        }
311
312                        patterns.push((&*arm.pattern, HasMatchGuard::No));
313                    }
314
315                    // The `built_tree` maps match arms to their basic block (where control flow
316                    // jumps to when a value matches the arm). This structure is stored so that a
317                    // `#[const_continue]` can figure out what basic block to jump to.
318                    let built_tree = this.lower_match_tree(
319                        body_block,
320                        scrutinee_span,
321                        &scrutinee_place_builder,
322                        match_start_span,
323                        patterns,
324                        false,
325                    );
326
327                    let state_place = scrutinee_place_builder.to_place(this);
328
329                    // This is logic for the labeled block: a block is a drop scope, hence
330                    // `in_scope`, and a labeled block can be broken out of with a `break 'label`,
331                    // hence the `in_breakable_scope`.
332                    //
333                    // Then `in_const_continuable_scope` stores information for the lowering of
334                    // `#[const_continue]`, and finally the match is lowered in the standard way.
335                    unpack!(
336                        body_block = this.in_scope(
337                            (region_scope, source_info),
338                            LintLevel::Inherited,
339                            move |this| {
340                                this.in_breakable_scope(None, state_place, expr_span, |this| {
341                                    Some(this.in_const_continuable_scope(
342                                        Box::from(arms),
343                                        built_tree.clone(),
344                                        state_place,
345                                        expr_span,
346                                        |this| {
347                                            this.lower_match_arms(
348                                                state_place,
349                                                scrutinee_place_builder,
350                                                scrutinee_span,
351                                                arms,
352                                                built_tree,
353                                                this.source_info(match_span),
354                                            )
355                                        },
356                                    ))
357                                })
358                            }
359                        )
360                    );
361
362                    this.cfg.goto(body_block, source_info, loop_block);
363
364                    // Loops are only exited by `break` expressions.
365                    None
366                })
367            }
368            ExprKind::Call { ty: _, fun, ref args, from_hir_call, fn_span } => {
369                let fun = unpack!(block = this.as_local_operand(block, fun));
370                let args: Box<[_]> = args
371                    .into_iter()
372                    .copied()
373                    .map(|arg| Spanned {
374                        node: unpack!(block = this.as_local_call_operand(block, arg)),
375                        span: this.thir.exprs[arg].span,
376                    })
377                    .collect();
378
379                let success = this.cfg.start_new_block();
380
381                this.record_operands_moved(&args);
382
383                debug!("expr_into_dest: fn_span={:?}", fn_span);
384
385                this.cfg.terminate(
386                    block,
387                    source_info,
388                    TerminatorKind::Call {
389                        func: fun,
390                        args,
391                        unwind: UnwindAction::Continue,
392                        destination,
393                        target: Some(success),
394                        call_source: if from_hir_call {
395                            CallSource::Normal
396                        } else {
397                            CallSource::OverloadedOperator
398                        },
399                        fn_span,
400                    },
401                );
402                this.diverge_from(block);
403                success.unit()
404            }
405            ExprKind::ByUse { expr, span } => {
406                let place = unpack!(block = this.as_place(block, expr));
407                let ty = place.ty(&this.local_decls, this.tcx).ty;
408
409                if this.tcx.type_is_copy_modulo_regions(this.infcx.typing_env(this.param_env), ty) {
410                    this.cfg.push_assign(
411                        block,
412                        source_info,
413                        destination,
414                        Rvalue::Use(Operand::Copy(place)),
415                    );
416                    block.unit()
417                } else if this.infcx.type_is_use_cloned_modulo_regions(this.param_env, ty) {
418                    // Convert `expr.use` to a call like `Clone::clone(&expr)`
419                    let success = this.cfg.start_new_block();
420                    let clone_trait = this.tcx.require_lang_item(LangItem::Clone, span);
421                    let clone_fn = this.tcx.associated_item_def_ids(clone_trait)[0];
422                    let func = Operand::function_handle(this.tcx, clone_fn, [ty.into()], expr_span);
423                    let ref_ty = Ty::new_imm_ref(this.tcx, this.tcx.lifetimes.re_erased, ty);
424                    let ref_place = this.temp(ref_ty, span);
425                    this.cfg.push_assign(
426                        block,
427                        source_info,
428                        ref_place,
429                        Rvalue::Ref(this.tcx.lifetimes.re_erased, BorrowKind::Shared, place),
430                    );
431                    this.cfg.terminate(
432                        block,
433                        source_info,
434                        TerminatorKind::Call {
435                            func,
436                            args: [Spanned { node: Operand::Move(ref_place), span: DUMMY_SP }]
437                                .into(),
438                            destination,
439                            target: Some(success),
440                            unwind: UnwindAction::Unreachable,
441                            call_source: CallSource::Use,
442                            fn_span: expr_span,
443                        },
444                    );
445                    success.unit()
446                } else {
447                    this.cfg.push_assign(
448                        block,
449                        source_info,
450                        destination,
451                        Rvalue::Use(Operand::Move(place)),
452                    );
453                    block.unit()
454                }
455            }
456            ExprKind::Use { source } => this.expr_into_dest(destination, block, source),
457            ExprKind::Borrow { arg, borrow_kind } => {
458                // We don't do this in `as_rvalue` because we use `as_place`
459                // for borrow expressions, so we cannot create an `RValue` that
460                // remains valid across user code. `as_rvalue` is usually called
461                // by this method anyway, so this shouldn't cause too many
462                // unnecessary temporaries.
463                let arg_place = match borrow_kind {
464                    BorrowKind::Shared => {
465                        unpack!(block = this.as_read_only_place(block, arg))
466                    }
467                    _ => unpack!(block = this.as_place(block, arg)),
468                };
469                let borrow = Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place);
470                this.cfg.push_assign(block, source_info, destination, borrow);
471                block.unit()
472            }
473            ExprKind::RawBorrow { mutability, arg } => {
474                let place = match mutability {
475                    hir::Mutability::Not => this.as_read_only_place(block, arg),
476                    hir::Mutability::Mut => this.as_place(block, arg),
477                };
478                let address_of = Rvalue::RawPtr(mutability.into(), unpack!(block = place));
479                this.cfg.push_assign(block, source_info, destination, address_of);
480                block.unit()
481            }
482            ExprKind::Adt(box AdtExpr {
483                adt_def,
484                variant_index,
485                args,
486                ref user_ty,
487                ref fields,
488                ref base,
489            }) => {
490                // See the notes for `ExprKind::Array` in `as_rvalue` and for
491                // `ExprKind::Borrow` above.
492                let is_union = adt_def.is_union();
493                let active_field_index = is_union.then(|| fields[0].name);
494
495                let scope = this.local_temp_lifetime();
496
497                // first process the set of fields that were provided
498                // (evaluating them in order given by user)
499                let fields_map: FxHashMap<_, _> = fields
500                    .into_iter()
501                    .map(|f| {
502                        (
503                            f.name,
504                            unpack!(
505                                block = this.as_operand(
506                                    block,
507                                    scope,
508                                    f.expr,
509                                    LocalInfo::AggregateTemp,
510                                    NeedsTemporary::Maybe,
511                                )
512                            ),
513                        )
514                    })
515                    .collect();
516
517                let variant = adt_def.variant(variant_index);
518                let field_names = variant.fields.indices();
519
520                let fields = match base {
521                    AdtExprBase::None => {
522                        field_names.filter_map(|n| fields_map.get(&n).cloned()).collect()
523                    }
524                    AdtExprBase::Base(FruInfo { base, field_types }) => {
525                        let place_builder = unpack!(block = this.as_place_builder(block, *base));
526
527                        // We desugar FRU as we lower to MIR, so for each
528                        // base-supplied field, generate an operand that
529                        // reads it from the base.
530                        itertools::zip_eq(field_names, &**field_types)
531                            .map(|(n, ty)| match fields_map.get(&n) {
532                                Some(v) => v.clone(),
533                                None => {
534                                    let place =
535                                        place_builder.clone_project(PlaceElem::Field(n, *ty));
536                                    this.consume_by_copy_or_move(place.to_place(this))
537                                }
538                            })
539                            .collect()
540                    }
541                    AdtExprBase::DefaultFields(field_types) => {
542                        itertools::zip_eq(field_names, field_types)
543                            .map(|(n, &ty)| match fields_map.get(&n) {
544                                Some(v) => v.clone(),
545                                None => match variant.fields[n].value {
546                                    Some(def) => {
547                                        let value = Const::Unevaluated(
548                                            UnevaluatedConst::new(def, args),
549                                            ty,
550                                        );
551                                        Operand::Constant(Box::new(ConstOperand {
552                                            span: expr_span,
553                                            user_ty: None,
554                                            const_: value,
555                                        }))
556                                    }
557                                    None => {
558                                        let name = variant.fields[n].name;
559                                        span_bug!(
560                                            expr_span,
561                                            "missing mandatory field `{name}` of type `{ty}`",
562                                        );
563                                    }
564                                },
565                            })
566                            .collect()
567                    }
568                };
569
570                let inferred_ty = expr.ty;
571                let user_ty = user_ty.as_ref().map(|user_ty| {
572                    this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
573                        span: source_info.span,
574                        user_ty: user_ty.clone(),
575                        inferred_ty,
576                    })
577                });
578                let adt = Box::new(AggregateKind::Adt(
579                    adt_def.did(),
580                    variant_index,
581                    args,
582                    user_ty,
583                    active_field_index,
584                ));
585                this.cfg.push_assign(
586                    block,
587                    source_info,
588                    destination,
589                    Rvalue::Aggregate(adt, fields),
590                );
591                block.unit()
592            }
593            ExprKind::InlineAsm(box InlineAsmExpr {
594                asm_macro,
595                template,
596                ref operands,
597                options,
598                line_spans,
599            }) => {
600                use rustc_middle::{mir, thir};
601
602                let destination_block = this.cfg.start_new_block();
603                let mut targets =
604                    if asm_macro.diverges(options) { vec![] } else { vec![destination_block] };
605
606                let operands = operands
607                    .into_iter()
608                    .map(|op| match *op {
609                        thir::InlineAsmOperand::In { reg, expr } => mir::InlineAsmOperand::In {
610                            reg,
611                            value: unpack!(block = this.as_local_operand(block, expr)),
612                        },
613                        thir::InlineAsmOperand::Out { reg, late, expr } => {
614                            mir::InlineAsmOperand::Out {
615                                reg,
616                                late,
617                                place: expr.map(|expr| unpack!(block = this.as_place(block, expr))),
618                            }
619                        }
620                        thir::InlineAsmOperand::InOut { reg, late, expr } => {
621                            let place = unpack!(block = this.as_place(block, expr));
622                            mir::InlineAsmOperand::InOut {
623                                reg,
624                                late,
625                                // This works because asm operands must be Copy
626                                in_value: Operand::Copy(place),
627                                out_place: Some(place),
628                            }
629                        }
630                        thir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
631                            mir::InlineAsmOperand::InOut {
632                                reg,
633                                late,
634                                in_value: unpack!(block = this.as_local_operand(block, in_expr)),
635                                out_place: out_expr.map(|out_expr| {
636                                    unpack!(block = this.as_place(block, out_expr))
637                                }),
638                            }
639                        }
640                        thir::InlineAsmOperand::Const { value, span } => {
641                            mir::InlineAsmOperand::Const {
642                                value: Box::new(ConstOperand {
643                                    span,
644                                    user_ty: None,
645                                    const_: value,
646                                }),
647                            }
648                        }
649                        thir::InlineAsmOperand::SymFn { value } => mir::InlineAsmOperand::SymFn {
650                            value: Box::new(this.as_constant(&this.thir[value])),
651                        },
652                        thir::InlineAsmOperand::SymStatic { def_id } => {
653                            mir::InlineAsmOperand::SymStatic { def_id }
654                        }
655                        thir::InlineAsmOperand::Label { block } => {
656                            let target = this.cfg.start_new_block();
657                            let target_index = targets.len();
658                            targets.push(target);
659
660                            let tmp = this.get_unit_temp();
661                            let target =
662                                this.ast_block(tmp, target, block, source_info).into_block();
663                            this.cfg.terminate(
664                                target,
665                                source_info,
666                                TerminatorKind::Goto { target: destination_block },
667                            );
668
669                            mir::InlineAsmOperand::Label { target_index }
670                        }
671                    })
672                    .collect();
673
674                if !expr.ty.is_never() {
675                    this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
676                }
677
678                let asm_macro = match asm_macro {
679                    AsmMacro::Asm | AsmMacro::GlobalAsm => InlineAsmMacro::Asm,
680                    AsmMacro::NakedAsm => InlineAsmMacro::NakedAsm,
681                };
682
683                this.cfg.terminate(
684                    block,
685                    source_info,
686                    TerminatorKind::InlineAsm {
687                        asm_macro,
688                        template,
689                        operands,
690                        options,
691                        line_spans,
692                        targets: targets.into_boxed_slice(),
693                        unwind: if options.contains(InlineAsmOptions::MAY_UNWIND) {
694                            UnwindAction::Continue
695                        } else {
696                            UnwindAction::Unreachable
697                        },
698                    },
699                );
700                if options.contains(InlineAsmOptions::MAY_UNWIND) {
701                    this.diverge_from(block);
702                }
703                destination_block.unit()
704            }
705
706            // These cases don't actually need a destination
707            ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
708                block = this.stmt_expr(block, expr_id, None).into_block();
709                this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
710                block.unit()
711            }
712
713            ExprKind::Continue { .. }
714            | ExprKind::ConstContinue { .. }
715            | ExprKind::Break { .. }
716            | ExprKind::Return { .. }
717            | ExprKind::Become { .. } => {
718                block = this.stmt_expr(block, expr_id, None).into_block();
719                // No assign, as these have type `!`.
720                block.unit()
721            }
722
723            // Avoid creating a temporary
724            ExprKind::VarRef { .. }
725            | ExprKind::UpvarRef { .. }
726            | ExprKind::PlaceTypeAscription { .. }
727            | ExprKind::ValueTypeAscription { .. }
728            | ExprKind::PlaceUnwrapUnsafeBinder { .. }
729            | ExprKind::ValueUnwrapUnsafeBinder { .. } => {
730                debug_assert!(Category::of(&expr.kind) == Some(Category::Place));
731
732                let place = unpack!(block = this.as_place(block, expr_id));
733                let rvalue = Rvalue::Use(this.consume_by_copy_or_move(place));
734                this.cfg.push_assign(block, source_info, destination, rvalue);
735                block.unit()
736            }
737            ExprKind::Index { .. } | ExprKind::Deref { .. } | ExprKind::Field { .. } => {
738                debug_assert_eq!(Category::of(&expr.kind), Some(Category::Place));
739
740                // Create a "fake" temporary variable so that we check that the
741                // value is Sized. Usually, this is caught in type checking, but
742                // in the case of box expr there is no such check.
743                if !destination.projection.is_empty() {
744                    this.local_decls.push(LocalDecl::new(expr.ty, expr.span));
745                }
746
747                let place = unpack!(block = this.as_place(block, expr_id));
748                let rvalue = Rvalue::Use(this.consume_by_copy_or_move(place));
749                this.cfg.push_assign(block, source_info, destination, rvalue);
750                block.unit()
751            }
752
753            ExprKind::Yield { value } => {
754                let scope = this.local_temp_lifetime();
755                let value = unpack!(
756                    block =
757                        this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No)
758                );
759                let resume = this.cfg.start_new_block();
760                this.cfg.terminate(
761                    block,
762                    source_info,
763                    TerminatorKind::Yield { value, resume, resume_arg: destination, drop: None },
764                );
765                this.coroutine_drop_cleanup(block);
766                resume.unit()
767            }
768
769            // these are the cases that are more naturally handled by some other mode
770            ExprKind::Unary { .. }
771            | ExprKind::Binary { .. }
772            | ExprKind::Box { .. }
773            | ExprKind::Cast { .. }
774            | ExprKind::PointerCoercion { .. }
775            | ExprKind::Repeat { .. }
776            | ExprKind::Array { .. }
777            | ExprKind::Tuple { .. }
778            | ExprKind::Closure { .. }
779            | ExprKind::ConstBlock { .. }
780            | ExprKind::Literal { .. }
781            | ExprKind::NamedConst { .. }
782            | ExprKind::NonHirLiteral { .. }
783            | ExprKind::ZstLiteral { .. }
784            | ExprKind::ConstParam { .. }
785            | ExprKind::ThreadLocalRef(_)
786            | ExprKind::StaticRef { .. }
787            | ExprKind::OffsetOf { .. }
788            | ExprKind::WrapUnsafeBinder { .. } => {
789                debug_assert!(match Category::of(&expr.kind).unwrap() {
790                    // should be handled above
791                    Category::Rvalue(RvalueFunc::Into) => false,
792
793                    // must be handled above or else we get an
794                    // infinite loop in the builder; see
795                    // e.g., `ExprKind::VarRef` above
796                    Category::Place => false,
797
798                    _ => true,
799                });
800
801                let rvalue = unpack!(block = this.as_local_rvalue(block, expr_id));
802                this.cfg.push_assign(block, source_info, destination, rvalue);
803                block.unit()
804            }
805        };
806
807        if !expr_is_block_or_scope {
808            let popped = this.block_context.pop();
809            assert!(popped.is_some());
810        }
811
812        block_and
813    }
814
815    fn is_let(&self, expr: ExprId) -> bool {
816        match self.thir[expr].kind {
817            ExprKind::Let { .. } => true,
818            ExprKind::Scope { value, .. } => self.is_let(value),
819            _ => false,
820        }
821    }
822}