Skip to content

Commit 9b0ef4c

Browse files
committed
promotion: do not promote const-fn calls in const when that may fail without the entire const failing
1 parent 7de1a1f commit 9b0ef4c

11 files changed

+193
-247
lines changed

compiler/rustc_mir_transform/src/lib.rs

+8-7
Original file line numberDiff line numberDiff line change
@@ -343,13 +343,6 @@ fn mir_promoted(
343343
body.tainted_by_errors = Some(error_reported);
344344
}
345345

346-
let mut required_consts = Vec::new();
347-
let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
348-
for (bb, bb_data) in traversal::reverse_postorder(&body) {
349-
required_consts_visitor.visit_basic_block_data(bb, bb_data);
350-
}
351-
body.required_consts = required_consts;
352-
353346
// What we need to run borrowck etc.
354347
let promote_pass = promote_consts::PromoteTemps::default();
355348
pm::run_passes(
@@ -359,6 +352,14 @@ fn mir_promoted(
359352
Some(MirPhase::Analysis(AnalysisPhase::Initial)),
360353
);
361354

355+
// Promotion generates new consts; we run this after promotion to ensure they are accounted for.
356+
let mut required_consts = Vec::new();
357+
let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
358+
for (bb, bb_data) in traversal::reverse_postorder(&body) {
359+
required_consts_visitor.visit_basic_block_data(bb, bb_data);
360+
}
361+
body.required_consts = required_consts;
362+
362363
let promoted = promote_pass.promoted_fragments.into_inner();
363364
(tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
364365
}

compiler/rustc_mir_transform/src/promote_consts.rs

+79-19
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
//! move analysis runs after promotion on broken MIR.
1414
1515
use either::{Left, Right};
16+
use rustc_data_structures::fx::FxHashSet;
1617
use rustc_hir as hir;
1718
use rustc_middle::mir;
1819
use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
@@ -175,6 +176,12 @@ fn collect_temps_and_candidates<'tcx>(
175176
struct Validator<'a, 'tcx> {
176177
ccx: &'a ConstCx<'a, 'tcx>,
177178
temps: &'a mut IndexSlice<Local, TempState>,
179+
/// For backwards compatibility, we are promoting function calls in `const`/`static`
180+
/// initializers. But we want to avoid evaluating code that might panic and that otherwise would
181+
/// not have been evaluated, so we only promote such calls in basic blocks that are guaranteed
182+
/// to execute. In other words, we only promote such calls in basic blocks that are definitely
183+
/// not dead code. Here we cache the result of computing that set of basic blocks.
184+
promotion_safe_blocks: Option<FxHashSet<BasicBlock>>,
178185
}
179186

180187
impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
@@ -260,7 +267,9 @@ impl<'tcx> Validator<'_, 'tcx> {
260267
self.validate_rvalue(rhs)
261268
}
262269
Right(terminator) => match &terminator.kind {
263-
TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
270+
TerminatorKind::Call { func, args, .. } => {
271+
self.validate_call(func, args, loc.block)
272+
}
264273
TerminatorKind::Yield { .. } => Err(Unpromotable),
265274
kind => {
266275
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
@@ -587,42 +596,93 @@ impl<'tcx> Validator<'_, 'tcx> {
587596
Ok(())
588597
}
589598

599+
/// Computes the sets of blocks of this MIR that are definitely going to be executed
600+
/// if the function returns successfully. That makes it safe to promote calls in them
601+
/// that might fail.
602+
fn promotion_safe_blocks(body: &mir::Body<'tcx>) -> FxHashSet<BasicBlock> {
603+
let mut safe_blocks = FxHashSet::default();
604+
let mut safe_block = START_BLOCK;
605+
loop {
606+
safe_blocks.insert(safe_block);
607+
// Let's see if we can find another safe block.
608+
safe_block = match body.basic_blocks[safe_block].terminator().kind {
609+
TerminatorKind::Goto { target } => target,
610+
TerminatorKind::Call { target: Some(target), .. }
611+
| TerminatorKind::Drop { target, .. } => {
612+
// This calls a function or the destructor. `target` does not get executed if
613+
// the callee loops or panics. But in both cases the const already fails to
614+
// evaluate, so we are fine considering `target` a safe block for promotion.
615+
target
616+
}
617+
TerminatorKind::Assert { target, .. } => {
618+
// Similar to above, we only consider successful execution.
619+
target
620+
}
621+
_ => {
622+
// No next safe block.
623+
break;
624+
}
625+
};
626+
}
627+
safe_blocks
628+
}
629+
630+
/// Returns whether the block is "safe" for promotion, which means it cannot be dead code.
631+
/// We use this to avoid promoting operations that can fail in dead code.
632+
fn is_promotion_safe_block(&mut self, block: BasicBlock) -> bool {
633+
let body = self.body;
634+
let safe_blocks =
635+
self.promotion_safe_blocks.get_or_insert_with(|| Self::promotion_safe_blocks(body));
636+
safe_blocks.contains(&block)
637+
}
638+
590639
fn validate_call(
591640
&mut self,
592641
callee: &Operand<'tcx>,
593642
args: &[Spanned<Operand<'tcx>>],
643+
block: BasicBlock,
594644
) -> Result<(), Unpromotable> {
645+
// Validate the operands. If they fail, there's no question -- we cannot promote.
646+
self.validate_operand(callee)?;
647+
for arg in args {
648+
self.validate_operand(&arg.node)?;
649+
}
650+
651+
// Functions marked `#[rustc_promotable]` are explicitly allowed to be promoted, so we can
652+
// accept them at this point.
595653
let fn_ty = callee.ty(self.body, self.tcx);
654+
if let ty::FnDef(def_id, _) = *fn_ty.kind() {
655+
if self.tcx.is_promotable_const_fn(def_id) {
656+
return Ok(());
657+
}
658+
}
596659

597-
// Inside const/static items, we promote all (eligible) function calls.
598-
// Everywhere else, we require `#[rustc_promotable]` on the callee.
599-
let promote_all_const_fn = matches!(
660+
// Ideally, we'd stop here and reject the rest.
661+
// But for backward compatibility, we have to accept some promotion in const/static
662+
// initializers. Inline consts are explicitly excluded, they are more recent so we have no
663+
// backwards compatibility reason to allow more promotion inside of them.
664+
let promote_all_fn = matches!(
600665
self.const_kind,
601666
Some(hir::ConstContext::Static(_) | hir::ConstContext::Const { inline: false })
602667
);
603-
if !promote_all_const_fn {
604-
if let ty::FnDef(def_id, _) = *fn_ty.kind() {
605-
// Never promote runtime `const fn` calls of
606-
// functions without `#[rustc_promotable]`.
607-
if !self.tcx.is_promotable_const_fn(def_id) {
608-
return Err(Unpromotable);
609-
}
610-
}
668+
if !promote_all_fn {
669+
return Err(Unpromotable);
611670
}
612-
671+
// Make sure the callee is a `const fn`.
613672
let is_const_fn = match *fn_ty.kind() {
614673
ty::FnDef(def_id, _) => self.tcx.is_const_fn_raw(def_id),
615674
_ => false,
616675
};
617676
if !is_const_fn {
618677
return Err(Unpromotable);
619678
}
620-
621-
self.validate_operand(callee)?;
622-
for arg in args {
623-
self.validate_operand(&arg.node)?;
679+
// The problem is, this may promote calls to functions that panic.
680+
// We don't want to introduce compilation errors if there's a panic in a call in dead code.
681+
// So we ensure that this is not dead code.
682+
if !self.is_promotion_safe_block(block) {
683+
return Err(Unpromotable);
624684
}
625-
685+
// This passed all checks, so let's accept.
626686
Ok(())
627687
}
628688
}
@@ -633,7 +693,7 @@ fn validate_candidates(
633693
temps: &mut IndexSlice<Local, TempState>,
634694
candidates: &[Candidate],
635695
) -> Vec<Candidate> {
636-
let mut validator = Validator { ccx, temps };
696+
let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
637697

638698
candidates
639699
.iter()

tests/ui/consts/const-eval/promoted_errors.noopt.stderr

-44
This file was deleted.

tests/ui/consts/const-eval/promoted_errors.opt.stderr

-44
This file was deleted.

tests/ui/consts/const-eval/promoted_errors.opt_with_overflow_checks.stderr

-44
This file was deleted.

tests/ui/consts/const-eval/promoted_errors.rs

-52
This file was deleted.

tests/ui/consts/promote-not.rs

+9
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,15 @@ const TEST_DROP_NOT_PROMOTE: &String = {
5151
};
5252

5353

54+
// We do not promote function calls in `const` initializers in dead code.
55+
const fn mk_panic() -> u32 { panic!() }
56+
const fn mk_false() -> bool { false }
57+
const Y: () = {
58+
if mk_false() {
59+
let _x: &'static u32 = &mk_panic(); //~ ERROR temporary value dropped while borrowed
60+
}
61+
};
62+
5463
fn main() {
5564
// We must not promote things with interior mutability. Not even if we "project it away".
5665
let _val: &'static _ = &(Cell::new(1), 2).0; //~ ERROR temporary value dropped while borrowed

0 commit comments

Comments
 (0)