rucc_codegen/layout.rs
1//! Putting the blocks in an order, and turning the edges between them into jumps.
2//!
3//! Design: `spec/10-backend.md` section 10.6.
4//!
5//! Up to here a function is a set of blocks and a set of edges, and nothing has said which block
6//! comes first in memory. A machine has no such thing: it runs the instruction after the one it
7//! just ran, so an order is not a presentation detail but the last piece of what the function
8//! means. This is what chooses one, and then writes the jumps that make the edges the order did
9//! not put next to each other still go where they went.
10//!
11//! # What the order is
12//!
13//! Two orders, and which one is used is what `-freorder-blocks` asks about.
14//!
15//! At `-O0`, reverse postorder over the CFG, with each block's successors walked in reverse, and
16//! anything unreachable put at the end in block order. That is the order `spec/10-backend.md`
17//! section 10.3 asks for, and it is not arbitrary. Walking the successors in reverse is what
18//! makes the first arm of a branch come out first, because a depth-first walk finishes its last
19//! child first and reverse postorder then puts that child last. So an `if` with no `else` falls
20//! through into its body, and a loop comes out as its header, its body and then whatever follows
21//! it, which is the shape where the back edge is the only jump in it.
22//!
23//! Above it, traces: the software trace cache construction of
24//! `spec/optimizer/38-scheduling-and-layout.md` section 38.4, which is `traces` below.
25//!
26//! Unreachable blocks are laid out rather than deleted. Deleting one is a decision about what the
27//! program does and this pass has no business making it, and a block nothing reaches costs the
28//! bytes it occupies and nothing else.
29//!
30//! # What a block looks like afterwards
31//!
32//! A block still holds where it goes, and it still holds every arm, which is what keeps the
33//! control flow graph readable after this has run. What changes is that the order the arms are in
34//! now means something it did not mean before:
35//!
36//! ```text
37//! no arms it returns
38//! one arm it falls into that block if that block is next, and jumps to it if not
39//! two arms a test and a conditional jump to the first, and the second is always next
40//! ```
41//!
42//! So a jump target is a block without an instruction growing a field for one.
43//! `rucc_mir::InstData` is twenty four bytes by assertion and a block reference does not fit in
44//! it, and every pass over the graph already reads the arms, so putting the target where the
45//! graph already is costs nothing and keeps the two from disagreeing.
46//!
47//! Which arm is which is no longer which way the condition went, because a block that falls into
48//! the arm the condition is true for is a block whose jump has to be taken when it is false. That
49//! is what the two conditional jumps in [`BranchInsts`] are for, and it is why the arms may come
50//! out swapped: what the condition meant is in the opcode afterwards, and what the arms mean is
51//! where the jump goes and what comes next.
52//!
53//! # The one block none of that is true of
54//!
55//! A block that ends in the jump through a register, which is what a computed `goto` is selected
56//! as. Where it goes is in the register, so the arms are the whole list of places it might arrive
57//! at and there may be any number of them. Nothing is written here for such a block: the jump is
58//! already in it, none of its arms is fallen into and none is jumped to from here, and a jump
59//! written behind that one would be a jump nothing reaches. The arms stay on the block for the
60//! reason they stay on every other one, which is that the liveness and this pass both read them.
61//!
62//! # The block a branch sometimes needs
63//!
64//! A branch whose second arm cannot be laid out next, because both its arms are blocks the walk
65//! has already been to, would need two jumps in one block. Rather than write one, this makes the
66//! block it needs: an empty one on the second edge, laid out immediately after the branch, that
67//! jumps where the edge went. That is exactly the critical edge splitting in [`crate::split`],
68//! done for a different reason, and it costs the same jump the second jump would have cost while
69//! leaving every block with at most one.
70//!
71//! # The test a comparison makes unnecessary
72//!
73//! Almost every branch a C program writes is on a comparison, and a comparison has already set
74//! the flags by the time the byte it wrote is tested against itself. So where the instruction in
75//! front of the branch is that comparison, and the branch is the whole of what reads its byte,
76//! the byte and the test both go and the jump names the condition the comparison was asked about
77//! instead of naming zero. Three instructions become two, and the two are what the machine has a
78//! comparison and a conditional jump for.
79//!
80//! This is where it happens rather than anywhere earlier because of what the flags are. Between
81//! the comparison and the jump they are live and they are not a register: no pass could be told
82//! about them, so no pass may put an instruction between the two. After this one there is no pass
83//! left, which is the whole of the argument, and it is the same argument
84//! `rucc_target::x86_64::Form::CmpSet` is one form rather than two under.
85//!
86//! What this cannot work out for itself is whether the byte has another reader. Every register is
87//! physical by the time this runs and a physical register is written many times in a function, so
88//! the question has to be asked while they are still virtual and written once. [`fusable`] is that
89//! question, asked before allocation, and its answer is one of the arguments to [`blocks`]. The
90//! same arrangement, and for the same reason, as the addresses [`crate::finish`] has still to
91//! write and [`crate::fold`] is handed.
92//!
93//! # Why it runs last
94//!
95//! [`crate::finish`] finds the blocks a function returns from by looking for the ones that go
96//! nowhere. Nothing here creates one of those, but everything here reads and writes the arms, and
97//! a pass that reorders them is one nothing before it should be looking at. Running the layout
98//! after the prologue and the epilogue are in is also what makes the epilogue something it can
99//! lay out around rather than something it has to leave room for.
100
101use std::cmp::Reverse;
102use std::collections::{BinaryHeap, HashMap, HashSet};
103
104use rucc_base::Interner;
105use rucc_mir as mir;
106use rucc_target::{BranchInsts, Fusion, Role};
107
108/// The scale a weight is in, which is what a share of a block is worked out against.
109const SCALE: u128 = mir::Weight::SCALE as u128;
110
111/// Puts a function's blocks in an order and writes the jumps that order needs.
112///
113/// Run last, after [`crate::finish`].
114///
115/// # Panics
116///
117/// Panics on a block with more than two successors that does not end in the jump through a
118/// register, which is the only thing that lowers to one, and on a block with two whose last
119/// instruction is not the conditional branch the target named. Both are a function that was built
120/// wrongly somewhere earlier, and both are worth finding here rather than as a jump to the wrong
121/// place.
122pub fn blocks(
123 func: &mut mir::Func,
124 insts: &BranchInsts,
125 names: &mut Interner,
126 fusable: &HashSet<mir::Inst>,
127 reorder: bool,
128) {
129 let table = table(insts, names);
130 let mut order = if reorder { traces(func) } else { order(func) };
131 let mut writer = Writer { func, insts, names, table, fusable };
132 let mut at = 0;
133 while at < order.len() {
134 // A branch that can fall into neither arm asks for a block to put the second jump in, and
135 // that block goes immediately after it, which is where the loop reaches it next.
136 if let Some(bridge) = writer.edges(order[at], order.get(at + 1).copied()) {
137 order.insert(at + 1, bridge);
138 }
139 at += 1;
140 }
141 func.set_block_order(&order);
142}
143
144/// The order the blocks are laid out in, which is every block the function has exactly once.
145fn order(func: &mir::Func) -> Vec<mir::Block> {
146 let mut order = Vec::with_capacity(func.block_count());
147 let mut seen = vec![false; func.block_count()];
148 if let Some(entry) = func.entry() {
149 seen[entry.index()] = true;
150 // The walk is explicit rather than recursive because a function with a hundred thousand
151 // blocks in it is a function somebody generated, and it should compile rather than run out
152 // of stack. Each entry is a block and how many of its arms have been started.
153 let mut stack = vec![(entry, 0usize)];
154 while let Some((block, next)) = stack.pop() {
155 let succs = &func[block].succs;
156 let Some(arm) = succs.len().checked_sub(next + 1) else {
157 order.push(block);
158 continue;
159 };
160 stack.push((block, next + 1));
161 let to = succs[arm].block;
162 if !std::mem::replace(&mut seen[to.index()], true) {
163 stack.push((to, 0));
164 }
165 }
166 order.reverse();
167 }
168 // Whatever the walk did not reach, in the order the blocks were made, which is the only order
169 // there is anything to be said for when nothing goes to any of them.
170 order.extend(func.blocks().filter(|block| !seen[block.index()]));
171 order
172}
173
174/// The rounds the traces are built in, each asking for less than the one before it.
175///
176/// Design: `spec/optimizer/38-scheduling-and-layout.md` section 38.4, which quotes
177/// `gcc/bb-reorder.cc:32` on why there is more than one round: a first round that only follows
178/// the arms almost always taken builds the trunk of the function, and the rounds below it pick up
179/// what is left without being able to break the trunk apart. It costs one more pass over the
180/// blocks per round and it is the difference between "stc" and "simple".
181///
182/// A round is a pair. The first number is how likely an arm has to be for the trace to follow it,
183/// in parts of [`mir::Weight::SCALE`], which is GCC's branch threshold. The second is how often
184/// the block at the end of that arm has to run, in the same parts of how often the function is
185/// entered, which is GCC's exec threshold. The last round asks for nothing, which is what makes
186/// every block end up somewhere.
187///
188/// The eight numbers are GCC's own, out of `branch_threshold` and `exec_threshold` in
189/// `gcc/bb-reorder.cc`, in ten thousandths where GCC writes thousandths. Two things about them
190/// are worth saying out loud because both were got wrong here first.
191///
192/// The branch threshold is low. Two fifths, not nine tenths: an arm taken half the time is an arm
193/// the first round follows, and since one arm of a two way branch always is, the first round walks
194/// straight through an unpredicted function the way a depth first walk would. A high threshold
195/// stops the trace at every branch nothing predicted, which is most of them, and hands both arms
196/// back to the seed list to be laid out by weight, and weight is exactly what has nothing to say
197/// about them.
198///
199/// The exec threshold is against the entry and not against the hottest block. A block that runs
200/// once per call is a block in the trunk of the function, and measuring it against a loop that
201/// runs twenty times a call makes the whole trunk cold: the preheader of every loop lands at the
202/// end of the function behind a jump, which is the opposite of what this is for.
203const ROUNDS: [(u64, u64); 4] = [(4_000, 5_000), (2_000, 2_000), (1_000, 500), (0, 0)];
204
205/// The order the blocks are laid out in above `-O0`, which is traces grown from the hottest
206/// blocks outwards.
207///
208/// Design: `spec/optimizer/38-scheduling-and-layout.md` section 38.4.
209///
210/// A trace is a run of blocks that control is expected to walk straight through. It is grown from
211/// a seed by repeatedly taking the arm most likely to be the one taken, stopping when no arm is
212/// likely enough for the round or when the likeliest one leads somewhere the layout has already
213/// been. Every block is a seed in some round, the hotter ones first, and the traces come out in
214/// the order they were grown. So the function's trunk is laid out first and contiguously, its
215/// error paths end up behind it, and the branch that leaves the trunk is the one that costs a
216/// jump.
217///
218/// The entry is the first seed whatever its weight, because on this machine a function is entered
219/// at its first byte and the block laid out first is the block that runs first. A hotter block
220/// inside a loop would otherwise take the seat.
221///
222/// The traces are then run together by [`connect`], which is what keeps a run of blocks the rounds
223/// cut in half from coming out in two places.
224///
225/// # Which block the next trace starts at
226///
227/// Not simply the hottest one left. A block something already laid out goes to comes first, and
228/// among those the one with the hottest edge into it, which is [`Seed`] and which is GCC's
229/// `bb_to_key` in `gcc/bb-reorder.cc`. The reason is the whole of what a layout costs: a block laid
230/// out in front of everything that reaches it pays a jump on every one of those paths and saves
231/// nothing, and a block laid out behind the trace that reaches it pays nothing on the path that
232/// falls into it. Seeding by weight alone gets this wrong on the commonest shape in C, which is two
233/// arms that both end at one block: the block both arms join at is the hottest of the three and
234/// goes first, and then both arms jump to it.
235///
236/// # Loop rotation, and where it comes from
237///
238/// Section 38.4 asks for the loop to be rotated so that its exit is the last block of the trace,
239/// and there is no step here that does it. It falls out of the walk instead: a trace that enters
240/// a loop header follows the body, reaches the latch, finds that the latch's likeliest arm is the
241/// header it has already laid out, and stops. The exit is then a seed of its own and comes next.
242/// That is the rotated order, back edge running backwards and exit falling through, arrived at
243/// from the greedy rule rather than from a rule about loops.
244///
245/// What that does not cover is a loop whose header is its exit test and whose body is cold, where
246/// GCC would duplicate the header. Section 38.4 says the first version should not copy code and
247/// this does not.
248fn traces(func: &mir::Func) -> Vec<mir::Block> {
249 // Where the shape of the graph would have put each block, which is what decides between two
250 // blocks that run equally often. Most branches in most functions have nothing to predict them
251 // by and come out even, so without this the seed order between them would be the order the
252 // blocks happen to have been made in, and a block that falls into the one after it under
253 // [`order`] would be laid out somewhere else for no reason and pay a jump for it.
254 let mut place = vec![usize::MAX; func.block_count()];
255 for (at, &block) in order(func).iter().enumerate() {
256 place[block.index()] = at;
257 }
258
259 let mut found: Vec<Vec<mir::Block>> = Vec::new();
260 let mut seen = vec![false; func.block_count()];
261 // How often the function is entered, which every exec threshold is a share of. A function
262 // whose entry says nothing is one nobody wrote a weight on, and then once is the right answer
263 // for every block in it and every round behaves the same.
264 let entered = func.entry().map_or(mir::Weight::ONCE, |entry| func[entry].weight).raw();
265 // The hottest edge into each block out of a block already laid out, which is what the queue is
266 // ordered by and what says whether an entry popped off it is out of date. It outlives the
267 // round it was written in on purpose: a trace that stops because the next block is below this
268 // round's exec threshold leaves that block remembered as reached, and the round that does take
269 // it starts its first trace there rather than wherever the weights happen to point. That is
270 // how a chain of comparisons whose tail cools off below the threshold stays a straight line.
271 let mut reached = vec![0; func.block_count()];
272
273 for (likely, often) in ROUNDS {
274 // The exec threshold as a number rather than a fraction. In a hundred and twenty eight
275 // bits because a weight saturates at the top of a sixty four bit one and a nest of loops
276 // gets there.
277 let floor =
278 u64::try_from(u128::from(entered) * u128::from(often) / SCALE).unwrap_or(u64::MAX);
279 // A round does not start a trace in a block colder than its exec threshold, which is what
280 // keeps an error path out of the middle of the trunk: it waits for a round that asks for
281 // less. The entry is the exception below, because the block laid out first is the block
282 // that runs first and that has to be the entry whatever it weighs.
283 let mut queue: BinaryHeap<Seed> = func
284 .blocks()
285 .filter(|&block| !seen[block.index()] && func[block].weight.raw() >= floor)
286 .map(|block| Seed {
287 reached: reached[block.index()],
288 weight: func[block].weight,
289 place: Reverse(place[block.index()]),
290 block,
291 })
292 .collect();
293 let mut start = func.entry().filter(|entry| !seen[entry.index()]);
294
295 while let Some(from) = start.take().or_else(|| next_seed(&mut queue, &seen, &reached)) {
296 let mut trace = Vec::new();
297 let mut block = from;
298 loop {
299 seen[block.index()] = true;
300 trace.push(block);
301 let next = along(func, block, &seen, likely, floor);
302 // Everything this block goes to and the trace does not, so that the next trace can
303 // start at one of them rather than wherever the weights point. A block too cold
304 // for this round is still written down as reached, because the round that is cold
305 // enough to take it wants to know it hangs off something already laid out.
306 for call in &func[block].succs {
307 let to = call.block;
308 if seen[to.index()]
309 || Some(to) == next
310 || call.weight.raw() <= reached[to.index()]
311 {
312 continue;
313 }
314 reached[to.index()] = call.weight.raw();
315 if func[to].weight.raw() >= floor {
316 queue.push(Seed {
317 reached: call.weight.raw(),
318 weight: func[to].weight,
319 place: Reverse(place[to.index()]),
320 block: to,
321 });
322 }
323 }
324 let Some(next) = next else { break };
325 block = next;
326 }
327 found.push(trace);
328 }
329 }
330 connect(func, found)
331}
332
333/// The traces run together into one order, each one followed where possible by the trace control
334/// leaves it for.
335///
336/// Design: `gcc/bb-reorder.cc`, `connect_traces`.
337///
338/// The rounds cut a straight run of blocks into pieces whenever the run cools below the round's
339/// exec threshold, and a chain of comparisons against a constant is exactly that: each comparison
340/// is reached only when every one before it failed, so the chain halves in weight at every step and
341/// the round that laid the head of it down will not touch the tail. Left alone, the pieces come out
342/// in round order with other traces between them, and every piece pays a jump to reach the next.
343///
344/// So the pieces are put back together. Each trace is followed by the unplaced trace its last block
345/// most often goes to, and that one by the trace its last block most often goes to, until there is
346/// none, and only then does the next trace in round order start a new run. The rounds still decide
347/// which trace is hot and comes first, and this decides what falls in behind it.
348fn connect(func: &mir::Func, traces: Vec<Vec<mir::Block>>) -> Vec<mir::Block> {
349 // Which trace each block starts, for the blocks that start one. A trace may only be joined at
350 // its first block, because joining it anywhere else would mean cutting it in half and the
351 // rounds put it together for a reason.
352 let mut head = vec![usize::MAX; func.block_count()];
353 for (at, trace) in traces.iter().enumerate() {
354 if let Some(&first) = trace.first() {
355 head[first.index()] = at;
356 }
357 }
358
359 let mut order = Vec::with_capacity(func.block_count());
360 let mut used = vec![false; traces.len()];
361 for from in 0..traces.len() {
362 if used[from] {
363 continue;
364 }
365 let mut at = from;
366 loop {
367 used[at] = true;
368 order.extend_from_slice(&traces[at]);
369 let Some(&last) = traces[at].last() else { break };
370 let mut best: Option<(u64, usize)> = None;
371 for call in &func[last].succs {
372 let to = head[call.block.index()];
373 if to == usize::MAX || used[to] {
374 continue;
375 }
376 let weight = call.weight.raw();
377 // Ties go to the trace found first, which is the hotter of the two, because the
378 // rounds laid the traces down hottest first.
379 if best.is_none_or(|(found, over)| weight > found || (weight == found && to < over))
380 {
381 best = Some((weight, to));
382 }
383 }
384 let Some((_, next)) = best else { break };
385 at = next;
386 }
387 }
388 order
389}
390
391/// A block a trace could start at, ordered so that the greatest is the one to start at next.
392///
393/// Design: `gcc/bb-reorder.cc`, `bb_to_key`, of which this is the same three answers in the order
394/// GCC asks them.
395#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
396struct Seed {
397 /// How often the hottest edge into this block out of a block already laid out is taken, and
398 /// zero while nothing laid out goes here. First, so that a block something reaches beats a
399 /// block nothing reaches however hot the second one is.
400 reached: u64,
401 /// How often the block runs, which decides between two blocks nothing laid out reaches.
402 weight: mir::Weight,
403 /// Where reverse postorder would have put it, which decides between two blocks that are equal
404 /// on both of the above, so that a function with no weights on it comes out in the order the
405 /// shape of its graph gives rather than in whatever order the queue settles.
406 place: Reverse<usize>,
407 /// The block, last, so that two blocks equal on everything else still come out in one order.
408 block: mir::Block,
409}
410
411/// The next block to start a trace at, out of the queue, or nothing when there is none left.
412///
413/// An entry whose block has been laid out since it was queued, or which was queued before a hotter
414/// edge into the same block was found, is thrown away here rather than found and updated in place
415/// when that happens. The queue is a heap and an entry in the middle of one cannot be reached, so
416/// the choice is between this and an index beside it, and a stale entry costs one pop.
417fn next_seed(queue: &mut BinaryHeap<Seed>, seen: &[bool], reached: &[u64]) -> Option<mir::Block> {
418 while let Some(seed) = queue.pop() {
419 if !seen[seed.block.index()] && seed.reached >= reached[seed.block.index()] {
420 return Some(seed.block);
421 }
422 }
423 None
424}
425
426/// The arm the trace follows out of a block, or nothing when no arm is worth following.
427///
428/// The likeliest arm that has not been laid out already, is taken at least as often as the
429/// round's floor, and takes at least the round's share of the times the block runs. Ties go to
430/// the arm written first, which is the arm a conditional branch takes when its condition holds,
431/// so a function with no weights on it at all comes out following the true arm.
432fn along(
433 func: &mir::Func,
434 block: mir::Block,
435 seen: &[bool],
436 likely: u64,
437 floor: u64,
438) -> Option<mir::Block> {
439 let whole = func[block].weight;
440 let mut best: Option<&mir::BlockCall> = None;
441 for call in &func[block].succs {
442 if seen[call.block.index()]
443 || call.weight.raw() < floor
444 || call.weight.out_of(whole) < likely
445 {
446 continue;
447 }
448 if best.is_none_or(|found| call.weight > found.weight) {
449 best = Some(call);
450 }
451 }
452 best.map(|call| call.block)
453}
454
455/// The comparisons a branch may be folded into, which [`blocks`] can then find by opcode.
456///
457/// One entry per name the target's table holds, interned once for the function rather than once
458/// per block, since a block that ends in a branch is most of the blocks there are.
459fn table(insts: &BranchInsts, names: &mut Interner) -> HashMap<mir::Opcode, &'static Fusion> {
460 insts
461 .fused
462 .iter()
463 .map(|fusion| {
464 (mir::Opcode::new(names.intern(&format!("{}{}", insts.prefix, fusion.set))), fusion)
465 })
466 .collect()
467}
468
469/// The comparisons a branch on their answer is the whole of what reads, which [`blocks`] may fold
470/// the test out of.
471///
472/// Run before allocation, on the same function [`blocks`] is later given. What it answers is
473/// whether anything but the branch reads the byte a comparison wrote, and that is a question about
474/// a virtual register: a physical one is written many times in a function and counting its readers
475/// would mean asking which of the writes each reader belongs to. So it is asked here, where a
476/// register is written once, and the answer is carried to the pass that can use it.
477///
478/// Being on this list is necessary and not sufficient. Allocation may put a reload between the
479/// comparison and the branch, and a comparison that is no longer the instruction in front of the
480/// branch is not one the flags survive to, so [`blocks`] checks that again on what it finds.
481#[must_use]
482pub fn fusable(func: &mir::Func, insts: &BranchInsts, names: &mut Interner) -> HashSet<mir::Inst> {
483 let table = table(insts, names);
484 let branch = mir::Opcode::new(names.intern(&format!("{}{}", insts.prefix, insts.cond)));
485 let reads = crate::changes::Reads::of(func);
486 let mut found = HashSet::new();
487 for block in func.blocks() {
488 let insts: Vec<mir::Inst> = func.insts(block).collect();
489 let [.., compare, last] = insts[..] else { continue };
490 if func[last].opcode != branch || !table.contains_key(&func[compare].opcode) {
491 continue;
492 }
493 let operands = &func[func[compare].operands];
494 let Some(byte) = operands.first().filter(|operand| operand.role != Role::Use) else {
495 continue;
496 };
497 if !byte.reg.is_virtual() || reads.count(byte.reg) != 1 {
498 continue;
499 }
500 // And it is this branch that reads it rather than one in some other block, which the
501 // count alone does not say.
502 if func[func[last].operands].first().map(|operand| operand.reg) == Some(byte.reg) {
503 found.insert(compare);
504 }
505 }
506 found
507}
508
509/// The one thing that writes an instruction here, over the function it writes into.
510struct Writer<'a> {
511 func: &'a mut mir::Func,
512 insts: &'a BranchInsts,
513 names: &'a mut Interner,
514 table: HashMap<mir::Opcode, &'static Fusion>,
515 fusable: &'a HashSet<mir::Inst>,
516}
517
518impl Writer<'_> {
519 /// Writes the jumps one block needs, given the block laid out after it, and gives back the
520 /// block that has to go between the two when the branch needed one.
521 fn edges(&mut self, block: mir::Block, next: Option<mir::Block>) -> Option<mir::Block> {
522 // A block that already ends in the jump through a register wants nothing written, whatever
523 // its arms are. Where it goes is in the register, so none of its arms is fallen into and
524 // none of them is jumped to from here, and a jump written behind that one would be a jump
525 // nothing reaches.
526 if self.leaves_indirectly(block) {
527 return None;
528 }
529 match self.func[block].succs.len() {
530 0 => None,
531 1 => {
532 self.one(block, next);
533 None
534 }
535 2 => self.two(block, next),
536 arms => panic!("a block with {arms} arms, and nothing lowers to one"),
537 }
538 }
539
540 /// Whether the block ends in the jump through a register a computed `goto` is selected as.
541 fn leaves_indirectly(&mut self, block: mir::Block) -> bool {
542 let Some(last) = self.func.terminator(block) else { return false };
543 let indirect = self.opcode(self.insts.indirect);
544 self.func[last].opcode == indirect
545 }
546
547 /// A block that goes to one place, which either follows it or has to be jumped to.
548 fn one(&mut self, block: mir::Block, next: Option<mir::Block>) {
549 if Some(self.func[block].succs[0].block) == next {
550 return;
551 }
552 let opcode = self.opcode(self.insts.jump);
553 self.func.build(block, opcode).finish();
554 }
555
556 /// A block that goes to two places, which is a test and a jump to one of them.
557 ///
558 /// The condition is read off the branch the rules selected and the branch is taken out, so the
559 /// register the test reads is the one the branch read and no new value is made. That is what
560 /// makes this safe to run after allocation: it writes no register that was not already
561 /// written and it asks for none that was not already asked for.
562 fn two(&mut self, block: mir::Block, next: Option<mir::Block>) -> Option<mir::Block> {
563 // Asked before the branch is taken out, because what it looks at is the instruction in
564 // front of the branch and taking the branch out would make that the last one.
565 let fused = self.fused(block);
566 let condition = self.take(block);
567
568 // Whichever arm is laid out next is the one the block falls into, and the jump is then
569 // the one taken when the condition sends it the other way. Falling into the arm the
570 // condition is false for leaves the jump taken when it holds, and falling into the arm it
571 // is true for leaves the other jump and the arms the other way round.
572 let (if_true, if_false) = match fused {
573 Some((_, fusion)) => (fusion.if_true, fusion.if_false),
574 None => (self.insts.if_true, self.insts.if_false),
575 };
576 let arms: Vec<mir::Block> = self.func[block].succs.iter().map(|arm| arm.block).collect();
577 let (name, bridge) = if next == Some(arms[1]) {
578 (if_true, None)
579 } else if next == Some(arms[0]) {
580 self.func.succs_mut(block).swap(0, 1);
581 (if_false, None)
582 } else {
583 (if_true, Some(self.bridge(block)))
584 };
585
586 match fused {
587 Some((compare, fusion)) => self.keep_only_the_flags(compare, fusion),
588 None => {
589 let opcode = self.opcode(self.insts.test);
590 self.func.build(block, opcode).operand(condition).finish();
591 }
592 }
593 let opcode = self.opcode(name);
594 self.func.build(block, opcode).finish();
595 bridge
596 }
597
598 /// The comparison the block's branch can be folded into, when there is one.
599 ///
600 /// Three things have to hold and [`fusable`] has already answered the one that cannot be
601 /// answered here. What is left is that the comparison is still the instruction in front of the
602 /// branch, since allocation may have put a reload between them and the flags do not survive
603 /// one, and that the byte the branch reads is the byte that comparison wrote, since the
604 /// allocator has since given both of them a physical register and two registers that were
605 /// different could have become the same one.
606 fn fused(&self, block: mir::Block) -> Option<(mir::Inst, &'static Fusion)> {
607 let insts: Vec<mir::Inst> = self.func.insts(block).collect();
608 let [.., compare, last] = insts[..] else { return None };
609 if !self.fusable.contains(&compare) {
610 return None;
611 }
612 let fusion = *self.table.get(&self.func[compare].opcode)?;
613 let byte = self.func[self.func[compare].operands].first()?.reg;
614 (self.func[self.func[last].operands].first()?.reg == byte).then_some((compare, fusion))
615 }
616
617 /// Turns a comparison that wrote a byte into the same comparison that writes nothing.
618 ///
619 /// The instruction stays where it is and keeps its immediate, which is the point: what it does
620 /// to the flags is what it already did, and the jump written behind it reads those. Only the
621 /// operand at the front goes, which is the byte, and the opcode changes to the one that has no
622 /// operand there.
623 fn keep_only_the_flags(&mut self, compare: mir::Inst, fusion: &Fusion) {
624 let read: Vec<mir::Operand> =
625 self.func[self.func[compare].operands].iter().skip(1).copied().collect();
626 let operands = self.func.push_operands(&read);
627 self.func[compare].opcode = self.opcode(fusion.cmp);
628 self.func[compare].operands = operands;
629 }
630
631 /// Takes the conditional branch off the end of a block and gives back what it read.
632 fn take(&mut self, block: mir::Block) -> mir::Operand {
633 let branch = self.func.terminator(block).expect("a block with two arms has a branch");
634 let cond = self.opcode(self.insts.cond);
635 assert_eq!(
636 self.func[branch].opcode, cond,
637 "a block with two arms whose last instruction is not the branch"
638 );
639 let operands = self.func[branch].operands;
640 let condition = self.func[operands][0];
641 self.func.remove_inst(branch);
642 condition
643 }
644
645 /// Puts an empty block on a branch's second edge, so that the branch has something to fall
646 /// into and the jump the edge really needs is in a block of its own.
647 fn bridge(&mut self, block: mir::Block) -> mir::Block {
648 let bridge = self.func.create_block();
649 let edge = self.func[block].succs[1].clone();
650 let weight = edge.weight;
651 self.func.set_weight(bridge, weight);
652 *self.func.succs_mut(bridge) = vec![edge];
653 self.func.succs_mut(block)[1] = mir::BlockCall::to(bridge).taken(weight);
654 bridge
655 }
656
657 /// The opcode of that name on this target, which is the name with the target's prefix in
658 /// front of it.
659 fn opcode(&mut self, name: &str) -> mir::Opcode {
660 mir::Opcode::new(self.names.intern(&format!("{}{name}", self.insts.prefix)))
661 }
662}
663
664#[cfg(test)]
665mod tests {
666 use rucc_mir::{BlockCall, Opcode, Operand, Reg};
667 use rucc_target::x86_64::{BRANCH, GPR, RAX, RCX, REGS};
668
669 use super::*;
670
671 /// A function with that many blocks, none of which goes anywhere yet.
672 fn blank(count: usize) -> (Interner, mir::Func, Vec<mir::Block>) {
673 let mut names = Interner::new();
674 let mut func = mir::Func::new(names.intern("f"));
675 let blocks = (0..count).map(|_| func.create_block()).collect();
676 (names, func, blocks)
677 }
678
679 /// Puts a conditional branch at the end of a block, on a register that is already physical
680 /// the way one is by the time this pass runs.
681 fn branch(func: &mut mir::Func, names: &mut Interner, block: mir::Block, arms: &[mir::Block]) {
682 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
683 func.build(block, opcode).operand(Operand::read(Reg::physical(RAX), GPR)).finish();
684 *func.succs_mut(block) = arms.iter().map(|&arm| BlockCall::to(arm)).collect();
685 }
686
687 /// Laying the blocks out for the one machine this crate has, and the dump of what came out.
688 ///
689 /// The dump rather than the function, because where a jump goes is on the block and the dump
690 /// is the one place the instruction and the arm are put back together. A test that read the
691 /// two separately would pass on a function whose jump and whose edge disagreed, which is the
692 /// mistake this pass is most able to make.
693 ///
694 /// A block is named in the dump by where it is in the layout rather than by the number it was
695 /// made with, which is why every expectation below reads that way and why the order is worth
696 /// asserting on its own.
697 fn laid_out(func: &mut mir::Func, names: &mut Interner) -> Vec<String> {
698 // Both halves, in the order the pipeline runs them, so that a test which builds a
699 // comparison in front of its branch sees what a compiled function would see.
700 let fusable = fusable(func, &BRANCH, names);
701 blocks(func, &BRANCH, names, &fusable, false);
702 mir::print_func(func, names, ®S)
703 .lines()
704 .filter(|line| !line.trim().is_empty() && !line.starts_with("mfunc") && *line != "}")
705 .map(|line| line.trim().to_string())
706 .collect()
707 }
708
709 /// The blocks in layout order, by the number each was made with.
710 fn order_of(func: &mir::Func) -> Vec<usize> {
711 func.blocks().map(mir::Block::index).collect()
712 }
713
714 #[test]
715 fn a_block_that_falls_into_the_next_one_gets_no_jump_at_all() {
716 let (mut names, mut func, made) = blank(2);
717 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
718
719 let text = laid_out(&mut func, &mut names);
720
721 // The arm is still on the block, because the graph is still worth reading, and there is
722 // no instruction on it because the block it goes to is the one that runs next anyway.
723 assert_eq!(text, ["block0:", "block1", "block1:"]);
724 }
725
726 #[test]
727 fn a_block_that_goes_somewhere_that_is_not_next_gets_a_jump() {
728 let (mut names, mut func, made) = blank(2);
729 // A loop with nothing in it and no way out, which is the smallest function there is with
730 // an edge that runs backwards. Every layout puts the two blocks in this order, so the
731 // second one has nothing after it and its edge has to be a jump.
732 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
733 *func.succs_mut(made[1]) = vec![BlockCall::to(made[0])];
734
735 let text = laid_out(&mut func, &mut names);
736
737 assert_eq!(text, ["block0:", "block1", "block1:", "x64.jmp block0"]);
738 }
739
740 #[test]
741 fn a_branch_that_falls_into_its_false_arm_jumps_when_the_condition_holds() {
742 let (mut names, mut func, made) = blank(3);
743 // A loop whose body is the block it came from: the arm taken when the condition holds is
744 // a block the walk has already been to, so the other arm is what comes next.
745 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
746 branch(&mut func, &mut names, made[1], &[made[0], made[2]]);
747
748 let text = laid_out(&mut func, &mut names);
749
750 assert_eq!(order_of(&func), [0, 1, 2]);
751 assert_eq!(
752 text,
753 [
754 "block0:",
755 "block1",
756 "block1:",
757 "x64.test_rr_8 $rax",
758 "x64.jcc_ne block0, block2",
759 "block2:",
760 ]
761 );
762 }
763
764 #[test]
765 fn a_branch_that_falls_into_its_true_arm_jumps_when_the_condition_does_not_hold() {
766 let (mut names, mut func, made) = blank(3);
767 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
768
769 let text = laid_out(&mut func, &mut names);
770
771 // The arms come out swapped, because after this the first is where the jump goes and the
772 // second is what runs next, and the jump is the one taken when the condition failed.
773 assert_eq!(order_of(&func), [0, 1, 2]);
774 assert_eq!(
775 text,
776 ["block0:", "x64.test_rr_8 $rax", "x64.jcc_e block2, block1", "block1:", "block2:"]
777 );
778 }
779
780 #[test]
781 fn a_block_that_leaves_through_a_register_is_given_no_jump_and_keeps_every_arm() {
782 let (mut names, mut func, made) = blank(4);
783 let jump = Opcode::new(names.intern("x64.jmp_reg"));
784 func.build(made[0], jump).operand(Operand::read(Reg::physical(RAX), GPR)).finish();
785 *func.succs_mut(made[0]) = made[1..].iter().map(|&arm| BlockCall::to(arm)).collect();
786
787 let text = laid_out(&mut func, &mut names);
788
789 // Nothing written behind the jump that is already there, whatever the first arm is, since
790 // where this block goes is in the register. The arms stay on the block because they are
791 // how everything downstream finds out where control can go.
792 assert_eq!(
793 text,
794 [
795 "block0:",
796 "x64.jmp_reg $rax, block1, block2, block3",
797 "block1:",
798 "block2:",
799 "block3:"
800 ]
801 );
802 }
803
804 #[test]
805 fn a_branch_that_can_fall_into_neither_arm_is_given_a_block_to_jump_from() {
806 let (mut names, mut func, made) = blank(2);
807 // A loop that goes back to the top or round again, so both arms are blocks the walk has
808 // already been to and nothing is left to lay out after it.
809 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
810 branch(&mut func, &mut names, made[1], &[made[0], made[1]]);
811
812 let text = laid_out(&mut func, &mut names);
813
814 // Block two is the one this made. It is empty, it is laid out where the branch falls into
815 // it, and the jump the second arm needed is in it rather than being a second jump in the
816 // block above.
817 assert_eq!(order_of(&func), [0, 1, 2]);
818 assert_eq!(
819 text,
820 [
821 "block0:",
822 "block1",
823 "block1:",
824 "x64.test_rr_8 $rax",
825 "x64.jcc_ne block0, block2",
826 "block2:",
827 "x64.jmp block1",
828 ]
829 );
830 }
831
832 #[test]
833 fn the_test_reads_the_register_the_branch_read() {
834 let (mut names, mut func, made) = blank(3);
835 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
836
837 let fusable = fusable(&func, &BRANCH, &mut names);
838 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
839
840 let test = func.insts(made[0]).next().expect("a test");
841 let operands = func[test].operands;
842 assert_eq!(func[operands], [Operand::read(Reg::physical(RAX), GPR)]);
843 }
844
845 #[test]
846 fn a_block_nothing_reaches_is_laid_out_at_the_end_rather_than_deleted() {
847 let (mut names, mut func, made) = blank(4);
848 *func.succs_mut(made[0]) = vec![BlockCall::to(made[3])];
849
850 let fusable = fusable(&func, &BRANCH, &mut names);
851 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
852
853 // Blocks one and two are reached by nothing, so they go last, in the order they were
854 // made. Deleting one would be a decision about what the program does, and this pass has
855 // no business making it.
856 assert_eq!(order_of(&func), [0, 3, 1, 2]);
857 }
858
859 #[test]
860 fn a_function_with_no_blocks_is_left_alone() {
861 let mut names = Interner::new();
862 let mut func = mir::Func::new(names.intern("f"));
863
864 let fusable = fusable(&func, &BRANCH, &mut names);
865 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
866
867 assert_eq!(func.block_count(), 0);
868 }
869
870 #[test]
871 #[should_panic(expected = "a block with 3 arms")]
872 fn a_block_with_three_arms_is_refused_rather_than_laid_out_wrongly() {
873 let (mut names, mut func, made) = blank(4);
874 branch(&mut func, &mut names, made[0], &[made[1], made[2], made[3]]);
875
876 let fusable = fusable(&func, &BRANCH, &mut names);
877 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
878 }
879
880 #[test]
881 #[should_panic(expected = "whose last instruction is not the branch")]
882 fn a_block_with_two_arms_and_no_branch_in_it_is_refused() {
883 let (mut names, mut func, made) = blank(3);
884 let opcode = Opcode::new(names.intern("x64.nop"));
885 func.build(made[0], opcode).finish();
886 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1]), BlockCall::to(made[2])];
887
888 let fusable = fusable(&func, &BRANCH, &mut names);
889 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
890 }
891
892 /// Puts a comparison and a branch on its answer at the end of a block.
893 ///
894 /// The byte is a virtual register, which is what it is when [`fusable`] is asked and is not
895 /// what it is when [`blocks`] runs. Nothing in either half cares which it is except the
896 /// counting, so a test that runs both over one function has to use the register the counting
897 /// wants, and what it costs is that this is one thing the unit tests cannot check about the
898 /// two halves running at different times. `crate::pipeline` runs them the real way round.
899 fn compare(
900 func: &mut mir::Func,
901 names: &mut Interner,
902 block: mir::Block,
903 arms: &[mir::Block],
904 ) -> Reg {
905 let byte = func.new_vreg(GPR);
906 let opcode = Opcode::new(names.intern("x64.cmp_set_l_32"));
907 func.build(block, opcode)
908 .def(byte, GPR)
909 .operand(Operand::read(Reg::physical(RAX), GPR))
910 .operand(Operand::read(Reg::physical(RCX), GPR))
911 .finish();
912 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
913 func.build(block, opcode).operand(Operand::read(byte, GPR)).finish();
914 *func.succs_mut(block) = arms.iter().map(|&arm| BlockCall::to(arm)).collect();
915 byte
916 }
917
918 /// A branch on a comparison is the comparison and a jump on what it found.
919 ///
920 /// Three instructions go in and two come out. The byte goes because nothing reads it, the test
921 /// goes because the comparison set the flags the test was going to set, and the jump names the
922 /// condition rather than naming zero. Which condition it names is the opposite of the one the
923 /// comparison asked about, since the block falls into the arm the comparison is true for.
924 #[test]
925 fn a_branch_on_a_comparison_is_the_comparison_and_a_jump_on_what_it_found() {
926 let (mut names, mut func, made) = blank(3);
927 compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
928
929 let text = laid_out(&mut func, &mut names);
930
931 assert_eq!(
932 text,
933 [
934 "block0:",
935 "x64.cmp_rr_32 $rax, $rcx",
936 "x64.jcc_ge block2, block1",
937 "block1:",
938 "block2:",
939 ]
940 );
941 }
942
943 /// The same comparison with something else reading its answer, which keeps everything.
944 ///
945 /// Folding the byte away when a second instruction wants it would be deleting a value the
946 /// program computes. This is the whole of what [`fusable`] is asked before allocation, and the
947 /// second reader here is in another block so that it is a question about the function rather
948 /// than about the block the branch is in.
949 #[test]
950 fn a_comparison_whose_answer_something_else_reads_keeps_its_byte_and_its_test() {
951 let (mut names, mut func, made) = blank(3);
952 let byte = compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
953 let opcode = Opcode::new(names.intern("x64.mov_rr_64"));
954 func.build(made[1], opcode)
955 .def(Reg::physical(RAX), GPR)
956 .operand(Operand::read(byte, GPR))
957 .finish();
958
959 let text = laid_out(&mut func, &mut names);
960
961 assert!(text.contains(&"x64.test_rr_8 %0".to_owned()), "{text:?}");
962 assert!(text.contains(&"x64.jcc_e block2, block1".to_owned()), "{text:?}");
963 }
964
965 /// A comparison allocation moved away from its branch, which keeps its test.
966 ///
967 /// [`fusable`] says the byte has one reader and says nothing about where the two instructions
968 /// end up, because allocation runs between the two halves and may put a reload in front of the
969 /// branch. The flags do not survive one, so the second half looks again, and this is the case
970 /// where it finds something and refuses. The instruction is put in between the two calls
971 /// because that is when allocation would have put it there.
972 #[test]
973 fn a_comparison_that_is_no_longer_in_front_of_its_branch_keeps_its_test() {
974 let (mut names, mut func, made) = blank(3);
975 compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
976 let fusable = fusable(&func, &BRANCH, &mut names);
977 assert_eq!(fusable.len(), 1, "the comparison is one the byte's count allows");
978
979 let branch = func.terminator(made[0]).expect("a block with two arms has a branch");
980 let opcode = Opcode::new(names.intern("x64.mov_rr_64"));
981 let reload = func
982 .build_loose(opcode)
983 .def(Reg::physical(RCX), GPR)
984 .operand(Operand::read(Reg::physical(RAX), GPR))
985 .finish();
986 func.insert_before(branch, reload);
987 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
988 let text = mir::print_func(&func, &names, ®S);
989
990 assert!(text.contains("x64.cmp_set_l_32"), "{text}");
991 assert!(text.contains("x64.test_rr_8"), "{text}");
992 assert!(!text.contains("x64.cmp_rr_32"), "{text}");
993 }
994
995 /// Laying the blocks out along the traces the weights say, which is what every level above
996 /// `-O0` asks for.
997 fn traced(func: &mut mir::Func, names: &mut Interner) -> Vec<String> {
998 let fusable = fusable(func, &BRANCH, names);
999 blocks(func, &BRANCH, names, &fusable, true);
1000 mir::print_func(func, names, ®S)
1001 .lines()
1002 .filter(|line| !line.trim().is_empty() && !line.starts_with("mfunc") && *line != "}")
1003 .map(|line| line.trim().to_string())
1004 .collect()
1005 }
1006
1007 /// Says how often a block runs and how often each of its arms is taken, in parts of ten
1008 /// thousand, the way `crate::weights` would have.
1009 fn runs(func: &mut mir::Func, block: mir::Block, weight: u64, arms: &[u64]) {
1010 func.set_weight(block, mir::Weight::parts(weight));
1011 for (index, &taken) in arms.iter().enumerate() {
1012 func.succs_mut(block)[index].weight = mir::Weight::parts(taken);
1013 }
1014 }
1015
1016 /// The arm almost always taken is the one laid out next, whichever of the two it is.
1017 ///
1018 /// Same function twice, with the two arms weighted the two ways round. At `-O0` the order is
1019 /// the shape of the graph and the first arm always comes next; here it is the weights, so the
1020 /// block that hardly ever runs goes behind the one that nearly always does and the jump is
1021 /// spent on it rather than on the common path.
1022 #[test]
1023 fn the_arm_that_is_nearly_always_taken_is_the_one_laid_out_next() {
1024 let (mut names, mut func, made) = blank(3);
1025 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1026 runs(&mut func, made[0], 10_000, &[200, 9_800]);
1027 runs(&mut func, made[1], 200, &[]);
1028 runs(&mut func, made[2], 9_800, &[]);
1029
1030 traced(&mut func, &mut names);
1031
1032 assert_eq!(order_of(&func), [0, 2, 1]);
1033
1034 let (mut names, mut func, made) = blank(3);
1035 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1036 runs(&mut func, made[0], 10_000, &[9_800, 200]);
1037 runs(&mut func, made[1], 9_800, &[]);
1038 runs(&mut func, made[2], 200, &[]);
1039
1040 traced(&mut func, &mut names);
1041
1042 assert_eq!(order_of(&func), [0, 1, 2]);
1043 }
1044
1045 /// A loop comes out as its header, its body and then its exit, with the back edge backwards.
1046 ///
1047 /// Nothing here rotates anything. The trace walks out of the header into the body because the
1048 /// body is where the header nearly always goes, stops at the latch because the header it
1049 /// wants next is already laid out, and the exit is picked up as the next seed. That is the
1050 /// order a branch predictor's static guess expects and it is what the greedy rule gives.
1051 #[test]
1052 fn a_loop_is_laid_out_with_its_exit_behind_it_and_its_back_edge_running_backwards() {
1053 let (mut names, mut func, made) = blank(4);
1054 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
1055 branch(&mut func, &mut names, made[1], &[made[2], made[3]]);
1056 *func.succs_mut(made[2]) = vec![BlockCall::to(made[1])];
1057 runs(&mut func, made[0], 10_000, &[10_000]);
1058 runs(&mut func, made[1], 100_000, &[90_000, 10_000]);
1059 runs(&mut func, made[2], 90_000, &[90_000]);
1060 runs(&mut func, made[3], 10_000, &[]);
1061
1062 let text = traced(&mut func, &mut names);
1063
1064 assert_eq!(order_of(&func), [0, 1, 2, 3]);
1065 assert_eq!(
1066 text,
1067 [
1068 "block0:",
1069 "block1",
1070 "block1:",
1071 "x64.test_rr_8 $rax",
1072 "x64.jcc_e block3, block2",
1073 "block2:",
1074 "x64.jmp block1",
1075 "block3:",
1076 ]
1077 );
1078 }
1079
1080 /// A block reached only from the cold arm is laid out behind everything the trunk reaches.
1081 ///
1082 /// The shape is `if (unlikely) handle(); rest();`, where the handler and the rest of the
1083 /// function are both reached from the branch. Reverse postorder puts the handler between the
1084 /// branch and the rest of the function; the trace puts the rest of the function next, because
1085 /// that is where the branch nearly always goes, and the handler ends up last.
1086 #[test]
1087 fn a_block_only_the_cold_arm_reaches_goes_behind_the_rest_of_the_function() {
1088 let (mut names, mut func, made) = blank(4);
1089 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1090 *func.succs_mut(made[1]) = vec![BlockCall::to(made[2])];
1091 *func.succs_mut(made[2]) = vec![BlockCall::to(made[3])];
1092 runs(&mut func, made[0], 10_000, &[100, 9_900]);
1093 runs(&mut func, made[1], 100, &[100]);
1094 runs(&mut func, made[2], 10_000, &[10_000]);
1095 runs(&mut func, made[3], 10_000, &[]);
1096
1097 assert_eq!(order(&func), [made[0], made[1], made[2], made[3]]);
1098
1099 traced(&mut func, &mut names);
1100
1101 assert_eq!(order_of(&func), [0, 2, 3, 1]);
1102 }
1103
1104 /// A block nothing reaches is still laid out, since the last round asks for nothing.
1105 #[test]
1106 fn the_last_round_picks_up_a_block_nothing_reaches() {
1107 let (mut names, mut func, made) = blank(3);
1108 *func.succs_mut(made[0]) = vec![BlockCall::to(made[2])];
1109 runs(&mut func, made[0], 10_000, &[10_000]);
1110 runs(&mut func, made[1], 0, &[]);
1111 runs(&mut func, made[2], 10_000, &[]);
1112
1113 traced(&mut func, &mut names);
1114
1115 assert_eq!(order_of(&func), [0, 2, 1]);
1116 }
1117
1118 /// The entry is laid out first however cold it is against the rest of the function.
1119 ///
1120 /// A function is entered at its first byte, so the block that runs first has to be the block
1121 /// that is written first, and the seed order is what makes that true rather than any check
1122 /// afterwards. Here the loop body runs ten times for every call and would otherwise have been
1123 /// the first seed.
1124 #[test]
1125 fn the_entry_is_the_first_seed_even_when_something_else_runs_more_often() {
1126 let (mut names, mut func, made) = blank(3);
1127 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
1128 branch(&mut func, &mut names, made[1], &[made[1], made[2]]);
1129 runs(&mut func, made[0], 10_000, &[10_000]);
1130 runs(&mut func, made[1], 100_000, &[90_000, 10_000]);
1131 runs(&mut func, made[2], 10_000, &[]);
1132
1133 traced(&mut func, &mut names);
1134
1135 assert_eq!(func.blocks().next().map(mir::Block::index), Some(0));
1136 }
1137
1138 /// A branch whose arms are even still falls into one of them rather than jumping to both.
1139 ///
1140 /// Nothing predicts a range check, so both arms come out at half, and half is under every
1141 /// branch threshold above the last round. The trace therefore ends at the branch, and what
1142 /// decides the layout is where the next one starts: at the likeliest arm out of the block the
1143 /// trace stopped in, which is a fall-through, and not at whichever of the two blocks was made
1144 /// first, which would have cost a jump on both paths out of an even branch.
1145 #[test]
1146 fn a_branch_whose_arms_are_even_is_still_laid_out_next_to_one_of_them() {
1147 let (mut names, mut func, made) = blank(3);
1148 // The second arm is the block made first, so a layout that fell back to the seed list
1149 // would lay that one out next and leave the arm written first to be jumped to.
1150 branch(&mut func, &mut names, made[0], &[made[2], made[1]]);
1151 runs(&mut func, made[0], 10_000, &[5_000, 5_000]);
1152 runs(&mut func, made[1], 5_000, &[]);
1153 runs(&mut func, made[2], 5_000, &[]);
1154
1155 traced(&mut func, &mut names);
1156
1157 assert_eq!(order_of(&func), [0, 2, 1]);
1158 }
1159
1160 /// A run of blocks the rounds cut in half comes back out in one piece.
1161 ///
1162 /// Two comparisons against a constant, one behind the other, which is what a switch over
1163 /// scattered labels is lowered to. The second comparison is only reached when the first one
1164 /// failed, so it runs half as often as the function is entered and the first round will not
1165 /// touch it: the trace stops at the first comparison and the block that was about to fall
1166 /// through it is left for a later round. What puts it back is [`connect`], and without it the
1167 /// body of the first case would sit between the two comparisons and both would pay a jump.
1168 #[test]
1169 fn a_chain_the_rounds_cut_in_half_is_run_back_together() {
1170 let (mut names, mut func, made) = blank(5);
1171 branch(&mut func, &mut names, made[0], &[made[2], made[1]]);
1172 branch(&mut func, &mut names, made[2], &[made[4], made[3]]);
1173 runs(&mut func, made[0], 10_000, &[5_000, 5_000]);
1174 runs(&mut func, made[1], 5_000, &[]);
1175 runs(&mut func, made[2], 5_000, &[3_000, 2_000]);
1176 runs(&mut func, made[3], 2_000, &[]);
1177 runs(&mut func, made[4], 3_000, &[]);
1178
1179 traced(&mut func, &mut names);
1180
1181 assert_eq!(order_of(&func), [0, 2, 4, 1, 3]);
1182 }
1183}