Auto merge of #147083 - dianne:non-extended-indices, r=matthewjasper

Do not lifetime-extend array/slice indices

When lowering non-overloaded indexing operations to MIR, this uses the temporary lifetime of the index expression for the index temporary, rather than applying the temporary lifetime of the indexing operation as a whole to the index.

For example, in
```rust
let x = &xs[i];
```
previously, the temporary containing the result of evaluating `i` would live until the end of the block due to the indexing operation being [lifetime-extended](https://doc.rust-lang.org/nightly/reference/destructors.html#temporary-lifetime-extension). Under this PR, the index temporary only lives to the end of the `let` statement because it uses the more precise temporary lifetime of the index expression.

I don't think this will affect semantics in an observable way, but the more precise `StorageDead` placement may slightly improve analysis/codegen performance.

r? mir
This commit is contained in:
bors
2025-10-28 03:02:00 +00:00
8 changed files with 31 additions and 32 deletions

View File

@@ -454,7 +454,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
index,
mutability,
fake_borrow_temps,
expr.temp_lifetime,
expr_span,
source_info,
),
@@ -625,7 +624,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
index: ExprId,
mutability: Mutability,
fake_borrow_temps: Option<&mut Vec<Local>>,
temp_lifetime: TempLifetime,
expr_span: Span,
source_info: SourceInfo,
) -> BlockAnd<PlaceBuilder<'tcx>> {
@@ -639,7 +637,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// Making this a *fresh* temporary means we do not have to worry about
// the index changing later: Nothing will ever change this temporary.
// The "retagging" transformation (for Stacked Borrows) relies on this.
let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not));
let index_lifetime = self.thir[index].temp_lifetime;
let idx = unpack!(block = self.as_temp(block, index_lifetime, index, Mutability::Not));
block = self.bounds_check(block, &base_place, idx, expr_span, source_info);