Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 7aa413d

Browse files
committedFeb 19, 2023
Auto merge of #107921 - cjgillot:codegen-overflow-check, r=tmiasko
Make codegen choose whether to emit overflow checks ConstProp and DataflowConstProp currently have a specific code path not to propagate constants when they overflow. This is meant to have the correct behaviour when inlining from a crate with overflow checks (like `core`) into a crate compiled without. This PR shifts the behaviour change to the `Assert(Overflow*)` MIR terminators: if the crate is compiled without overflow checks, just skip emitting the assertions. This is already what happens with `OverflowNeg`. This allows ConstProp and DataflowConstProp to transform `CheckedBinaryOp(Add, u8::MAX, 1)` into `const (0, true)`, and let codegen ignore the `true`. The interpreter is modified to conform to this behaviour. Fixes #35310
2 parents dc89a80 + 9f6c1df commit 7aa413d

File tree

24 files changed

+250
-217
lines changed

24 files changed

+250
-217
lines changed
 

‎compiler/rustc_codegen_cranelift/src/base.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,12 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
347347
}
348348
TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
349349
if !fx.tcx.sess.overflow_checks() {
350-
if let mir::AssertKind::OverflowNeg(_) = *msg {
350+
let overflow_not_to_check = match msg {
351+
AssertKind::OverflowNeg(..) => true,
352+
AssertKind::Overflow(op, ..) => op.is_checkable(),
353+
_ => false,
354+
};
355+
if overflow_not_to_check {
351356
let target = fx.get_block(*target);
352357
fx.bcx.ins().jump(target, &[]);
353358
continue;
@@ -567,15 +572,7 @@ fn codegen_stmt<'tcx>(
567572
let lhs = codegen_operand(fx, &lhs_rhs.0);
568573
let rhs = codegen_operand(fx, &lhs_rhs.1);
569574

570-
let res = if !fx.tcx.sess.overflow_checks() {
571-
let val =
572-
crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
573-
let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
574-
CValue::by_val_pair(val, is_overflow, lval.layout())
575-
} else {
576-
crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
577-
};
578-
575+
let res = crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs);
579576
lval.write_cvalue(fx, res);
580577
}
581578
Rvalue::UnaryOp(un_op, ref operand) => {

‎compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -493,20 +493,6 @@ fn codegen_regular_intrinsic_call<'tcx>(
493493
let res = crate::num::codegen_int_binop(fx, bin_op, x, y);
494494
ret.write_cvalue(fx, res);
495495
}
496-
sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
497-
intrinsic_args!(fx, args => (x, y); intrinsic);
498-
499-
assert_eq!(x.layout().ty, y.layout().ty);
500-
let bin_op = match intrinsic {
501-
sym::add_with_overflow => BinOp::Add,
502-
sym::sub_with_overflow => BinOp::Sub,
503-
sym::mul_with_overflow => BinOp::Mul,
504-
_ => unreachable!(),
505-
};
506-
507-
let res = crate::num::codegen_checked_int_binop(fx, bin_op, x, y);
508-
ret.write_cvalue(fx, res);
509-
}
510496
sym::saturating_add | sym::saturating_sub => {
511497
intrinsic_args!(fx, args => (lhs, rhs); intrinsic);
512498

‎compiler/rustc_codegen_ssa/src/mir/block.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -563,11 +563,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
563563
// with #[rustc_inherit_overflow_checks] and inlined from
564564
// another crate (mostly core::num generic/#[inline] fns),
565565
// while the current crate doesn't use overflow checks.
566-
// NOTE: Unlike binops, negation doesn't have its own
567-
// checked operation, just a comparison with the minimum
568-
// value, so we have to check for the assert message.
569-
if !bx.check_overflow() {
570-
if let AssertKind::OverflowNeg(_) = *msg {
566+
if !bx.cx().check_overflow() {
567+
let overflow_not_to_check = match msg {
568+
AssertKind::OverflowNeg(..) => true,
569+
AssertKind::Overflow(op, ..) => op.is_checkable(),
570+
_ => false,
571+
};
572+
if overflow_not_to_check {
571573
const_cond = Some(expected);
572574
}
573575
}

‎compiler/rustc_codegen_ssa/src/mir/intrinsic.rs

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -218,9 +218,6 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
218218
args[1].val.unaligned_volatile_store(bx, dst);
219219
return;
220220
}
221-
sym::add_with_overflow
222-
| sym::sub_with_overflow
223-
| sym::mul_with_overflow
224221
| sym::unchecked_div
225222
| sym::unchecked_rem
226223
| sym::unchecked_shl
@@ -232,28 +229,6 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
232229
let ty = arg_tys[0];
233230
match int_type_width_signed(ty, bx.tcx()) {
234231
Some((_width, signed)) => match name {
235-
sym::add_with_overflow
236-
| sym::sub_with_overflow
237-
| sym::mul_with_overflow => {
238-
let op = match name {
239-
sym::add_with_overflow => OverflowOp::Add,
240-
sym::sub_with_overflow => OverflowOp::Sub,
241-
sym::mul_with_overflow => OverflowOp::Mul,
242-
_ => bug!(),
243-
};
244-
let (val, overflow) =
245-
bx.checked_binop(op, ty, args[0].immediate(), args[1].immediate());
246-
// Convert `i1` to a `bool`, and write it to the out parameter
247-
let val = bx.from_immediate(val);
248-
let overflow = bx.from_immediate(overflow);
249-
250-
let dest = result.project_field(bx, 0);
251-
bx.store(val, dest.llval, dest.align);
252-
let dest = result.project_field(bx, 1);
253-
bx.store(overflow, dest.llval, dest.align);
254-
255-
return;
256-
}
257232
sym::exact_div => {
258233
if signed {
259234
bx.exactsdiv(args[0].immediate(), args[1].immediate())

‎compiler/rustc_codegen_ssa/src/mir/rvalue.rs

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -652,15 +652,6 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
652652
rhs: Bx::Value,
653653
input_ty: Ty<'tcx>,
654654
) -> OperandValue<Bx::Value> {
655-
// This case can currently arise only from functions marked
656-
// with #[rustc_inherit_overflow_checks] and inlined from
657-
// another crate (mostly core::num generic/#[inline] fns),
658-
// while the current crate doesn't use overflow checks.
659-
if !bx.cx().check_overflow() {
660-
let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
661-
return OperandValue::Pair(val, bx.cx().const_bool(false));
662-
}
663-
664655
let (val, of) = match op {
665656
// These are checked using intrinsics
666657
mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -210,19 +210,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
210210
let out_val = numeric_intrinsic(intrinsic_name, bits, kind);
211211
self.write_scalar(out_val, dest)?;
212212
}
213-
sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
214-
let lhs = self.read_immediate(&args[0])?;
215-
let rhs = self.read_immediate(&args[1])?;
216-
let bin_op = match intrinsic_name {
217-
sym::add_with_overflow => BinOp::Add,
218-
sym::sub_with_overflow => BinOp::Sub,
219-
sym::mul_with_overflow => BinOp::Mul,
220-
_ => bug!(),
221-
};
222-
self.binop_with_overflow(
223-
bin_op, /*force_overflow_checks*/ true, &lhs, &rhs, dest,
224-
)?;
225-
}
226213
sym::saturating_add | sym::saturating_sub => {
227214
let l = self.read_immediate(&args[0])?;
228215
let r = self.read_immediate(&args[1])?;

‎compiler/rustc_const_eval/src/interpret/machine.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,9 @@ pub trait Machine<'mir, 'tcx>: Sized {
147147
true
148148
}
149149

150-
/// Whether CheckedBinOp MIR statements should actually check for overflow.
151-
fn checked_binop_checks_overflow(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
150+
/// Whether Assert(OverflowNeg) and Assert(Overflow) MIR terminators should actually
151+
/// check for overflow.
152+
fn ignore_checkable_overflow_assertions(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
152153

153154
/// Entry point for obtaining the MIR of anything that should get evaluated.
154155
/// So not just functions and shims, but also const/static initializers, anonymous
@@ -466,8 +467,8 @@ pub macro compile_time_machine(<$mir: lifetime, $tcx: lifetime>) {
466467
}
467468

468469
#[inline(always)]
469-
fn checked_binop_checks_overflow(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
470-
true
470+
fn ignore_checkable_overflow_assertions(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
471+
false
471472
}
472473

473474
#[inline(always)]

‎compiler/rustc_const_eval/src/interpret/operator.rs

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,9 @@ use super::{ImmTy, Immediate, InterpCx, Machine, PlaceTy};
1010
impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
1111
/// Applies the binary operation `op` to the two operands and writes a tuple of the result
1212
/// and a boolean signifying the potential overflow to the destination.
13-
///
14-
/// `force_overflow_checks` indicates whether overflow checks should be done even when
15-
/// `tcx.sess.overflow_checks()` is `false`.
1613
pub fn binop_with_overflow(
1714
&mut self,
1815
op: mir::BinOp,
19-
force_overflow_checks: bool,
2016
left: &ImmTy<'tcx, M::Provenance>,
2117
right: &ImmTy<'tcx, M::Provenance>,
2218
dest: &PlaceTy<'tcx, M::Provenance>,
@@ -28,10 +24,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
2824
"type mismatch for result of {:?}",
2925
op,
3026
);
31-
// As per https://github.com/rust-lang/rust/pull/98738, we always return `false` in the 2nd
32-
// component when overflow checking is disabled.
33-
let overflowed =
34-
overflowed && (force_overflow_checks || M::checked_binop_checks_overflow(self));
3527
// Write the result to `dest`.
3628
if let Abi::ScalarPair(..) = dest.layout.abi {
3729
// We can use the optimized path and avoid `place_field` (which might do

‎compiler/rustc_const_eval/src/interpret/step.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
185185
let left = self.read_immediate(&self.eval_operand(left, None)?)?;
186186
let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
187187
let right = self.read_immediate(&self.eval_operand(right, layout)?)?;
188-
self.binop_with_overflow(
189-
bin_op, /*force_overflow_checks*/ false, &left, &right, &dest,
190-
)?;
188+
self.binop_with_overflow(bin_op, &left, &right, &dest)?;
191189
}
192190

193191
UnaryOp(un_op, ref operand) => {

‎compiler/rustc_const_eval/src/interpret/terminator.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,14 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
137137
}
138138

139139
Assert { ref cond, expected, ref msg, target, cleanup } => {
140+
let ignored = M::ignore_checkable_overflow_assertions(self)
141+
&& match msg {
142+
mir::AssertKind::OverflowNeg(..) => true,
143+
mir::AssertKind::Overflow(op, ..) => op.is_checkable(),
144+
_ => false,
145+
};
140146
let cond_val = self.read_scalar(&self.eval_operand(cond, None)?)?.to_bool()?;
141-
if expected == cond_val {
147+
if ignored || expected == cond_val {
142148
self.go_to_block(target);
143149
} else {
144150
M::assert_panic(self, msg, cleanup)?;

‎compiler/rustc_middle/src/mir/syntax.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,12 @@ pub enum TerminatorKind<'tcx> {
671671
/// as parameters, and `None` for the destination. Keep in mind that the `cleanup` path is not
672672
/// necessarily executed even in the case of a panic, for example in `-C panic=abort`. If the
673673
/// assertion does not fail, execution continues at the specified basic block.
674+
///
675+
/// When overflow checking is disabled and this is run-time MIR (as opposed to compile-time MIR
676+
/// that is used for CTFE), the following variants of this terminator behave as `goto target`:
677+
/// - `OverflowNeg(..)`,
678+
/// - `Overflow(op, ..)` if op is a "checkable" operation (add, sub, mul, shl, shr, but NOT
679+
/// div or rem).
674680
Assert {
675681
cond: Operand<'tcx>,
676682
expected: bool,
@@ -1103,10 +1109,6 @@ pub enum Rvalue<'tcx> {
11031109

11041110
/// Same as `BinaryOp`, but yields `(T, bool)` with a `bool` indicating an error condition.
11051111
///
1106-
/// When overflow checking is disabled and we are generating run-time code, the error condition
1107-
/// is false. Otherwise, and always during CTFE, the error condition is determined as described
1108-
/// below.
1109-
///
11101112
/// For addition, subtraction, and multiplication on integers the error condition is set when
11111113
/// the infinite precision result would be unequal to the actual result.
11121114
///

‎compiler/rustc_mir_transform/src/const_prop.rs

Lines changed: 15 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use rustc_middle::mir::visit::{
1515
};
1616
use rustc_middle::mir::{
1717
BasicBlock, BinOp, Body, Constant, ConstantKind, Local, LocalDecl, LocalKind, Location,
18-
Operand, Place, Rvalue, SourceInfo, Statement, StatementKind, Terminator, TerminatorKind, UnOp,
18+
Operand, Place, Rvalue, SourceInfo, Statement, StatementKind, Terminator, TerminatorKind,
1919
RETURN_PLACE,
2020
};
2121
use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
@@ -503,55 +503,6 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
503503
}
504504
}
505505

506-
fn check_unary_op(&mut self, op: UnOp, arg: &Operand<'tcx>) -> Option<()> {
507-
if self.use_ecx(|this| {
508-
let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
509-
let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
510-
Ok(overflow)
511-
})? {
512-
// `AssertKind` only has an `OverflowNeg` variant, so make sure that is
513-
// appropriate to use.
514-
assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
515-
return None;
516-
}
517-
518-
Some(())
519-
}
520-
521-
fn check_binary_op(
522-
&mut self,
523-
op: BinOp,
524-
left: &Operand<'tcx>,
525-
right: &Operand<'tcx>,
526-
) -> Option<()> {
527-
let r = self.use_ecx(|this| this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?));
528-
let l = self.use_ecx(|this| this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?));
529-
// Check for exceeding shifts *even if* we cannot evaluate the LHS.
530-
if matches!(op, BinOp::Shr | BinOp::Shl) {
531-
let r = r.clone()?;
532-
// We need the type of the LHS. We cannot use `place_layout` as that is the type
533-
// of the result, which for checked binops is not the same!
534-
let left_ty = left.ty(self.local_decls, self.tcx);
535-
let left_size = self.ecx.layout_of(left_ty).ok()?.size;
536-
let right_size = r.layout.size;
537-
let r_bits = r.to_scalar().to_bits(right_size).ok();
538-
if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
539-
return None;
540-
}
541-
}
542-
543-
if let (Some(l), Some(r)) = (&l, &r) {
544-
// The remaining operators are handled through `overflowing_binary_op`.
545-
if self.use_ecx(|this| {
546-
let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
547-
Ok(overflow)
548-
})? {
549-
return None;
550-
}
551-
}
552-
Some(())
553-
}
554-
555506
fn propagate_operand(&mut self, operand: &mut Operand<'tcx>) {
556507
match *operand {
557508
Operand::Copy(l) | Operand::Move(l) => {
@@ -587,28 +538,6 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
587538
// 2. Working around bugs in other parts of the compiler
588539
// - In this case, we'll return `None` from this function to stop evaluation.
589540
match rvalue {
590-
// Additional checking: give lints to the user if an overflow would occur.
591-
// We do this here and not in the `Assert` terminator as that terminator is
592-
// only sometimes emitted (overflow checks can be disabled), but we want to always
593-
// lint.
594-
Rvalue::UnaryOp(op, arg) => {
595-
trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
596-
self.check_unary_op(*op, arg)?;
597-
}
598-
Rvalue::BinaryOp(op, box (left, right)) => {
599-
trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
600-
self.check_binary_op(*op, left, right)?;
601-
}
602-
Rvalue::CheckedBinaryOp(op, box (left, right)) => {
603-
trace!(
604-
"checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
605-
op,
606-
left,
607-
right
608-
);
609-
self.check_binary_op(*op, left, right)?;
610-
}
611-
612541
// Do not try creating references (#67862)
613542
Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
614543
trace!("skipping AddressOf | Ref for {:?}", place);
@@ -638,7 +567,10 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
638567
| Rvalue::Cast(..)
639568
| Rvalue::ShallowInitBox(..)
640569
| Rvalue::Discriminant(..)
641-
| Rvalue::NullaryOp(..) => {}
570+
| Rvalue::NullaryOp(..)
571+
| Rvalue::UnaryOp(..)
572+
| Rvalue::BinaryOp(..)
573+
| Rvalue::CheckedBinaryOp(..) => {}
642574
}
643575

644576
// FIXME we need to revisit this for #67176
@@ -1079,31 +1011,18 @@ impl<'tcx> MutVisitor<'tcx> for ConstPropagator<'_, 'tcx> {
10791011
// Do NOT early return in this function, it does some crucial fixup of the state at the end!
10801012
match &mut terminator.kind {
10811013
TerminatorKind::Assert { expected, ref mut cond, .. } => {
1082-
if let Some(ref value) = self.eval_operand(&cond) {
1083-
trace!("assertion on {:?} should be {:?}", value, expected);
1084-
let expected = Scalar::from_bool(*expected);
1014+
if let Some(ref value) = self.eval_operand(&cond)
10851015
// FIXME should be used use_ecx rather than a local match... but we have
10861016
// quite a few of these read_scalar/read_immediate that need fixing.
1087-
if let Ok(value_const) = self.ecx.read_scalar(&value) {
1088-
if expected != value_const {
1089-
// Poison all places this operand references so that further code
1090-
// doesn't use the invalid value
1091-
match cond {
1092-
Operand::Move(ref place) | Operand::Copy(ref place) => {
1093-
Self::remove_const(&mut self.ecx, place.local);
1094-
}
1095-
Operand::Constant(_) => {}
1096-
}
1097-
} else {
1098-
if self.should_const_prop(value) {
1099-
*cond = self.operand_from_scalar(
1100-
value_const,
1101-
self.tcx.types.bool,
1102-
source_info.span,
1103-
);
1104-
}
1105-
}
1106-
}
1017+
&& let Ok(value_const) = self.ecx.read_scalar(&value)
1018+
&& self.should_const_prop(value)
1019+
{
1020+
trace!("assertion on {:?} should be {:?}", value, expected);
1021+
*cond = self.operand_from_scalar(
1022+
value_const,
1023+
self.tcx.types.bool,
1024+
source_info.span,
1025+
);
11071026
}
11081027
}
11091028
TerminatorKind::SwitchInt { ref mut discr, .. } => {

‎compiler/rustc_mir_transform/src/dataflow_const_prop.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -180,12 +180,7 @@ impl<'tcx> ValueAnalysis<'tcx> for ConstAnalysis<'_, 'tcx> {
180180
let overflow = match overflow {
181181
FlatSet::Top => FlatSet::Top,
182182
FlatSet::Elem(overflow) => {
183-
if overflow {
184-
// Overflow cannot be reliably propagated. See: https://github.com/rust-lang/rust/pull/101168#issuecomment-1288091446
185-
FlatSet::Top
186-
} else {
187-
self.wrap_scalar(Scalar::from_bool(false), self.tcx.types.bool)
188-
}
183+
self.wrap_scalar(Scalar::from_bool(overflow), self.tcx.types.bool)
189184
}
190185
FlatSet::Bottom => FlatSet::Bottom,
191186
};

‎compiler/rustc_mir_transform/src/lower_intrinsics.rs

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,29 @@ impl<'tcx> MirPass<'tcx> for LowerIntrinsics {
107107
}
108108
}
109109
sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
110-
// The checked binary operations are not suitable target for lowering here,
111-
// since their semantics depend on the value of overflow-checks flag used
112-
// during codegen. Issue #35310.
110+
if let Some(target) = *target {
111+
let lhs;
112+
let rhs;
113+
{
114+
let mut args = args.drain(..);
115+
lhs = args.next().unwrap();
116+
rhs = args.next().unwrap();
117+
}
118+
let bin_op = match intrinsic_name {
119+
sym::add_with_overflow => BinOp::Add,
120+
sym::sub_with_overflow => BinOp::Sub,
121+
sym::mul_with_overflow => BinOp::Mul,
122+
_ => bug!("unexpected intrinsic"),
123+
};
124+
block.statements.push(Statement {
125+
source_info: terminator.source_info,
126+
kind: StatementKind::Assign(Box::new((
127+
*destination,
128+
Rvalue::CheckedBinaryOp(bin_op, Box::new((lhs, rhs))),
129+
))),
130+
});
131+
terminator.kind = TerminatorKind::Goto { target };
132+
}
113133
}
114134
sym::size_of | sym::min_align_of => {
115135
if let Some(target) = *target {

‎src/tools/miri/src/machine.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -815,8 +815,8 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
815815
}
816816

817817
#[inline(always)]
818-
fn checked_binop_checks_overflow(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
819-
ecx.tcx.sess.overflow_checks()
818+
fn ignore_checkable_overflow_assertions(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
819+
!ecx.tcx.sess.overflow_checks()
820820
}
821821

822822
#[inline(always)]

‎tests/codegen/inherit_overflow.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// compile-flags: -Zmir-enable-passes=+Inline,+ConstProp --crate-type lib
2+
// revisions: ASSERT NOASSERT
3+
//[ASSERT] compile-flags: -Coverflow-checks=on
4+
//[NOASSERT] compile-flags: -Coverflow-checks=off
5+
6+
// CHECK-LABEL: define{{.*}} @assertion
7+
// ASSERT: call void @_ZN4core9panicking5panic17h
8+
// NOASSERT: ret i8 0
9+
#[no_mangle]
10+
pub fn assertion() -> u8 {
11+
// Optimized MIR will replace this `CheckedBinaryOp` by `const (0, true)`.
12+
// Verify that codegen does or does not emit the panic.
13+
<u8 as std::ops::Add>::add(255, 1)
14+
}

‎tests/mir-opt/const_prop/bad_op_div_by_zero.main.ConstProp.diff

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,10 @@
2424
StorageLive(_3); // scope 1 at $DIR/bad_op_div_by_zero.rs:+2:18: +2:19
2525
- _3 = _1; // scope 1 at $DIR/bad_op_div_by_zero.rs:+2:18: +2:19
2626
- _4 = Eq(_3, const 0_i32); // scope 1 at $DIR/bad_op_div_by_zero.rs:+2:14: +2:19
27+
- assert(!move _4, "attempt to divide `{}` by zero", const 1_i32) -> bb1; // scope 1 at $DIR/bad_op_div_by_zero.rs:+2:14: +2:19
2728
+ _3 = const 0_i32; // scope 1 at $DIR/bad_op_div_by_zero.rs:+2:18: +2:19
2829
+ _4 = const true; // scope 1 at $DIR/bad_op_div_by_zero.rs:+2:14: +2:19
29-
assert(!move _4, "attempt to divide `{}` by zero", const 1_i32) -> bb1; // scope 1 at $DIR/bad_op_div_by_zero.rs:+2:14: +2:19
30+
+ assert(!const true, "attempt to divide `{}` by zero", const 1_i32) -> bb1; // scope 1 at $DIR/bad_op_div_by_zero.rs:+2:14: +2:19
3031
}
3132

3233
bb1: {
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
- // MIR for `main` before ConstProp
2+
+ // MIR for `main` after ConstProp
3+
4+
fn main() -> () {
5+
let mut _0: (); // return place in scope 0 at $DIR/inherit_overflow.rs:+0:11: +0:11
6+
let mut _1: u8; // in scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
7+
let mut _2: u8; // in scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
8+
let mut _3: u8; // in scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
9+
scope 1 {
10+
}
11+
scope 2 (inlined <u8 as Add>::add) { // at $DIR/inherit_overflow.rs:8:13: 8:47
12+
debug self => _2; // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
13+
debug other => _3; // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
14+
let mut _4: (u8, bool); // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
15+
}
16+
17+
bb0: {
18+
StorageLive(_1); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
19+
StorageLive(_2); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
20+
_2 = const u8::MAX; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
21+
StorageLive(_3); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
22+
_3 = const 1_u8; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
23+
- _4 = CheckedAdd(_2, _3); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
24+
- assert(!move (_4.1: bool), "attempt to compute `{} + {}`, which would overflow", _2, _3) -> bb1; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
25+
+ _4 = const (0_u8, true); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
26+
+ assert(!const true, "attempt to compute `{} + {}`, which would overflow", _2, _3) -> bb1; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
27+
}
28+
29+
bb1: {
30+
- _1 = move (_4.0: u8); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
31+
+ _1 = const 0_u8; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
32+
StorageDead(_3); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
33+
StorageDead(_2); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
34+
StorageDead(_1); // scope 0 at $DIR/inherit_overflow.rs:+3:47: +3:48
35+
_0 = const (); // scope 0 at $DIR/inherit_overflow.rs:+0:11: +4:2
36+
return; // scope 0 at $DIR/inherit_overflow.rs:+4:2: +4:2
37+
}
38+
}
39+
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// unit-test: ConstProp
2+
// compile-flags: -Zmir-enable-passes=+Inline
3+
4+
// EMIT_MIR inherit_overflow.main.ConstProp.diff
5+
fn main() {
6+
// After inlining, this will contain a `CheckedBinaryOp`.
7+
// Propagating the overflow is ok as codegen will just skip emitting the panic.
8+
let _ = <u8 as std::ops::Add>::add(255, 1);
9+
}

‎tests/mir-opt/dataflow-const-prop/checked.main.DataflowConstProp.diff

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
- assert(!move (_10.1: bool), "attempt to compute `{} + {}`, which would overflow", move _9, const 1_i32) -> bb2; // scope 4 at $DIR/checked.rs:+6:13: +6:18
6262
+ _9 = const i32::MAX; // scope 4 at $DIR/checked.rs:+6:13: +6:14
6363
+ _10 = CheckedAdd(const i32::MAX, const 1_i32); // scope 4 at $DIR/checked.rs:+6:13: +6:18
64-
+ assert(!move (_10.1: bool), "attempt to compute `{} + {}`, which would overflow", const i32::MAX, const 1_i32) -> bb2; // scope 4 at $DIR/checked.rs:+6:13: +6:18
64+
+ assert(!const true, "attempt to compute `{} + {}`, which would overflow", const i32::MAX, const 1_i32) -> bb2; // scope 4 at $DIR/checked.rs:+6:13: +6:18
6565
}
6666

6767
bb2: {

‎tests/mir-opt/dataflow-const-prop/inherit_overflow.main.DataflowConstProp.diff

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,34 @@
55
let mut _0: (); // return place in scope 0 at $DIR/inherit_overflow.rs:+0:11: +0:11
66
let mut _1: u8; // in scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
77
let mut _2: u8; // in scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
8+
let mut _3: u8; // in scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
89
scope 1 {
910
}
10-
scope 2 (inlined <u8 as Add>::add) { // at $DIR/inherit_overflow.rs:7:13: 7:47
11-
debug self => _1; // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
12-
debug other => _2; // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
13-
let mut _3: (u8, bool); // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
11+
scope 2 (inlined <u8 as Add>::add) { // at $DIR/inherit_overflow.rs:8:13: 8:47
12+
debug self => _2; // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
13+
debug other => _3; // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
14+
let mut _4: (u8, bool); // in scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
1415
}
1516

1617
bb0: {
1718
StorageLive(_1); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
18-
_1 = const u8::MAX; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
1919
StorageLive(_2); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
20-
_2 = const 1_u8; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
21-
_3 = CheckedAdd(const u8::MAX, const 1_u8); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
22-
assert(!move (_3.1: bool), "attempt to compute `{} + {}`, which would overflow", const u8::MAX, const 1_u8) -> bb1; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
20+
_2 = const u8::MAX; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
21+
StorageLive(_3); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
22+
_3 = const 1_u8; // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
23+
- _4 = CheckedAdd(_2, _3); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
24+
- assert(!move (_4.1: bool), "attempt to compute `{} + {}`, which would overflow", _2, _3) -> bb1; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
25+
+ _4 = CheckedAdd(const u8::MAX, const 1_u8); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
26+
+ assert(!const true, "attempt to compute `{} + {}`, which would overflow", const u8::MAX, const 1_u8) -> bb1; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
2327
}
2428

2529
bb1: {
30+
- _1 = move (_4.0: u8); // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
31+
+ _1 = const 0_u8; // scope 2 at $SRC_DIR/core/src/ops/arith.rs:LL:COL
32+
StorageDead(_3); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
2633
StorageDead(_2); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
27-
StorageDead(_1); // scope 0 at $DIR/inherit_overflow.rs:+3:13: +3:47
34+
StorageDead(_1); // scope 0 at $DIR/inherit_overflow.rs:+3:47: +3:48
35+
_0 = const (); // scope 0 at $DIR/inherit_overflow.rs:+0:11: +4:2
2836
return; // scope 0 at $DIR/inherit_overflow.rs:+4:2: +4:2
2937
}
3038
}
Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
// compile-flags: -Zunsound-mir-opts
1+
// unit-test: DataflowConstProp
2+
// compile-flags: -Zmir-enable-passes=+Inline
23

34
// EMIT_MIR inherit_overflow.main.DataflowConstProp.diff
45
fn main() {
5-
// After inlining, this will contain a `CheckedBinaryOp`. The overflow
6-
// must be ignored by the constant propagation to avoid triggering a panic.
6+
// After inlining, this will contain a `CheckedBinaryOp`.
7+
// Propagating the overflow is ok as codegen will just skip emitting the panic.
78
let _ = <u8 as std::ops::Add>::add(255, 1);
89
}

‎tests/mir-opt/lower_intrinsics.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,10 @@ pub fn assume() {
7272
std::intrinsics::assume(true);
7373
}
7474
}
75+
76+
// EMIT_MIR lower_intrinsics.with_overflow.LowerIntrinsics.diff
77+
pub fn with_overflow(a: i32, b: i32) {
78+
let _x = core::intrinsics::add_with_overflow(a, b);
79+
let _y = core::intrinsics::sub_with_overflow(a, b);
80+
let _z = core::intrinsics::mul_with_overflow(a, b);
81+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
- // MIR for `with_overflow` before LowerIntrinsics
2+
+ // MIR for `with_overflow` after LowerIntrinsics
3+
4+
fn with_overflow(_1: i32, _2: i32) -> () {
5+
debug a => _1; // in scope 0 at $DIR/lower_intrinsics.rs:+0:22: +0:23
6+
debug b => _2; // in scope 0 at $DIR/lower_intrinsics.rs:+0:30: +0:31
7+
let mut _0: (); // return place in scope 0 at $DIR/lower_intrinsics.rs:+0:38: +0:38
8+
let _3: (i32, bool); // in scope 0 at $DIR/lower_intrinsics.rs:+1:9: +1:11
9+
let mut _4: i32; // in scope 0 at $DIR/lower_intrinsics.rs:+1:50: +1:51
10+
let mut _5: i32; // in scope 0 at $DIR/lower_intrinsics.rs:+1:53: +1:54
11+
let mut _7: i32; // in scope 0 at $DIR/lower_intrinsics.rs:+2:50: +2:51
12+
let mut _8: i32; // in scope 0 at $DIR/lower_intrinsics.rs:+2:53: +2:54
13+
let mut _10: i32; // in scope 0 at $DIR/lower_intrinsics.rs:+3:50: +3:51
14+
let mut _11: i32; // in scope 0 at $DIR/lower_intrinsics.rs:+3:53: +3:54
15+
scope 1 {
16+
debug _x => _3; // in scope 1 at $DIR/lower_intrinsics.rs:+1:9: +1:11
17+
let _6: (i32, bool); // in scope 1 at $DIR/lower_intrinsics.rs:+2:9: +2:11
18+
scope 2 {
19+
debug _y => _6; // in scope 2 at $DIR/lower_intrinsics.rs:+2:9: +2:11
20+
let _9: (i32, bool); // in scope 2 at $DIR/lower_intrinsics.rs:+3:9: +3:11
21+
scope 3 {
22+
debug _z => _9; // in scope 3 at $DIR/lower_intrinsics.rs:+3:9: +3:11
23+
}
24+
}
25+
}
26+
27+
bb0: {
28+
StorageLive(_3); // scope 0 at $DIR/lower_intrinsics.rs:+1:9: +1:11
29+
StorageLive(_4); // scope 0 at $DIR/lower_intrinsics.rs:+1:50: +1:51
30+
_4 = _1; // scope 0 at $DIR/lower_intrinsics.rs:+1:50: +1:51
31+
StorageLive(_5); // scope 0 at $DIR/lower_intrinsics.rs:+1:53: +1:54
32+
_5 = _2; // scope 0 at $DIR/lower_intrinsics.rs:+1:53: +1:54
33+
- _3 = add_with_overflow::<i32>(move _4, move _5) -> bb1; // scope 0 at $DIR/lower_intrinsics.rs:+1:14: +1:55
34+
- // mir::Constant
35+
- // + span: $DIR/lower_intrinsics.rs:78:14: 78:49
36+
- // + literal: Const { ty: extern "rust-intrinsic" fn(i32, i32) -> (i32, bool) {add_with_overflow::<i32>}, val: Value(<ZST>) }
37+
+ _3 = CheckedAdd(move _4, move _5); // scope 0 at $DIR/lower_intrinsics.rs:+1:14: +1:55
38+
+ goto -> bb1; // scope 0 at $DIR/lower_intrinsics.rs:+1:14: +1:55
39+
}
40+
41+
bb1: {
42+
StorageDead(_5); // scope 0 at $DIR/lower_intrinsics.rs:+1:54: +1:55
43+
StorageDead(_4); // scope 0 at $DIR/lower_intrinsics.rs:+1:54: +1:55
44+
StorageLive(_6); // scope 1 at $DIR/lower_intrinsics.rs:+2:9: +2:11
45+
StorageLive(_7); // scope 1 at $DIR/lower_intrinsics.rs:+2:50: +2:51
46+
_7 = _1; // scope 1 at $DIR/lower_intrinsics.rs:+2:50: +2:51
47+
StorageLive(_8); // scope 1 at $DIR/lower_intrinsics.rs:+2:53: +2:54
48+
_8 = _2; // scope 1 at $DIR/lower_intrinsics.rs:+2:53: +2:54
49+
- _6 = sub_with_overflow::<i32>(move _7, move _8) -> bb2; // scope 1 at $DIR/lower_intrinsics.rs:+2:14: +2:55
50+
- // mir::Constant
51+
- // + span: $DIR/lower_intrinsics.rs:79:14: 79:49
52+
- // + literal: Const { ty: extern "rust-intrinsic" fn(i32, i32) -> (i32, bool) {sub_with_overflow::<i32>}, val: Value(<ZST>) }
53+
+ _6 = CheckedSub(move _7, move _8); // scope 1 at $DIR/lower_intrinsics.rs:+2:14: +2:55
54+
+ goto -> bb2; // scope 1 at $DIR/lower_intrinsics.rs:+2:14: +2:55
55+
}
56+
57+
bb2: {
58+
StorageDead(_8); // scope 1 at $DIR/lower_intrinsics.rs:+2:54: +2:55
59+
StorageDead(_7); // scope 1 at $DIR/lower_intrinsics.rs:+2:54: +2:55
60+
StorageLive(_9); // scope 2 at $DIR/lower_intrinsics.rs:+3:9: +3:11
61+
StorageLive(_10); // scope 2 at $DIR/lower_intrinsics.rs:+3:50: +3:51
62+
_10 = _1; // scope 2 at $DIR/lower_intrinsics.rs:+3:50: +3:51
63+
StorageLive(_11); // scope 2 at $DIR/lower_intrinsics.rs:+3:53: +3:54
64+
_11 = _2; // scope 2 at $DIR/lower_intrinsics.rs:+3:53: +3:54
65+
- _9 = mul_with_overflow::<i32>(move _10, move _11) -> bb3; // scope 2 at $DIR/lower_intrinsics.rs:+3:14: +3:55
66+
- // mir::Constant
67+
- // + span: $DIR/lower_intrinsics.rs:80:14: 80:49
68+
- // + literal: Const { ty: extern "rust-intrinsic" fn(i32, i32) -> (i32, bool) {mul_with_overflow::<i32>}, val: Value(<ZST>) }
69+
+ _9 = CheckedMul(move _10, move _11); // scope 2 at $DIR/lower_intrinsics.rs:+3:14: +3:55
70+
+ goto -> bb3; // scope 2 at $DIR/lower_intrinsics.rs:+3:14: +3:55
71+
}
72+
73+
bb3: {
74+
StorageDead(_11); // scope 2 at $DIR/lower_intrinsics.rs:+3:54: +3:55
75+
StorageDead(_10); // scope 2 at $DIR/lower_intrinsics.rs:+3:54: +3:55
76+
_0 = const (); // scope 0 at $DIR/lower_intrinsics.rs:+0:38: +4:2
77+
StorageDead(_9); // scope 2 at $DIR/lower_intrinsics.rs:+4:1: +4:2
78+
StorageDead(_6); // scope 1 at $DIR/lower_intrinsics.rs:+4:1: +4:2
79+
StorageDead(_3); // scope 0 at $DIR/lower_intrinsics.rs:+4:1: +4:2
80+
return; // scope 0 at $DIR/lower_intrinsics.rs:+4:2: +4:2
81+
}
82+
}
83+

0 commit comments

Comments
 (0)
Please sign in to comment.