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 ///
624 /// An addressing mode comes with the rest of it and does not survive the move on its own. What
625 /// a mode holds is where in the operand vector its base and its index are, and every operand
626 /// has just come down one place, so the two positions come down with them. A comparison
627 /// against a register or a constant has no mode and nothing to do here, and a comparison
628 /// against memory is the one that does.
629 fn keep_only_the_flags(&mut self, compare: mir::Inst, fusion: &Fusion) {
630 let read: Vec<mir::Operand> =
631 self.func[self.func[compare].operands].iter().skip(1).copied().collect();
632 let operands = self.func.push_operands(&read);
633 self.func[compare].opcode = self.opcode(fusion.cmp);
634 self.func[compare].operands = operands;
635 if let Some(at) = self.func[compare].mem {
636 let mut amode = self.func[at];
637 amode.base = amode.base.map(|position| position - 1);
638 amode.index = amode.index.map(|position| position - 1);
639 self.func[compare].mem = Some(self.func.add_amode(amode));
640 }
641 }
642
643 /// Takes the conditional branch off the end of a block and gives back what it read.
644 fn take(&mut self, block: mir::Block) -> mir::Operand {
645 let branch = self.func.terminator(block).expect("a block with two arms has a branch");
646 let cond = self.opcode(self.insts.cond);
647 assert_eq!(
648 self.func[branch].opcode, cond,
649 "a block with two arms whose last instruction is not the branch"
650 );
651 let operands = self.func[branch].operands;
652 let condition = self.func[operands][0];
653 self.func.remove_inst(branch);
654 condition
655 }
656
657 /// Puts an empty block on a branch's second edge, so that the branch has something to fall
658 /// into and the jump the edge really needs is in a block of its own.
659 fn bridge(&mut self, block: mir::Block) -> mir::Block {
660 let bridge = self.func.create_block();
661 let edge = self.func[block].succs[1].clone();
662 let weight = edge.weight;
663 self.func.set_weight(bridge, weight);
664 *self.func.succs_mut(bridge) = vec![edge];
665 self.func.succs_mut(block)[1] = mir::BlockCall::to(bridge).taken(weight);
666 bridge
667 }
668
669 /// The opcode of that name on this target, which is the name with the target's prefix in
670 /// front of it.
671 fn opcode(&mut self, name: &str) -> mir::Opcode {
672 mir::Opcode::new(self.names.intern(&format!("{}{name}", self.insts.prefix)))
673 }
674}
675
676#[cfg(test)]
677mod tests {
678 use rucc_mir::{BlockCall, Mem, Opcode, Operand, Reg};
679 use rucc_target::x86_64::{BRANCH, GPR, RAX, RCX, REGS};
680
681 use super::*;
682
683 /// A function with that many blocks, none of which goes anywhere yet.
684 fn blank(count: usize) -> (Interner, mir::Func, Vec<mir::Block>) {
685 let mut names = Interner::new();
686 let mut func = mir::Func::new(names.intern("f"));
687 let blocks = (0..count).map(|_| func.create_block()).collect();
688 (names, func, blocks)
689 }
690
691 /// Puts a conditional branch at the end of a block, on a register that is already physical
692 /// the way one is by the time this pass runs.
693 fn branch(func: &mut mir::Func, names: &mut Interner, block: mir::Block, arms: &[mir::Block]) {
694 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
695 func.build(block, opcode).operand(Operand::read(Reg::physical(RAX), GPR)).finish();
696 *func.succs_mut(block) = arms.iter().map(|&arm| BlockCall::to(arm)).collect();
697 }
698
699 /// Laying the blocks out for the one machine this crate has, and the dump of what came out.
700 ///
701 /// The dump rather than the function, because where a jump goes is on the block and the dump
702 /// is the one place the instruction and the arm are put back together. A test that read the
703 /// two separately would pass on a function whose jump and whose edge disagreed, which is the
704 /// mistake this pass is most able to make.
705 ///
706 /// A block is named in the dump by where it is in the layout rather than by the number it was
707 /// made with, which is why every expectation below reads that way and why the order is worth
708 /// asserting on its own.
709 fn laid_out(func: &mut mir::Func, names: &mut Interner) -> Vec<String> {
710 // Both halves, in the order the pipeline runs them, so that a test which builds a
711 // comparison in front of its branch sees what a compiled function would see.
712 let fusable = fusable(func, &BRANCH, names);
713 blocks(func, &BRANCH, names, &fusable, false);
714 mir::print_func(func, names, ®S)
715 .lines()
716 .filter(|line| !line.trim().is_empty() && !line.starts_with("mfunc") && *line != "}")
717 .map(|line| line.trim().to_string())
718 .collect()
719 }
720
721 /// The blocks in layout order, by the number each was made with.
722 fn order_of(func: &mir::Func) -> Vec<usize> {
723 func.blocks().map(mir::Block::index).collect()
724 }
725
726 #[test]
727 fn a_block_that_falls_into_the_next_one_gets_no_jump_at_all() {
728 let (mut names, mut func, made) = blank(2);
729 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
730
731 let text = laid_out(&mut func, &mut names);
732
733 // The arm is still on the block, because the graph is still worth reading, and there is
734 // no instruction on it because the block it goes to is the one that runs next anyway.
735 assert_eq!(text, ["block0:", "block1", "block1:"]);
736 }
737
738 #[test]
739 fn a_block_that_goes_somewhere_that_is_not_next_gets_a_jump() {
740 let (mut names, mut func, made) = blank(2);
741 // A loop with nothing in it and no way out, which is the smallest function there is with
742 // an edge that runs backwards. Every layout puts the two blocks in this order, so the
743 // second one has nothing after it and its edge has to be a jump.
744 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
745 *func.succs_mut(made[1]) = vec![BlockCall::to(made[0])];
746
747 let text = laid_out(&mut func, &mut names);
748
749 assert_eq!(text, ["block0:", "block1", "block1:", "x64.jmp block0"]);
750 }
751
752 #[test]
753 fn a_branch_that_falls_into_its_false_arm_jumps_when_the_condition_holds() {
754 let (mut names, mut func, made) = blank(3);
755 // A loop whose body is the block it came from: the arm taken when the condition holds is
756 // a block the walk has already been to, so the other arm is what comes next.
757 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
758 branch(&mut func, &mut names, made[1], &[made[0], made[2]]);
759
760 let text = laid_out(&mut func, &mut names);
761
762 assert_eq!(order_of(&func), [0, 1, 2]);
763 assert_eq!(
764 text,
765 [
766 "block0:",
767 "block1",
768 "block1:",
769 "x64.test_rr_8 $rax",
770 "x64.jcc_ne block0, block2",
771 "block2:",
772 ]
773 );
774 }
775
776 #[test]
777 fn a_branch_that_falls_into_its_true_arm_jumps_when_the_condition_does_not_hold() {
778 let (mut names, mut func, made) = blank(3);
779 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
780
781 let text = laid_out(&mut func, &mut names);
782
783 // The arms come out swapped, because after this the first is where the jump goes and the
784 // second is what runs next, and the jump is the one taken when the condition failed.
785 assert_eq!(order_of(&func), [0, 1, 2]);
786 assert_eq!(
787 text,
788 ["block0:", "x64.test_rr_8 $rax", "x64.jcc_e block2, block1", "block1:", "block2:"]
789 );
790 }
791
792 #[test]
793 fn a_block_that_leaves_through_a_register_is_given_no_jump_and_keeps_every_arm() {
794 let (mut names, mut func, made) = blank(4);
795 let jump = Opcode::new(names.intern("x64.jmp_reg"));
796 func.build(made[0], jump).operand(Operand::read(Reg::physical(RAX), GPR)).finish();
797 *func.succs_mut(made[0]) = made[1..].iter().map(|&arm| BlockCall::to(arm)).collect();
798
799 let text = laid_out(&mut func, &mut names);
800
801 // Nothing written behind the jump that is already there, whatever the first arm is, since
802 // where this block goes is in the register. The arms stay on the block because they are
803 // how everything downstream finds out where control can go.
804 assert_eq!(
805 text,
806 [
807 "block0:",
808 "x64.jmp_reg $rax, block1, block2, block3",
809 "block1:",
810 "block2:",
811 "block3:"
812 ]
813 );
814 }
815
816 #[test]
817 fn a_branch_that_can_fall_into_neither_arm_is_given_a_block_to_jump_from() {
818 let (mut names, mut func, made) = blank(2);
819 // A loop that goes back to the top or round again, so both arms are blocks the walk has
820 // already been to and nothing is left to lay out after it.
821 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
822 branch(&mut func, &mut names, made[1], &[made[0], made[1]]);
823
824 let text = laid_out(&mut func, &mut names);
825
826 // Block two is the one this made. It is empty, it is laid out where the branch falls into
827 // it, and the jump the second arm needed is in it rather than being a second jump in the
828 // block above.
829 assert_eq!(order_of(&func), [0, 1, 2]);
830 assert_eq!(
831 text,
832 [
833 "block0:",
834 "block1",
835 "block1:",
836 "x64.test_rr_8 $rax",
837 "x64.jcc_ne block0, block2",
838 "block2:",
839 "x64.jmp block1",
840 ]
841 );
842 }
843
844 #[test]
845 fn the_test_reads_the_register_the_branch_read() {
846 let (mut names, mut func, made) = blank(3);
847 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
848
849 let fusable = fusable(&func, &BRANCH, &mut names);
850 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
851
852 let test = func.insts(made[0]).next().expect("a test");
853 let operands = func[test].operands;
854 assert_eq!(func[operands], [Operand::read(Reg::physical(RAX), GPR)]);
855 }
856
857 #[test]
858 fn a_block_nothing_reaches_is_laid_out_at_the_end_rather_than_deleted() {
859 let (mut names, mut func, made) = blank(4);
860 *func.succs_mut(made[0]) = vec![BlockCall::to(made[3])];
861
862 let fusable = fusable(&func, &BRANCH, &mut names);
863 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
864
865 // Blocks one and two are reached by nothing, so they go last, in the order they were
866 // made. Deleting one would be a decision about what the program does, and this pass has
867 // no business making it.
868 assert_eq!(order_of(&func), [0, 3, 1, 2]);
869 }
870
871 #[test]
872 fn a_function_with_no_blocks_is_left_alone() {
873 let mut names = Interner::new();
874 let mut func = mir::Func::new(names.intern("f"));
875
876 let fusable = fusable(&func, &BRANCH, &mut names);
877 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
878
879 assert_eq!(func.block_count(), 0);
880 }
881
882 #[test]
883 #[should_panic(expected = "a block with 3 arms")]
884 fn a_block_with_three_arms_is_refused_rather_than_laid_out_wrongly() {
885 let (mut names, mut func, made) = blank(4);
886 branch(&mut func, &mut names, made[0], &[made[1], made[2], made[3]]);
887
888 let fusable = fusable(&func, &BRANCH, &mut names);
889 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
890 }
891
892 #[test]
893 #[should_panic(expected = "whose last instruction is not the branch")]
894 fn a_block_with_two_arms_and_no_branch_in_it_is_refused() {
895 let (mut names, mut func, made) = blank(3);
896 let opcode = Opcode::new(names.intern("x64.nop"));
897 func.build(made[0], opcode).finish();
898 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1]), BlockCall::to(made[2])];
899
900 let fusable = fusable(&func, &BRANCH, &mut names);
901 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
902 }
903
904 /// Puts a comparison and a branch on its answer at the end of a block.
905 ///
906 /// The byte is a virtual register, which is what it is when [`fusable`] is asked and is not
907 /// what it is when [`blocks`] runs. Nothing in either half cares which it is except the
908 /// counting, so a test that runs both over one function has to use the register the counting
909 /// wants, and what it costs is that this is one thing the unit tests cannot check about the
910 /// two halves running at different times. `crate::pipeline` runs them the real way round.
911 fn compare(
912 func: &mut mir::Func,
913 names: &mut Interner,
914 block: mir::Block,
915 arms: &[mir::Block],
916 ) -> Reg {
917 let byte = func.new_vreg(GPR);
918 let opcode = Opcode::new(names.intern("x64.cmp_set_l_32"));
919 func.build(block, opcode)
920 .def(byte, GPR)
921 .operand(Operand::read(Reg::physical(RAX), GPR))
922 .operand(Operand::read(Reg::physical(RCX), GPR))
923 .finish();
924 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
925 func.build(block, opcode).operand(Operand::read(byte, GPR)).finish();
926 *func.succs_mut(block) = arms.iter().map(|&arm| BlockCall::to(arm)).collect();
927 byte
928 }
929
930 /// A branch on a comparison is the comparison and a jump on what it found.
931 ///
932 /// Three instructions go in and two come out. The byte goes because nothing reads it, the test
933 /// goes because the comparison set the flags the test was going to set, and the jump names the
934 /// condition rather than naming zero. Which condition it names is the opposite of the one the
935 /// comparison asked about, since the block falls into the arm the comparison is true for.
936 #[test]
937 fn a_branch_on_a_comparison_is_the_comparison_and_a_jump_on_what_it_found() {
938 let (mut names, mut func, made) = blank(3);
939 compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
940
941 let text = laid_out(&mut func, &mut names);
942
943 assert_eq!(
944 text,
945 [
946 "block0:",
947 "x64.cmp_rr_32 $rax, $rcx",
948 "x64.jcc_ge block2, block1",
949 "block1:",
950 "block2:",
951 ]
952 );
953 }
954
955 /// The same thing for a comparison that reads memory, where the address has to come down with
956 /// the operands.
957 ///
958 /// What an addressing mode holds is where its base register is in the operand vector, and
959 /// taking the byte off the front moves every operand one place. A mode left pointing at where
960 /// the base used to be would name the operand in front of it, which here is the value being
961 /// compared, so the instruction would read an address it was never given. The count of the
962 /// operands is checked as well as the position, since a mode that points past the end is the
963 /// other way this goes wrong.
964 #[test]
965 fn a_folded_comparison_keeps_its_address_when_the_byte_comes_off_the_front() {
966 let (mut names, mut func, made) = blank(3);
967 let byte = func.new_vreg(GPR);
968 let opcode = Opcode::new(names.intern("x64.cmp_set_l_rm_32"));
969 func.build(made[0], opcode)
970 .def(byte, GPR)
971 .operand(Operand::read(Reg::physical(RAX), GPR))
972 .mem(Mem { disp: 24, ..Mem::at(Operand::read(Reg::physical(RCX), GPR)) })
973 .finish();
974 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
975 func.build(made[0], opcode).operand(Operand::read(byte, GPR)).finish();
976 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1]), BlockCall::to(made[2])];
977
978 let text = laid_out(&mut func, &mut names);
979
980 assert_eq!(
981 text,
982 [
983 "block0:",
984 "x64.cmp_rm_32 $rax, [$rcx + 24]",
985 "x64.jcc_ge block2, block1",
986 "block1:",
987 "block2:",
988 ]
989 );
990 let compare = func.insts(made[0]).next().expect("the comparison");
991 let mem = func[compare].mem.expect("it reads memory");
992 assert_eq!(func[mem].base, Some(1), "the base came down with the operands");
993 assert_eq!(func[func[compare].operands].len(), 2, "the value and the base of the address");
994 }
995
996 /// The same comparison with something else reading its answer, which keeps everything.
997 ///
998 /// Folding the byte away when a second instruction wants it would be deleting a value the
999 /// program computes. This is the whole of what [`fusable`] is asked before allocation, and the
1000 /// second reader here is in another block so that it is a question about the function rather
1001 /// than about the block the branch is in.
1002 #[test]
1003 fn a_comparison_whose_answer_something_else_reads_keeps_its_byte_and_its_test() {
1004 let (mut names, mut func, made) = blank(3);
1005 let byte = compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
1006 let opcode = Opcode::new(names.intern("x64.mov_rr_64"));
1007 func.build(made[1], opcode)
1008 .def(Reg::physical(RAX), GPR)
1009 .operand(Operand::read(byte, GPR))
1010 .finish();
1011
1012 let text = laid_out(&mut func, &mut names);
1013
1014 assert!(text.contains(&"x64.test_rr_8 %0".to_owned()), "{text:?}");
1015 assert!(text.contains(&"x64.jcc_e block2, block1".to_owned()), "{text:?}");
1016 }
1017
1018 /// A comparison allocation moved away from its branch, which keeps its test.
1019 ///
1020 /// [`fusable`] says the byte has one reader and says nothing about where the two instructions
1021 /// end up, because allocation runs between the two halves and may put a reload in front of the
1022 /// branch. The flags do not survive one, so the second half looks again, and this is the case
1023 /// where it finds something and refuses. The instruction is put in between the two calls
1024 /// because that is when allocation would have put it there.
1025 #[test]
1026 fn a_comparison_that_is_no_longer_in_front_of_its_branch_keeps_its_test() {
1027 let (mut names, mut func, made) = blank(3);
1028 compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
1029 let fusable = fusable(&func, &BRANCH, &mut names);
1030 assert_eq!(fusable.len(), 1, "the comparison is one the byte's count allows");
1031
1032 let branch = func.terminator(made[0]).expect("a block with two arms has a branch");
1033 let opcode = Opcode::new(names.intern("x64.mov_rr_64"));
1034 let reload = func
1035 .build_loose(opcode)
1036 .def(Reg::physical(RCX), GPR)
1037 .operand(Operand::read(Reg::physical(RAX), GPR))
1038 .finish();
1039 func.insert_before(branch, reload);
1040 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
1041 let text = mir::print_func(&func, &names, ®S);
1042
1043 assert!(text.contains("x64.cmp_set_l_32"), "{text}");
1044 assert!(text.contains("x64.test_rr_8"), "{text}");
1045 assert!(!text.contains("x64.cmp_rr_32"), "{text}");
1046 }
1047
1048 /// Laying the blocks out along the traces the weights say, which is what every level above
1049 /// `-O0` asks for.
1050 fn traced(func: &mut mir::Func, names: &mut Interner) -> Vec<String> {
1051 let fusable = fusable(func, &BRANCH, names);
1052 blocks(func, &BRANCH, names, &fusable, true);
1053 mir::print_func(func, names, ®S)
1054 .lines()
1055 .filter(|line| !line.trim().is_empty() && !line.starts_with("mfunc") && *line != "}")
1056 .map(|line| line.trim().to_string())
1057 .collect()
1058 }
1059
1060 /// Says how often a block runs and how often each of its arms is taken, in parts of ten
1061 /// thousand, the way `crate::weights` would have.
1062 fn runs(func: &mut mir::Func, block: mir::Block, weight: u64, arms: &[u64]) {
1063 func.set_weight(block, mir::Weight::parts(weight));
1064 for (index, &taken) in arms.iter().enumerate() {
1065 func.succs_mut(block)[index].weight = mir::Weight::parts(taken);
1066 }
1067 }
1068
1069 /// The arm almost always taken is the one laid out next, whichever of the two it is.
1070 ///
1071 /// Same function twice, with the two arms weighted the two ways round. At `-O0` the order is
1072 /// the shape of the graph and the first arm always comes next; here it is the weights, so the
1073 /// block that hardly ever runs goes behind the one that nearly always does and the jump is
1074 /// spent on it rather than on the common path.
1075 #[test]
1076 fn the_arm_that_is_nearly_always_taken_is_the_one_laid_out_next() {
1077 let (mut names, mut func, made) = blank(3);
1078 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1079 runs(&mut func, made[0], 10_000, &[200, 9_800]);
1080 runs(&mut func, made[1], 200, &[]);
1081 runs(&mut func, made[2], 9_800, &[]);
1082
1083 traced(&mut func, &mut names);
1084
1085 assert_eq!(order_of(&func), [0, 2, 1]);
1086
1087 let (mut names, mut func, made) = blank(3);
1088 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1089 runs(&mut func, made[0], 10_000, &[9_800, 200]);
1090 runs(&mut func, made[1], 9_800, &[]);
1091 runs(&mut func, made[2], 200, &[]);
1092
1093 traced(&mut func, &mut names);
1094
1095 assert_eq!(order_of(&func), [0, 1, 2]);
1096 }
1097
1098 /// A loop comes out as its header, its body and then its exit, with the back edge backwards.
1099 ///
1100 /// Nothing here rotates anything. The trace walks out of the header into the body because the
1101 /// body is where the header nearly always goes, stops at the latch because the header it
1102 /// wants next is already laid out, and the exit is picked up as the next seed. That is the
1103 /// order a branch predictor's static guess expects and it is what the greedy rule gives.
1104 #[test]
1105 fn a_loop_is_laid_out_with_its_exit_behind_it_and_its_back_edge_running_backwards() {
1106 let (mut names, mut func, made) = blank(4);
1107 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
1108 branch(&mut func, &mut names, made[1], &[made[2], made[3]]);
1109 *func.succs_mut(made[2]) = vec![BlockCall::to(made[1])];
1110 runs(&mut func, made[0], 10_000, &[10_000]);
1111 runs(&mut func, made[1], 100_000, &[90_000, 10_000]);
1112 runs(&mut func, made[2], 90_000, &[90_000]);
1113 runs(&mut func, made[3], 10_000, &[]);
1114
1115 let text = traced(&mut func, &mut names);
1116
1117 assert_eq!(order_of(&func), [0, 1, 2, 3]);
1118 assert_eq!(
1119 text,
1120 [
1121 "block0:",
1122 "block1",
1123 "block1:",
1124 "x64.test_rr_8 $rax",
1125 "x64.jcc_e block3, block2",
1126 "block2:",
1127 "x64.jmp block1",
1128 "block3:",
1129 ]
1130 );
1131 }
1132
1133 /// A block reached only from the cold arm is laid out behind everything the trunk reaches.
1134 ///
1135 /// The shape is `if (unlikely) handle(); rest();`, where the handler and the rest of the
1136 /// function are both reached from the branch. Reverse postorder puts the handler between the
1137 /// branch and the rest of the function; the trace puts the rest of the function next, because
1138 /// that is where the branch nearly always goes, and the handler ends up last.
1139 #[test]
1140 fn a_block_only_the_cold_arm_reaches_goes_behind_the_rest_of_the_function() {
1141 let (mut names, mut func, made) = blank(4);
1142 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1143 *func.succs_mut(made[1]) = vec![BlockCall::to(made[2])];
1144 *func.succs_mut(made[2]) = vec![BlockCall::to(made[3])];
1145 runs(&mut func, made[0], 10_000, &[100, 9_900]);
1146 runs(&mut func, made[1], 100, &[100]);
1147 runs(&mut func, made[2], 10_000, &[10_000]);
1148 runs(&mut func, made[3], 10_000, &[]);
1149
1150 assert_eq!(order(&func), [made[0], made[1], made[2], made[3]]);
1151
1152 traced(&mut func, &mut names);
1153
1154 assert_eq!(order_of(&func), [0, 2, 3, 1]);
1155 }
1156
1157 /// A block nothing reaches is still laid out, since the last round asks for nothing.
1158 #[test]
1159 fn the_last_round_picks_up_a_block_nothing_reaches() {
1160 let (mut names, mut func, made) = blank(3);
1161 *func.succs_mut(made[0]) = vec![BlockCall::to(made[2])];
1162 runs(&mut func, made[0], 10_000, &[10_000]);
1163 runs(&mut func, made[1], 0, &[]);
1164 runs(&mut func, made[2], 10_000, &[]);
1165
1166 traced(&mut func, &mut names);
1167
1168 assert_eq!(order_of(&func), [0, 2, 1]);
1169 }
1170
1171 /// The entry is laid out first however cold it is against the rest of the function.
1172 ///
1173 /// A function is entered at its first byte, so the block that runs first has to be the block
1174 /// that is written first, and the seed order is what makes that true rather than any check
1175 /// afterwards. Here the loop body runs ten times for every call and would otherwise have been
1176 /// the first seed.
1177 #[test]
1178 fn the_entry_is_the_first_seed_even_when_something_else_runs_more_often() {
1179 let (mut names, mut func, made) = blank(3);
1180 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
1181 branch(&mut func, &mut names, made[1], &[made[1], made[2]]);
1182 runs(&mut func, made[0], 10_000, &[10_000]);
1183 runs(&mut func, made[1], 100_000, &[90_000, 10_000]);
1184 runs(&mut func, made[2], 10_000, &[]);
1185
1186 traced(&mut func, &mut names);
1187
1188 assert_eq!(func.blocks().next().map(mir::Block::index), Some(0));
1189 }
1190
1191 /// A branch whose arms are even still falls into one of them rather than jumping to both.
1192 ///
1193 /// Nothing predicts a range check, so both arms come out at half, and half is under every
1194 /// branch threshold above the last round. The trace therefore ends at the branch, and what
1195 /// decides the layout is where the next one starts: at the likeliest arm out of the block the
1196 /// trace stopped in, which is a fall-through, and not at whichever of the two blocks was made
1197 /// first, which would have cost a jump on both paths out of an even branch.
1198 #[test]
1199 fn a_branch_whose_arms_are_even_is_still_laid_out_next_to_one_of_them() {
1200 let (mut names, mut func, made) = blank(3);
1201 // The second arm is the block made first, so a layout that fell back to the seed list
1202 // would lay that one out next and leave the arm written first to be jumped to.
1203 branch(&mut func, &mut names, made[0], &[made[2], made[1]]);
1204 runs(&mut func, made[0], 10_000, &[5_000, 5_000]);
1205 runs(&mut func, made[1], 5_000, &[]);
1206 runs(&mut func, made[2], 5_000, &[]);
1207
1208 traced(&mut func, &mut names);
1209
1210 assert_eq!(order_of(&func), [0, 2, 1]);
1211 }
1212
1213 /// A run of blocks the rounds cut in half comes back out in one piece.
1214 ///
1215 /// Two comparisons against a constant, one behind the other, which is what a switch over
1216 /// scattered labels is lowered to. The second comparison is only reached when the first one
1217 /// failed, so it runs half as often as the function is entered and the first round will not
1218 /// touch it: the trace stops at the first comparison and the block that was about to fall
1219 /// through it is left for a later round. What puts it back is [`connect`], and without it the
1220 /// body of the first case would sit between the two comparisons and both would pay a jump.
1221 #[test]
1222 fn a_chain_the_rounds_cut_in_half_is_run_back_together() {
1223 let (mut names, mut func, made) = blank(5);
1224 branch(&mut func, &mut names, made[0], &[made[2], made[1]]);
1225 branch(&mut func, &mut names, made[2], &[made[4], made[3]]);
1226 runs(&mut func, made[0], 10_000, &[5_000, 5_000]);
1227 runs(&mut func, made[1], 5_000, &[]);
1228 runs(&mut func, made[2], 5_000, &[3_000, 2_000]);
1229 runs(&mut func, made[3], 2_000, &[]);
1230 runs(&mut func, made[4], 3_000, &[]);
1231
1232 traced(&mut func, &mut names);
1233
1234 assert_eq!(order_of(&func), [0, 2, 4, 1, 3]);
1235 }
1236}