1use std::cell::RefCell;
6use std::fmt::Formatter;
7
8use rustc_abi::{BackendRepr, FIRST_VARIANT, FieldIdx, Size, VariantIdx};
9use rustc_const_eval::const_eval::{DummyMachine, throw_machine_stop_str};
10use rustc_const_eval::interpret::{
11 ImmTy, Immediate, InterpCx, OpTy, PlaceTy, Projectable, interp_ok,
12};
13use rustc_data_structures::assert_matches;
14use rustc_data_structures::fx::FxHashMap;
15use rustc_hir::def::DefKind;
16use rustc_middle::bug;
17use rustc_middle::mir::interpret::{InterpResult, Scalar};
18use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
19use rustc_middle::mir::*;
20use rustc_middle::ty::{self, Ty, TyCtxt};
21use rustc_mir_dataflow::fmt::DebugWithContext;
22use rustc_mir_dataflow::lattice::{FlatSet, HasBottom};
23use rustc_mir_dataflow::value_analysis::{
24 Map, PlaceCollectionMode, PlaceIndex, State, TrackElem, ValueOrPlace, debug_with_context,
25};
26use rustc_mir_dataflow::{Analysis, ResultsVisitor, visit_reachable_results};
27use rustc_span::DUMMY_SP;
28use tracing::{debug, debug_span, instrument};
29
30const BLOCK_LIMIT: usize = 100;
33const PLACE_LIMIT: usize = 100;
34
35pub(super) struct DataflowConstProp;
36
37impl<'tcx> crate::MirPass<'tcx> for DataflowConstProp {
38 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
39 sess.mir_opt_level() >= 3
40 }
41
42 #[instrument(skip_all level = "debug")]
43 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
44 debug!(def_id = ?body.source.def_id());
45 if tcx.sess.mir_opt_level() < 4 && body.basic_blocks.len() > BLOCK_LIMIT {
46 debug!("aborted dataflow const prop due too many basic blocks");
47 return;
48 }
49
50 let value_limit = if tcx.sess.mir_opt_level() < 4 { Some(PLACE_LIMIT) } else { None };
59
60 let map = Map::new(tcx, body, PlaceCollectionMode::Full { value_limit });
62
63 let const_ = debug_span!("analyze")
65 .in_scope(|| ConstAnalysis::new(tcx, body, map).iterate_to_fixpoint(tcx, body, None));
66
67 let mut visitor = Collector::new(tcx, &body.local_decls);
69 debug_span!("collect").in_scope(|| visit_reachable_results(body, &const_, &mut visitor));
70 let mut patch = visitor.patch;
71 debug_span!("patch").in_scope(|| patch.visit_body_preserves_cfg(body));
72 }
73
74 fn is_required(&self) -> bool {
75 false
76 }
77}
78
79struct ConstAnalysis<'a, 'tcx> {
84 map: Map<'tcx>,
85 tcx: TyCtxt<'tcx>,
86 local_decls: &'a LocalDecls<'tcx>,
87 ecx: RefCell<InterpCx<'tcx, DummyMachine>>,
88 typing_env: ty::TypingEnv<'tcx>,
89}
90
91impl<'tcx> Analysis<'tcx> for ConstAnalysis<'_, 'tcx> {
92 type Domain = State<FlatSet<Scalar>>;
93
94 const NAME: &'static str = "ConstAnalysis";
95
96 fn bottom_value(&self, _body: &Body<'tcx>) -> Self::Domain {
100 State::Unreachable
101 }
102
103 fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
104 assert_matches!(state, State::Unreachable);
106 *state = State::new_reachable();
107 for arg in body.args_iter() {
108 state.flood(PlaceRef { local: arg, projection: &[] }, &self.map);
109 }
110 }
111
112 fn apply_primary_statement_effect(
113 &self,
114 state: &mut Self::Domain,
115 statement: &Statement<'tcx>,
116 _location: Location,
117 ) {
118 if state.is_reachable() {
119 self.handle_statement(statement, state);
120 }
121 }
122
123 fn apply_primary_terminator_effect<'mir>(
124 &self,
125 state: &mut Self::Domain,
126 terminator: &'mir Terminator<'tcx>,
127 _location: Location,
128 ) -> TerminatorEdges<'mir, 'tcx> {
129 if state.is_reachable() {
130 self.handle_terminator(terminator, state)
131 } else {
132 TerminatorEdges::None
133 }
134 }
135
136 fn apply_call_return_effect(
137 &self,
138 state: &mut Self::Domain,
139 _block: BasicBlock,
140 return_places: CallReturnPlaces<'_, 'tcx>,
141 ) {
142 if state.is_reachable() {
143 self.handle_call_return(return_places, state)
144 }
145 }
146}
147
148impl<'a, 'tcx> ConstAnalysis<'a, 'tcx> {
149 fn new(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, map: Map<'tcx>) -> Self {
150 let typing_env = body.typing_env(tcx);
151 Self {
152 map,
153 tcx,
154 local_decls: &body.local_decls,
155 ecx: RefCell::new(InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine)),
156 typing_env,
157 }
158 }
159
160 fn handle_statement(&self, statement: &Statement<'tcx>, state: &mut State<FlatSet<Scalar>>) {
161 match &statement.kind {
162 StatementKind::Assign(box (place, rvalue)) => {
163 self.handle_assign(*place, rvalue, state);
164 }
165 StatementKind::SetDiscriminant { box place, variant_index } => {
166 self.handle_set_discriminant(*place, *variant_index, state);
167 }
168 StatementKind::Intrinsic(box intrinsic) => {
169 self.handle_intrinsic(intrinsic);
170 }
171 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
172 state.flood_with(
175 Place::from(*local).as_ref(),
176 &self.map,
177 FlatSet::<Scalar>::BOTTOM,
178 );
179 }
180 StatementKind::Retag(..) => {
181 }
183 StatementKind::ConstEvalCounter
184 | StatementKind::Nop
185 | StatementKind::FakeRead(..)
186 | StatementKind::PlaceMention(..)
187 | StatementKind::Coverage(..)
188 | StatementKind::BackwardIncompatibleDropHint { .. }
189 | StatementKind::AscribeUserType(..) => {}
190 }
191 }
192
193 fn handle_intrinsic(&self, intrinsic: &NonDivergingIntrinsic<'tcx>) {
194 match intrinsic {
195 NonDivergingIntrinsic::Assume(..) => {
196 }
198 NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping {
199 dst: _,
200 src: _,
201 count: _,
202 }) => {
203 }
205 }
206 }
207
208 fn handle_operand(
209 &self,
210 operand: &Operand<'tcx>,
211 state: &mut State<FlatSet<Scalar>>,
212 ) -> ValueOrPlace<FlatSet<Scalar>> {
213 match operand {
214 Operand::RuntimeChecks(_) => ValueOrPlace::TOP,
215 Operand::Constant(box constant) => {
216 ValueOrPlace::Value(self.handle_constant(constant, state))
217 }
218 Operand::Copy(place) | Operand::Move(place) => {
219 self.map.find(place.as_ref()).map(ValueOrPlace::Place).unwrap_or(ValueOrPlace::TOP)
222 }
223 }
224 }
225
226 fn handle_terminator<'mir>(
229 &self,
230 terminator: &'mir Terminator<'tcx>,
231 state: &mut State<FlatSet<Scalar>>,
232 ) -> TerminatorEdges<'mir, 'tcx> {
233 match &terminator.kind {
234 TerminatorKind::Call { .. } | TerminatorKind::InlineAsm { .. } => {
235 }
237 TerminatorKind::Drop { place, .. } => {
238 state.flood_with(place.as_ref(), &self.map, FlatSet::<Scalar>::BOTTOM);
239 }
240 TerminatorKind::Yield { .. } => {
241 bug!("encountered disallowed terminator");
243 }
244 TerminatorKind::SwitchInt { discr, targets } => {
245 return self.handle_switch_int(discr, targets, state);
246 }
247 TerminatorKind::TailCall { .. } => {
248 }
251 TerminatorKind::Goto { .. }
252 | TerminatorKind::UnwindResume
253 | TerminatorKind::UnwindTerminate(_)
254 | TerminatorKind::Return
255 | TerminatorKind::Unreachable
256 | TerminatorKind::Assert { .. }
257 | TerminatorKind::CoroutineDrop
258 | TerminatorKind::FalseEdge { .. }
259 | TerminatorKind::FalseUnwind { .. } => {
260 }
262 }
263 terminator.edges()
264 }
265
266 fn handle_call_return(
267 &self,
268 return_places: CallReturnPlaces<'_, 'tcx>,
269 state: &mut State<FlatSet<Scalar>>,
270 ) {
271 return_places.for_each(|place| {
272 state.flood(place.as_ref(), &self.map);
273 })
274 }
275
276 fn handle_set_discriminant(
277 &self,
278 place: Place<'tcx>,
279 variant_index: VariantIdx,
280 state: &mut State<FlatSet<Scalar>>,
281 ) {
282 state.flood_discr(place.as_ref(), &self.map);
283 if self.map.find_discr(place.as_ref()).is_some() {
284 let enum_ty = place.ty(self.local_decls, self.tcx).ty;
285 if let Some(discr) = self.eval_discriminant(enum_ty, variant_index) {
286 state.assign_discr(
287 place.as_ref(),
288 ValueOrPlace::Value(FlatSet::Elem(discr)),
289 &self.map,
290 );
291 }
292 }
293 }
294
295 fn handle_assign(
296 &self,
297 target: Place<'tcx>,
298 rvalue: &Rvalue<'tcx>,
299 state: &mut State<FlatSet<Scalar>>,
300 ) {
301 match rvalue {
302 Rvalue::Use(operand) => {
303 state.flood(target.as_ref(), &self.map);
304 if let Some(target) = self.map.find(target.as_ref()) {
305 self.assign_operand(state, target, operand);
306 }
307 }
308 Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in runtime MIR"),
309 Rvalue::Aggregate(kind, operands) => {
310 state.flood(target.as_ref(), &self.map);
313
314 let Some(target_idx) = self.map.find(target.as_ref()) else { return };
315
316 let (variant_target, variant_index) = match **kind {
317 AggregateKind::Tuple | AggregateKind::Closure(..) => (Some(target_idx), None),
318 AggregateKind::Adt(def_id, variant_index, ..) => {
319 match self.tcx.def_kind(def_id) {
320 DefKind::Struct => (Some(target_idx), None),
321 DefKind::Enum => (
322 self.map.apply(target_idx, TrackElem::Variant(variant_index)),
323 Some(variant_index),
324 ),
325 _ => return,
326 }
327 }
328 _ => return,
329 };
330 if let Some(variant_target_idx) = variant_target {
331 for (field_index, operand) in operands.iter_enumerated() {
332 if let Some(field) =
333 self.map.apply(variant_target_idx, TrackElem::Field(field_index))
334 {
335 self.assign_operand(state, field, operand);
336 }
337 }
338 }
339 if let Some(variant_index) = variant_index
340 && let Some(discr_idx) = self.map.apply(target_idx, TrackElem::Discriminant)
341 {
342 let enum_ty = target.ty(self.local_decls, self.tcx).ty;
348 if let Some(discr_val) = self.eval_discriminant(enum_ty, variant_index) {
349 state.insert_value_idx(discr_idx, FlatSet::Elem(discr_val), &self.map);
350 }
351 }
352 }
353 Rvalue::BinaryOp(op, box (left, right)) if op.is_overflowing() => {
354 state.flood(target.as_ref(), &self.map);
356
357 let Some(target) = self.map.find(target.as_ref()) else { return };
358
359 let value_target = self.map.apply(target, TrackElem::Field(0_u32.into()));
360 let overflow_target = self.map.apply(target, TrackElem::Field(1_u32.into()));
361
362 if value_target.is_some() || overflow_target.is_some() {
363 let (val, overflow) = self.binary_op(state, *op, left, right);
364
365 if let Some(value_target) = value_target {
366 state.insert_value_idx(value_target, val, &self.map);
368 }
369 if let Some(overflow_target) = overflow_target {
370 state.insert_value_idx(overflow_target, overflow, &self.map);
372 }
373 }
374 }
375 Rvalue::Cast(
376 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
377 operand,
378 _,
379 ) => {
380 let pointer = self.handle_operand(operand, state);
381 state.assign(target.as_ref(), pointer, &self.map);
382
383 if let Some(target_len) = self.map.find_len(target.as_ref())
384 && let operand_ty = operand.ty(self.local_decls, self.tcx)
385 && let Some(operand_ty) = operand_ty.builtin_deref(true)
386 && let ty::Array(_, len) = operand_ty.kind()
387 && let Some(len) = Const::Ty(self.tcx.types.usize, *len)
388 .try_eval_scalar_int(self.tcx, self.typing_env)
389 {
390 state.insert_value_idx(target_len, FlatSet::Elem(len.into()), &self.map);
391 }
392 }
393 _ => {
394 let result = self.handle_rvalue(rvalue, state);
395 state.assign(target.as_ref(), result, &self.map);
396 }
397 }
398 }
399
400 fn handle_rvalue(
401 &self,
402 rvalue: &Rvalue<'tcx>,
403 state: &mut State<FlatSet<Scalar>>,
404 ) -> ValueOrPlace<FlatSet<Scalar>> {
405 let val = match rvalue {
406 Rvalue::Cast(CastKind::IntToInt | CastKind::IntToFloat, operand, ty) => {
407 let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(*ty)) else {
408 return ValueOrPlace::Value(FlatSet::Top);
409 };
410 match self.eval_operand(operand, state) {
411 FlatSet::Elem(op) => self
412 .ecx
413 .borrow()
414 .int_to_int_or_float(&op, layout)
415 .discard_err()
416 .map_or(FlatSet::Top, |result| self.wrap_immediate(*result)),
417 FlatSet::Bottom => FlatSet::Bottom,
418 FlatSet::Top => FlatSet::Top,
419 }
420 }
421 Rvalue::Cast(CastKind::FloatToInt | CastKind::FloatToFloat, operand, ty) => {
422 let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(*ty)) else {
423 return ValueOrPlace::Value(FlatSet::Top);
424 };
425 match self.eval_operand(operand, state) {
426 FlatSet::Elem(op) => self
427 .ecx
428 .borrow()
429 .float_to_float_or_int(&op, layout)
430 .discard_err()
431 .map_or(FlatSet::Top, |result| self.wrap_immediate(*result)),
432 FlatSet::Bottom => FlatSet::Bottom,
433 FlatSet::Top => FlatSet::Top,
434 }
435 }
436 Rvalue::Cast(CastKind::Transmute | CastKind::Subtype, operand, _) => {
437 match self.eval_operand(operand, state) {
438 FlatSet::Elem(op) => self.wrap_immediate(*op),
439 FlatSet::Bottom => FlatSet::Bottom,
440 FlatSet::Top => FlatSet::Top,
441 }
442 }
443 Rvalue::BinaryOp(op, box (left, right)) if !op.is_overflowing() => {
444 let (val, _overflow) = self.binary_op(state, *op, left, right);
447 val
448 }
449 Rvalue::UnaryOp(op, operand) => {
450 if let UnOp::PtrMetadata = op
451 && let Some(place) = operand.place()
452 && let Some(len) = self.map.find_len(place.as_ref())
453 {
454 return ValueOrPlace::Place(len);
455 }
456 match self.eval_operand(operand, state) {
457 FlatSet::Elem(value) => self
458 .ecx
459 .borrow()
460 .unary_op(*op, &value)
461 .discard_err()
462 .map_or(FlatSet::Top, |val| self.wrap_immediate(*val)),
463 FlatSet::Bottom => FlatSet::Bottom,
464 FlatSet::Top => FlatSet::Top,
465 }
466 }
467 Rvalue::Discriminant(place) => state.get_discr(place.as_ref(), &self.map),
468 Rvalue::Use(operand) => return self.handle_operand(operand, state),
469 Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in runtime MIR"),
470 Rvalue::Ref(..) | Rvalue::RawPtr(..) => {
471 return ValueOrPlace::TOP;
473 }
474 Rvalue::Repeat(..)
475 | Rvalue::ThreadLocalRef(..)
476 | Rvalue::Cast(..)
477 | Rvalue::BinaryOp(..)
478 | Rvalue::Aggregate(..)
479 | Rvalue::WrapUnsafeBinder(..) => {
480 return ValueOrPlace::TOP;
482 }
483 };
484 ValueOrPlace::Value(val)
485 }
486
487 fn handle_constant(
488 &self,
489 constant: &ConstOperand<'tcx>,
490 _state: &mut State<FlatSet<Scalar>>,
491 ) -> FlatSet<Scalar> {
492 constant
493 .const_
494 .try_eval_scalar(self.tcx, self.typing_env)
495 .map_or(FlatSet::Top, FlatSet::Elem)
496 }
497
498 fn handle_switch_int<'mir>(
499 &self,
500 discr: &'mir Operand<'tcx>,
501 targets: &'mir SwitchTargets,
502 state: &mut State<FlatSet<Scalar>>,
503 ) -> TerminatorEdges<'mir, 'tcx> {
504 let value = match self.handle_operand(discr, state) {
505 ValueOrPlace::Value(value) => value,
506 ValueOrPlace::Place(place) => state.get_idx(place, &self.map),
507 };
508 match value {
509 FlatSet::Bottom => TerminatorEdges::None,
512 FlatSet::Elem(scalar) => {
513 if let Ok(scalar_int) = scalar.try_to_scalar_int() {
514 TerminatorEdges::Single(
515 targets.target_for_value(scalar_int.to_bits_unchecked()),
516 )
517 } else {
518 TerminatorEdges::SwitchInt { discr, targets }
519 }
520 }
521 FlatSet::Top => TerminatorEdges::SwitchInt { discr, targets },
522 }
523 }
524
525 fn assign_operand(
527 &self,
528 state: &mut State<FlatSet<Scalar>>,
529 place: PlaceIndex,
530 operand: &Operand<'tcx>,
531 ) {
532 match operand {
533 Operand::RuntimeChecks(_) => {}
534 Operand::Copy(rhs) | Operand::Move(rhs) => {
535 if let Some(rhs) = self.map.find(rhs.as_ref()) {
536 state.insert_place_idx(place, rhs, &self.map);
537 } else if rhs.projection.first() == Some(&PlaceElem::Deref)
538 && let FlatSet::Elem(pointer) = state.get(rhs.local.into(), &self.map)
539 && let rhs_ty = self.local_decls[rhs.local].ty
540 && let Ok(rhs_layout) =
541 self.tcx.layout_of(self.typing_env.as_query_input(rhs_ty))
542 {
543 let op = ImmTy::from_scalar(pointer, rhs_layout).into();
544 self.assign_constant(state, place, op, rhs.projection);
545 }
546 }
547 Operand::Constant(box constant) => {
548 if let Some(constant) = self
549 .ecx
550 .borrow()
551 .eval_mir_constant(&constant.const_, constant.span, None)
552 .discard_err()
553 {
554 self.assign_constant(state, place, constant, &[]);
555 }
556 }
557 }
558 }
559
560 #[instrument(level = "trace", skip(self, state))]
564 fn assign_constant(
565 &self,
566 state: &mut State<FlatSet<Scalar>>,
567 place: PlaceIndex,
568 mut operand: OpTy<'tcx>,
569 projection: &[PlaceElem<'tcx>],
570 ) {
571 for &(mut proj_elem) in projection {
572 if let PlaceElem::Index(index) = proj_elem {
573 if let FlatSet::Elem(index) = state.get(index.into(), &self.map)
574 && let Some(offset) = index.to_target_usize(&self.tcx).discard_err()
575 && let Some(min_length) = offset.checked_add(1)
576 {
577 proj_elem = PlaceElem::ConstantIndex { offset, min_length, from_end: false };
578 } else {
579 return;
580 }
581 }
582 operand = if let Some(operand) =
583 self.ecx.borrow().project(&operand, proj_elem).discard_err()
584 {
585 operand
586 } else {
587 return;
588 }
589 }
590
591 self.map.for_each_projection_value(
592 place,
593 operand,
594 &mut |elem, op| match elem {
595 TrackElem::Field(idx) => self.ecx.borrow().project_field(op, idx).discard_err(),
596 TrackElem::Variant(idx) => {
597 self.ecx.borrow().project_downcast(op, idx).discard_err()
598 }
599 TrackElem::Discriminant => {
600 let variant = self.ecx.borrow().read_discriminant(op).discard_err()?;
601 let discr_value = self
602 .ecx
603 .borrow()
604 .discriminant_for_variant(op.layout.ty, variant)
605 .discard_err()?;
606 Some(discr_value.into())
607 }
608 TrackElem::DerefLen => {
609 let op: OpTy<'_> = self.ecx.borrow().deref_pointer(op).discard_err()?.into();
610 let len_usize = op.len(&self.ecx.borrow()).discard_err()?;
611 let layout = self
612 .tcx
613 .layout_of(self.typing_env.as_query_input(self.tcx.types.usize))
614 .unwrap();
615 Some(ImmTy::from_uint(len_usize, layout).into())
616 }
617 },
618 &mut |place, op| {
619 if let Some(imm) = self.ecx.borrow().read_immediate_raw(op).discard_err()
620 && let Some(imm) = imm.right()
621 {
622 let elem = self.wrap_immediate(*imm);
623 state.insert_value_idx(place, elem, &self.map);
624 }
625 },
626 );
627 }
628
629 fn binary_op(
630 &self,
631 state: &mut State<FlatSet<Scalar>>,
632 op: BinOp,
633 left: &Operand<'tcx>,
634 right: &Operand<'tcx>,
635 ) -> (FlatSet<Scalar>, FlatSet<Scalar>) {
636 let left = self.eval_operand(left, state);
637 let right = self.eval_operand(right, state);
638
639 match (left, right) {
640 (FlatSet::Bottom, _) | (_, FlatSet::Bottom) => (FlatSet::Bottom, FlatSet::Bottom),
641 (FlatSet::Elem(left), FlatSet::Elem(right)) => {
643 match self.ecx.borrow().binary_op(op, &left, &right).discard_err() {
644 Some(val) => {
648 if matches!(val.layout.backend_repr, BackendRepr::ScalarPair(..)) {
649 let (val, overflow) = val.to_scalar_pair();
650 (FlatSet::Elem(val), FlatSet::Elem(overflow))
651 } else {
652 (FlatSet::Elem(val.to_scalar()), FlatSet::Bottom)
653 }
654 }
655 _ => (FlatSet::Top, FlatSet::Top),
656 }
657 }
658 (FlatSet::Elem(const_arg), _) | (_, FlatSet::Elem(const_arg)) => {
660 let layout = const_arg.layout;
661 if !matches!(layout.backend_repr, rustc_abi::BackendRepr::Scalar(..)) {
662 return (FlatSet::Top, FlatSet::Top);
663 }
664
665 let arg_scalar = const_arg.to_scalar();
666 let Some(arg_value) = arg_scalar.to_bits(layout.size).discard_err() else {
667 return (FlatSet::Top, FlatSet::Top);
668 };
669
670 match op {
671 BinOp::BitAnd if arg_value == 0 => (FlatSet::Elem(arg_scalar), FlatSet::Bottom),
672 BinOp::BitOr
673 if arg_value == layout.size.truncate(u128::MAX)
674 || (layout.ty.is_bool() && arg_value == 1) =>
675 {
676 (FlatSet::Elem(arg_scalar), FlatSet::Bottom)
677 }
678 BinOp::Mul if layout.ty.is_integral() && arg_value == 0 => {
679 (FlatSet::Elem(arg_scalar), FlatSet::Elem(Scalar::from_bool(false)))
680 }
681 _ => (FlatSet::Top, FlatSet::Top),
682 }
683 }
684 (FlatSet::Top, FlatSet::Top) => (FlatSet::Top, FlatSet::Top),
685 }
686 }
687
688 fn eval_operand(
689 &self,
690 op: &Operand<'tcx>,
691 state: &mut State<FlatSet<Scalar>>,
692 ) -> FlatSet<ImmTy<'tcx>> {
693 let value = match self.handle_operand(op, state) {
694 ValueOrPlace::Value(value) => value,
695 ValueOrPlace::Place(place) => state.get_idx(place, &self.map),
696 };
697 match value {
698 FlatSet::Top => FlatSet::Top,
699 FlatSet::Elem(scalar) => {
700 let ty = op.ty(self.local_decls, self.tcx);
701 self.tcx
702 .layout_of(self.typing_env.as_query_input(ty))
703 .map_or(FlatSet::Top, |layout| {
704 FlatSet::Elem(ImmTy::from_scalar(scalar, layout))
705 })
706 }
707 FlatSet::Bottom => FlatSet::Bottom,
708 }
709 }
710
711 fn eval_discriminant(&self, enum_ty: Ty<'tcx>, variant_index: VariantIdx) -> Option<Scalar> {
712 if !enum_ty.is_enum() {
713 return None;
714 }
715 let enum_ty_layout = self.tcx.layout_of(self.typing_env.as_query_input(enum_ty)).ok()?;
716 let discr_value = self
717 .ecx
718 .borrow()
719 .discriminant_for_variant(enum_ty_layout.ty, variant_index)
720 .discard_err()?;
721 Some(discr_value.to_scalar())
722 }
723
724 fn wrap_immediate(&self, imm: Immediate) -> FlatSet<Scalar> {
725 match imm {
726 Immediate::Scalar(scalar) => FlatSet::Elem(scalar),
727 Immediate::Uninit => FlatSet::Bottom,
728 _ => FlatSet::Top,
729 }
730 }
731}
732
733impl<'tcx> DebugWithContext<ConstAnalysis<'_, 'tcx>> for State<FlatSet<Scalar>> {
735 fn fmt_with(&self, ctxt: &ConstAnalysis<'_, 'tcx>, f: &mut Formatter<'_>) -> std::fmt::Result {
736 match self {
737 State::Reachable(values) => debug_with_context(values, None, &ctxt.map, f),
738 State::Unreachable => write!(f, "unreachable"),
739 }
740 }
741
742 fn fmt_diff_with(
743 &self,
744 old: &Self,
745 ctxt: &ConstAnalysis<'_, 'tcx>,
746 f: &mut Formatter<'_>,
747 ) -> std::fmt::Result {
748 match (self, old) {
749 (State::Reachable(this), State::Reachable(old)) => {
750 debug_with_context(this, Some(old), &ctxt.map, f)
751 }
752 _ => Ok(()), }
754 }
755}
756
757struct Patch<'tcx> {
758 tcx: TyCtxt<'tcx>,
759
760 before_effect: FxHashMap<(Location, Place<'tcx>), Const<'tcx>>,
764
765 assignments: FxHashMap<Location, Const<'tcx>>,
767}
768
769impl<'tcx> Patch<'tcx> {
770 pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
771 Self { tcx, before_effect: FxHashMap::default(), assignments: FxHashMap::default() }
772 }
773
774 fn make_operand(&self, const_: Const<'tcx>) -> Operand<'tcx> {
775 Operand::Constant(Box::new(ConstOperand { span: DUMMY_SP, user_ty: None, const_ }))
776 }
777}
778
779struct Collector<'a, 'tcx> {
780 patch: Patch<'tcx>,
781 local_decls: &'a LocalDecls<'tcx>,
782}
783
784impl<'a, 'tcx> Collector<'a, 'tcx> {
785 pub(crate) fn new(tcx: TyCtxt<'tcx>, local_decls: &'a LocalDecls<'tcx>) -> Self {
786 Self { patch: Patch::new(tcx), local_decls }
787 }
788
789 #[instrument(level = "trace", skip(self, ecx, map), ret)]
790 fn try_make_constant(
791 &self,
792 ecx: &mut InterpCx<'tcx, DummyMachine>,
793 place: Place<'tcx>,
794 state: &State<FlatSet<Scalar>>,
795 map: &Map<'tcx>,
796 ) -> Option<Const<'tcx>> {
797 let ty = place.ty(self.local_decls, self.patch.tcx).ty;
798 let layout = ecx.layout_of(ty).ok()?;
799
800 if layout.is_zst() {
801 return Some(Const::zero_sized(ty));
802 }
803
804 if layout.is_unsized() {
805 return None;
806 }
807
808 let place = map.find(place.as_ref())?;
809 if layout.backend_repr.is_scalar()
810 && let Some(value) = propagatable_scalar(place, state, map)
811 {
812 return Some(Const::Val(ConstValue::Scalar(value), ty));
813 }
814
815 if matches!(layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
816 let alloc_id = ecx
817 .intern_with_temp_alloc(layout, |ecx, dest| {
818 try_write_constant(ecx, dest, place, ty, state, map)
819 })
820 .discard_err()?;
821 return Some(Const::Val(ConstValue::Indirect { alloc_id, offset: Size::ZERO }, ty));
822 }
823
824 None
825 }
826}
827
828#[instrument(level = "trace", skip(map), ret)]
829fn propagatable_scalar(
830 place: PlaceIndex,
831 state: &State<FlatSet<Scalar>>,
832 map: &Map<'_>,
833) -> Option<Scalar> {
834 if let FlatSet::Elem(value) = state.get_idx(place, map)
835 && value.try_to_scalar_int().is_ok()
836 {
837 Some(value)
839 } else {
840 None
841 }
842}
843
844#[instrument(level = "trace", skip(ecx, state, map), ret)]
845fn try_write_constant<'tcx>(
846 ecx: &mut InterpCx<'tcx, DummyMachine>,
847 dest: &PlaceTy<'tcx>,
848 place: PlaceIndex,
849 ty: Ty<'tcx>,
850 state: &State<FlatSet<Scalar>>,
851 map: &Map<'tcx>,
852) -> InterpResult<'tcx> {
853 let layout = ecx.layout_of(ty)?;
854
855 if layout.is_zst() {
857 return interp_ok(());
858 }
859
860 if layout.backend_repr.is_scalar()
862 && let Some(value) = propagatable_scalar(place, state, map)
863 {
864 return ecx.write_immediate(Immediate::Scalar(value), dest);
865 }
866
867 match ty.kind() {
868 ty::FnDef(..) => {}
870
871 ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char =>
873 throw_machine_stop_str!("primitive type with provenance"),
874
875 ty::Tuple(elem_tys) => {
876 for (i, elem) in elem_tys.iter().enumerate() {
877 let i = FieldIdx::from_usize(i);
878 let Some(field) = map.apply(place, TrackElem::Field(i)) else {
879 throw_machine_stop_str!("missing field in tuple")
880 };
881 let field_dest = ecx.project_field(dest, i)?;
882 try_write_constant(ecx, &field_dest, field, elem, state, map)?;
883 }
884 }
885
886 ty::Adt(def, args) => {
887 if def.is_union() {
888 throw_machine_stop_str!("cannot propagate unions")
889 }
890
891 let (variant_idx, variant_def, variant_place, variant_dest) = if def.is_enum() {
892 let Some(discr) = map.apply(place, TrackElem::Discriminant) else {
893 throw_machine_stop_str!("missing discriminant for enum")
894 };
895 let FlatSet::Elem(Scalar::Int(discr)) = state.get_idx(discr, map) else {
896 throw_machine_stop_str!("discriminant with provenance")
897 };
898 let discr_bits = discr.to_bits(discr.size());
899 let Some((variant, _)) = def.discriminants(*ecx.tcx).find(|(_, var)| discr_bits == var.val) else {
900 throw_machine_stop_str!("illegal discriminant for enum")
901 };
902 let Some(variant_place) = map.apply(place, TrackElem::Variant(variant)) else {
903 throw_machine_stop_str!("missing variant for enum")
904 };
905 let variant_dest = ecx.project_downcast(dest, variant)?;
906 (variant, def.variant(variant), variant_place, variant_dest)
907 } else {
908 (FIRST_VARIANT, def.non_enum_variant(), place, dest.clone())
909 };
910
911 for (i, field) in variant_def.fields.iter_enumerated() {
912 let ty = field.ty(*ecx.tcx, args);
913 let Some(field) = map.apply(variant_place, TrackElem::Field(i)) else {
914 throw_machine_stop_str!("missing field in ADT")
915 };
916 let field_dest = ecx.project_field(&variant_dest, i)?;
917 try_write_constant(ecx, &field_dest, field, ty, state, map)?;
918 }
919 ecx.write_discriminant(variant_idx, dest)?;
920 }
921
922 ty::Array(_, _)
924 | ty::Pat(_, _)
925
926 | ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Str | ty::Slice(_)
928
929 | ty::Never
930 | ty::Foreign(..)
931 | ty::Alias(..)
932 | ty::Param(_)
933 | ty::Bound(..)
934 | ty::Placeholder(..)
935 | ty::Closure(..)
936 | ty::CoroutineClosure(..)
937 | ty::Coroutine(..)
938 | ty::Dynamic(..)
939 | ty::UnsafeBinder(_) => throw_machine_stop_str!("unsupported type"),
940
941 ty::Error(_) | ty::Infer(..) | ty::CoroutineWitness(..) => bug!(),
942 }
943
944 interp_ok(())
945}
946
947impl<'tcx> ResultsVisitor<'tcx, ConstAnalysis<'_, 'tcx>> for Collector<'_, 'tcx> {
948 #[instrument(level = "trace", skip(self, analysis, statement))]
949 fn visit_after_early_statement_effect(
950 &mut self,
951 analysis: &ConstAnalysis<'_, 'tcx>,
952 state: &State<FlatSet<Scalar>>,
953 statement: &Statement<'tcx>,
954 location: Location,
955 ) {
956 match &statement.kind {
957 StatementKind::Assign(box (_, rvalue)) => {
958 OperandCollector {
959 state,
960 visitor: self,
961 ecx: &mut analysis.ecx.borrow_mut(),
962 map: &analysis.map,
963 }
964 .visit_rvalue(rvalue, location);
965 }
966 _ => (),
967 }
968 }
969
970 #[instrument(level = "trace", skip(self, analysis, statement))]
971 fn visit_after_primary_statement_effect(
972 &mut self,
973 analysis: &ConstAnalysis<'_, 'tcx>,
974 state: &State<FlatSet<Scalar>>,
975 statement: &Statement<'tcx>,
976 location: Location,
977 ) {
978 match statement.kind {
979 StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(_)))) => {
980 }
982 StatementKind::Assign(box (place, _)) => {
983 if let Some(value) = self.try_make_constant(
984 &mut analysis.ecx.borrow_mut(),
985 place,
986 state,
987 &analysis.map,
988 ) {
989 self.patch.assignments.insert(location, value);
990 }
991 }
992 _ => (),
993 }
994 }
995
996 fn visit_after_early_terminator_effect(
997 &mut self,
998 analysis: &ConstAnalysis<'_, 'tcx>,
999 state: &State<FlatSet<Scalar>>,
1000 terminator: &Terminator<'tcx>,
1001 location: Location,
1002 ) {
1003 OperandCollector {
1004 state,
1005 visitor: self,
1006 ecx: &mut analysis.ecx.borrow_mut(),
1007 map: &analysis.map,
1008 }
1009 .visit_terminator(terminator, location);
1010 }
1011}
1012
1013impl<'tcx> MutVisitor<'tcx> for Patch<'tcx> {
1014 fn tcx(&self) -> TyCtxt<'tcx> {
1015 self.tcx
1016 }
1017
1018 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1019 if let Some(value) = self.assignments.get(&location) {
1020 match &mut statement.kind {
1021 StatementKind::Assign(box (_, rvalue)) => {
1022 *rvalue = Rvalue::Use(self.make_operand(*value));
1023 }
1024 _ => bug!("found assignment info for non-assign statement"),
1025 }
1026 } else {
1027 self.super_statement(statement, location);
1028 }
1029 }
1030
1031 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1032 match operand {
1033 Operand::Copy(place) | Operand::Move(place) => {
1034 if let Some(value) = self.before_effect.get(&(location, *place)) {
1035 *operand = self.make_operand(*value);
1036 } else if !place.projection.is_empty() {
1037 self.super_operand(operand, location)
1038 }
1039 }
1040 Operand::Constant(_) | Operand::RuntimeChecks(_) => {}
1041 }
1042 }
1043
1044 fn process_projection_elem(
1045 &mut self,
1046 elem: PlaceElem<'tcx>,
1047 location: Location,
1048 ) -> Option<PlaceElem<'tcx>> {
1049 if let PlaceElem::Index(local) = elem {
1050 let offset = self.before_effect.get(&(location, local.into()))?;
1051 let offset = offset.try_to_scalar()?;
1052 let offset = offset.to_target_usize(&self.tcx).discard_err()?;
1053 let min_length = offset.checked_add(1)?;
1054 Some(PlaceElem::ConstantIndex { offset, min_length, from_end: false })
1055 } else {
1056 None
1057 }
1058 }
1059}
1060
1061struct OperandCollector<'a, 'b, 'tcx> {
1062 state: &'a State<FlatSet<Scalar>>,
1063 visitor: &'a mut Collector<'b, 'tcx>,
1064 ecx: &'a mut InterpCx<'tcx, DummyMachine>,
1065 map: &'a Map<'tcx>,
1066}
1067
1068impl<'tcx> Visitor<'tcx> for OperandCollector<'_, '_, 'tcx> {
1069 fn visit_projection_elem(
1070 &mut self,
1071 _: PlaceRef<'tcx>,
1072 elem: PlaceElem<'tcx>,
1073 _: PlaceContext,
1074 location: Location,
1075 ) {
1076 if let PlaceElem::Index(local) = elem
1077 && let Some(value) =
1078 self.visitor.try_make_constant(self.ecx, local.into(), self.state, self.map)
1079 {
1080 self.visitor.patch.before_effect.insert((location, local.into()), value);
1081 }
1082 }
1083
1084 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
1085 if let Some(place) = operand.place() {
1086 if let Some(value) =
1087 self.visitor.try_make_constant(self.ecx, place, self.state, self.map)
1088 {
1089 self.visitor.patch.before_effect.insert((location, place), value);
1090 } else if !place.projection.is_empty() {
1091 self.super_operand(operand, location)
1093 }
1094 }
1095 }
1096}