Skip to content

Commit 777003a

Browse files
committed
Likely unlikely fix
1 parent f2a3542 commit 777003a

File tree

22 files changed

+256
-73
lines changed

22 files changed

+256
-73
lines changed

compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -453,11 +453,6 @@ fn codegen_regular_intrinsic_call<'tcx>(
453453
fx.bcx.ins().trap(TrapCode::user(2).unwrap());
454454
return Ok(());
455455
}
456-
sym::likely | sym::unlikely => {
457-
intrinsic_args!(fx, args => (a); intrinsic);
458-
459-
ret.write_cvalue(fx, a);
460-
}
461456
sym::breakpoint => {
462457
intrinsic_args!(fx, args => (); intrinsic);
463458

@@ -1267,6 +1262,10 @@ fn codegen_regular_intrinsic_call<'tcx>(
12671262
);
12681263
}
12691264

1265+
sym::cold_path => {
1266+
// This is a no-op. The intrinsic is just a hint to the optimizer.
1267+
}
1268+
12701269
// Unimplemented intrinsics must have a fallback body. The fallback body is obtained
12711270
// by converting the `InstanceKind::Intrinsic` to an `InstanceKind::Item`.
12721271
_ => {

compiler/rustc_codegen_gcc/src/intrinsic/mod.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,6 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc
139139
&args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
140140
)
141141
}
142-
sym::likely => self.expect(args[0].immediate(), true),
143-
sym::unlikely => self.expect(args[0].immediate(), false),
144142
sym::is_val_statically_known => {
145143
let a = args[0].immediate();
146144
let builtin = self.context.get_builtin_function("__builtin_constant_p");

compiler/rustc_codegen_llvm/src/intrinsic.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
192192
Some(instance),
193193
)
194194
}
195-
sym::likely => self.expect(args[0].immediate(), true),
196195
sym::is_val_statically_known => {
197196
let intrinsic_type = args[0].layout.immediate_llvm_type(self.cx);
198197
let kind = self.type_kind(intrinsic_type);
@@ -213,7 +212,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
213212
self.const_bool(false)
214213
}
215214
}
216-
sym::unlikely => self.expect(args[0].immediate(), false),
217215
sym::select_unpredictable => {
218216
let cond = args[0].immediate();
219217
assert_eq!(args[1].layout, args[2].layout);

compiler/rustc_codegen_ssa/src/mir/block.rs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -377,20 +377,32 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
377377
// If there are two targets (one conditional, one fallback), emit `br` instead of
378378
// `switch`.
379379
let (test_value, target) = target_iter.next().unwrap();
380-
let lltrue = helper.llbb_with_cleanup(self, target);
381-
let llfalse = helper.llbb_with_cleanup(self, targets.otherwise());
380+
let otherwise = targets.otherwise();
381+
let lltarget = helper.llbb_with_cleanup(self, target);
382+
let llotherwise = helper.llbb_with_cleanup(self, otherwise);
383+
let target_cold = self.cold_blocks[target];
384+
let otherwise_cold = self.cold_blocks[otherwise];
385+
// If `target_cold == otherwise_cold`, the branches have the same weight
386+
// so there is no expectation. If they differ, the `target` branch is expected
387+
// when the `otherwise` branch is cold.
388+
let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
382389
if switch_ty == bx.tcx().types.bool {
383390
// Don't generate trivial icmps when switching on bool.
384391
match test_value {
385-
0 => bx.cond_br(discr_value, llfalse, lltrue),
386-
1 => bx.cond_br(discr_value, lltrue, llfalse),
392+
0 => {
393+
let expect = expect.map(|e| !e);
394+
bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
395+
}
396+
1 => {
397+
bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
398+
}
387399
_ => bug!(),
388400
}
389401
} else {
390402
let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
391403
let llval = bx.const_uint_big(switch_llty, test_value);
392404
let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
393-
bx.cond_br(cmp, lltrue, llfalse);
405+
bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
394406
}
395407
} else if self.cx.sess().opts.optimize == OptLevel::No
396408
&& target_iter.len() == 2

compiler/rustc_codegen_ssa/src/mir/intrinsic.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,11 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
498498
}
499499
}
500500

501+
sym::cold_path => {
502+
// This is a no-op. The intrinsic is just a hint to the optimizer.
503+
return Ok(());
504+
}
505+
501506
_ => {
502507
// Need to use backend-specific things in the implementation.
503508
return bx.codegen_intrinsic_call(instance, fn_abi, args, llresult, span);

compiler/rustc_codegen_ssa/src/mir/mod.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
9191
/// Cached terminate upon unwinding block and its reason
9292
terminate_block: Option<(Bx::BasicBlock, UnwindTerminateReason)>,
9393

94+
/// A bool flag for each basic block indicating whether it is a cold block.
95+
/// A cold block is a block that is unlikely to be executed at runtime.
96+
cold_blocks: IndexVec<mir::BasicBlock, bool>,
97+
9498
/// The location where each MIR arg/var/tmp/ret is stored. This is
9599
/// usually an `PlaceRef` representing an alloca, but not always:
96100
/// sometimes we can skip the alloca and just store the value
@@ -207,6 +211,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
207211
cleanup_kinds,
208212
landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
209213
funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks.len()),
214+
cold_blocks: find_cold_blocks(cx.tcx(), mir),
210215
locals: locals::Locals::empty(),
211216
debug_context,
212217
per_local_var_debug_info: None,
@@ -477,3 +482,39 @@ fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
477482

