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
use rustc_middle::mir::patch::MirPatch;
use rustc_middle::mir::*;
use rustc_middle::ty::{Ty, TyCtxt};
use std::fmt::Debug;
use super::simplify::simplify_cfg;
pub struct EarlyOtherwiseBranch;
impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch {
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
if !tcx.sess.opts.debugging_opts.unsound_mir_opts {
return;
}
if tcx.sess.mir_opt_level() < 3 {
return;
}
trace!("running EarlyOtherwiseBranch on {:?}", body.source);
let bbs_with_switch =
body.basic_blocks().iter_enumerated().filter(|(_, bb)| is_switch(bb.terminator()));
let opts_to_apply: Vec<OptimizationToApply<'tcx>> = bbs_with_switch
.flat_map(|(bb_idx, bb)| {
let switch = bb.terminator();
let helper = Helper { body, tcx };
let infos = helper.go(bb, switch)?;
Some(OptimizationToApply { infos, basic_block_first_switch: bb_idx })
})
.collect();
let should_cleanup = !opts_to_apply.is_empty();
for opt_to_apply in opts_to_apply {
if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {:?}", &opt_to_apply)) {
break;
}
trace!("SUCCESS: found optimization possibility to apply: {:?}", &opt_to_apply);
let statements_before =
body.basic_blocks()[opt_to_apply.basic_block_first_switch].statements.len();
let end_of_block_location = Location {
block: opt_to_apply.basic_block_first_switch,
statement_index: statements_before,
};
let mut patch = MirPatch::new(body);
let discr_type = opt_to_apply.infos[0].second_switch_info.discr_ty;
let discr_span = opt_to_apply.infos[0].second_switch_info.discr_source_info.span;
let second_discriminant_temp = patch.new_temp(discr_type, discr_span);
patch.add_statement(
end_of_block_location,
StatementKind::StorageLive(second_discriminant_temp),
);
let place_of_adt_to_get_discriminant_of =
opt_to_apply.infos[0].second_switch_info.place_of_adt_discr_read;
patch.add_assign(
end_of_block_location,
Place::from(second_discriminant_temp),
Rvalue::Discriminant(place_of_adt_to_get_discriminant_of),
);
let not_equal = BinOp::Ne;
let not_equal_res_type = not_equal.ty(tcx, discr_type, discr_type);
let not_equal_temp = patch.new_temp(not_equal_res_type, discr_span);
patch.add_statement(end_of_block_location, StatementKind::StorageLive(not_equal_temp));
let first_descriminant_place =
opt_to_apply.infos[0].first_switch_info.discr_used_in_switch;
let not_equal_rvalue = Rvalue::BinaryOp(
not_equal,
Box::new((
Operand::Copy(Place::from(second_discriminant_temp)),
Operand::Copy(first_descriminant_place),
)),
);
patch.add_statement(
end_of_block_location,
StatementKind::Assign(Box::new((Place::from(not_equal_temp), not_equal_rvalue))),
);
let new_targets = opt_to_apply
.infos
.iter()
.flat_map(|x| x.second_switch_info.targets_with_values.iter())
.cloned();
let targets = SwitchTargets::new(
new_targets,
opt_to_apply.infos[0].first_switch_info.otherwise_bb,
);
let new_switch_data = BasicBlockData::new(Some(Terminator {
source_info: opt_to_apply.infos[0].second_switch_info.discr_source_info,
kind: TerminatorKind::SwitchInt {
discr: Operand::Copy(first_descriminant_place),
switch_ty: discr_type,
targets,
},
}));
let new_switch_bb = patch.new_block(new_switch_data);
let true_case = opt_to_apply.infos[0].first_switch_info.otherwise_bb;
let false_case = new_switch_bb;
patch.patch_terminator(
opt_to_apply.basic_block_first_switch,
TerminatorKind::if_(
tcx,
Operand::Move(Place::from(not_equal_temp)),
true_case,
false_case,
),
);
patch.add_statement(
end_of_block_location,
StatementKind::StorageDead(second_discriminant_temp),
);
for bb in [false_case, true_case].iter() {
patch.add_statement(
Location { block: *bb, statement_index: 0 },
StatementKind::StorageDead(not_equal_temp),
);
}
patch.apply(body);
}
if should_cleanup {
simplify_cfg(tcx, body);
}
}
}
fn is_switch<'tcx>(terminator: &Terminator<'tcx>) -> bool {
matches!(terminator.kind, TerminatorKind::SwitchInt { .. })
}
struct Helper<'a, 'tcx> {
body: &'a Body<'tcx>,
tcx: TyCtxt<'tcx>,
}
#[derive(Debug, Clone)]
struct SwitchDiscriminantInfo<'tcx> {
discr_ty: Ty<'tcx>,
otherwise_bb: BasicBlock,
targets_with_values: Vec<(u128, BasicBlock)>,
discr_source_info: SourceInfo,
discr_used_in_switch: Place<'tcx>,
place_of_adt_discr_read: Place<'tcx>,
type_adt_matched_on: Ty<'tcx>,
}
#[derive(Debug)]
struct OptimizationToApply<'tcx> {
infos: Vec<OptimizationInfo<'tcx>>,
basic_block_first_switch: BasicBlock,
}
#[derive(Debug)]
struct OptimizationInfo<'tcx> {
first_switch_info: SwitchDiscriminantInfo<'tcx>,
second_switch_info: SwitchDiscriminantInfo<'tcx>,
}
impl<'a, 'tcx> Helper<'a, 'tcx> {
pub fn go(
&self,
bb: &BasicBlockData<'tcx>,
switch: &Terminator<'tcx>,
) -> Option<Vec<OptimizationInfo<'tcx>>> {
let discr = self.find_switch_discriminant_info(bb, switch)?;
let results = discr
.targets_with_values
.iter()
.map(|(value, target)| self.find_discriminant_switch_pairing(&discr, *target, *value));
if results.clone().any(|x| x.is_none()) || results.len() == 0 {
trace!("NO: not all of the targets matched the pattern for optimization");
return None;
}
Some(results.flatten().collect())
}
fn find_discriminant_switch_pairing(
&self,
discr_info: &SwitchDiscriminantInfo<'tcx>,
target: BasicBlock,
value: u128,
) -> Option<OptimizationInfo<'tcx>> {
let bb = &self.body.basic_blocks()[target];
let terminator = bb.terminator();
if is_switch(terminator) {
let this_bb_discr_info = self.find_switch_discriminant_info(bb, terminator)?;
if discr_info.type_adt_matched_on != this_bb_discr_info.type_adt_matched_on {
trace!(
"NO: types do not match. LHS: {:?}, RHS: {:?}",
discr_info.type_adt_matched_on,
this_bb_discr_info.type_adt_matched_on
);
return None;
}
if discr_info.otherwise_bb != this_bb_discr_info.otherwise_bb {
trace!("NO: otherwise target is not the same");
return None;
}
if !this_bb_discr_info.targets_with_values.iter().any(|x| x.0 == value) {
trace!("NO: values being matched on are not the same");
return None;
}
if !(this_bb_discr_info.targets_with_values.len() == 1
&& this_bb_discr_info.targets_with_values[0].0 == value)
{
trace!(
"NO: The second switch did not have only 1 target (besides otherwise) that had the same value as the value from the first switch that got us here"
);
return None;
}
let discr_place = discr_info.place_of_adt_discr_read;
let this_discr_place = this_bb_discr_info.place_of_adt_discr_read;
if discr_place.local == this_discr_place.local
&& this_discr_place.projection.starts_with(discr_place.projection)
{
trace!("NO: one target is the projection of another");
return None;
}
Some(OptimizationInfo {
first_switch_info: discr_info.clone(),
second_switch_info: this_bb_discr_info,
})
} else {
None
}
}
fn find_switch_discriminant_info(
&self,
bb: &BasicBlockData<'tcx>,
switch: &Terminator<'tcx>,
) -> Option<SwitchDiscriminantInfo<'tcx>> {
match &switch.kind {
TerminatorKind::SwitchInt { discr, targets, .. } => {
let discr_local = discr.place()?.as_local()?;
let discr_decl = &self.body.local_decls()[discr_local];
let discr_ty = discr_decl.ty;
let otherwise_bb = targets.otherwise();
let targets_with_values = targets.iter().collect();
let place_of_adt_discr_read = match bb.statements.last()?.kind {
StatementKind::Assign(box (_, Rvalue::Discriminant(adt_place))) => {
Some(adt_place)
}
_ => None,
}?;
let type_adt_matched_on = place_of_adt_discr_read.ty(self.body, self.tcx).ty;
Some(SwitchDiscriminantInfo {
discr_used_in_switch: discr.place()?,
discr_ty,
otherwise_bb,
targets_with_values,
discr_source_info: discr_decl.source_info,
place_of_adt_discr_read,
type_adt_matched_on,
})
}
_ => unreachable!("must only be passed terminator that is a switch"),
}
}
}