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
use rustc::mir::*;
use rustc::mir::visit::{LvalueContext, MutVisitor, Visitor};
use rustc::mir::traversal::ReversePostorder;
use rustc::ty::TyCtxt;
use syntax_pos::Span;
use rustc_data_structures::indexed_vec::{IndexVec, Idx};
use std::iter;
use std::mem;
use std::usize;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TempState {
Undefined,
Defined {
location: Location,
uses: usize
},
Unpromotable,
PromotedOut
}
impl TempState {
pub fn is_promotable(&self) -> bool {
if let TempState::Defined { uses, .. } = *self {
uses > 0
} else {
false
}
}
}
#[derive(Debug)]
pub enum Candidate {
Ref(Location),
ShuffleIndices(BasicBlock)
}
struct TempCollector<'tcx> {
temps: IndexVec<Local, TempState>,
span: Span,
mir: &'tcx Mir<'tcx>,
}
impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> {
fn visit_lvalue(&mut self,
lvalue: &Lvalue<'tcx>,
context: LvalueContext<'tcx>,
location: Location) {
self.super_lvalue(lvalue, context, location);
if let Lvalue::Local(index) = *lvalue {
if self.mir.local_kind(index) != LocalKind::Temp {
return;
}
if context.is_drop() || context.is_storage_marker() {
return;
}
let temp = &mut self.temps[index];
if *temp == TempState::Undefined {
match context {
LvalueContext::Store |
LvalueContext::Call => {
*temp = TempState::Defined {
location: location,
uses: 0
};
return;
}
_ => { }
}
} else if let TempState::Defined { ref mut uses, .. } = *temp {
let allowed_use = match context {
LvalueContext::Borrow {..} => true,
_ => context.is_nonmutating_use()
};
if allowed_use {
*uses += 1;
return;
}
}
*temp = TempState::Unpromotable;
}
}
fn visit_source_info(&mut self, source_info: &SourceInfo) {
self.span = source_info.span;
}
}
pub fn collect_temps(mir: &Mir, rpo: &mut ReversePostorder) -> IndexVec<Local, TempState> {
let mut collector = TempCollector {
temps: IndexVec::from_elem(TempState::Undefined, &mir.local_decls),
span: mir.span,
mir: mir,
};
for (bb, data) in rpo {
collector.visit_basic_block_data(bb, data);
}
collector.temps
}
struct Promoter<'a, 'tcx: 'a> {
source: &'a mut Mir<'tcx>,
promoted: Mir<'tcx>,
temps: &'a mut IndexVec<Local, TempState>,
keep_original: bool
}
impl<'a, 'tcx> Promoter<'a, 'tcx> {
fn new_block(&mut self) -> BasicBlock {
let span = self.promoted.span;
self.promoted.basic_blocks_mut().push(BasicBlockData {
statements: vec![],
terminator: Some(Terminator {
source_info: SourceInfo {
span: span,
scope: ARGUMENT_VISIBILITY_SCOPE
},
kind: TerminatorKind::Return
}),
is_cleanup: false
})
}
fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
let last = self.promoted.basic_blocks().last().unwrap();
let data = &mut self.promoted[last];
data.statements.push(Statement {
source_info: SourceInfo {
span: span,
scope: ARGUMENT_VISIBILITY_SCOPE
},
kind: StatementKind::Assign(Lvalue::Local(dest), rvalue)
});
}
fn promote_temp(&mut self, temp: Local) -> Local {
let old_keep_original = self.keep_original;
let loc = match self.temps[temp] {
TempState::Defined { location, uses } if uses > 0 => {
if uses > 1 {
self.keep_original = true;
}
location
}
state => {
span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
temp, state);
}
};
if !self.keep_original {
self.temps[temp] = TempState::PromotedOut;
}
let no_stmts = self.source[loc.block].statements.len();
let new_temp = self.promoted.local_decls.push(
LocalDecl::new_temp(self.source.local_decls[temp].ty));
debug!("promote({:?} @ {:?}/{:?}, {:?})",
temp, loc, no_stmts, self.keep_original);
if loc.statement_index < no_stmts {
let (mut rvalue, source_info) = {
let statement = &mut self.source[loc.block].statements[loc.statement_index];
let rhs = match statement.kind {
StatementKind::Assign(_, ref mut rhs) => rhs,
_ => {
span_bug!(statement.source_info.span, "{:?} is not an assignment",
statement);
}
};
(if self.keep_original {
rhs.clone()
} else {
let unit = Rvalue::Aggregate(AggregateKind::Tuple, vec![]);
mem::replace(rhs, unit)
}, statement.source_info)
};
self.visit_rvalue(&mut rvalue, loc);
self.assign(new_temp, rvalue, source_info.span);
} else {
let terminator = if self.keep_original {
self.source[loc.block].terminator().clone()
} else {
let terminator = self.source[loc.block].terminator_mut();
let target = match terminator.kind {
TerminatorKind::Call { destination: Some((_, target)), .. } => target,
ref kind => {
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
}
};
Terminator {
source_info: terminator.source_info,
kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
target: target
})
}
};
match terminator.kind {
TerminatorKind::Call { mut func, mut args, .. } => {
self.visit_operand(&mut func, loc);
for arg in &mut args {
self.visit_operand(arg, loc);
}
let last = self.promoted.basic_blocks().last().unwrap();
let new_target = self.new_block();
*self.promoted[last].terminator_mut() = Terminator {
kind: TerminatorKind::Call {
func: func,
args: args,
cleanup: None,
destination: Some((Lvalue::Local(new_temp), new_target))
},
..terminator
};
}
ref kind => {
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
}
};
};
self.keep_original = old_keep_original;
new_temp
}
fn promote_candidate(mut self, candidate: Candidate) {
let span = self.promoted.span;
let new_operand = Operand::Constant(Constant {
span: span,
ty: self.promoted.return_ty,
literal: Literal::Promoted {
index: Promoted::new(self.source.promoted.len())
}
});
let mut rvalue = match candidate {
Candidate::Ref(Location { block: bb, statement_index: stmt_idx }) => {
let ref mut statement = self.source[bb].statements[stmt_idx];
match statement.kind {
StatementKind::Assign(_, ref mut rvalue) => {
mem::replace(rvalue, Rvalue::Use(new_operand))
}
_ => bug!()
}
}
Candidate::ShuffleIndices(bb) => {
match self.source[bb].terminator_mut().kind {
TerminatorKind::Call { ref mut args, .. } => {
Rvalue::Use(mem::replace(&mut args[2], new_operand))
}
_ => bug!()
}
}
};
self.visit_rvalue(&mut rvalue, Location {
block: BasicBlock::new(0),
statement_index: usize::MAX
});
self.assign(RETURN_POINTER, rvalue, span);
self.source.promoted.push(self.promoted);
}
}
impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
fn visit_lvalue(&mut self,
lvalue: &mut Lvalue<'tcx>,
context: LvalueContext<'tcx>,
location: Location) {
if let Lvalue::Local(ref mut temp) = *lvalue {
if self.source.local_kind(*temp) == LocalKind::Temp {
*temp = self.promote_temp(*temp);
}
}
self.super_lvalue(lvalue, context, location);
}
}
pub fn promote_candidates<'a, 'tcx>(mir: &mut Mir<'tcx>,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
mut temps: IndexVec<Local, TempState>,
candidates: Vec<Candidate>) {
debug!("promote_candidates({:?})", candidates);
for candidate in candidates.into_iter().rev() {
let (span, ty) = match candidate {
Candidate::Ref(Location { block: bb, statement_index: stmt_idx }) => {
let statement = &mir[bb].statements[stmt_idx];
let dest = match statement.kind {
StatementKind::Assign(ref dest, _) => dest,
_ => {
span_bug!(statement.source_info.span,
"expected assignment to promote");
}
};
if let Lvalue::Local(index) = *dest {
if temps[index] == TempState::PromotedOut {
continue;
}
}
(statement.source_info.span, dest.ty(mir, tcx).to_ty(tcx))
}
Candidate::ShuffleIndices(bb) => {
let terminator = mir[bb].terminator();
let ty = match terminator.kind {
TerminatorKind::Call { ref args, .. } => {
args[2].ty(mir, tcx)
}
_ => {
span_bug!(terminator.source_info.span,
"expected simd_shuffleN call to promote");
}
};
(terminator.source_info.span, ty)
}
};
let initial_locals = iter::once(LocalDecl::new_return_pointer(ty)).collect();
let mut promoter = Promoter {
promoted: Mir::new(
IndexVec::new(),
Some(VisibilityScopeData {
span: span,
parent_scope: None
}).into_iter().collect(),
IndexVec::new(),
ty,
initial_locals,
0,
vec![],
span
),
source: mir,
temps: &mut temps,
keep_original: false
};
assert_eq!(promoter.new_block(), START_BLOCK);
promoter.promote_candidate(candidate);
}
let promoted = |index: Local| temps[index] == TempState::PromotedOut;
for block in mir.basic_blocks_mut() {
block.statements.retain(|statement| {
match statement.kind {
StatementKind::Assign(Lvalue::Local(index), _) |
StatementKind::StorageLive(Lvalue::Local(index)) |
StatementKind::StorageDead(Lvalue::Local(index)) => {
!promoted(index)
}
_ => true
}
});
let terminator = block.terminator_mut();
match terminator.kind {
TerminatorKind::Drop { location: Lvalue::Local(index), target, .. } => {
if promoted(index) {
terminator.kind = TerminatorKind::Goto {
target: target
};
}
}
_ => {}
}
}
}