Skip to main content

rapx/analysis/dataflow/
call.rs

1//! MIR dataflow queries used to describe a callee at a call site.
2
3use rustc_hir::def_id::DefId;
4use rustc_middle::{
5    mir::{Body, Operand},
6    ty::{Mutability, TyCtxt, TyKind},
7};
8
9use super::{
10    call_write::{self, WriteSemantics},
11    graph::build_dataflow_graph,
12};
13use crate::compat::Spanned;
14
15/// Dependencies needed to retain a call during backward slicing.
16#[derive(Clone, Debug)]
17pub(crate) struct CallDependencies {
18    /// Arguments that can affect the call's return value.
19    pub return_depends_on_args: Vec<usize>,
20    /// Arguments whose referents the call may write.
21    pub write_args: Vec<usize>,
22    /// Arguments needed to model those writes during backward slicing.
23    pub write_inputs: Vec<usize>,
24}
25
26impl CallDependencies {
27    pub(crate) fn fallback(arg_count: usize) -> Self {
28        Self {
29            return_depends_on_args: (0..arg_count).collect(),
30            write_args: Vec::new(),
31            write_inputs: Vec::new(),
32        }
33    }
34}
35
36/// Verification-specific call models supplement MIR-derived dependencies.
37pub(crate) trait CallSemantics: WriteSemantics {
38    fn special_dependencies<'tcx>(
39        &self,
40        tcx: TyCtxt<'tcx>,
41        caller: DefId,
42        callee: DefId,
43        func: &Operand<'tcx>,
44        args: &[Spanned<Operand<'tcx>>],
45        body: &Body<'tcx>,
46    ) -> Option<CallDependencies>;
47
48    fn skip_mir_dependencies(&self, tcx: TyCtxt<'_>, callee: DefId) -> bool;
49    fn preserve_all_return_args(&self, tcx: TyCtxt<'_>, callee: DefId) -> bool;
50}
51
52/// Combine MIR dataflow with the verifier's special call semantics.
53pub(crate) fn dependencies<'tcx>(
54    tcx: TyCtxt<'tcx>,
55    caller: DefId,
56    func: &Operand<'tcx>,
57    args: &[Spanned<Operand<'tcx>>],
58    body: &Body<'tcx>,
59    semantics: &impl CallSemantics,
60) -> CallDependencies {
61    let arg_count = args.len();
62    let Some(callee) = crate::util::mir_utils::dep_callee_def_id(func) else {
63        return CallDependencies::fallback(arg_count);
64    };
65    if let Some(summary) = semantics.special_dependencies(tcx, caller, callee, func, args, body) {
66        return summary;
67    }
68    if semantics.skip_mir_dependencies(tcx, callee) {
69        return CallDependencies::fallback(arg_count);
70    }
71
72    // The write and return dependencies are independent: a callee can write
73    // through an argument while returning a value derived from another one.
74    let write_args =
75        call_write::callsite_write_args(semantics, tcx, caller, func).unwrap_or_else(|| {
76            tcx.fn_sig(callee)
77                .skip_binder()
78                .inputs()
79                .skip_binder()
80                .iter()
81                .enumerate()
82                .filter_map(|(i, ty)| {
83                    (i < arg_count
84                        && matches!(
85                            ty.kind(),
86                            TyKind::Ref(_, _, Mutability::Mut) | TyKind::RawPtr(_, Mutability::Mut)
87                        ))
88                    .then_some(i)
89                })
90                .collect()
91        });
92    let write_args: Vec<_> = write_args.into_iter().filter(|i| *i < arg_count).collect();
93    let return_deps = if semantics.preserve_all_return_args(tcx, callee) {
94        Some((0..arg_count).collect())
95    } else {
96        return_dependencies(tcx, callee)
97    };
98    if !write_args.is_empty() || return_deps.is_some() {
99        return CallDependencies {
100            return_depends_on_args: return_deps
101                .map(|args| args.into_iter().filter(|i| *i < arg_count).collect())
102                .unwrap_or_else(|| (0..arg_count).collect()),
103            write_inputs: write_args.clone(),
104            write_args,
105        };
106    }
107    CallDependencies::fallback(arg_count)
108}
109
110/// Arguments that can flow into the return value of a callee with available MIR.
111///
112/// `None` means the graph could not be built; callers must retain all arguments
113/// in that case. An empty vector means the return is independent of arguments.
114pub(crate) fn return_dependencies(tcx: TyCtxt<'_>, callee: DefId) -> Option<Vec<usize>> {
115    if !tcx.is_mir_available(callee) {
116        return None;
117    }
118    crate::util::mir_utils::catch_panic(|| {
119        build_dataflow_graph(tcx, callee)
120            .param_return_deps()
121            .iter_enumerated()
122            .filter_map(|(local, depends)| {
123                (*depends && local.as_usize() > 0).then(|| local.as_usize() - 1)
124            })
125            .collect()
126    })
127    .ok()
128}