/
as_place.rs
506 lines (476 loc) · 18.2 KB
/
as_place.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! See docs in build/expr/mod.rs
use crate::build::expr::category::Category;
use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
use crate::build::{BlockAnd, BlockAndExtension, Builder};
use crate::hair::*;
use rustc::middle::region;
use rustc::mir::interpret::{PanicInfo::BoundsCheck};
use rustc::mir::*;
use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance};
use syntax_pos::Span;
use rustc_index::vec::Idx;
/// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
/// place by pushing more and more projections onto the end, and then convert the final set into a
/// place using the `into_place` method.
///
/// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
/// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
#[derive(Clone)]
struct PlaceBuilder<'tcx> {
base: PlaceBase<'tcx>,
projection: Vec<PlaceElem<'tcx>>,
}
impl PlaceBuilder<'tcx> {
fn into_place(self, tcx: TyCtxt<'tcx>) -> Place<'tcx> {
Place {
base: self.base,
projection: tcx.intern_place_elems(&self.projection),
}
}
fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
self.project(PlaceElem::Field(f, ty))
}
fn deref(self) -> Self {
self.project(PlaceElem::Deref)
}
fn index(self, index: Local) -> Self {
self.project(PlaceElem::Index(index))
}
fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
self.projection.push(elem);
self
}
}
impl From<Local> for PlaceBuilder<'tcx> {
fn from(local: Local) -> Self {
Self {
base: local.into(),
projection: Vec::new(),
}
}
}
impl From<PlaceBase<'tcx>> for PlaceBuilder<'tcx> {
fn from(base: PlaceBase<'tcx>) -> Self {
Self {
base,
projection: Vec::new(),
}
}
}
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Compile `expr`, yielding a place that we can move from etc.
///
/// WARNING: Any user code might:
/// * Invalidate any slice bounds checks performed.
/// * Change the address that this `Place` refers to.
/// * Modify the memory that this place refers to.
/// * Invalidate the memory that this place refers to, this will be caught
/// by borrow checking.
///
/// Extra care is needed if any user code is allowed to run between calling
/// this method and using it, as is the case for `match` and index
/// expressions.
pub fn as_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
where
M: Mirror<'tcx, Output = Expr<'tcx>>,
{
let place_builder = unpack!(block = self.as_place_builder(block, expr));
block.and(place_builder.into_place(self.hir.tcx()))
}
/// This is used when constructing a compound `Place`, so that we can avoid creating
/// intermediate `Place` values until we know the full set of projections.
fn as_place_builder<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<PlaceBuilder<'tcx>>
where
M: Mirror<'tcx, Output = Expr<'tcx>>,
{
let expr = self.hir.mirror(expr);
self.expr_as_place(block, expr, Mutability::Mut, None)
}
/// Compile `expr`, yielding a place that we can move from etc.
/// Mutability note: The caller of this method promises only to read from the resulting
/// place. The place itself may or may not be mutable:
/// * If this expr is a place expr like a.b, then we will return that place.
/// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
pub fn as_read_only_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
where
M: Mirror<'tcx, Output = Expr<'tcx>>,
{
let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
block.and(place_builder.into_place(self.hir.tcx()))
}
/// This is used when constructing a compound `Place`, so that we can avoid creating
/// intermediate `Place` values until we know the full set of projections.
/// Mutability note: The caller of this method promises only to read from the resulting
/// place. The place itself may or may not be mutable:
/// * If this expr is a place expr like a.b, then we will return that place.
/// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
fn as_read_only_place_builder<M>(
&mut self,
block: BasicBlock,
expr: M,
) -> BlockAnd<PlaceBuilder<'tcx>>
where
M: Mirror<'tcx, Output = Expr<'tcx>>,
{
let expr = self.hir.mirror(expr);
self.expr_as_place(block, expr, Mutability::Not, None)
}
fn expr_as_place(
&mut self,
mut block: BasicBlock,
expr: Expr<'tcx>,
mutability: Mutability,
fake_borrow_temps: Option<&mut Vec<Local>>,
) -> BlockAnd<PlaceBuilder<'tcx>> {
debug!(
"expr_as_place(block={:?}, expr={:?}, mutability={:?})",
block, expr, mutability
);
let this = self;
let expr_span = expr.span;
let source_info = this.source_info(expr_span);
match expr.kind {
ExprKind::Scope {
region_scope,
lint_level,
value,
} => this.in_scope((region_scope, source_info), lint_level, |this| {
let value = this.hir.mirror(value);
this.expr_as_place(block, value, mutability, fake_borrow_temps)
}),
ExprKind::Field { lhs, name } => {
let lhs = this.hir.mirror(lhs);
let place_builder = unpack!(block = this.expr_as_place(
block,
lhs,
mutability,
fake_borrow_temps,
));
block.and(place_builder.field(name, expr.ty))
}
ExprKind::Deref { arg } => {
let arg = this.hir.mirror(arg);
let place_builder = unpack!(block = this.expr_as_place(
block,
arg,
mutability,
fake_borrow_temps,
));
block.and(place_builder.deref())
}
ExprKind::Index { lhs, index } => {
this.lower_index_expression(
block,
lhs,
index,
mutability,
fake_borrow_temps,
expr.temp_lifetime,
expr_span,
source_info,
)
}
ExprKind::SelfRef => block.and(PlaceBuilder::from(Local::new(1))),
ExprKind::VarRef { id } => {
let place_builder = if this.is_bound_var_in_guard(id) {
let index = this.var_local_id(id, RefWithinGuard);
PlaceBuilder::from(index).deref()
} else {
let index = this.var_local_id(id, OutsideGuard);
PlaceBuilder::from(index)
};
block.and(place_builder)
}
ExprKind::PlaceTypeAscription { source, user_ty } => {
let source = this.hir.mirror(source);
let place_builder = unpack!(block = this.expr_as_place(
block,
source,
mutability,
fake_borrow_temps,
));
if let Some(user_ty) = user_ty {
let annotation_index = this.canonical_user_type_annotations.push(
CanonicalUserTypeAnnotation {
span: source_info.span,
user_ty,
inferred_ty: expr.ty,
}
);
let place = place_builder.clone().into_place(this.hir.tcx());
this.cfg.push(
block,
Statement {
source_info,
kind: StatementKind::AscribeUserType(
box(
place,
UserTypeProjection { base: annotation_index, projs: vec![], }
),
Variance::Invariant,
),
},
);
}
block.and(place_builder)
}
ExprKind::ValueTypeAscription { source, user_ty } => {
let source = this.hir.mirror(source);
let temp = unpack!(
block = this.as_temp(block, source.temp_lifetime, source, mutability)
);
if let Some(user_ty) = user_ty {
let annotation_index = this.canonical_user_type_annotations.push(
CanonicalUserTypeAnnotation {
span: source_info.span,
user_ty,
inferred_ty: expr.ty,
}
);
this.cfg.push(
block,
Statement {
source_info,
kind: StatementKind::AscribeUserType(
box(
Place::from(temp.clone()),
UserTypeProjection { base: annotation_index, projs: vec![], },
),
Variance::Invariant,
),
},
);
}
block.and(PlaceBuilder::from(temp))
}
ExprKind::Array { .. }
| ExprKind::Tuple { .. }
| ExprKind::Adt { .. }
| ExprKind::Closure { .. }
| ExprKind::Unary { .. }
| ExprKind::Binary { .. }
| ExprKind::LogicalOp { .. }
| ExprKind::Box { .. }
| ExprKind::Cast { .. }
| ExprKind::Use { .. }
| ExprKind::NeverToAny { .. }
| ExprKind::Pointer { .. }
| ExprKind::Repeat { .. }
| ExprKind::Borrow { .. }
| ExprKind::Match { .. }
| ExprKind::Loop { .. }
| ExprKind::Block { .. }
| ExprKind::Assign { .. }
| ExprKind::AssignOp { .. }
| ExprKind::Break { .. }
| ExprKind::Continue { .. }
| ExprKind::Return { .. }
| ExprKind::Literal { .. }
| ExprKind::InlineAsm { .. }
| ExprKind::Yield { .. }
| ExprKind::Call { .. } => {
// these are not places, so we need to make a temporary.
debug_assert!(match Category::of(&expr.kind) {
Some(Category::Place) => false,
_ => true,
});
let temp =
unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
block.and(PlaceBuilder::from(temp))
}
}
}
/// Lower an index expression
///
/// This has two complications;
///
/// * We need to do a bounds check.
/// * We need to ensure that the bounds check can't be invalidated using an
/// expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
/// that this is the case.
fn lower_index_expression(
&mut self,
mut block: BasicBlock,
base: ExprRef<'tcx>,
index: ExprRef<'tcx>,
mutability: Mutability,
fake_borrow_temps: Option<&mut Vec<Local>>,
temp_lifetime: Option<region::Scope>,
expr_span: Span,
source_info: SourceInfo
) -> BlockAnd<PlaceBuilder<'tcx>> {
let lhs = self.hir.mirror(base);
let base_fake_borrow_temps = &mut Vec::new();
let is_outermost_index = fake_borrow_temps.is_none();
let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
let base_place = unpack!(block = self.expr_as_place(
block,
lhs,
mutability,
Some(fake_borrow_temps),
));
// 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,
));
block = self.bounds_check(
block,
base_place.clone().into_place(self.hir.tcx()),
idx,
expr_span,
source_info,
);
if is_outermost_index {
self.read_fake_borrows(block, fake_borrow_temps, source_info)
} else {
self.add_fake_borrows_of_base(
&base_place,
block,
fake_borrow_temps,
expr_span,
source_info,
);
}
block.and(base_place.index(idx))
}
fn bounds_check(
&mut self,
block: BasicBlock,
slice: Place<'tcx>,
index: Local,
expr_span: Span,
source_info: SourceInfo,
) -> BasicBlock {
let usize_ty = self.hir.usize_ty();
let bool_ty = self.hir.bool_ty();
// bounds check:
let len = self.temp(usize_ty, expr_span);
let lt = self.temp(bool_ty, expr_span);
// len = len(slice)
self.cfg.push_assign(
block,
source_info,
&len,
Rvalue::Len(slice),
);
// lt = idx < len
self.cfg.push_assign(
block,
source_info,
<,
Rvalue::BinaryOp(
BinOp::Lt,
Operand::Copy(Place::from(index)),
Operand::Copy(len.clone()),
),
);
let msg = BoundsCheck {
len: Operand::Move(len),
index: Operand::Copy(Place::from(index)),
};
// assert!(lt, "...")
self.assert(block, Operand::Move(lt), true, msg, expr_span)
}
fn add_fake_borrows_of_base(
&mut self,
base_place: &PlaceBuilder<'tcx>,
block: BasicBlock,
fake_borrow_temps: &mut Vec<Local>,
expr_span: Span,
source_info: SourceInfo,
) {
let tcx = self.hir.tcx();
let place_ty = Place::ty_from(
&base_place.base,
&base_place.projection,
&self.local_decls,
tcx,
);
if let ty::Slice(_) = place_ty.ty.kind {
// We need to create fake borrows to ensure that the bounds
// check that we just did stays valid. Since we can't assign to
// unsized values, we only need to ensure that none of the
// pointers in the base place are modified.
for (idx, elem) in base_place.projection.iter().enumerate().rev() {
match elem {
ProjectionElem::Deref => {
let fake_borrow_deref_ty = Place::ty_from(
&base_place.base,
&base_place.projection[..idx],
&self.local_decls,
tcx,
).ty;
let fake_borrow_ty = tcx.mk_imm_ref(
tcx.lifetimes.re_erased,
fake_borrow_deref_ty,
);
let fake_borrow_temp = self.local_decls.push(
LocalDecl::new_temp(fake_borrow_ty, expr_span)
);
let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
self.cfg.push_assign(
block,
source_info,
&fake_borrow_temp.into(),
Rvalue::Ref(
tcx.lifetimes.re_erased,
BorrowKind::Shallow,
Place {
base: base_place.base.clone(),
projection,
}
),
);
fake_borrow_temps.push(fake_borrow_temp);
}
ProjectionElem::Index(_) => {
let index_ty = Place::ty_from(
&base_place.base,
&base_place.projection[..idx],
&self.local_decls,
tcx,
);
match index_ty.ty.kind {
// The previous index expression has already
// done any index expressions needed here.
ty::Slice(_) => break,
ty::Array(..) => (),
_ => bug!("unexpected index base"),
}
}
ProjectionElem::Field(..)
| ProjectionElem::Downcast(..)
| ProjectionElem::ConstantIndex { .. }
| ProjectionElem::Subslice { .. } => (),
}
}
}
}
fn read_fake_borrows(
&mut self,
block: BasicBlock,
fake_borrow_temps: &mut Vec<Local>,
source_info: SourceInfo,
) {
// All indexes have been evaluated now, read all of the
// fake borrows so that they are live across those index
// expressions.
for temp in fake_borrow_temps {
self.cfg.push(
block,
Statement {
source_info,
kind: StatementKind::FakeRead(
FakeReadCause::ForIndex,
Box::new(Place::from(*temp)),
)
}
);
}
}
}