478483
args
479484
}
485+
486+
fn find_cold_blocks<'tcx>(
487+
tcx: TyCtxt<'tcx>,
488+
mir: &mir::Body<'tcx>,
489+
) -> IndexVec<mir::BasicBlock, bool> {
490+
let local_decls = &mir.local_decls;
491+
492+
let mut cold_blocks: IndexVec<mir::BasicBlock, bool> =
493+
IndexVec::from_elem(false, &mir.basic_blocks);
494+
495+
// Traverse all basic blocks from end of the function to the start.
496+
for (bb, bb_data) in traversal::postorder(mir) {
497+
let terminator = bb_data.terminator();
498+
499+
// If a BB ends with a call to a cold function, mark it as cold.
500+
if let mir::TerminatorKind::Call { ref func, .. } = terminator.kind
501+
&& let ty::FnDef(def_id, ..) = *func.ty(local_decls, tcx).kind()
502+
&& let attrs = tcx.codegen_fn_attrs(def_id)
503+
&& attrs.flags.contains(CodegenFnAttrFlags::COLD)
504+
{
505+
cold_blocks[bb] = true;
506+
continue;
507+
}
508+
509+
// If all successors of a BB are cold and there's at least one of them, mark this BB as cold
510+
let mut succ = terminator.successors();
511+
if let Some(first) = succ.next()
512+
&& cold_blocks[first]
513+
&& succ.all(|s| cold_blocks[s])
514+
{
515+
cold_blocks[bb] = true;
516+
}
517+
}
518+
519+
cold_blocks
520+
}

compiler/rustc_codegen_ssa/src/traits/builder.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,26 @@ pub trait BuilderMethods<'a, 'tcx>:
8484
then_llbb: Self::BasicBlock,
8585
else_llbb: Self::BasicBlock,
8686
);
87+
88+
// Conditional with expectation.
89+
//
90+
// This function is opt-in for back ends.
91+
//
92+
// The default implementation calls `self.expect()` before emiting the branch
93+
// by calling `self.cond_br()`
94+
fn cond_br_with_expect(
95+
&mut self,
96+
mut cond: Self::Value,
97+
then_llbb: Self::BasicBlock,
98+
else_llbb: Self::BasicBlock,
99+
expect: Option<bool>,
100+
) {
101+
if let Some(expect) = expect {
102+
cond = self.expect(cond, expect);
103+
}
104+
self.cond_br(cond, then_llbb, else_llbb)
105+
}
106+
87107
fn switch(
88108
&mut self,
89109
v: Self::Value,

compiler/rustc_const_eval/src/interpret/intrinsics.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
417417
// These just return their argument
418418
self.copy_op(&args[0], dest)?;
419419
}
420+
sym::cold_path => {
421+
// This is a no-op. The intrinsic is just a hint to the optimizer.
422+
}
420423
sym::raw_eq => {
421424
let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
422425
self.write_scalar(result, dest)?;

compiler/rustc_hir_analysis/src/check/intrinsic.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,8 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -
109109
| sym::three_way_compare
110110
| sym::discriminant_value
111111
| sym::type_id
112-
| sym::likely
113-
| sym::unlikely
114112
| sym::select_unpredictable
113+
| sym::cold_path
115114
| sym::ptr_guaranteed_cmp
116115
| sym::minnumf16
117116
| sym::minnumf32
@@ -489,9 +488,8 @@ pub fn check_intrinsic_type(
489488
sym::float_to_int_unchecked => (2, 0, vec![param(0)], param(1)),
490489

491490
sym::assume => (0, 0, vec![tcx.types.bool], tcx.types.unit),
492-
sym::likely => (0, 0, vec![tcx.types.bool], tcx.types.bool),
493-
sym::unlikely => (0, 0, vec![tcx.types.bool], tcx.types.bool),
494491
sym::select_unpredictable => (1, 0, vec![tcx.types.bool, param(0), param(0)], param(0)),
492+
sym::cold_path => (0, 0, vec![], tcx.types.unit),
495493

496494
sym::read_via_copy => (1, 0, vec![Ty::new_imm_ptr(tcx, param(0))], param(0)),
497495
sym::write_via_move => {

compiler/rustc_span/src/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,7 @@ symbols! {
589589
cmse_nonsecure_entry,
590590
coerce_unsized,
591591
cold,
592+
cold_path,
592593
collapse_debuginfo,
593594
column,
594595
compare_bytes,

0 commit comments

Comments
 (0)