-
Notifications
You must be signed in to change notification settings - Fork 34
/
func.rs
675 lines (619 loc) · 23.5 KB
/
func.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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/*
* Released under the terms of the Apache 2.0 license with LLVM
* exception. See `LICENSE` for details.
*/
use crate::{
domtree, postorder, Allocation, Block, Function, Inst, InstRange, MachineEnv, Operand,
OperandConstraint, OperandKind, OperandPos, PReg, PRegSet, RegClass, VReg,
};
use alloc::vec::Vec;
use alloc::{format, vec};
use super::arbitrary::Result as ArbitraryResult;
use super::arbitrary::{Arbitrary, Unstructured};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InstOpcode {
Op,
Ret,
Branch,
}
#[derive(Clone, Debug)]
pub struct InstData {
op: InstOpcode,
operands: Vec<Operand>,
clobbers: Vec<PReg>,
is_safepoint: bool,
}
impl InstData {
pub fn branch() -> InstData {
InstData {
op: InstOpcode::Branch,
operands: vec![],
clobbers: vec![],
is_safepoint: false,
}
}
pub fn ret() -> InstData {
InstData {
op: InstOpcode::Ret,
operands: vec![],
clobbers: vec![],
is_safepoint: false,
}
}
}
#[derive(Clone)]
pub struct Func {
insts: Vec<InstData>,
blocks: Vec<InstRange>,
block_preds: Vec<Vec<Block>>,
block_succs: Vec<Vec<Block>>,
block_params_in: Vec<Vec<VReg>>,
block_params_out: Vec<Vec<Vec<VReg>>>,
num_vregs: usize,
reftype_vregs: Vec<VReg>,
debug_value_labels: Vec<(VReg, Inst, Inst, u32)>,
}
impl Function for Func {
fn num_insts(&self) -> usize {
self.insts.len()
}
fn num_blocks(&self) -> usize {
self.blocks.len()
}
fn entry_block(&self) -> Block {
debug_assert!(self.blocks.len() > 0);
Block::new(0)
}
fn block_insns(&self, block: Block) -> InstRange {
self.blocks[block.index()]
}
fn block_succs(&self, block: Block) -> &[Block] {
&self.block_succs[block.index()][..]
}
fn block_preds(&self, block: Block) -> &[Block] {
&self.block_preds[block.index()][..]
}
fn block_params(&self, block: Block) -> &[VReg] {
&self.block_params_in[block.index()][..]
}
fn is_ret(&self, insn: Inst) -> bool {
self.insts[insn.index()].op == InstOpcode::Ret
}
fn is_branch(&self, insn: Inst) -> bool {
self.insts[insn.index()].op == InstOpcode::Branch
}
fn branch_blockparams(&self, block: Block, _: Inst, succ: usize) -> &[VReg] {
&self.block_params_out[block.index()][succ][..]
}
fn requires_refs_on_stack(&self, insn: Inst) -> bool {
self.insts[insn.index()].is_safepoint
}
fn reftype_vregs(&self) -> &[VReg] {
&self.reftype_vregs[..]
}
fn debug_value_labels(&self) -> &[(VReg, Inst, Inst, u32)] {
&self.debug_value_labels[..]
}
fn inst_operands(&self, insn: Inst) -> &[Operand] {
&self.insts[insn.index()].operands[..]
}
fn inst_clobbers(&self, insn: Inst) -> PRegSet {
let mut set = PRegSet::default();
for &preg in &self.insts[insn.index()].clobbers {
set = set.with(preg);
}
set
}
fn num_vregs(&self) -> usize {
self.num_vregs
}
fn spillslot_size(&self, regclass: RegClass) -> usize {
match regclass {
// Test the case where 2 classes share the same
RegClass::Int => 1,
RegClass::Float => 1,
RegClass::Vector => 2,
}
}
}
struct FuncBuilder {
postorder: Vec<Block>,
idom: Vec<Block>,
f: Func,
insts_per_block: Vec<Vec<InstData>>,
}
impl FuncBuilder {
fn new() -> Self {
FuncBuilder {
postorder: vec![],
idom: vec![],
f: Func {
block_preds: vec![],
block_succs: vec![],
block_params_in: vec![],
block_params_out: vec![],
insts: vec![],
blocks: vec![],
num_vregs: 0,
reftype_vregs: vec![],
debug_value_labels: vec![],
},
insts_per_block: vec![],
}
}
pub fn add_block(&mut self) -> Block {
let b = Block::new(self.f.blocks.len());
self.f
.blocks
.push(InstRange::new(Inst::new(0), Inst::new(0)));
self.f.block_preds.push(vec![]);
self.f.block_succs.push(vec![]);
self.f.block_params_in.push(vec![]);
self.f.block_params_out.push(vec![]);
self.insts_per_block.push(vec![]);
b
}
pub fn add_inst(&mut self, block: Block, data: InstData) {
self.insts_per_block[block.index()].push(data);
}
pub fn add_edge(&mut self, from: Block, to: Block) {
self.f.block_succs[from.index()].push(to);
self.f.block_preds[to.index()].push(from);
}
pub fn set_block_params_in(&mut self, block: Block, params: &[VReg]) {
self.f.block_params_in[block.index()] = params.iter().cloned().collect();
}
pub fn set_block_params_out(&mut self, block: Block, params: Vec<Vec<VReg>>) {
self.f.block_params_out[block.index()] = params;
}
fn compute_doms(&mut self) {
self.postorder = postorder::calculate(self.f.blocks.len(), Block::new(0), |block| {
&self.f.block_succs[block.index()][..]
});
self.idom = domtree::calculate(
self.f.blocks.len(),
|block| &self.f.block_preds[block.index()][..],
&self.postorder[..],
Block::new(0),
);
}
fn finalize(mut self) -> Func {
for (blocknum, blockrange) in self.f.blocks.iter_mut().enumerate() {
let begin_inst = self.f.insts.len();
for inst in &self.insts_per_block[blocknum] {
self.f.insts.push(inst.clone());
}
let end_inst = self.f.insts.len();
*blockrange = InstRange::new(Inst::new(begin_inst), Inst::new(end_inst));
}
self.f
}
}
impl Arbitrary<'_> for RegClass {
fn arbitrary(u: &mut Unstructured) -> ArbitraryResult<Self> {
Ok(*u.choose(&[RegClass::Int, RegClass::Float, RegClass::Vector])?)
}
}
impl Arbitrary<'_> for OperandConstraint {
fn arbitrary(u: &mut Unstructured) -> ArbitraryResult<Self> {
Ok(*u.choose(&[OperandConstraint::Any, OperandConstraint::Reg])?)
}
}
fn choose_dominating_block(
idom: &[Block],
mut block: Block,
allow_self: bool,
u: &mut Unstructured,
) -> ArbitraryResult<Block> {
debug_assert!(block.is_valid());
let orig_block = block;
loop {
if (allow_self || block != orig_block) && bool::arbitrary(u)? {
break;
}
if idom[block.index()].is_invalid() {
break;
}
block = idom[block.index()];
}
let block = if block != orig_block || allow_self {
block
} else {
Block::invalid()
};
Ok(block)
}
#[derive(Clone, Copy, Debug)]
pub struct Options {
pub reused_inputs: bool,
pub fixed_regs: bool,
pub fixed_nonallocatable: bool,
pub clobbers: bool,
pub reftypes: bool,
}
impl core::default::Default for Options {
fn default() -> Self {
Options {
reused_inputs: false,
fixed_regs: false,
fixed_nonallocatable: false,
clobbers: false,
reftypes: false,
}
}
}
impl Arbitrary<'_> for Func {
fn arbitrary(u: &mut Unstructured) -> ArbitraryResult<Func> {
Func::arbitrary_with_options(u, &Options::default())
}
}
impl Func {
pub fn arbitrary_with_options(u: &mut Unstructured, opts: &Options) -> ArbitraryResult<Func> {
// General strategy:
// 1. Create an arbitrary CFG.
// 2. Create a list of vregs to define in each block.
// 3. Define some of those vregs in each block as blockparams.f.
// 4. Populate blocks with ops that define the rest of the vregs.
// - For each use, choose an available vreg: either one
// already defined (via blockparam or inst) in this block,
// or one defined in a dominating block.
let mut builder = FuncBuilder::new();
for _ in 0..u.int_in_range(1..=100)? {
builder.add_block();
}
let num_blocks = builder.f.blocks.len();
// Generate a CFG. Create a "spine" of either single blocks,
// with links to the next; or fork patterns, with the left
// fork linking to the next and the right fork in `out_blocks`
// to be connected below. This creates an arbitrary CFG with
// split critical edges, which is a property that we require
// for the regalloc.
let mut from = 0;
let mut out_blocks = vec![];
let mut in_blocks = vec![];
while from < num_blocks {
in_blocks.push(from);
if num_blocks > 3 && from < num_blocks - 3 && bool::arbitrary(u)? {
// To avoid critical edges, we use from+1 as an edge
// block, and advance `from` an extra block; `from+2`
// will be the next normal iteration.
builder.add_edge(Block::new(from), Block::new(from + 1));
builder.add_edge(Block::new(from), Block::new(from + 2));
builder.add_edge(Block::new(from + 2), Block::new(from + 3));
out_blocks.push(from + 1);
from += 2;
} else if from < num_blocks - 1 {
builder.add_edge(Block::new(from), Block::new(from + 1));
}
from += 1;
}
for pred in out_blocks {
let succ = *u.choose(&in_blocks[..])?;
builder.add_edge(Block::new(pred), Block::new(succ));
}
builder.compute_doms();
for block in 0..num_blocks {
builder.f.block_preds[block].clear();
}
for block in 0..num_blocks {
for &succ in &builder.f.block_succs[block] {
builder.f.block_preds[succ.index()].push(Block::new(block));
}
}
builder.compute_doms();
let mut vregs_by_block = vec![];
let mut vregs_by_block_to_be_defined = vec![];
let mut block_params = vec![vec![]; num_blocks];
for block in 0..num_blocks {
let mut vregs = vec![];
for _ in 0..u.int_in_range(5..=15)? {
let vreg = VReg::new(builder.f.num_vregs, RegClass::arbitrary(u)?);
builder.f.num_vregs += 1;
vregs.push(vreg);
if opts.reftypes && bool::arbitrary(u)? {
builder.f.reftype_vregs.push(vreg);
}
if bool::arbitrary(u)? {
let assumed_end_inst = 10 * num_blocks;
let mut start = u.int_in_range::<usize>(0..=assumed_end_inst)?;
for _ in 0..10 {
if start >= assumed_end_inst {
break;
}
let end = u.int_in_range::<usize>(start..=assumed_end_inst)?;
let label = u.int_in_range::<u32>(0..=100)?;
builder.f.debug_value_labels.push((
vreg,
Inst::new(start),
Inst::new(end),
label,
));
start = end;
}
}
}
vregs_by_block.push(vregs.clone());
let mut vregs_to_be_defined = vec![];
let mut max_block_params = u.int_in_range(0..=core::cmp::min(3, vregs.len() / 3))?;
for &vreg in &vregs {
if block > 0 && bool::arbitrary(u)? && max_block_params > 0 {
block_params[block].push(vreg);
max_block_params -= 1;
} else {
vregs_to_be_defined.push(vreg);
}
}
vregs_to_be_defined.reverse();
vregs_by_block_to_be_defined.push(vregs_to_be_defined);
builder.set_block_params_in(Block::new(block), &block_params[block][..]);
}
for block in 0..num_blocks {
let mut avail = block_params[block].clone();
let mut remaining_nonlocal_uses = u.int_in_range(0..=3)?;
while let Some(vreg) = vregs_by_block_to_be_defined[block].pop() {
let def_constraint = OperandConstraint::arbitrary(u)?;
let def_pos = if bool::arbitrary(u)? {
OperandPos::Early
} else {
OperandPos::Late
};
let mut operands = vec![Operand::new(
vreg,
def_constraint,
OperandKind::Def,
def_pos,
)];
let mut allocations = vec![Allocation::none()];
for _ in 0..u.int_in_range(0..=3)? {
let vreg = if avail.len() > 0
&& (remaining_nonlocal_uses == 0 || bool::arbitrary(u)?)
{
*u.choose(&avail[..])?
} else {
let def_block = choose_dominating_block(
&builder.idom[..],
Block::new(block),
/* allow_self = */ false,
u,
)?;
if !def_block.is_valid() {
// No vregs already defined, and no pred blocks that dominate us
// (perhaps we are the entry block): just stop generating inputs.
break;
}
remaining_nonlocal_uses -= 1;
*u.choose(&vregs_by_block[def_block.index()])?
};
let use_constraint = OperandConstraint::arbitrary(u)?;
operands.push(Operand::new(
vreg,
use_constraint,
OperandKind::Use,
OperandPos::Early,
));
allocations.push(Allocation::none());
}
let mut clobbers: Vec<PReg> = vec![];
if operands.len() > 1 && opts.reused_inputs && bool::arbitrary(u)? {
// Make the def a reused input.
let op = operands[0];
debug_assert_eq!(op.kind(), OperandKind::Def);
let reused = u.int_in_range(1..=(operands.len() - 1))?;
if op.class() == operands[reused].class() {
operands[0] = Operand::new(
op.vreg(),
OperandConstraint::Reuse(reused),
op.kind(),
OperandPos::Late,
);
// Make sure reused input is a Reg.
let op = operands[reused];
operands[reused] = Operand::new(
op.vreg(),
OperandConstraint::Reg,
op.kind(),
OperandPos::Early,
);
}
} else if opts.fixed_regs && bool::arbitrary(u)? {
let mut fixed_early = vec![];
let mut fixed_late = vec![];
for _ in 0..u.int_in_range(0..=operands.len() - 1)? {
// Pick an operand and make it a fixed reg.
let i = u.int_in_range(0..=(operands.len() - 1))?;
let op = operands[i];
let fixed_reg = PReg::new(u.int_in_range(0..=62)?, op.class());
if op.kind() == OperandKind::Def && op.pos() == OperandPos::Early {
// Early-defs with fixed constraints conflict with
// any other fixed uses of the same preg.
if fixed_late.contains(&fixed_reg) {
break;
}
}
if op.kind() == OperandKind::Use && op.pos() == OperandPos::Late {
// Late-use with fixed constraints conflict with
// any other fixed uses of the same preg.
if fixed_early.contains(&fixed_reg) {
break;
}
}
let fixed_list = match op.pos() {
OperandPos::Early => &mut fixed_early,
OperandPos::Late => &mut fixed_late,
};
if fixed_list.contains(&fixed_reg) {
break;
}
fixed_list.push(fixed_reg);
operands[i] = Operand::new(
op.vreg(),
OperandConstraint::FixedReg(fixed_reg),
op.kind(),
op.pos(),
);
}
} else if opts.clobbers && bool::arbitrary(u)? {
for _ in 0..u.int_in_range(0..=5)? {
let reg = u.int_in_range(0..=30)?;
if clobbers.iter().any(|r| r.hw_enc() == reg) {
break;
}
clobbers.push(PReg::new(reg, RegClass::arbitrary(u)?));
}
} else if opts.fixed_nonallocatable && bool::arbitrary(u)? {
operands.push(Operand::fixed_nonallocatable(PReg::new(
63,
RegClass::arbitrary(u)?,
)));
}
let is_safepoint = opts.reftypes
&& operands
.iter()
.all(|op| !builder.f.reftype_vregs.contains(&op.vreg()))
&& bool::arbitrary(u)?;
builder.add_inst(
Block::new(block),
InstData {
op: InstOpcode::Op,
operands,
clobbers,
is_safepoint,
},
);
avail.push(vreg);
}
// Define the branch with blockparam args that must end
// the block.
if builder.f.block_succs[block].len() > 0 {
let mut params = vec![];
for &succ in &builder.f.block_succs[block] {
let mut args = vec![];
for i in 0..builder.f.block_params_in[succ.index()].len() {
let dom_block = choose_dominating_block(
&builder.idom[..],
Block::new(block),
false,
u,
)?;
// Look for a vreg with a suitable class. If no
// suitable vreg is available then we error out, which
// causes the fuzzer to skip this function.
let vregs = if dom_block.is_valid() && bool::arbitrary(u)? {
&vregs_by_block[dom_block.index()][..]
} else {
&avail[..]
};
let suitable_vregs: Vec<_> = vregs
.iter()
.filter(|vreg| {
vreg.class() == builder.f.block_params_in[succ.index()][i].class()
})
.copied()
.collect();
let vreg = u.choose(&suitable_vregs)?;
args.push(*vreg);
}
params.push(args);
}
builder.set_block_params_out(Block::new(block), params);
builder.add_inst(Block::new(block), InstData::branch());
} else {
builder.add_inst(Block::new(block), InstData::ret());
}
}
builder.f.debug_value_labels.sort_unstable();
Ok(builder.finalize())
}
}
impl core::fmt::Debug for Func {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "{{\n")?;
for vreg in self.reftype_vregs() {
write!(f, " REF: {}\n", vreg)?;
}
for (i, blockrange) in self.blocks.iter().enumerate() {
let succs = self.block_succs[i]
.iter()
.map(|b| b.index())
.collect::<Vec<_>>();
let preds = self.block_preds[i]
.iter()
.map(|b| b.index())
.collect::<Vec<_>>();
let params_in = self.block_params_in[i]
.iter()
.map(|v| format!("v{}", v.vreg()))
.collect::<Vec<_>>()
.join(", ");
let params_out = self.block_params_out[i]
.iter()
.enumerate()
.map(|(succ_idx, vec)| {
let succ = self.block_succs[i][succ_idx];
let params = vec
.iter()
.map(|v| format!("v{}", v.vreg()))
.collect::<Vec<_>>()
.join(", ");
format!("block{}({})", succ.index(), params)
})
.collect::<Vec<_>>()
.join(", ");
write!(
f,
" block{}({}): # succs:{:?} preds:{:?}\n",
i, params_in, succs, preds
)?;
for inst in blockrange.iter() {
if self.requires_refs_on_stack(inst) {
write!(f, " -- SAFEPOINT --\n")?;
}
write!(
f,
" inst{}: {:?} ops:{:?} clobber:{:?}\n",
inst.index(),
self.insts[inst.index()].op,
self.insts[inst.index()].operands,
self.insts[inst.index()].clobbers
)?;
if let InstOpcode::Branch = self.insts[inst.index()].op {
write!(f, " params: {}\n", params_out)?;
}
}
}
write!(f, "}}\n")?;
Ok(())
}
}
pub fn machine_env() -> MachineEnv {
fn regs(r: core::ops::Range<usize>, c: RegClass) -> Vec<PReg> {
r.map(|i| PReg::new(i, c)).collect()
}
let preferred_regs_by_class: [Vec<PReg>; 3] = [
regs(0..24, RegClass::Int),
regs(0..24, RegClass::Float),
regs(0..24, RegClass::Vector),
];
let non_preferred_regs_by_class: [Vec<PReg>; 3] = [
regs(24..32, RegClass::Int),
regs(24..32, RegClass::Float),
regs(24..32, RegClass::Vector),
];
let scratch_by_class: [Option<PReg>; 3] = [None, None, None];
let fixed_stack_slots = (32..63)
.flat_map(|i| {
[
PReg::new(i, RegClass::Int),
PReg::new(i, RegClass::Float),
PReg::new(i, RegClass::Vector),
]
})
.collect();
// Register 63 is reserved for use as a fixed non-allocatable register.
MachineEnv {
preferred_regs_by_class,
non_preferred_regs_by_class,
scratch_by_class,
fixed_stack_slots,
}
}