diff --git a/README.md b/README.md index 483084de..877283c5 100644 --- a/README.md +++ b/README.md @@ -750,7 +750,7 @@ trace-merge [OPTIONS] ... [-o ] - Re-links `external` call edges (`functions.is_defined = 0` or `call_edges.resolution = 'external'`) against matching exported definitions (`is_defined = 1`, `linkage = 'external'`) from other repositories, updating edge resolution to `direct` or `ambiguous`, while preserving original non-direct resolutions (`indirect` and `ipc`). - **May-analysis over-approximation**: External calls retain edges to every selected definition, including each image's copy of a shared header body. Distinct source origins make the call ambiguous; shared-origin copies retain a resolved classification. Deduplicates call edges per call site to eliminate duplicate edges. - Keeps internal-linkage (`static`) functions file-scoped and preserves resolved definitions in known link images; see [merge linking rules](docs/ANALYSIS.md#invariants-and-linking-rules) for weak-symbol precedence and ambiguous matches. -- Uses normalized parameter signatures in `functions.signature` (`name(type1, type2)`) to disambiguate C++ overloads and avoid false collisions; falls back to all same-name candidates if exact signature matching misses. +- Uses normalized parameter types, known C++ reference bindings, and allocator template identity in `functions.signature` to disambiguate overloads. The ` >` and ` >` markers preserve known primary provenance. Relinking accepts equivalent legacy spellings for definition selection and keeps shared-header copies reachable. See [function signature storage](docs/SQLITE_SCHEMA.md#functions) for matching, strength, and diagnostic rules. - Prevents accidental overwriting of any input database when specifying `-o`. - Opens inputs read-only and publishes through a unique temporary file beside the output. Failed merges clean up staging files and preserve the existing destination. - Merger output supports call graphs, call chains, and editor call hierarchy. It omits variables, arg-flow, points-to, and all PAG/provenance tables; call-site variable bindings remain NULL. Dataflow inspection requires an original analysis database or a new analysis of the combined source tree; see the [merger schema contract](docs/SQLITE_SCHEMA.md#merger-inputs-and-output). diff --git a/crates/trace-analysis/src/ipc.rs b/crates/trace-analysis/src/ipc.rs index 71e9e104..7ff393a7 100644 --- a/crates/trace-analysis/src/ipc.rs +++ b/crates/trace-analysis/src/ipc.rs @@ -1114,11 +1114,17 @@ mod tests { explicit_arity: None, default_args: 0, reference_params: Vec::new(), + parameter_references: Vec::new(), owner_unresolved: false, variadic: false, pack_positions: Vec::new(), + non_deduced_pack: false, + is_explicit_constructor: false, defaulted_in_class: false, + is_deleted: false, declared_in_class: false, + is_free_function_template: false, + allocator_template: None, is_member_template: false, is_const_member: false, ref_qualifier: None, diff --git a/crates/trace-analysis/src/linking.rs b/crates/trace-analysis/src/linking.rs index b08fd485..2fb41f58 100644 --- a/crates/trace-analysis/src/linking.rs +++ b/crates/trace-analysis/src/linking.rs @@ -6,6 +6,8 @@ pub struct LinkedMember { pub site: CallSiteId, pub caller: FnId, pub callee: FnId, + /// Original declaration selected for this candidate's call-site variant. + pub selected: Option, } // Keep source-specific guesses distinct from a namesake another provider @@ -121,8 +123,13 @@ pub fn link_graph_facts_in_targets( owner_unresolved: false, variadic: f.variadic, pack_positions: Vec::new(), + non_deduced_pack: false, + is_explicit_constructor: false, defaulted_in_class: false, + is_deleted: false, declared_in_class: true, + is_free_function_template: false, + allocator_template: None, is_member_template: false, is_const_member: false, ref_qualifier: None, @@ -130,6 +137,7 @@ pub fn link_graph_facts_in_targets( is_static_member: f.static_member, default_args: 0, reference_params: vec![], + parameter_references: Vec::new(), is_virtual: f.virtual_member, is_final: f.final_member, is_cpp: true, @@ -343,6 +351,7 @@ pub fn link_graph_facts_in_targets( site: call.source_site, caller: call.caller, callee: id, + selected: call.callee, }); } } diff --git a/crates/trace-analysis/src/pag.rs b/crates/trace-analysis/src/pag.rs index 3821c1de..ceafcb8b 100644 --- a/crates/trace-analysis/src/pag.rs +++ b/crates/trace-analysis/src/pag.rs @@ -1,11 +1,13 @@ use crate::constraints::{AbstractLocation, Constraint, ConstraintKind, LocKind}; use crate::ipc::detect_ipc_pairs_with_models; -use crate::summaries::{Effect, EffectGroup, FnModelSet, ModelLookup}; +use crate::summaries::{AllocationTargets, Effect, EffectGroup, FnModelSet, ModelLookup}; use indexmap::IndexMap; use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; +use std::borrow::Cow; +use std::sync::Arc; use trace_ir::{ - CallSite, ContainerOwner, FieldId, FlowConstraint, FnId, LocId, PagNodeId, Program, ReturnFlow, - StorageClass, TargetId, TypeDesc, TypeId, VarId, + CallReturnBinding, CallSite, ContainerOwner, FieldId, FlowConstraint, FnId, LocId, PagNodeId, + Program, ReturnFlow, StorageClass, TargetId, TypeDesc, TypeId, VarId, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -127,6 +129,7 @@ pub struct Pag { pub indices: SolverIndices, /// Call results produced by `return_field`, for transitive return expansion. return_field_values: FxHashSet, + allocation_targets: Arc, } impl Pag { @@ -145,6 +148,7 @@ impl Pag { ) -> Self { let mut pag = Self { ipc_enabled: enable_ipc, + allocation_targets: Arc::clone(models.allocation_targets()), ..Self::default() }; pag.build_variables(program); @@ -160,6 +164,20 @@ impl Pag { pag } + /// Resolve direct return facts using the same call selections as PAG + /// construction, so export can attribute the wiring to its occurrence. + pub fn return_candidates( + &self, + program: &Program, + name: &str, + caller: Option, + dst: VarId, + binding: Option<&CallReturnBinding>, + ) -> Cow<'_, [FnId]> { + self.allocation_targets + .candidates(program, name, caller, dst, binding) + } + fn alloc_node(&mut self, kind: PagNodeKind) -> PagNodeId { let id = PagNodeId(self.nodes.len() as u32); self.nodes.push(PagNode { id, kind }); @@ -896,15 +914,32 @@ impl Pag { dst, callee_name, caller, + binding, } => { let dst_n = self.var_node_id(*dst); let mut visited = FxHashSet::default(); - let candidates = - program - .symbols - .call_return_candidates(*caller, *dst, callee_name); + let candidates = models.allocation_targets().candidates( + program, + callee_name, + *caller, + *dst, + binding.as_deref(), + ); + let declared = matches!( + binding.as_deref(), + Some(CallReturnBinding::InitializerDeclarations(_)), + ); + if declared { + for (callee, args) in program.symbols.initializer_call_targets( + *dst, + flow.initializer_calls(), + &program.types, + ) { + self.wire_initializer_arguments(program, callee, args); + } + } let mut any_real = false; - for callee in &candidates { + for callee in candidates.iter() { if self.expand_return_flows(program, dst_n, *callee, models, &mut visited) { any_real = true; } @@ -912,15 +947,15 @@ impl Pag { // Modeled return effects fire only when no real return // flow exists (bodyless callees: libc realloc, vendor // allocators). Synthesized externals never enter the - // name-resolution maps, so the model is consulted by - // call name directly. - if !any_real { - if let Some(model) = models.model(callee_name, EffectGroup::Return) { - let params = candidates - .iter() - .find(|c| !program.symbols.function(**c).params.is_empty()) - .map(|c| program.symbols.function(*c).params.clone()); - self.apply_return_model(program, dst_n, model, params.as_deref()); + // name-resolution maps. Fall back to a return model + // using the selected targets and the call spelling. + if !any_real && (!declared || !candidates.is_empty()) { + if let Some((model, params)) = models.return_model( + callee_name, + &candidates, + declared || matches!(candidates, Cow::Borrowed(_)), + ) { + self.apply_return_model(program, dst_n, model, params); // A file-scope initializer has no call record. if caller.is_none() { self.apply_return_fields(program, *dst, model, &candidates, None); @@ -952,14 +987,7 @@ impl Pag { *callee, &program.types, ) { - for (formal, actual) in program - .symbols - .initializer_argument_bindings(definition, args) - { - let dst = self.var_node_id(formal); - let src = self.var_node_id(actual); - self.add_copy(dst, src); - } + self.wire_initializer_arguments(program, definition, args); self.expand_reference_returns( program, dst_node, @@ -1089,11 +1117,10 @@ impl Pag { } if !any_real { for cs in sites { - if let Some(model) = models.model(&cs.callee_name, EffectGroup::Return) { - let params = cs - .callee_fn_id - .map(|fid| program.symbols.function(fid).params.clone()); - self.apply_return_model(program, dst_n, model, params.as_deref()); + if let Some((model, params)) = + models.return_model(&cs.callee_name, &program.callees_of(cs), true) + { + self.apply_return_model(program, dst_n, model, params); break; } } @@ -1226,8 +1253,13 @@ impl Pag { callee_name, result, } => { - let inner_candidates = - program.symbols.return_flow_candidates(callee, &callee_name); + let inner_candidates = models.allocation_targets().candidates( + program, + &callee_name, + Some(callee), + result, + None, + ); let mut inner_applied = false; for inner in inner_candidates.iter().copied() { if self.expand_returns_in_mode( @@ -1240,18 +1272,13 @@ impl Pag { // realloc has no tree body): fall back to the // modeled return effects. if !inner_applied && !address { - if let Some(model) = models.model(&callee_name, EffectGroup::Return) - { - let params = inner_candidates - .iter() - .find(|c| !program.symbols.function(**c).params.is_empty()) - .map(|c| program.symbols.function(*c).params.clone()); - inner_applied = self.apply_return_model( - program, - dst, - model, - params.as_deref(), - ); + if let Some((model, params)) = models.return_model( + &callee_name, + &inner_candidates, + matches!(inner_candidates, Cow::Borrowed(_)), + ) { + inner_applied = + self.apply_return_model(program, dst, model, params); } } if !address && self.return_field_values.contains(&result) { @@ -1539,6 +1566,19 @@ impl Pag { id } + fn wire_initializer_arguments( + &mut self, + program: &Program, + callee: FnId, + args: &[(u32, VarId)], + ) { + for (formal, actual) in program.symbols.initializer_argument_bindings(callee, args) { + let dst = self.var_node_id(formal); + let src = self.var_node_id(actual); + self.add_copy(dst, src); + } + } + pub fn add_copy(&mut self, dst: PagNodeId, src: PagNodeId) { self.constraints.push(Constraint { kind: crate::constraints::ConstraintKind::Copy, diff --git a/crates/trace-analysis/src/solver.rs b/crates/trace-analysis/src/solver.rs index 054c9dcb..69cf91cf 100644 --- a/crates/trace-analysis/src/solver.rs +++ b/crates/trace-analysis/src/solver.rs @@ -1062,7 +1062,7 @@ fn solve( &mut st, &mut scratch, cs, - &f.name, + f, models, &mut terminator_events, ); @@ -1662,7 +1662,7 @@ fn solve( &mut st, &mut scratch, cs, - &program.symbols.function(callee).name, + program.symbols.function(callee), models, &mut terminator_events, ); @@ -1825,11 +1825,11 @@ fn apply_fn_model( st: &mut SolverState, scratch: &mut Scratch, cs: &trace_ir::CallSite, - callee_name: &str, + callee: &trace_ir::Function, models: &ModelLookup, terminator_events: &mut Vec<(CallSiteId, u32)>, ) { - let Some(model) = models.model(callee_name, EffectGroup::Args) else { + let Some(model) = models.argument_model(callee) else { return; }; // Unresolved member addresses may still name the base variable; @@ -2664,23 +2664,15 @@ fn wire_actuals( ) { let callee_fn = program.symbols.function(callee); let this = u32::from(program.symbols.has_this_param(callee)); - callee_fn.debug_assert_pack_positions(this as usize); - let mut packs = callee_fn - .pack_positions - .iter() - .map(|at| at + this) - .peekable(); - let mut packs_before = 0; - for (i, formal) in callee_fn.params.iter().enumerate() { + for (i, (formal, first, is_pack)) in callee_fn.parameter_actual_starts(this).enumerate() { let formal_idx = i as u32; - let is_pack = packs.next_if_eq(&formal_idx).is_some(); debug_assert_eq!( is_pack, - program.pack_vars.contains(formal), + program.pack_vars.contains(&formal), "{}: parameter pack metadata disagrees with formal {formal_idx}", callee_fn.name ); - if is_pack || packs_before > 0 { + if is_pack || first < formal_idx { // A pack formal takes every argument from its position on: the // positions the site passes, mapped as the callee takes them, // each wired once however many positions an expansion covers. @@ -2689,9 +2681,6 @@ fn wire_actuals( .max() .map_or(1, |last| last + 1); let mut taken: Vec = Vec::new(); - // Earlier packs may all be empty. Omit each of their synthetic - // slots to find this formal's first possible actual position. - let first = formal_idx - packs_before; for slot in first..first.saturating_add(reach) { let Some(idx) = actual_of(slot) else { continue; @@ -2713,7 +2702,7 @@ fn wire_actuals( cs, st, scratch, - *formal, + formal, formal_idx, at, &mut on_wired, @@ -2728,13 +2717,12 @@ fn wire_actuals( cs, st, scratch, - *formal, + formal, formal_idx, at, &mut on_wired, ); } - packs_before += u32::from(is_pack); } } @@ -4290,11 +4278,17 @@ mod tests { explicit_arity: None, default_args: 0, reference_params: Vec::new(), + parameter_references: Vec::new(), owner_unresolved: false, variadic: false, pack_positions: Vec::new(), + non_deduced_pack: false, + is_explicit_constructor: false, defaulted_in_class: false, + is_deleted: false, declared_in_class: false, + is_free_function_template: false, + allocator_template: None, is_member_template: false, is_const_member: false, ref_qualifier: None, diff --git a/crates/trace-analysis/src/summaries.rs b/crates/trace-analysis/src/summaries.rs index 7a872bae..2aa278bd 100644 --- a/crates/trace-analysis/src/summaries.rs +++ b/crates/trace-analysis/src/summaries.rs @@ -7,9 +7,13 @@ //! models") for semantics and the configuration format. use rustc_hash::{FxHashMap, FxHashSet}; -use std::cell::RefCell; +use std::borrow::Cow; +use std::cell::{OnceCell, RefCell}; use std::sync::Arc; -use trace_ir::{ContainerModel, ContainerModels, Program}; +use trace_ir::{ + CallOccurrence, CallReturnBinding, ContainerModel, ContainerModels, FnId, Function, Program, + TempKind, VarId, +}; /// One parameter relation of a function model. #[derive(Debug, Clone, PartialEq, Eq)] @@ -275,6 +279,8 @@ impl FnModel { #[derive(Debug, Default, Clone)] pub struct FnModelSet { by_name: FxHashMap, + /// Built-in models for C APIs that can share a name with C++ overloads. + c_api_models: FxHashSet, /// Class → the model registered for its constructor (`C` → `C::C`). constructors: FxHashMap, /// Member name → the qualified models of that name (`PostTask` → @@ -402,10 +408,23 @@ impl FnModelSet { ] { reg(name, vec![Effect::Entry { context }]); } - reg("epoll_ctl", vec![Effect::EpollRegister { param: 3 }]); - for name in ["epoll_wait", "epoll_pwait", "epoll_pwait2"] { - reg(name, vec![Effect::EpollWait { param: 1 }]); + for n in ["zalloc", "kmalloc", "OsalMemAlloc", "OsalMemCalloc"] { + reg(n, vec![Effect::ReturnHeap]); + } + for n in ["dlsym", "dlvsym", "GetProcAddress"] { + reg(n, vec![Effect::Dlsym { name_param: 1 }]); + } + let mut reg = |name: &str, effects| { + set.register(FnModel::new(name, effects)); + set.c_api_models.insert(name.to_owned()); + }; + for name in ["malloc", "calloc"] { + reg(name, vec![Effect::ReturnHeap]); } + reg( + "realloc", + vec![Effect::ReturnAlias { param: 0 }, Effect::ReturnHeap], + ); for n in ["memcpy", "memmove", "strcpy", "strncpy"] { reg(n, vec![Effect::MemCopy { dst: 0, src: 1 }]); } @@ -423,22 +442,13 @@ impl FnModelSet { for n in ["memset", "memset_s"] { reg(n, vec![Effect::Clears { param: 0 }]); } - for n in [ - "malloc", - "calloc", - "zalloc", - "kmalloc", - "OsalMemAlloc", - "OsalMemCalloc", + for (name, effect) in [ + ("epoll_ctl", Effect::EpollRegister { param: 3 }), + ("epoll_wait", Effect::EpollWait { param: 1 }), + ("epoll_pwait", Effect::EpollWait { param: 1 }), + ("epoll_pwait2", Effect::EpollWait { param: 1 }), ] { - reg(n, vec![Effect::ReturnHeap]); - } - reg( - "realloc", - vec![Effect::ReturnAlias { param: 0 }, Effect::ReturnHeap], - ); - for n in ["dlsym", "dlvsym", "GetProcAddress"] { - reg(n, vec![Effect::Dlsym { name_param: 1 }]); + reg(name, vec![effect]); } set } @@ -496,10 +506,12 @@ impl FnModelSet { models: self, program, member_models: RefCell::default(), + allocation_targets: OnceCell::new(), } } pub fn register(&mut self, model: FnModel) { + self.c_api_models.remove(&model.name); if let Some((class, last)) = model.name.rsplit_once("::") { if class.rsplit("::").next() == Some(last) { self.constructors @@ -636,6 +648,54 @@ impl FnModel { } } +#[derive(Debug, Default)] +pub(crate) struct AllocationTargets { + sites: FxHashMap<(FnId, VarId, Option), Vec>, +} + +impl AllocationTargets { + pub(crate) fn candidates( + &self, + program: &Program, + name: &str, + caller: Option, + dst: VarId, + binding: Option<&CallReturnBinding>, + ) -> Cow<'_, [FnId]> { + let occurrence = match binding { + Some(CallReturnBinding::InitializerDeclarations(calls)) => { + let mut candidates = Vec::new(); + let calls = calls.iter().map(|call| (call.callee, call.args.as_slice())); + for (callee, _) in + program + .symbols + .initializer_call_targets(dst, calls, &program.types) + { + if !candidates.contains(&callee) { + candidates.push(callee); + } + } + return Cow::Owned(candidates); + } + Some(CallReturnBinding::Occurrence(occurrence)) => Some(*occurrence), + None => None, + }; + // Ordinary lookup can name a different namespace than the target + // selected by ADL. Its leaf identifies the allocation candidate index. + let name = if trace_ir::is_allocator_name(name) { + if let Some(selected) = + caller.and_then(|caller| self.sites.get(&(caller, dst, occurrence))) + { + return Cow::Borrowed(selected); + } + name.trim_start_matches("::") + } else { + name + }; + Cow::Owned(program.symbols.call_return_candidates(caller, dst, name)) + } +} + /// The one matcher every model lookup of an analysis goes through /// (`docs/MODELS.md`, "Model matching"): the model named for the function /// (`FnModelSet::named`), else the member models of a class the @@ -648,6 +708,8 @@ pub struct ModelLookup<'m> { /// Function name → the member models the class rule admits for it, /// nearest class first, then by model name. member_models: RefCell>>, + /// Lowering's selected targets for allocations with a recorded call site. + allocation_targets: OnceCell>, } impl<'m> ModelLookup<'m> { @@ -667,6 +729,103 @@ impl<'m> ModelLookup<'m> { .map(|(model, ())| model) } + pub(crate) fn argument_model(&self, callee: &Function) -> Option<&'m FnModel> { + let model = self.model(&callee.name, EffectGroup::Args)?; + (!self.models.c_api_models.contains(&model.name) || Self::can_name_c_api(callee)) + .then_some(model) + } + + pub(crate) fn allocation_targets(&self) -> &Arc { + self.allocation_targets + .get_or_init(|| Arc::new(self.collect_allocation_targets())) + } + + pub(crate) fn return_model( + &self, + name: &str, + candidates: &[FnId], + selected: bool, + ) -> Option<(&'m FnModel, Option<&'m [VarId]>)> { + let model = self.model(name, EffectGroup::Return).or_else(|| { + // Ordinary lookup can name a different namespace from the + // allocator that won ADL. Only ranked targets can recover a + // built-in model whose name did not match the return fact. + if !selected || !self.has_allocator_leaf(name) { + return None; + } + candidates.iter().find_map(|&id| { + let callee = self.program.symbols.function(id); + (Self::can_name_c_api(callee) && self.is_builtin_allocator(&callee.name)) + .then(|| self.model(&callee.name, EffectGroup::Return)) + .flatten() + }) + })?; + let guarded = self.models.c_api_models.contains(&model.name); + let mut eligible = candidates + .iter() + .map(|&id| self.program.symbols.function(id)) + .filter(|callee| !guarded || Self::can_name_c_api(callee)) + .peekable(); + if !candidates.is_empty() && eligible.peek().is_none() { + return None; + } + let params = eligible + .find(|callee| !callee.params.is_empty()) + .map(|callee| callee.params.as_slice()); + Some((model, params)) + } + + fn is_builtin_allocator(&self, name: &str) -> bool { + self.models + .named(name, EffectGroup::Return) + .is_some_and(|model| { + self.models.c_api_models.contains(&model.name) && model.has(EffectGroup::Return) + }) + } + + fn has_allocator_leaf(&self, name: &str) -> bool { + self.is_builtin_allocator(name.rsplit("::").next().unwrap_or(name)) + } + + fn collect_allocation_targets(&self) -> AllocationTargets { + let mut targets = AllocationTargets::default(); + for site in &self.program.symbols.call_sites { + let Some(dst) = site + .return_dst + .filter(|_| !site.unevaluated && site.callee_var.is_none()) + else { + continue; + }; + let spelling = site.callee_name.as_str(); + // Additional ranked overloads of the same call site append + // their numeric ID to the spelling. + let name = spelling + .rsplit_once("::") + .filter(|(_, suffix)| suffix.parse::().is_ok()) + .map_or(spelling, |(name, _)| name); + // ADL can select a namespace's own overload even when the + // return fact names the global allocator from ordinary lookup. + if !trace_ir::is_allocator_name(name) { + continue; + } + let occurrence = (self.program.symbols.variable(dst).temp + != Some(TempKind::ReturnedCall)) + .then(|| site.occurrence()); + targets + .sites + .entry((site.caller, dst, occurrence)) + .or_default() + .extend(self.program.callees_of(site)); + } + targets + } + + fn can_name_c_api(callee: &Function) -> bool { + // Calls without a declaration may still name a C API outside the + // index. A declared C++ overload has its own linker symbol. + !callee.is_cpp || callee.c_linkage || callee.explicit_arity.is_none() + } + /// The `entry` model the function named `name` is the member of or an /// override of, with the context it states (`docs/MODELS.md`, /// "Execution contexts"). diff --git a/crates/trace-cli/tests/it/call_sites.rs b/crates/trace-cli/tests/it/call_sites.rs index 04bff15b..81064528 100644 --- a/crates/trace-cli/tests/it/call_sites.rs +++ b/crates/trace-cli/tests/it/call_sites.rs @@ -557,6 +557,7 @@ fn conditional_compound_arms_keep_one_return_destination_per_call() { dst, callee_name, caller: owner, + .. } if *owner == Some(calls[0].caller) && callee_name == name => Some(*dst), _ => None, }) @@ -704,6 +705,7 @@ fn conditional_and_standalone_comma_values_keep_operand_provenance() { dst, callee_name, caller, + .. } if *caller == Some(owner) && callee_name == name => Some(*dst), _ => None, }) diff --git a/crates/trace-cli/tests/it/fn_model_cases.rs b/crates/trace-cli/tests/it/fn_model_cases.rs index 1e6686ee..6ca58c02 100644 --- a/crates/trace-cli/tests/it/fn_model_cases.rs +++ b/crates/trace-cli/tests/it/fn_model_cases.rs @@ -724,6 +724,15 @@ fn epoll_registration_reaches_wait_dispatch() { }, ); assert!(with.solve.converged); + let overload_targets: Vec<_> = with + .call_edges + .iter() + .filter(|edge| fn_name(&program, edge.caller) == "other::wait_overload") + .map(|edge| program.symbols.function(edge.callee)) + .collect(); + assert_eq!(overload_targets.len(), 1); + assert_eq!(overload_targets[0].name, "epoll_pwait"); + assert!(overload_targets[0].is_cpp && !overload_targets[0].c_linkage); let registration = program .symbols .call_sites @@ -917,3 +926,1876 @@ fn alias_models_accept_precise_members_but_reject_container_fallbacks() { } } } + +#[test] +fn adl_overloads_do_not_take_builtin_libc_models() { + let dir = scratch(&[( + "main.cpp", + r#" +using size_t = decltype(sizeof(0)); +struct Tag {}; +void memcpy(Tag*, Tag*) {} +extern "C" void *memcpy(void *, const void *, size_t); +namespace app { +void memcpy(int); +Tag tag; +Tag* destination; +Tag* source = &tag; +void copy() { memcpy(destination, source); } +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let targets: Vec<_> = result + .call_edges + .iter() + .filter(|edge| fn_name(&program, edge.caller) == "app::copy") + .map(|edge| program.symbols.function(edge.callee)) + .collect(); + assert_eq!(targets.len(), 1); + assert_eq!(targets[0].name, "memcpy"); + assert!(targets[0].is_cpp && !targets[0].c_linkage); + let destination = program + .symbols + .variables + .iter() + .find(|v| v.name == "destination") + .unwrap(); + assert!(result + .points_to + .get(&pag.var_node[&destination.id]) + .is_none_or(|pts| pts.is_empty())); +} + +#[test] +fn libc_allocation_models_follow_the_selected_call_target() { + let dir = scratch(&[( + "main.cpp", + r#" +struct Tag {}; +Tag* malloc(Tag*) { return nullptr; } +namespace std { extern "C" void* malloc(unsigned long); } +namespace app { +void malloc(int, int); +Tag tag; +void unqualified() { Tag* p = malloc(&tag); } +void qualified() { Tag* p = ::malloc(&tag); } +void genuine() { void* p = std::malloc(sizeof(Tag)); } +} +namespace ordinary { +void unqualified() { Tag* p = malloc(&app::tag); } +Tag* forwarded() { return malloc(&app::tag); } +void through_return() { Tag* p = forwarded(); } +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for caller in [ + "app::unqualified", + "app::qualified", + "ordinary::unqualified", + "ordinary::forwarded", + "app::genuine", + ] { + let targets: Vec<_> = result + .call_edges + .iter() + .filter(|edge| fn_name(&program, edge.caller) == caller) + .map(|edge| program.symbols.function(edge.callee)) + .collect(); + assert_eq!(targets.len(), 1, "{caller}"); + assert_eq!( + targets[0].name, + if caller == "app::genuine" { + "std::malloc" + } else { + "malloc" + }, + "{caller}" + ); + assert_eq!(targets[0].c_linkage, caller == "app::genuine", "{caller}"); + } + for (caller, allocates) in [ + ("app::unqualified", false), + ("app::qualified", false), + ("ordinary::unqualified", false), + ("ordinary::through_return", false), + ("app::genuine", true), + ] { + let var = local_variable(&program, caller, "p"); + let heap = result + .points_to + .get(&pag.var_node[&var]) + .is_some_and(|pts| { + pts.iter() + .any(|l| pag.locations[l.0 as usize].kind == trace_analysis::LocKind::Heap) + }); + assert_eq!(heap, allocates, "{caller}"); + } +} + +#[test] +fn allocation_models_keep_calls_to_the_same_destination_separate() { + let dir = scratch(&[( + "main.cpp", + r#" +struct Tag {} tag; +Tag* malloc(Tag*) { return nullptr; } +namespace std { extern "C" void* malloc(unsigned long); } +#define ASSIGN(dst, callee, arg) dst = callee(arg) +void run() { + void* p; + ASSIGN(p, std::malloc, 8UL); + ASSIGN(p, ::malloc, &tag); +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let dst = local_variable(&program, "run", "p"); + let pointees = &result.points_to[&pag.var_node[&dst]]; + assert_eq!(pointees.len(), 1, "{pointees:?}"); + let loc = &pag.locations[pointees.iter().next().unwrap().0 as usize]; + assert_eq!(loc.kind, trace_analysis::LocKind::Heap); +} + +#[test] +fn unselected_overload_returns_cannot_suppress_libc_allocation() { + let dir = scratch(&[( + "main.cpp", + r#" +struct Tag {} tag; +extern "C" void* malloc(unsigned long); +Tag* malloc(Tag*, int) { return &tag; } +void run() { void* p = malloc(8UL); } +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let allocators: Vec<_> = result + .call_edges + .iter() + .filter(|edge| fn_name(&program, edge.caller) == "run") + .map(|edge| program.symbols.function(edge.callee)) + .collect(); + assert_eq!(allocators.len(), 1); + assert_eq!(allocators[0].name, "malloc"); + assert!(allocators[0].c_linkage); + let dst = local_variable(&program, "run", "p"); + let pointees = &result.points_to[&pag.var_node[&dst]]; + assert_eq!(pointees.len(), 1, "{pointees:?}"); + let loc = &pag.locations[pointees.iter().next().unwrap().0 as usize]; + assert_eq!(loc.kind, trace_analysis::LocKind::Heap); +} + +#[test] +fn namespaced_adl_allocator_overload_controls_return_flow() { + let dir = scratch(&[( + "main.cpp", + r#" +extern "C" void* malloc(unsigned long); +namespace app { +struct Tag {}; +Tag* malloc(Tag*) { return nullptr; } +} + +void adl(app::Tag* tag) { void* p = malloc(tag); } +void* forward(app::Tag* tag) { return malloc(tag); } +void forwarded(app::Tag* tag) { void* p = forward(tag); } +void libc() { void* p = malloc(8UL); } +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for caller in ["adl", "forward"] { + let targets: Vec<_> = result + .call_edges + .iter() + .filter(|edge| fn_name(&program, edge.caller) == caller) + .map(|edge| fn_name(&program, edge.callee)) + .collect(); + assert_eq!(targets, ["app::malloc"], "{caller}"); + } + for (caller, allocates) in [("adl", false), ("forwarded", false), ("libc", true)] { + let dst = local_variable(&program, caller, "p"); + let has_heap = result + .points_to + .get(&pag.var_node[&dst]) + .is_some_and(|pts| { + pts.iter() + .any(|loc| pag.locations[loc.0 as usize].kind == trace_analysis::LocKind::Heap) + }); + assert_eq!(has_heap, allocates, "{caller}"); + } +} + +#[test] +fn adl_selected_c_allocator_supplies_return_flow() { + let dir = scratch(&[( + "main.cpp", + r#" +extern "C" void* malloc(unsigned long); +struct Size { operator unsigned long() const { return 8; } }; +namespace app { +void* malloc(int, int); +void direct(Size size) { void* p = malloc(size); } +void* forward(Size size) { return malloc(size); } +void forwarded(Size size) { void* p = forward(size); } +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for caller in ["app::direct", "app::forward"] { + let targets: Vec<_> = result + .call_edges + .iter() + .filter(|edge| fn_name(&program, edge.caller) == caller) + .map(|edge| fn_name(&program, edge.callee)) + .collect(); + assert_eq!(targets, ["malloc"], "{caller}"); + } + for caller in ["app::direct", "app::forwarded"] { + let dst = local_variable(&program, caller, "p"); + let pointees = &result.points_to[&pag.var_node[&dst]]; + assert_eq!(pointees.len(), 1, "{caller}: {pointees:?}"); + let loc = &pag.locations[pointees.iter().next().unwrap().0 as usize]; + assert_eq!(loc.kind, trace_analysis::LocKind::Heap, "{caller}"); + } +} + +#[test] +fn file_scope_allocator_returns_follow_adl_selection() { + let dir = scratch(&[ + ( + "main.cpp", + r#" +extern "C" void* malloc(unsigned long); +namespace app { +struct Tag {}; +Tag tag; +Tag* malloc(Tag*); +} +namespace address { +struct Tag {}; +Tag address_tag; +Tag* malloc(Tag*) { return &address_tag; } +} +namespace identity { +struct Tag {}; +Tag identity_tag; +Tag* malloc(Tag*); +} +struct Size { operator unsigned long() const { return 8; } }; +void* no_allocation = malloc(&app::tag); +void* adl_address = malloc(&address::address_tag); +void* libc_allocation = malloc(8UL); +void* adl_argument = malloc(&identity::identity_tag); +namespace inner { +void* malloc(int, int); +Size size; +void* adl_allocation = malloc(size); +} +"#, + ), + ( + "casts.cpp", + r#" +extern "C" void* malloc(unsigned long); +struct CastTag {}; +CastTag cast_tag; +CastTag* malloc(CastTag*) { return &cast_tag; } +void* cast_allocation = malloc(((unsigned long)8)); +void* cast_address = malloc((CastTag*)&cast_tag); +"#, + ), + ( + "overload.cpp", + r#" +namespace app { struct Tag {}; Tag* malloc(Tag*) { return nullptr; } } +namespace identity { struct Tag {}; Tag* malloc(Tag* value) { return value; } } +"#, + ), + ]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let pointees = |name| { + let dst = only_variable(&program, name); + result + .points_to + .get(&pag.var_node[&dst]) + .into_iter() + .flatten() + }; + assert_eq!(pointees("no_allocation").count(), 0); + for (result, object) in [ + ("adl_address", "address_tag"), + ("cast_address", "cast_tag"), + ("adl_argument", "identity_tag"), + ] { + let tag = only_variable(&program, object); + assert_eq!( + pointees(result).copied().collect::>(), + [pag.var_location[&tag]], + "{result}", + ); + } + for name in ["libc_allocation", "cast_allocation", "adl_allocation"] { + let locations: Vec<_> = pointees(name).collect(); + assert_eq!(locations.len(), 1, "{name}"); + assert_eq!( + pag.locations[locations[0].0 as usize].kind, + trace_analysis::LocKind::Heap, + "{name}", + ); + } +} + +#[test] +fn file_scope_allocator_returns_bind_formals_after_packs() { + let dir = scratch(&[( + "main.cpp", + r#" +extern "C" void* malloc(unsigned long); +namespace leading { +struct Tag {}; +Tag leading_tag; +template Tag* malloc(P... ignored, Tag* value) { return value; } +} +namespace prefixed { +struct Tag {}; +Tag prefix_tag; +Tag tail_tag; +template +Tag* malloc(Tag* prefix, P... ignored, Tag* value) { return value; } +} +void* leading_result = malloc(&leading::leading_tag); +void* prefixed_result = malloc(&prefixed::prefix_tag, &prefixed::tail_tag); +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (dst, tag) in [ + ("leading_result", "leading_tag"), + ("prefixed_result", "tail_tag"), + ] { + let var = only_variable(&program, dst); + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "{dst}"); + } +} + +#[test] +fn file_scope_allocator_formals_after_packs_get_addresses_and_only_omitted_defaults() { + let dir = scratch(&[ + ( + "main.cpp", + r#" +namespace reference { +struct Tag {}; +Tag referent; +template Tag* malloc(P... ignored, Tag& value); +} +namespace supplied_default { +struct Tag {}; +Tag supplied, unused_fallback; +template +Tag* malloc(P... ignored, Tag* value = &unused_fallback) { return value; } +} +namespace omitted_default { +struct Tag {}; +Tag fallback; +template +Tag* malloc(P... ignored, Tag* value = &fallback) { return value; } +} +void* address = reference::malloc(reference::referent); +void* supplied_result = supplied_default::malloc(&supplied_default::supplied); +void* omitted = omitted_default::malloc(); +"#, + ), + ( + "definition.cpp", + r#" +namespace reference { +struct Tag {}; +template Tag* malloc(P... ignored, Tag& value) { return &value; } +template Tag* malloc<>(Tag&); +} +"#, + ), + ]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (dst, tag) in [ + ("address", "referent"), + ("supplied_result", "supplied"), + ("omitted", "fallback"), + ] { + let var = only_variable(&program, dst); + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "{dst}"); + } +} + +#[test] +fn file_scope_allocator_empty_packs_align_each_fixed_argument() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace ordered { +struct Tag {}; +Tag a, b; +template +Tag* malloc(P... ignored, Tag* first, Tag* second) { return first; } +} +namespace empty { +struct Tag {}; +Tag supplied, unused_fallback; +template +Tag* malloc(P... ignored, Tag* value = &unused_fallback) { return value; } +} +namespace explicit_pack { +struct Tag {}; +Tag fallback; +template +Tag* malloc(P... ignored, Tag* value = &fallback) { return value; } +} +namespace deduced_pack { +struct Tag {}; +Tag deduced_fallback; +template struct Types {}; +Types types; +template +Tag* malloc(Types, P... ignored, Tag* value = &deduced_fallback) { return value; } +} +void* deduced_result = deduced_pack::malloc(deduced_pack::types, 42); +void* first_result = ordered::malloc(&ordered::a, &ordered::b); +void* supplied_result = empty::malloc<>(&empty::supplied); +void* explicit_result = explicit_pack::malloc(42); +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (dst, tag) in [ + ("first_result", "a"), + ("supplied_result", "supplied"), + ("explicit_result", "fallback"), + ("deduced_result", "deduced_fallback"), + ] { + let var = only_variable(&program, dst); + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "{dst}"); + } +} + +#[test] +fn file_scope_allocator_template_id_excludes_non_templates_before_ranking() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace app { +struct Tag {}; +Tag ordinary, expected; +Tag* malloc(int) { return &ordinary; } +template +Tag* malloc(P... ignored, int value) { return &expected; } +} +void* empty_id = app::malloc<>(7); +void* explicit_id = app::malloc(6, 7); +void* bare_name = app::malloc(7); +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (dst, tag) in [ + ("empty_id", "expected"), + ("explicit_id", "expected"), + ("bare_name", "ordinary"), + ] { + let var = only_variable(&program, dst); + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "{dst}"); + } +} + +#[test] +fn body_allocator_template_id_excludes_the_ordinary_overload() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace app { +struct Tag {}; +Tag wrong, expected; +Tag* malloc(int) { return &wrong; } +template +Tag* malloc(P... ignored, int value) { return &expected; } +} +auto* use_template() { + auto* p = app::malloc<>(7); + return p; +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let caller = only_function(&program, "use_template"); + let targets: Vec<_> = result + .call_edges + .iter() + .filter(|edge| edge.caller == caller) + .map(|edge| program.symbols.function(edge.callee)) + .collect(); + assert_eq!(targets.len(), 1, "{targets:?}"); + assert!(targets[0].is_free_function_template, "{targets:?}"); + let var = local_variable(&program, "use_template", "p"); + let expected = pag.var_location[&only_variable(&program, "expected")]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected]); +} + +#[test] +fn file_scope_allocator_template_id_retains_the_explicit_specialization() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace app { +struct Tag {}; +Tag ordinary, primary, specialized; +Tag* malloc(int) { return &ordinary; } +template +Tag* malloc(P... ignored, int value) { return &primary; } +template<> Tag* malloc(int value) { return &specialized; } +} +auto* empty_id = app::malloc<>(7); +auto* nonempty_id = app::malloc(6, 7); +auto* bare_name = app::malloc(7); +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (dst, tag) in [ + ("empty_id", "specialized"), + ("nonempty_id", "primary"), + ("bare_name", "ordinary"), + ] { + let var = only_variable(&program, dst); + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "{dst}"); + } +} + +#[test] +fn allocator_template_ids_respect_specializations_written_arguments() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace app { +struct Tag {}; +Tag primary, int_result, short_result; +template +Tag* malloc(P... ignored, int value) { return &primary; } +template<> Tag* malloc(int value); +template<> Tag* malloc(int value) { return &short_result; } +} +template<> app::Tag* app::malloc(int value) { return &int_result; } +auto* global_long = app::malloc(7); +auto* global_int = app::malloc(7); +auto* global_short = app::malloc(7); +auto* local_long() { + auto* p = app::malloc(7); + return p; +} +auto* local_alias() { + using Selected = int; + auto* p = app::malloc(7); + return p; +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (var, tag) in [ + (only_variable(&program, "global_long"), "primary"), + (only_variable(&program, "global_int"), "int_result"), + (only_variable(&program, "global_short"), "short_result"), + (local_variable(&program, "local_long", "p"), "primary"), + (local_variable(&program, "local_alias", "p"), "int_result"), + ] { + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "expected {tag}"); + } +} + +#[test] +fn allocator_template_ids_check_pack_length_and_integral_values() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace lengths { +struct Tag {}; +Tag primary_length, empty_pack; +template +Tag* malloc(P... args, int value = 0) { return &primary_length; } +template<> Tag* malloc(int value) { return &empty_pack; } +} +namespace packed { +struct Tag {}; +Tag primary_packed, nonempty_pack; +template +Tag* malloc(P... args, int value) { return &primary_packed; } +template<> Tag* malloc(long arg, int value) { return &nonempty_pack; } +} +namespace values { +struct Tag {}; +Tag primary_value, one, three; +template +Tag* malloc(P... args, int value) { return &primary_value; } +template<> Tag* malloc<1>(int value) { return &one; } +template<> Tag* malloc<3>(int value) { return &three; } +} +auto* global_longer = lengths::malloc(7); +auto* global_shorter = lengths::malloc(7); +auto* global_packed = packed::malloc(6, 7); +auto* global_other = values::malloc<2>(7); +auto* global_same = values::malloc<0x1>(7); +auto* global_three = values::malloc<3>(7); +auto* local_longer() { + auto* p = lengths::malloc(7); + return p; +} +auto* local_other() { + auto* p = values::malloc<2>(7); + return p; +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (var, tag) in [ + (only_variable(&program, "global_longer"), "primary_length"), + (only_variable(&program, "global_shorter"), "empty_pack"), + (only_variable(&program, "global_packed"), "nonempty_pack"), + (only_variable(&program, "global_other"), "primary_value"), + (only_variable(&program, "global_same"), "one"), + (only_variable(&program, "global_three"), "three"), + ( + local_variable(&program, "local_longer", "p"), + "primary_length", + ), + ( + local_variable(&program, "local_other", "p"), + "primary_value", + ), + ] { + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "expected {tag}"); + } +} + +#[test] +fn allocator_specializations_distinguish_deduced_integral_types() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace deduced { +struct Tag {}; +Tag primary, unsigned_result; +template +Tag* malloc(P... args, int value) { return &primary; } +template<> Tag* malloc<1u>(int value) { return &unsigned_result; } +} +namespace converted { +struct Tag {}; +Tag converted_primary, converted_result; +template +Tag* malloc(P... args, int value) { return &converted_primary; } +template<> Tag* malloc<1u>(int value) { return &converted_result; } +} +auto* signed_call = deduced::malloc<1>(7); +auto* unsigned_call = deduced::malloc<0x1u>(7); +auto* converted_call = converted::malloc<1>(7); +auto* local_signed() { + auto* p = deduced::malloc<1>(7); + return p; +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (var, tag) in [ + (only_variable(&program, "signed_call"), "primary"), + (only_variable(&program, "unsigned_call"), "unsigned_result"), + ( + only_variable(&program, "converted_call"), + "converted_result", + ), + (local_variable(&program, "local_signed", "p"), "primary"), + ] { + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "expected {tag}"); + } +} + +#[test] +fn uncertain_allocator_specialization_keeps_primary_return_flow() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace app { +struct Tag {}; +Tag primary, specialized; +template +Tag* malloc(P... args, int value) { return &primary; } +template<> Tag* malloc<1>(int value) { return &specialized; } +} +constexpr int n = 2; +auto* global = app::malloc(7); +auto* local() { + auto* p = app::malloc(7); + return p; +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let primary = pag.var_location[&only_variable(&program, "primary")]; + let specialization = pag.var_location[&only_variable(&program, "specialized")]; + for var in [ + only_variable(&program, "global"), + local_variable(&program, "local", "p"), + ] { + let pointees = &result.points_to[&pag.var_node[&var]]; + assert_eq!(pointees.len(), 2, "{pointees:?}"); + assert!(pointees.contains(&primary), "{pointees:?}"); + assert!(pointees.contains(&specialization), "{pointees:?}"); + } +} + +#[test] +fn allocator_specializations_without_template_ids_keep_the_primary() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace implicit_args { +struct Tag {}; +Tag default_primary, wrong_default; +template +Tag* malloc(P... args, int value) { return &default_primary; } +template<> Tag* malloc<1>(int value) { return &wrong_default; } +} +auto* global = implicit_args::malloc(7); +auto* local() { + auto* p = implicit_args::malloc(7); + return p; +} +"#, + )]); + assert_allocator_return_candidates(dir.path(), &["default_primary", "wrong_default"]); +} + +#[test] +fn uncertain_allocator_specializations_are_ranked_independently() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace dependent { +struct Tag {}; +Tag dependent_primary, wrong_int, selected_long; +template +Tag* malloc(P... args, decltype(N) value) { return &dependent_primary; } +template<> Tag* malloc<1>(int value) { return &wrong_int; } +template<> Tag* malloc<2L>(long value) { return &selected_long; } +} +constexpr long n = 2; +auto* global = dependent::malloc(7); +auto* local() { + auto* p = dependent::malloc(7); + return p; +} +"#, + )]); + assert_allocator_return_candidates( + dir.path(), + &["dependent_primary", "wrong_int", "selected_long"], + ); +} + +#[test] +fn allocator_template_ids_accept_abbreviated_templates() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace app { +struct Tag {}; +Tag expected, ordinary; +Tag* malloc(int) { return &ordinary; } +Tag* malloc(auto value); +} +auto* global = app::malloc(7); +auto* local() { + auto* p = app::malloc(7); + return p; +} +namespace app { +Tag* malloc(auto value) { return &expected; } +} +"#, + )]); + assert_allocator_return_candidates(dir.path(), &["expected"]); +} + +#[test] +fn allocator_template_ids_accept_abbreviated_static_members() { + let dir = scratch(&[( + "main.cpp", + r#" +struct Tag {}; +Tag expected, ordinary; +struct Alloc { + static Tag* malloc(int) { return &ordinary; } + static Tag* malloc(auto value) { return &expected; } +}; +struct DeferredAlloc { + static Tag* malloc(auto value); +}; +Tag* global = Alloc::malloc(7); +auto* local() { + auto* p = DeferredAlloc::malloc(7); + return p; +} +Tag* DeferredAlloc::malloc(auto value) { return &expected; } +"#, + )]); + assert_allocator_return_candidates(dir.path(), &["expected"]); +} + +#[test] +fn allocator_template_ids_select_static_member_specializations() { + let dir = scratch(&[( + "main.cpp", + r#" +struct Tag {}; +Tag primary, specialized; +struct Alloc { + template + static Tag* malloc(P... args, int value) { return &primary; } +}; +template<> Tag* Alloc::malloc(int value) { return &specialized; } +auto* empty_id = Alloc::malloc<>(7); +auto* nonempty_id = Alloc::malloc(6L, 7); +auto* local() { + auto* p = Alloc::malloc<>(7); + return p; +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (var, tag) in [ + (only_variable(&program, "empty_id"), "specialized"), + (only_variable(&program, "nonempty_id"), "primary"), + (local_variable(&program, "local", "p"), "specialized"), + ] { + let expected = pag.var_location[&only_variable(&program, tag)]; + let pointees: Vec<_> = result + .points_to + .get(&pag.var_node[&var]) + .into_iter() + .flatten() + .copied() + .collect(); + assert_eq!(pointees, [expected], "expected {tag}"); + } +} + +#[test] +fn allocator_specialization_can_belong_to_an_explicit_class_specialization() { + let dir = scratch(&[( + "owner.cpp", + r#" +struct Tag {}; +Tag primary, specialized; +namespace app { +template struct Alloc; +template struct OtherAlloc { + static Tag* malloc(int value); +}; +template<> struct OtherAlloc {}; +template<> Tag* OtherAlloc::malloc(int value) { return &primary; } +} +template<> struct app::Alloc { + template + static Tag* malloc(P... args, int value) { return &primary; } +}; +template<> Tag* app::Alloc::malloc(int value) { return &specialized; } +Tag* result = app::Alloc::malloc<>(7); +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let ordinary = only_function(&program, "app::OtherAlloc::malloc"); + assert!(program + .symbols + .function(ordinary) + .allocator_specialization_args() + .is_none()); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let dst = only_variable(&program, "result"); + let expected = pag.var_location[&only_variable(&program, "specialized")]; + assert_eq!(result.points_to[&pag.var_node[&dst]].len(), 1); + assert!(result.points_to[&pag.var_node[&dst]].contains(&expected)); +} + +#[test] +fn in_class_allocator_specialization_declaration_guides_cross_tu_return() { + let dir = scratch(&[ + ( + "alloc.hpp", + r#" +#pragma once +struct Tag {}; +inline Tag primary; +struct Alloc { + template + static Tag* malloc(P... args, int value) { return &primary; } + template<> Tag* malloc<>(int); +}; +"#, + ), + ( + "caller.cpp", + r#" +#include "alloc.hpp" +Tag* result = Alloc::malloc<>(7); +"#, + ), + ( + "impl.cpp", + r#" +#include "alloc.hpp" +Tag specialized; +template<> Tag* Alloc::malloc<>(int value) { return &specialized; } +"#, + ), + ]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let dst = only_variable(&program, "result"); + let expected = pag.var_location[&only_variable(&program, "specialized")]; + assert_eq!(result.points_to[&pag.var_node[&dst]].len(), 1); + assert!(result.points_to[&pag.var_node[&dst]].contains(&expected)); +} + +#[test] +fn allocator_specialization_owner_type_alias_selects_the_explicit_specialization() { + let dir = scratch(&[( + "owner.cpp", + r#" +struct Tag {}; +Tag primary, specialized; +template struct Alloc; +template<> struct Alloc { + template + static Tag* malloc(P... args, int value) { return &primary; } +}; +using Key = int; +template<> Tag* Alloc::malloc(int value) { return &specialized; } +Tag* result = Alloc::malloc<>(7); +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let dst = only_variable(&program, "result"); + let expected = pag.var_location[&only_variable(&program, "specialized")]; + assert_eq!(result.points_to[&pag.var_node[&dst]].len(), 1); + assert!(result.points_to[&pag.var_node[&dst]].contains(&expected)); +} + +#[test] +fn allocator_specialization_alias_owner_keeps_cv_distinct() { + let dir = scratch(&[( + "owner.cpp", + r#" +struct Tag {}; +Tag primary, const_specialized; +template struct Alloc; +template<> struct Alloc { + template + static Tag* malloc(P... args, int value) { return &primary; } +}; +using ConstKey = const int; +template<> Tag* Alloc::malloc(int value) { return &const_specialized; } +Tag* result = Alloc::malloc<>(7); +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let dst = only_variable(&program, "result"); + let expected = pag.var_location[&only_variable(&program, "const_specialized")]; + assert_eq!(result.points_to[&pag.var_node[&dst]].len(), 1); + assert!(result.points_to[&pag.var_node[&dst]].contains(&expected)); +} + +#[test] +fn allocator_specialization_owner_recorded_through_a_type_alias() { + let dir = scratch(&[( + "owner.cpp", + r#" +struct Tag {}; +Tag primary, specialized; +template struct Alloc; +using Key = int; +template<> struct Alloc { + template + static Tag* malloc(P... args, int value) { return &primary; } +}; +template<> Tag* Alloc::malloc(int value) { return &specialized; } +Tag* result = Alloc::malloc<>(7); +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + let dst = only_variable(&program, "result"); + let expected = pag.var_location[&only_variable(&program, "specialized")]; + assert_eq!(result.points_to[&pag.var_node[&dst]].len(), 1); + assert!(result.points_to[&pag.var_node[&dst]].contains(&expected)); +} + +fn assert_allocator_return_candidates(root: &std::path::Path, tags: &[&str]) { + let program = build_program(root, &default_opts(root)).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for var in [ + only_variable(&program, "global"), + local_variable(&program, "local", "p"), + ] { + let pointees = &result.points_to[&pag.var_node[&var]]; + assert_eq!(pointees.len(), tags.len(), "{pointees:?}"); + for tag in tags { + let expected = pag.var_location[&only_variable(&program, tag)]; + assert!(pointees.contains(&expected), "missing {tag}: {pointees:?}"); + } + } +} + +#[test] +fn allocator_specializations_preserve_identity_and_cross_tu_selection() { + let dir = scratch(&[ + ( + "api.hpp", + r#" +#pragma once +struct Tag {}; +struct Arena { + static Tag* malloc(Tag*); + template static Tag* malloc(Tag*); +}; +struct Special { + template static Tag* malloc(int); +}; +template<> Tag* Special::malloc(int); +template<> Tag* Special::malloc(int); +namespace free_allocator { + template Tag* malloc(int); + template<> Tag* malloc(int); + template<> Tag* malloc(int); +} +"#, + ), + ( + "caller.cpp", + r#" +#include "api.hpp" +Tag wrong; +Tag one; +template<> Tag* free_allocator::malloc(int) { return &one; } +template void run() { + auto* p = free_allocator::malloc(7); +} +Tag* selected = Arena::malloc(&wrong); +Tag* first = Special::malloc(7); +Tag* second = Special::malloc(7); +"#, + ), + ( + "impl.cpp", + r#" +#include "api.hpp" +Tag correct, special_int, special_int_long, two; +Tag* Arena::malloc(Tag* value) { return value; } +template Tag* Arena::malloc(Tag*) { return &correct; } +template<> Tag* Special::malloc(int) { return &special_int; } +template<> Tag* Special::malloc(int) { return &special_int_long; } +template<> Tag* free_allocator::malloc(int) { return &two; } +"#, + ), + ]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let members: Vec<_> = program + .symbols + .functions + .iter() + .filter(|f| f.name == "Special::malloc" && f.allocator_specialization_args().is_some()) + .collect(); + assert_eq!(members.len(), 2, "{members:?}"); + assert!(members.iter().all(|f| f.is_defined), "{members:?}"); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (dst, tag) in [ + ("selected", "correct"), + ("first", "special_int"), + ("second", "special_int_long"), + ] { + let dst = only_variable(&program, dst); + let expected = pag.var_location[&only_variable(&program, tag)]; + assert_eq!( + result.points_to[&pag.var_node[&dst]] + .iter() + .copied() + .collect::>(), + [expected], + "expected {tag}" + ); + } + let pointees = &result.points_to[&pag.var_node[&local_variable(&program, "run", "p")]]; + for tag in ["one", "two"] { + assert!( + pointees.contains(&pag.var_location[&only_variable(&program, tag)]), + "missing {tag}" + ); + } +} + +#[test] +fn allocator_specialization_can_deduce_arguments_from_a_trailing_return() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace app { +struct Tag {}; +Tag specialized; +template auto malloc(int) -> T*; +template auto malloc(int) -> T* { return nullptr; } +template<> auto malloc(int) -> Tag* { return &specialized; } +} +auto* global = app::malloc(7); +auto* local() { + auto* p = app::malloc(7); + return p; +} +"#, + )]); + assert_allocator_return_candidates(dir.path(), &["specialized"]); +} + +#[test] +fn nested_allocator_specialization_uses_its_declared_owner() { + let dir = scratch(&[( + "nested.cpp", + r#" +namespace app { +struct Tag {}; +Tag primary, specialized; +template struct Outer; +template<> struct Outer { template struct Inner; }; +template<> struct Outer::Inner { + template static Tag* malloc(P... args, int value) { return &primary; } +}; +template<> Tag* Outer::Inner::malloc(int) { return &specialized; } +} +auto* global = app::Outer::Inner::malloc<>(7); +auto* local() { auto* p = app::Outer::Inner::malloc<>(7); return p; } +"#, + )]); + assert_allocator_return_candidates(dir.path(), &["specialized"]); +} + +#[test] +fn allocator_specialization_arguments_can_be_deduced_from_wrapped_declarators() { + let dir = scratch(&[( + "wrapped.cpp", + r#" +struct Tag {}; +Tag array[4]; +Tag* helper(int) { return nullptr; } +namespace fn_result { +template Tag* (*malloc(T))(int) { return nullptr; } +template<> Tag* (*malloc(int))(int) { return &helper; } +} +namespace array_result { +template Tag (*malloc(int))[N] { return nullptr; } +template<> Tag (*malloc(int))[4] { return &array; } +} +void run() { + auto f = fn_result::malloc(7); + f(0); + auto p = array_result::malloc<4>(7); +} +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for name in ["fn_result::malloc", "array_result::malloc"] { + assert!( + result.call_edges.iter().any(|e| { + fn_name(&program, e.caller) == "run" + && program.symbols.function_by_id(e.callee).is_some_and(|f| { + f.name == name && f.allocator_specialization_args().is_some() + }) + }), + "{name}" + ); + } + let p = local_variable(&program, "run", "p"); + let array = pag.var_location[&only_variable(&program, "array")]; + assert!(result.points_to[&pag.var_node[&p]].contains(&array)); + assert_eq!(indirect_targets(&program, &result, "run"), ["helper"]); +} + +#[test] +fn allocator_specialization_pack_lengths_without_complete_primary_metadata() { + let dir = scratch(&[ + ( + "api.hpp", + r#" +#pragma once +struct Tag {}; +namespace deduced { +template Tag* malloc(T); +template<> Tag* malloc(int); +template<> Tag* malloc(int); +} +struct Arena { + template static Tag* malloc(int); + template static Tag* malloc(int, int); +}; +template<> Tag* Arena::malloc(int); +template<> Tag* Arena::malloc(int); +"#, + ), + ( + "caller.cpp", + r#" +#include "api.hpp" +Tag one, member_one; +template<> Tag* deduced::malloc(int) { return &one; } +template<> Tag* Arena::malloc(int) { return &member_one; } +Tag* global = deduced::malloc(7); +Tag* member_global = Arena::malloc(7); +auto* local() { auto* p = deduced::malloc(7); return p; } +auto* member_local() { auto* p = Arena::malloc(7); return p; } +"#, + ), + ( + "impl.cpp", + r#" +#include "api.hpp" +Tag two, member_two; +template<> Tag* deduced::malloc(int) { return &two; } +template<> Tag* Arena::malloc(int) { return &member_two; } +"#, + ), + ]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let (pag, result) = analyze_with_options( + &program, + AnalyzeOptions { + retain_points_to: true, + ..Default::default() + }, + ); + for (dst, tag) in [ + (only_variable(&program, "global"), "two"), + (local_variable(&program, "local", "p"), "two"), + (only_variable(&program, "member_global"), "member_two"), + (local_variable(&program, "member_local", "p"), "member_two"), + ] { + let expected = pag.var_location[&only_variable(&program, tag)]; + assert!( + result.points_to[&pag.var_node[&dst]].contains(&expected), + "{tag}" + ); + } + for name in ["deduced::malloc", "Arena::malloc"] { + let mut lengths: Vec<_> = program + .symbols + .functions + .iter() + .filter(|f| f.is_defined && f.name == name) + .filter_map(|f| f.allocator_specialization_args().map(<[_]>::len)) + .collect(); + lengths.sort_unstable(); + assert_eq!(lengths, [1, 2], "{name}"); + } +} + +#[test] +fn allocator_specialization_matches_a_redeclaration_with_more_explicit_arguments() { + let dir = scratch(&[ + ( + "api.hpp", + r#" +#pragma once +namespace app { +struct Tag {}; +template Tag* malloc(T, U); +template Tag* malloc(T, T, T); +template<> Tag* malloc(int, long); +} +"#, + ), + ( + "caller.cpp", + r#" +#include "api.hpp" +auto* global = app::malloc(7, 8L); +auto* local() { auto* p = app::malloc(7, 8L); return p; } +"#, + ), + ( + "impl.cpp", + r#" +#include "api.hpp" +app::Tag expected; +template<> app::Tag* app::malloc(int, long) { return &expected; } +"#, + ), + ]); + assert_allocator_return_candidates(dir.path(), &["expected"]); +} + +#[test] +fn allocator_specialization_matches_a_redeclaration_with_a_deduced_pointer_argument() { + let dir = scratch(&[ + ( + "api.hpp", + r#" +#pragma once +namespace app { +struct Tag {}; +template Tag* malloc(T, U); +template Tag* malloc(T, T, T); +template<> Tag* malloc(int, long*); +} +"#, + ), + ( + "caller.cpp", + r#" +#include "api.hpp" +auto* global = app::malloc(7, nullptr); +auto* local() { auto* p = app::malloc(7, nullptr); return p; } +"#, + ), + ( + "impl.cpp", + r#" +#include "api.hpp" +app::Tag expected; +template<> app::Tag* app::malloc(int, long*) { return &expected; } +"#, + ), + ]); + assert_allocator_return_candidates(dir.path(), &["expected"]); +} + +#[test] +fn allocator_specialization_matches_a_redeclaration_with_a_deduced_reference_argument() { + let sources = [ + ( + "api.hpp", + r#" +#pragma once +namespace app { +struct Tag {}; +template Tag* malloc(T, U&); +template Tag* malloc(T, T, T); +template<> Tag* malloc(int, long&); +} +"#, + ), + ( + "caller.cpp", + r#" +#include "api.hpp" +long value; +auto* global = app::malloc(7, value); +auto* local() { auto* p = app::malloc(7, value); return p; } +"#, + ), + ( + "impl.cpp", + r#" +#include "api.hpp" +app::Tag expected; +template<> app::Tag* app::malloc(int, long&) { return &expected; } +"#, + ), + ]; + for (primary, formal, argument, actual) in [ + ("U&", "long&", "long", "value"), + ("const U&", "const long&", "long", "value"), + ("U&&", "long&&", "long", "8L"), + ("U&&", "long&", "long&", "value"), + ] { + let sources = sources.map(|(name, source)| { + ( + name, + source + .replace("U&", primary) + .replace("long&", formal) + .replace("", &format!("")) + .replace("7, value", &format!("7, {actual}")), + ) + }); + let inputs = sources + .each_ref() + .map(|(name, source)| (*name, source.as_str())); + let dir = scratch(&inputs); + assert_allocator_return_candidates(dir.path(), &["expected"]); + } +} + +#[test] +fn allocator_primary_and_ordinary_functions_keep_distinct_symbols() { + let dir = scratch(&[( + "main.cpp", + r#" +namespace app { +struct Tag {}; +Tag expected, ordinary; +Tag* malloc(int) { return &ordinary; } +template Tag* malloc(int); +template Tag* malloc(int) { return &expected; } +} +auto* global = app::malloc<>(0); +auto* local() { auto* p = app::malloc<>(0); return p; } +"#, + )]); + assert_allocator_return_candidates(dir.path(), &["expected"]); +} + +#[test] +fn allocator_specialization_inherits_omitted_primary_default() { + let (program, analysis) = analyze_source(&[( + "main.cpp", + r#" +namespace app { +using Fn = void(*)(); +void hit() {} +template Fn malloc(T, Fn callback = hit) { return nullptr; } +template Fn malloc(T, T, T) { return nullptr; } +template Fn malloc(T, int) { return nullptr; } +template Fn malloc(T*, Fn callback = hit) { return nullptr; } +template<> Fn malloc(int, Fn callback) { return callback; } +} +auto callback = app::malloc(0); +void global_call() { callback(); } +void local_call() { auto cb = app::malloc(0); cb(); } +"#, + )]); + for caller in ["global_call", "local_call"] { + assert_eq!( + indirect_targets(&program, &analysis, caller), + ["app::hit"], + "{caller}" + ); + } +} + +#[test] +fn allocator_specialization_inherits_default_before_a_trailing_pack() { + let (program, analysis) = analyze_source(&[( + "main.cpp", + r#" +namespace app { +using Fn = void(*)(); +void hit() {} +template Fn malloc(T, Fn callback = hit, P... tail) { return nullptr; } +template<> Fn malloc(int, Fn callback) { return callback; } +} +auto callback = app::malloc(0); +void global_call() { callback(); } +void local_call() { auto cb = app::malloc(0); cb(); } +"#, + )]); + for caller in ["global_call", "local_call"] { + assert_eq!( + indirect_targets(&program, &analysis, caller), + ["app::hit"], + "{caller}" + ); + } +} + +#[test] +fn allocator_specialization_inherits_default_from_the_reference_primary() { + let (program, analysis) = analyze_source(&[( + "main.cpp", + r#" +namespace app { +using Fn = void(*)(); +void hit() {} +template Fn malloc(T&, Fn callback = hit) { return nullptr; } +template Fn malloc(T*, Fn callback = hit) { return nullptr; } +template<> Fn malloc(int&, Fn callback) { return callback; } +} +int value; +auto callback = app::malloc(value); +void global_call() { callback(); } +void local_call() { auto cb = app::malloc(value); cb(); } +"#, + )]); + for caller in ["global_call", "local_call"] { + assert_eq!( + indirect_targets(&program, &analysis, caller), + ["app::hit"], + "{caller}" + ); + } +} + +#[test] +fn allocator_result_type_comes_from_the_ranked_specialization() { + let (program, analysis) = analyze_source(&[( + "main.cpp", + r#" +namespace app { +struct A { void Touch() {} }; +struct B { void Touch() {} }; +A a; +B b; +template T* malloc(int) { return nullptr; } +template<> A* malloc(int) { return &a; } +template<> B* malloc(int) { return &b; } +} +void direct() { app::malloc(0)->Touch(); } +void via_auto() { auto* b = app::malloc(0); b->Touch(); } +"#, + )]); + for caller in ["direct", "via_auto"] { + assert!( + has_any_edge(&program, &analysis, caller, "app::B::Touch"), + "{caller}" + ); + assert!(!has_any_edge(&program, &analysis, caller, "app::A::Touch")); + } +} + +#[test] +fn allocator_occurrence_binding_survives_a_model_override() { + use trace_analysis::{Effect, FnModel, FnModelSet}; + let dir = scratch(&[( + "main.cpp", + r#" +using Fn = void(*)(); +void right() {} +void wrong() {} +struct Arena { + static Fn malloc(int) { return right; } + static Fn malloc(void*) { return wrong; } +}; +void run() { auto p = Arena::malloc(1); p(); } +"#, + )]); + let program = build_program(dir.path(), &default_opts(dir.path())).unwrap(); + let mut models = FnModelSet::builtin(); + models.register(FnModel { + name: "malloc".into(), + effects: vec![Effect::ReturnHeap], + }); + let (_, result) = analyze_with_options( + &program, + AnalyzeOptions { + models: Arc::new(models), + ..Default::default() + }, + ); + assert_eq!(indirect_targets(&program, &result, "run"), ["right"]); +} + +#[test] +fn allocator_specialization_matches_a_fixed_arity_deduced_suffix_across_tus() { + let (program, result) = analyze_source(&[ + ( + "api.hpp", + r#" +#pragma once +namespace app { +using Fn = void (*)(); +template Fn malloc(T, U*); +template<> Fn malloc(int, long*); +} +"#, + ), + ( + "caller.cpp", + r#" +#include "api.hpp" +void run(long* arg) { + app::Fn cb = app::malloc(7, arg); + cb(); +} +"#, + ), + ( + "provider.cpp", + r#" +#include "api.hpp" +void callback() {} +template<> app::Fn app::malloc(int, long*) { return callback; } +"#, + ), + ]); + assert!(has_any_edge(&program, &result, "run", "callback")); +} + +#[test] +fn allocator_specialization_matches_trailing_padding_across_tus() { + let (program, result) = analyze_source(&[ + ( + "caller.cpp", + r#" +namespace app { +template int* malloc(T, U*); +template<> int* malloc(int, long*); +} +void run(long* arg) { app::malloc(7, arg); } +"#, + ), + ( + "provider.cpp", + r#" +namespace app { +template int* malloc(T, U*); +template int* malloc(double, double); +template<> int* malloc(int, long*) { return nullptr; } +} +"#, + ), + ]); + assert!(has_edge( + &program, + &result, + "run", + "app::malloc", + ResolutionKind::Direct + )); +} diff --git a/crates/trace-cli/tests/it/main.rs b/crates/trace-cli/tests/it/main.rs index 4a1b51ee..2a8c290f 100644 --- a/crates/trace-cli/tests/it/main.rs +++ b/crates/trace-cli/tests/it/main.rs @@ -55,3 +55,5 @@ mod cpp_review_257_invocations; mod cpp_review_257_opaque; mod cpp_review_257_postfix; mod cpp_review_257_templates; + +mod std_move; diff --git a/crates/trace-cli/tests/it/std_move.rs b/crates/trace-cli/tests/it/std_move.rs new file mode 100644 index 00000000..ac73f11a --- /dev/null +++ b/crates/trace-cli/tests/it/std_move.rs @@ -0,0 +1,2094 @@ +use crate::common::{analysis_rows, analyze_source, cli_analyze, has_any_edge, scratch}; +use trace_analysis::AnalysisResult; +use trace_ir::{FlowConstraint, Program}; + +fn analyze(source: &str) -> (Program, AnalysisResult) { + analyze_source(&[("move.cpp", source)]) +} + +fn assert_edge(program: &Program, result: &AnalysisResult, caller: &str, callee: &str) { + assert!( + has_any_edge(program, result, caller, callee), + "missing edge from {caller} to {callee}" + ); +} + +#[test] +fn move_and_forward_spellings_preserve_flow_and_dispatch() { + let (p, a) = analyze( + r#" +namespace std { + template T&& move(T& t); + template T&& forward(T& t); +} +namespace s = std; +#define MOVED(x) std::move(x) +struct C { void f() {} }; +int *g; +int *qualified, *global, *parenthesized, *macro, *explicit_arg; +int *imported, *directive, *alias, *forwarded, *using_forward, *qualified_alias; +void spellings(C& c) { + qualified = std :: move(g); + global = ::std::move(g); + parenthesized = (std::move)(g); + macro = MOVED(g); + explicit_arg = std::move(g); + s::move(c).f(); +} +void imports(C& c) { + using std::move; + using s::forward; + imported = move(g); + using_forward = forward(g); + move(c).f(); +} +void directives(C& c) { + using namespace s; + directive = move(g); + forwarded = forward(g); + forward(c).f(); +} +namespace outer { namespace reexport = ::s; } +void qualified_aliases() { qualified_alias = ::outer::reexport::move(g); } +void aliases(C& c) { + alias = s::move(g); + s::forward(c).f(); +} +int *other; +namespace custom { int *move(int *p) { return other; } } +int *shadowed; +void ordinary() { + using namespace std; + using custom::move; + shadowed = move(g); +} +"#, + ); + for dst in [ + "qualified", + "global", + "parenthesized", + "macro", + "explicit_arg", + "imported", + "directive", + "alias", + "forwarded", + "using_forward", + "qualified_alias", + ] { + assert!( + p.flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst: d, src } + if p.symbols.variable(*d).name == dst && p.symbols.variable(*src).name == "g")), + "missing g -> {dst}" + ); + } + for caller in ["spellings", "imports", "directives", "aliases"] { + assert_edge(&p, &a, caller, "C::f"); + } + assert_edge(&p, &a, "ordinary", "custom::move"); + assert!(!p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == "shadowed" && p.symbols.variable(*src).name == "g"))); +} + +#[test] +fn explicit_template_arguments_type_the_receiver() { + let (p, a) = analyze( + r#" +struct B { void m() {} }; +struct D : B { void m() {} }; +void forwarded(D& d) { std::forward(d).m(); } +void moved(D& d) { std::move(d).m(); } +void cast(D& d) { std::move(static_cast(d)).m(); } +"#, + ); + for caller in ["forwarded", "moved", "cast"] { + assert_edge(&p, &a, caller, "B::m"); + assert!(!has_any_edge(&p, &a, caller, "D::m"), "{caller}"); + } +} + +#[test] +fn ref_qualified_member_edges_agree_with_return_flow() { + let (p, a) = analyze( + r#" +void lvalue() {} +void rvalue() {} +void first() {} +void second() {} +struct R { void (*visit)(); }; +struct S { void (*visit)(); }; +R r; +S s; +struct C { + R* f() & { lvalue(); return &r; } + S* f() && { rvalue(); return &s; } +}; +void prepare() { r.visit = first; s.visit = second; } +void moved(C& c) { auto x = std::move(c).f(); x->visit(); } +void forwarded(C& c) { auto x = std::forward(c).f(); x->visit(); } +void original(C& c) { auto x = c.f(); x->visit(); } +void forwarded_lvalue(C& c) { auto x = std::forward(c).f(); x->visit(); } +void array_lvalue(C (&c)[2]) { auto x = (*c).f(); x->visit(); } +void smart_lvalue(std::shared_ptr c) { auto x = (*c).f(); x->visit(); } +void comma_lvalue(C& c) { auto x = (c, c).f(); x->visit(); } +void assigned_lvalue(C& c) { auto x = (c = c).f(); x->visit(); } +void conditional_rvalue(C& c, bool b) { auto x = (b ? c : C{}).f(); x->visit(); } +C& uncertain(int); +C&& uncertain(long); +void unknown() { uncertain(untyped()).f(); } +"#, + ); + for (caller, qualifier, target, excluded) in [ + ("moved", true, "second", "first"), + ("forwarded", true, "second", "first"), + ("original", false, "first", "second"), + ("forwarded_lvalue", false, "first", "second"), + ("array_lvalue", false, "first", "second"), + ("smart_lvalue", false, "first", "second"), + ("comma_lvalue", false, "first", "second"), + ("assigned_lvalue", false, "first", "second"), + ("conditional_rvalue", true, "second", "first"), + ] { + let overloads: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == caller && target.name == "C::f") + .then_some(target.ref_qualifier) + }) + .collect(); + assert_eq!(overloads, [Some(qualifier)], "{caller}"); + assert_edge(&p, &a, caller, target); + assert!(!has_any_edge(&p, &a, caller, excluded), "{caller}"); + } + assert_eq!( + a.call_edges + .iter() + .filter(|edge| { + p.symbols.function(edge.caller).name == "unknown" + && p.symbols + .function_by_id(edge.callee) + .is_some_and(|f| f.name == "C::f") + }) + .count(), + 2 + ); +} + +fn assert_reference_target( + p: &Program, + a: &AnalysisResult, + caller: &str, + callee: &str, + rvalue: bool, +) { + let bindings: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let f = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == caller && f.name == callee).then(|| { + f.parameter_references + .first() + .copied() + .flatten() + .map(|r| r.rvalue) + }) + }) + .collect(); + assert_eq!(bindings, [Some(rvalue)], "{caller} -> {callee}"); +} + +#[test] +fn rvalue_arguments_select_free_functions_and_constructors() { + let (p, a) = analyze( + r#" +struct D {}; +void f(D&) {} +void f(D&&) {} +void free_function(D d) { f(std::move(d)); } +struct T { T(const T&); T(T&&); }; +void braced(T t) { T x{std::move(t)}; } +void direct(T t) { T x((std::move(t))); } +void heap(T t) { T* x = new T(std::move(t)); } +"#, + ); + assert_reference_target(&p, &a, "free_function", "f", true); + for caller in ["braced", "direct", "heap"] { + assert_reference_target(&p, &a, caller, "T::T", true); + } +} + +#[test] +fn copy_initialization_and_assignment_have_constructor_and_operator_edges() { + let (p, a) = analyze( + r#" +struct T { + T(const T&) {} + T(T&&) {} + T& operator=(const T&) { return *this; } + T& operator=(T&&) { return *this; } +}; +void copy(T t) { T x = t; } +void move(T t) { T x = std::move(t); } +void copy_assign(T a, T b) { a = b; } +void move_assign(T a, T b) { a = std::move(b); } +"#, + ); + for (caller, target, rvalue) in [ + ("copy", "T::T", false), + ("move", "T::T", true), + ("copy_assign", "T::operator=", false), + ("move_assign", "T::operator=", true), + ] { + assert_reference_target(&p, &a, caller, target, rvalue); + } +} + +#[test] +fn moved_parenthesized_and_cast_functors_dispatch() { + let (p, a) = analyze( + r#" +void target() {} +struct F { void operator()() { target(); } }; +void plain(F& f) { f(); } +void moved(F& f) { std::move(f)(); } +void enclosed(F& f) { (f)(); } +void cast(F& f) { static_cast(f)(); } +void pointer() { void (*cb)() = target; std::move(cb)(); } +void closure() { auto l = [] { target(); }; std::move(l)(); } +"#, + ); + for caller in ["plain", "moved", "enclosed", "cast"] { + assert_edge(&p, &a, caller, "F::operator()"); + } + assert_edge(&p, &a, "pointer", "target"); + assert!(a + .call_edges + .iter() + .any(|edge| p.symbols.function(edge.caller).name == "closure" + && p.symbols + .function_by_id(edge.callee) + .is_some_and(|f| f.name.contains("$lambda")))); +} + +#[test] +fn moved_from_values_remain_in_the_may_analysis() { + let (p, a) = analyze( + r#" +struct Obj { void ok() {} }; +void ownership() { + Obj object; + std::unique_ptr a = &object, b = std::move(a); + a->ok(); +} +void target() {} +void other() {} +struct H { void (*cb)(); }; +void fields() { + H a; + a.cb = target; + H b = std::move(a); + a.cb = other; + b.cb(); +} +"#, + ); + assert_edge(&p, &a, "ownership", "Obj::ok"); + assert_edge(&p, &a, "fields", "target"); + assert_edge(&p, &a, "fields", "other"); +} + +#[test] +fn move_and_forward_export_ordinary_edges_deterministically() { + let root = scratch(&[( + "move.cpp", + r#" +namespace std { template T&& forward(T& t) { return static_cast(t); } } +namespace s = std; +int *input, *output; +void run() { + using std::forward; + output = s::move(input); + output = forward(input); +} +"#, + )]); + let first = cli_analyze(root.path(), &["--jobs", "1"]); + let repeated = cli_analyze(root.path(), &["--jobs", "2"]); + let conn = rusqlite::Connection::open(first.path()).unwrap(); + let mut query = conn + .prepare( + "SELECT cs.callee_text, e.resolution + FROM raw_call_edges e + JOIN raw_call_sites cs ON cs.id = e.call_site_id + JOIN raw_functions f ON f.id = e.caller_fn_id + WHERE f.name = 'run' + ORDER BY cs.callee_text", + ) + .unwrap(); + let rows: Vec<(String, String)> = query + .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) + .unwrap() + .map(Result::unwrap) + .collect(); + assert_eq!( + rows, + [ + ("std::forward".to_owned(), "direct".to_owned()), + ("std::move".to_owned(), "external".to_owned()), + ] + ); + assert_eq!(analysis_rows(&first), analysis_rows(&repeated)); +} + +#[test] +fn deeply_nested_imported_moves_preserve_receiver_type() { + let nested = format!("{}object{}", "move(".repeat(32), ")".repeat(32)); + let (p, a) = analyze(&format!( + "struct C {{ void f() {{}} }}; void nested(C& object) {{ using std::move; {nested}.f(); }}" + )); + assert_edge(&p, &a, "nested", "C::f"); +} + +#[test] +fn receiver_viability_precedes_argument_binding_preference() { + let (p, a) = analyze( + r#" +struct T {}; +struct L { void visit_left() {} }; +struct R { void visit_right() {} }; +struct C { + R* f(T&&) &&; + L* f(const T&) const &; + void implicit(T& t) const { f(std::move(t))->visit_left(); } +}; +struct Derived : C { + void qualified(T& t) const { C::f(std::move(t))->visit_left(); } + void global_qualified(T& t) const { ::C::f(std::move(t))->visit_left(); } +}; +void run(const C& c, T& t) { c.f(std::move(t))->visit_left(); } +namespace n { + struct Base { + R* f(T&&) &&; + L* f(const T&) const &; + }; + struct Derived : Base { + void qualified(T& t) const { Base::f(std::move(t))->visit_left(); } + }; +} +"#, + ); + assert_reference_target(&p, &a, "run", "C::f", false); + assert_edge(&p, &a, "run", "L::visit_left"); + assert_reference_target(&p, &a, "C::implicit", "C::f", false); + assert_edge(&p, &a, "C::implicit", "L::visit_left"); + assert_reference_target(&p, &a, "Derived::qualified", "C::f", false); + assert_edge(&p, &a, "Derived::qualified", "L::visit_left"); + assert_reference_target(&p, &a, "Derived::global_qualified", "C::f", false); + assert_edge(&p, &a, "Derived::global_qualified", "L::visit_left"); + assert_reference_target(&p, &a, "n::Derived::qualified", "n::Base::f", false); + assert_edge(&p, &a, "n::Derived::qualified", "L::visit_left"); +} + +#[test] +fn unresolved_forwarded_receiver_keeps_overloads_for_both_categories() { + let (p, a) = analyze( + r#" +struct A {}; +struct C { + void f(const A&) &; + void f(A&&) &&; +}; +template +void run(C& c, A& a) { std::forward(c).f(std::move(a)); } +"#, + ); + let mut categories: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function(edge.callee); + (p.symbols.function(edge.caller).name == "run" && target.name == "C::f") + .then_some(target.ref_qualifier) + .flatten() + }) + .collect(); + categories.sort_unstable(); + assert_eq!(categories, [false, true]); +} + +#[test] +fn dependent_receiver_keeps_candidates_for_each_cv_and_reference_category() { + let (p, a) = analyze( + r#" +struct B {}; +struct D : B {}; +struct A {}; +struct C { + void f(const B&) &; + void f(D&&) &&; + void g(A&&) &; + void g(const A&) const &; +}; +template +void category(C& c, D& d) { std::forward(c).f(std::move(d)); } +template +void qualification(C& c, A& a) { std::forward(c).g(std::move(a)); } +"#, + ); + for (caller, method) in [("category", "C::f"), ("qualification", "C::g")] { + let mut bindings: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function(edge.callee); + (p.symbols.function(edge.caller).name == caller && target.name == method) + .then(|| target.parameter_references[0].unwrap().rvalue) + }) + .collect(); + bindings.sort_unstable(); + assert_eq!(bindings, [false, true], "{caller}"); + } +} + +#[test] +fn virtual_move_calls_rank_the_static_overload_set() { + let (p, a) = analyze( + r#" +struct A {}; +struct B : A {}; +struct Base { + virtual void f(const A&) & {} +}; +struct Derived : Base { + void f(const A&) & override {} + void f(B&&) & {} +}; +void run(Base& base, B& b) { base.f(std::move(b)); } +"#, + ); + let mut owners: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function(edge.callee); + if p.symbols.function(edge.caller).name == "run" + && matches!(target.name.as_str(), "Base::f" | "Derived::f") + { + assert!(!target.parameter_references[0].unwrap().rvalue); + Some(target.name.as_str()) + } else { + None + } + }) + .collect(); + owners.sort_unstable(); + assert_eq!(owners, ["Base::f", "Derived::f"]); +} + +#[test] +fn reference_ranking_applies_to_base_subobjects() { + let (p, a) = analyze( + r#" +struct A {}; +struct B : A {}; +void take(A&); +void take(A&&); +void run(B& b) { take(std::move(b)); } +"#, + ); + assert_reference_target(&p, &a, "run", "take", true); +} + +#[test] +fn forwarded_receiver_alternatives_survive_ordinary_arguments() { + let (p, a) = analyze( + r#" +struct B {}; +struct D : B {}; +struct C { + void f(const B&) &; + void f(D&) &&; +}; +struct Wrapper { C field; }; +template +void conditional(bool flag, C& lhs, C& rhs, D& d) { + (flag ? std::forward(lhs) : std::forward(rhs)).f(d); +} +template +void member(Wrapper& wrapper, D& d) { std::forward(wrapper).field.f(d); } +template +void run(C& c, D& d) { std::forward(c).f(d); } +template +void comma(C& c, D& d) { (static_cast(0), std::forward(c)).f(d); } +"#, + ); + for caller in ["run", "comma", "member", "conditional"] { + let mut categories: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function(edge.callee); + (p.symbols.function(edge.caller).name == caller && target.name == "C::f") + .then_some(target.ref_qualifier) + .flatten() + }) + .collect(); + categories.sort_unstable(); + assert_eq!(categories, [false, true], "{caller}"); + } +} + +#[test] +fn default_arguments_follow_the_receiver_selected_overload() { + let (p, a) = analyze( + r#" +struct B {}; +struct D : B {}; +int left_default(); +int right_default(); +struct C { + void f(const B&, int = left_default()) &; + void f(D&&, int = right_default()) &&; +}; +void run(C& c, D& d) { c.f(std::move(d)); } +"#, + ); + assert_reference_target(&p, &a, "run", "C::f", false); + assert_edge(&p, &a, "run", "left_default"); + assert!(!has_any_edge(&p, &a, "run", "right_default")); +} + +#[test] +fn global_adl_candidate_keeps_its_ordinary_call_and_return() { + let (p, a) = analyze( + r#" +struct T {}; +T* other; +T* move(T*) { return other; } +T* out; +void run(T* in) { + using std::move; + out = move(in); +} +"#, + ); + assert_edge(&p, &a, "run", "move"); + assert!(!has_any_edge(&p, &a, "run", "std::move")); + assert!(!p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == "out" && p.symbols.variable(*src).name == "in"))); +} + +#[test] +fn adl_uses_class_and_enum_template_argument_namespaces() { + let (p, a) = analyze( + r#" +template struct Box {}; +namespace app { + struct Tag {}; + Box* move(Box*); +} +namespace enums { + enum class E {}; + Box* move(Box*); +} +Box* out; +Box* enum_out; +void run(Box* in) { + using std::move; + out = move(in); +} +void dereference(Box** in) { + using std::move; + out = move(*in); +} +void address_of(Box& in) { + using std::move; + out = move(&in); +} +void enum_argument(Box* in) { + using std::move; + enum_out = move(in); +} +"#, + ); + for (caller, callee) in [ + ("run", "app::move"), + ("dereference", "app::move"), + ("address_of", "app::move"), + ("enum_argument", "enums::move"), + ] { + assert_edge(&p, &a, caller, callee); + assert!(!has_any_edge(&p, &a, caller, "std::move")); + } + assert!(!p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if matches!(p.symbols.variable(*dst).name.as_str(), "out" | "enum_out") + && p.symbols.variable(*src).name == "in"))); +} + +#[test] +fn mutable_lvalue_reference_adl_candidate_cannot_bind_an_xvalue_pointer() { + let (p, a) = analyze( + r#" +namespace app { + struct T {}; + T* move(T*&); +} +app::T* out; +void run(app::T* in) { + using std::move; + out = move(static_cast(in)); +} +void lvalue(app::T* in) { + using std::move; + move(in); +} +"#, + ); + assert_edge(&p, &a, "run", "std::move"); + assert!(!has_any_edge(&p, &a, "run", "app::move")); + assert!(p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == "out" && p.symbols.variable(*src).name == "in"))); + assert_edge(&p, &a, "lvalue", "app::move"); +} + +#[test] +fn rvalue_reference_adl_candidate_cannot_bind_a_named_pointer() { + let (p, a) = analyze( + r#" +namespace app { + struct T {}; + T* move(T*&&); +} +app::T* out; +void run(app::T* in) { + using std::move; + out = move(in); +} +void rvalue(app::T* in) { + using std::move; + move(static_cast(in)); +} +"#, + ); + assert_edge(&p, &a, "run", "std::move"); + assert!(!has_any_edge(&p, &a, "run", "app::move")); + assert!(p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == "out" && p.symbols.variable(*src).name == "in"))); + assert_edge(&p, &a, "rvalue", "app::move"); +} + +#[test] +fn conditional_base_glvalue_invokes_copy_constructor() { + let (p, a) = analyze( + r#" +struct B { B(); B(const B&); B(B&&); }; +struct D : B {}; +void run(bool flag, B& b, D& d) { B x = flag ? b : d; } +"#, + ); + assert_reference_target(&p, &a, "run", "B::B", false); +} + +#[test] +fn adl_candidates_prevent_an_imported_move_from_becoming_an_identity() { + let (p, a) = analyze( + r#" +namespace std { template T&& move(T&); } +namespace app { + struct T {}; + T* other; + T* move(T*) { return other; } +} +app::T* dst; +void run(app::T* src) { + using std::move; + dst = move(src); +} +"#, + ); + assert_edge(&p, &a, "run", "app::move"); + assert!(!p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == "dst" && p.symbols.variable(*src).name == "src"))); +} + +#[test] +fn nearer_types_shadow_the_standard_namespace() { + let (p, a) = analyze( + r#" +namespace app { + struct std { static int* move(int* p) { return p; } }; + int* shadowed; + int* standard; + void shadow(int* src) { shadowed = std::move(src); } + void global(int* src) { standard = ::std::move(src); } +} +"#, + ); + assert_edge(&p, &a, "app::shadow", "app::std::move"); + assert!(!has_any_edge(&p, &a, "app::shadow", "std::move")); + let copies_from_src = |name| { + p.flow.iter().any(|flow| { + matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == name && p.symbols.variable(*src).name == "src") + }) + }; + assert!(!copies_from_src("shadowed")); + assert!(copies_from_src("standard")); +} + +#[test] +fn selected_move_overload_supplies_return_constness() { + let (p, a) = analyze( + r#" +struct T {}; +struct C { void f() &; void f() const &; }; +C& get(T&); +const C& get(T&&); +void run(T& t) { get(std::move(t)).f(); } +"#, + ); + assert_reference_target(&p, &a, "run", "get", true); + let constness: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let f = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == "run" && f.name == "C::f") + .then_some(f.is_const_member) + }) + .collect(); + assert_eq!(constness, [true]); +} + +#[test] +fn explicit_move_constructors_are_eligible_only_for_direct_initialization() { + let (p, a) = analyze( + r#" +struct T { + T(const T&) {} + explicit T(T&&); +}; +T::T(T&&) {} +struct U { + U(const U&) {} + explicit(false) U(U&&) {} +}; +struct V { + V(const V&) {} + explicit(true) V(V&&) {} +}; +void copy(T& t) { T x = std::move(t); } +void direct(T& t) { T x((std::move(t))); } +void implicit_condition(U& u) { U x = std::move(u); } +void explicit_condition(V& v) { V x = std::move(v); } +"#, + ); + for (caller, name, rvalue) in [ + ("copy", "T::T", false), + ("direct", "T::T", true), + ("implicit_condition", "U::U", true), + ("explicit_condition", "V::V", false), + ] { + assert_reference_target(&p, &a, caller, name, rvalue); + } +} + +#[test] +fn forwarding_lvalues_and_preserving_mutable_referents_narrows_overloads() { + let (p, a) = analyze( + r#" +struct T {}; +void choose(T&); +void choose(T&&); +void cv_lvalue(T&); +void cv_lvalue(const T&); +void cv_rvalue(T&&); +void cv_rvalue(const T&&); +void forwarded(T& t) { choose(std::forward(t)); } +void forwarded_cv(T& t) { cv_lvalue(std::forward(t)); } +void moved(T& t) { cv_rvalue(std::move(t)); } +void moved_const(const T& t) { cv_rvalue(std::move(t)); } +"#, + ); + assert_reference_target(&p, &a, "forwarded", "choose", false); + for (caller, callee, rvalue, is_const) in [ + ("forwarded_cv", "cv_lvalue", false, false), + ("moved", "cv_rvalue", true, false), + ("moved_const", "cv_rvalue", true, true), + ] { + assert_reference_target(&p, &a, caller, callee, rvalue); + let target = a + .call_edges + .iter() + .find_map(|edge| { + let f = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == caller && f.name == callee).then_some(f) + }) + .unwrap(); + assert_eq!( + target.parameter_references[0].unwrap().is_const, + Some(is_const), + "{caller}" + ); + } +} + +#[test] +fn reference_initialization_does_not_construct_an_object() { + let (p, a) = analyze( + r#" +struct T { T(const T&) {} T(T&&) {} }; +using Ref = T&; +void bind(T& t) { + T& lvalue = t; + T&& rvalue = std::move(t); + Ref collapsed = t; +} +"#, + ); + assert!(!has_any_edge(&p, &a, "bind", "T::T")); +} + +#[test] +fn copy_initialization_uses_glvalue_category() { + let (p, a) = analyze( + r#" +struct T { T(); T(const T&) {} T(T&&) {} }; +struct Box { T field; }; +T& get_ref(); +T&& get_rvalue_ref(); +T produce(); +void field(Box& box) { T copy = box.field; } +void reference() { T copy = get_ref(); } +void rvalue_reference() { T copy = get_rvalue_ref(); } +void dereference(T* p) { T copy = *p; } +void conditional(T& a, T& b, bool c) { T copy = c ? a : b; } +void value() { T copy = produce(); } +void mixed(T& a, bool c) { T copy = c ? a : produce(); } +"#, + ); + for caller in ["field", "reference", "dereference", "conditional"] { + assert_reference_target(&p, &a, caller, "T::T", false); + } + assert_reference_target(&p, &a, "rvalue_reference", "T::T", true); + for caller in ["value", "mixed"] { + assert!(!has_any_edge(&p, &a, caller, "T::T"), "{caller}"); + } +} + +#[test] +fn move_and_forward_imports_use_the_lexical_namespace_alias() { + let (p, a) = analyze( + r#" +struct Input { void run() {} }; +struct Output { void run() {} }; +namespace custom { + Output move(Input&); + Output forward(Input&); +} +namespace app { + namespace std = custom; + void local_move(Input& x) { using std::move; move(x).run(); } + void local_forward(Input& x) { using std::forward; forward(x).run(); } + void directive(Input& x) { using namespace std; move(x).run(); } + void standard(Input& x) { using ::std::move; move(x).run(); } +} +"#, + ); + for (caller, callee) in [ + ("app::local_move", "custom::move"), + ("app::local_forward", "custom::forward"), + ("app::directive", "custom::move"), + ] { + assert_edge(&p, &a, caller, callee); + assert_edge(&p, &a, caller, "Output::run"); + assert!(!has_any_edge(&p, &a, caller, "Input::run")); + assert!(!has_any_edge(&p, &a, caller, "std::move")); + assert!(!has_any_edge(&p, &a, caller, "std::forward")); + } + assert_edge(&p, &a, "app::standard", "Input::run"); +} + +#[test] +fn parenthesized_move_and_forward_suppress_adl() { + let (p, a) = analyze( + r#" +namespace std { + template T&& move(T&); + template T&& forward(T&); +} +namespace app { + struct T { void run() {} }; + struct Other { void run() {} }; + Other move(T&); + template Other forward(T&); +} +void moved(app::T& x) { using std::move; (move)(x).run(); } +void forwarded(app::T& x) { using std::forward; (forward)(x).run(); } +"#, + ); + for (caller, callee) in [("moved", "app::move"), ("forwarded", "app::forward")] { + assert_edge(&p, &a, caller, "app::T::run"); + assert!(!has_any_edge(&p, &a, caller, callee)); + assert!(!has_any_edge(&p, &a, caller, "app::Other::run")); + } +} + +#[test] +fn forward_recovers_the_referent_of_a_reference_alias() { + let (p, a) = analyze( + r#" +struct T {}; +using Ref = T&; +void choose(T&); +void choose(T&&); +void test(T& obj) { choose(std::forward(obj)); } +"#, + ); + assert_reference_target(&p, &a, "test", "choose", false); +} + +#[test] +fn overload_parameters_use_collapsed_reference_categories() { + let (p, a) = analyze( + r#" +struct T {}; +using Ref = T&; +void choose(Ref&&); +void choose(const T&); +void test(T& obj) { choose(std::forward(obj)); } +"#, + ); + assert_reference_target(&p, &a, "test", "choose", false); + let target = a + .call_edges + .iter() + .find_map(|edge| { + let target = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == "test" && target.name == "choose") + .then_some(target) + }) + .unwrap(); + assert_eq!( + target.parameter_references[0].unwrap().is_const, + Some(false) + ); +} + +#[test] +fn class_assignment_skips_unrelated_overloads() { + let (p, a) = analyze( + r#" +struct A {}; +struct Handle { Handle& operator=(A*); }; +struct Mixed { + Mixed& operator=(A*); + Mixed& operator=(const Mixed&); +}; +struct H { + H& operator=(const H&) = default; + H& operator=(H&& value) { return *this; } +}; +void defaulted_copy(H& a, H& b) { a = b; } +void explicit_move(H& a, H& b) { a = std::move(b); } +void implicit_copy(Handle& a, Handle& b) { a = b; } +void explicit_copy(Mixed& a, Mixed& b) { a = b; } +"#, + ); + assert!(!has_any_edge(&p, &a, "implicit_copy", "Handle::operator=")); + assert_reference_target(&p, &a, "explicit_copy", "Mixed::operator=", false); + assert!(!has_any_edge(&p, &a, "defaulted_copy", "H::operator=")); + assert_reference_target(&p, &a, "explicit_move", "H::operator=", true); +} + +#[test] +fn forwarding_resolves_decltype_and_keeps_unknown_categories() { + let (p, a) = analyze( + r#" +struct Q { void f() &; void f() &&; }; +void declared_reference(Q& q) { std::forward(q).f(); } +void declared_rvalue_reference(Q&& q) { std::forward(q).f(); } +void parenthesized_reference(Q&& q) { std::forward(q).f(); } +void local_reference(Q& obj) { Q& q = obj; std::forward(q).f(); } +void local_rvalue_reference(Q&& obj) { + Q&& q = std::move(obj); std::forward(q).f(); +} +void unresolved(Q& q) { std::forward(q).f(); } +template +void dependent(Q& q) { std::forward(q).f(); } +"#, + ); + for (caller, expected) in [ + ("declared_reference", vec![false]), + ("declared_rvalue_reference", vec![true]), + ("parenthesized_reference", vec![false]), + ("local_reference", vec![false]), + ("local_rvalue_reference", vec![true]), + ("unresolved", vec![false, true]), + ("dependent", vec![false, true]), + ] { + let mut categories: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let function = p.symbols.function_by_id(edge.callee)?; + (function.name == "Q::f" && p.symbols.function(edge.caller).name == caller) + .then_some(function.ref_qualifier) + .flatten() + }) + .collect(); + categories.sort_unstable(); + assert_eq!(categories, expected, "{caller}"); + } +} + +#[test] +fn forwarding_through_decltype_preserves_constness() { + let (p, a) = analyze( + r#" +struct Q { void f() &; void f() const &; }; +void declared(const Q& q) { std::forward(q).f(); } +void parenthesized(const Q& q) { std::forward(q).f(); } +void qualified(Q q) { std::forward(q).f(); } +struct D : Q { void f() &; }; +void base(Q& q, D& d) { std::forward(d).f(); } +"#, + ); + for caller in ["declared", "parenthesized", "qualified"] { + let targets: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function(edge.callee); + (p.symbols.function(edge.caller).name == caller && target.name == "Q::f") + .then_some(target.is_const_member) + }) + .collect(); + assert_eq!(targets, [true], "{caller}"); + } + assert_edge(&p, &a, "base", "Q::f"); + assert!(!has_any_edge(&p, &a, "base", "D::f")); +} + +#[test] +fn explicit_forward_ignores_non_template_adl_overloads() { + let (p, a) = analyze( + r#" +namespace app { + struct T { void f() {}; }; + int forward(T&); +} +void non_template(app::T& x) { + using std::forward; + forward(x).f(); +} +namespace other { + struct T {}; + struct U {}; + template U forward(T&); +} +void template_competitor(other::T& x) { + using std::forward; + forward(x); +} +"#, + ); + assert_edge(&p, &a, "non_template", "std::forward"); + assert_edge(&p, &a, "non_template", "app::T::f"); + assert!(!has_any_edge(&p, &a, "non_template", "app::forward")); + assert_edge(&p, &a, "template_competitor", "other::forward"); +} + +#[test] +fn pointer_reference_parameters_keep_their_overload_identity() { + let (p, a) = analyze( + r#" +struct Q {}; +void take(Q*&); +void take(Q*&&); +void lvalue(Q* p) { take(std::forward(p)); } +void rvalue(Q* p) { take(std::move(p)); } +void take(Q*& p) {} +void take(Q*&& p) {} +"#, + ); + assert_reference_target(&p, &a, "lvalue", "take", false); + assert_reference_target(&p, &a, "rvalue", "take", true); +} + +#[test] +fn pointer_reference_overloads_keep_pointee_constness() { + let (p, a) = analyze( + r#" +struct Q {}; +void take(Q*&&) {} +void take(const Q*&&) {} +void mutable_pointee(Q* p) { take(std::move(p)); } +void const_pointee(const Q* p) { take(std::move(p)); } +"#, + ); + for (caller, is_const) in [("mutable_pointee", false), ("const_pointee", true)] { + let targets: Vec<_> = a + .call_edges + .iter() + .filter(|edge| { + p.symbols.function(edge.caller).name == caller + && p.symbols.function(edge.callee).name == "take" + }) + .map(|edge| { + p.symbols.function(edge.callee).parameter_references[0] + .unwrap() + .pointee_const + }) + .collect(); + assert_eq!(targets, [Some(is_const)], "{caller}"); + } +} + +#[test] +fn local_move_import_hides_a_global_variable() { + let (p, a) = analyze( + r#" +int move; +int* out; +void run(int* p) { + using std::move; + out = move(p); +} +"#, + ); + assert_edge(&p, &a, "run", "std::move"); + assert!(p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == "out" && p.symbols.variable(*src).name == "p"))); +} + +#[test] +fn wrong_arity_adl_overloads_keep_the_standard_identity() { + let (p, a) = analyze( + r#" +namespace app { + struct T {}; + T* move(T*&, int); + T* forward(T*&, int); +} +app::T* moved; +app::T* forwarded; +void run(app::T* src) { + using std::move; + using std::forward; + moved = move(src); + forwarded = forward(src); +} +"#, + ); + assert_edge(&p, &a, "run", "std::move"); + assert_edge(&p, &a, "run", "std::forward"); + for name in ["moved", "forwarded"] { + assert!(p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == name && p.symbols.variable(*src).name == "src"))); + } +} + +#[test] +fn unrelated_adl_pointer_parameter_keeps_the_standard_move_identity() { + let (p, a) = analyze( + r#" +namespace app { + struct T {}; + struct U {}; + T* move(U*); +} +app::T* out; +void run(app::T* in) { + using std::move; + out = move(in); +} +"#, + ); + assert_edge(&p, &a, "run", "std::move"); + assert!(!has_any_edge(&p, &a, "run", "app::move")); + assert!(p + .flow + .iter() + .any(|flow| matches!(flow, FlowConstraint::Copy { dst, src } + if p.symbols.variable(*dst).name == "out" && p.symbols.variable(*src).name == "in"))); +} + +#[test] +fn namespace_aliases_expand_each_qualified_component() { + let (p, a) = analyze( + r#" +struct Q { void f() {} }; +namespace outer { namespace alias = std; } +namespace other = outer; +void qualified(Q& q) { other::alias::move(q).f(); } +void imported(Q& q) { using ::other::alias::forward; forward(q).f(); } +"#, + ); + assert_edge(&p, &a, "qualified", "std::move"); + assert_edge(&p, &a, "imported", "std::forward"); + for caller in ["qualified", "imported"] { + assert_edge(&p, &a, caller, "Q::f"); + } +} + +#[test] +fn moving_scalar_literals_preserves_their_argument_type() { + let (p, a) = analyze( + r#" +void take(int&); +void take(int&&); +void qualified() { take(std::move(1)); } +void imported() { using std::move; take(move(1)); } +"#, + ); + for caller in ["qualified", "imported"] { + assert_reference_target(&p, &a, caller, "take", true); + } +} + +#[test] +fn pointer_values_and_references_have_distinct_declarations() { + let (p, _) = analyze( + r#" +struct T {}; +void one(T*); +void one(T*&&); +void two(T*&, T*); +void two(T*&, T*&&); +void one(T*&&) {} +void two(T*&, T*&&) {} +"#, + ); + for (name, slot) in [("one", 0), ("two", 1)] { + let functions: Vec<_> = p + .symbols + .functions + .iter() + .filter(|f| f.name == name) + .collect(); + assert_eq!(functions.len(), 2, "{functions:?}"); + let defined = functions.iter().find(|f| f.is_defined).unwrap(); + assert!(defined.parameter_references[slot].unwrap().rvalue); + let declared = functions.iter().find(|f| !f.is_defined).unwrap(); + assert!(declared.parameter_references.get(slot).is_none()); + } +} + +#[test] +fn member_edges_rank_known_arguments_alongside_unknown_arguments() { + let (p, a) = analyze( + r#" +struct T {}; +struct C { + void f(T&&, int, int) & {} + void f(T&&, int, double) & {} + void implicit(T& t) { f(std::move(t), opaque(), 5); } + void qualified(T& t) { C::f(std::move(t), opaque(), 5); } +}; +void explicit_receiver(C& c, T& t) { c.f(std::move(t), opaque(), 5); } +"#, + ); + for caller in ["explicit_receiver", "C::implicit", "C::qualified"] { + let lines: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let f = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == caller && f.name == "C::f") + .then_some(f.span.line) + }) + .collect(); + assert_eq!(lines, [4], "{caller}"); + } +} + +#[test] +fn copy_initialization_does_not_emit_bodyless_constructor_calls() { + let (p, a) = analyze( + r#" +struct T { + T(const T&) {} + T(T&&) = default; +}; +struct U { + U(const U&) = default; + U(U&&) {} +}; +void defaulted_move(T& x) { T y = std::move(x); } +void written_copy(T& x) { T y = x; } +void defaulted_copy(U& x) { U y = x; } +void written_move(U& x) { U y = std::move(x); } +"#, + ); + for (caller, ctor) in [("defaulted_move", "T::T"), ("defaulted_copy", "U::U")] { + assert!(!has_any_edge(&p, &a, caller, ctor)); + assert!(!p + .symbols + .call_sites + .iter() + .any(|s| { p.symbols.function(s.caller).name == caller && s.callee_name == ctor })); + } + assert_reference_target(&p, &a, "written_copy", "T::T", false); + assert_reference_target(&p, &a, "written_move", "U::U", true); +} + +#[test] +fn reference_parameters_preserve_alias_qualification() { + let (p, a) = analyze( + r#" +using I = int; +using CI = const int; +using Ptr = int*; +using CPtr = int* const; +void take(I&) {} +void take(const I&) {} +void same(I&); +void same(CI&) {} +void pointer(Ptr&) {} +void pointer(CPtr&) {} +void nested(Ptr*&) {} +void run(I& x, const I& cx, Ptr p, CPtr cp) { + take(std::forward(x)); + take(std::forward(cx)); + pointer(std::forward(p)); + pointer(std::forward(cp)); +} +"#, + ); + for name in ["take", "same", "pointer"] { + let mut qualifiers: Vec<_> = p + .symbols + .functions + .iter() + .filter(|f| f.name == name) + .map(|f| f.parameter_references[0].unwrap().is_const) + .collect(); + qualifiers.sort(); + assert_eq!(qualifiers, [Some(false), Some(true)], "{name}"); + } + for (line, expected) in [(14, false), (15, true), (16, false), (17, true)] { + let form: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let site = p.symbols.call_site_by_id(edge.call_site)?; + let f = p.symbols.function_by_id(edge.callee)?; + (site.span.line == line && matches!(f.name.as_str(), "take" | "pointer")) + .then(|| f.parameter_references[0].unwrap().is_const) + }) + .collect(); + assert_eq!(form, [Some(expected)], "line {line}"); + } + let nested = p + .symbols + .functions + .iter() + .find(|f| f.name == "nested") + .unwrap(); + assert_eq!(nested.parameter_references[0].unwrap().pointee_const, None); +} + +#[test] +fn forwarding_with_decltype_of_auto_rvalue_reference_uses_collapsed_binding() { + let (p, a) = analyze( + r#" +struct T { + T(const T&) {} + T(T&&) {} + void f() & {} + void f() && {} +}; +void sink(T&) {} +void sink(T&&) {} +void from_lvalue(T& t) { + auto&& r = t; + std::forward(r).f(); + sink(std::forward(r)); + T copy = std::forward(r); +} +void from_rvalue(T& t) { + auto&& r = std::move(t); + std::forward(r).f(); + sink(std::forward(r)); + T moved = std::forward(r); +} +"#, + ); + for (caller, rvalue) in [("from_lvalue", false), ("from_rvalue", true)] { + assert_reference_target(&p, &a, caller, "sink", rvalue); + assert_reference_target(&p, &a, caller, "T::T", rvalue); + let categories: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let f = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == caller && f.name == "T::f") + .then_some(f.ref_qualifier) + }) + .collect(); + assert_eq!(categories, [Some(rvalue)], "{caller}"); + } +} + +#[test] +fn respelled_internal_declarations_only_match_their_own_reference_overload() { + let (p, a) = analyze( + r#" +struct T {}; +static void take(const T&); +static void take(T&&) {} +void run(const T& t) { take(std::forward(t)); } +"#, + ); + let overloads: Vec<_> = p + .symbols + .functions + .iter() + .filter(|f| f.name == "take") + .collect(); + assert_eq!(overloads.len(), 2, "{overloads:?}"); + assert_reference_target(&p, &a, "run", "take", false); +} + +#[test] +fn template_reference_parameters_shadow_outer_type_aliases() { + let (p, _) = analyze( + r#" +using P = const int; +using R = int&; +template void same(P&); +template void same(Q&) {} +template void move_only(R&&); +template void move_only(Q&&) {} +"#, + ); + for (name, rvalue) in [("same", false), ("move_only", true)] { + let overloads: Vec<_> = p + .symbols + .functions + .iter() + .filter(|f| f.name == name) + .collect(); + assert_eq!(overloads.len(), 1, "{overloads:?}"); + assert!(overloads[0].is_defined); + assert_eq!(overloads[0].parameter_references[0].unwrap().rvalue, rvalue); + } +} + +#[test] +fn implicitly_deleted_defaulted_move_preserves_copy_edge() { + let (p, a) = analyze( + r#" +struct Member { + Member(const Member&) {} + Member(Member&&) = delete; +}; +struct Owner { + Member items[2]; + Owner(const Owner& other) : items{other.items[0], other.items[1]} {} + Owner(Owner&&) = default; +}; +struct Derived : Member { + Derived(const Derived& other) : Member(other) {} + Derived(Derived&&) = default; +}; +struct Simple { int value; }; +struct Movable { + Simple member; + Movable(const Movable&) {} + Movable(Movable&&) = default; +}; +struct Deleted { + Member member; + Deleted(const Deleted& other) : member(other.member) {} + Deleted(Deleted&&) = delete; +}; +void copy_member(Owner& owner) { Owner dst = std::move(owner); } +void copy_base(Derived& derived) { Derived dst = std::move(derived); } +void simple_move(Movable& movable) { Movable dst = std::move(movable); } +// Keep the explicitly deleted overload in selection for this ill-formed call. +void explicit_delete(Deleted& deleted) { Deleted dst = std::move(deleted); } +"#, + ); + assert_reference_target(&p, &a, "copy_member", "Owner::Owner", false); + assert_reference_target(&p, &a, "copy_base", "Derived::Derived", false); + assert!(!has_any_edge(&p, &a, "simple_move", "Movable::Movable")); + assert!(!has_any_edge(&p, &a, "explicit_delete", "Deleted::Deleted")); +} + +#[test] +fn move_assignment_can_delete_a_subobjects_implicit_constructors() { + let (p, a) = analyze( + r#" +struct Member { Member& operator=(Member&&) = default; }; +struct Owner { + Member member; + Owner(const Owner&) {} + Owner(Owner&&) = default; +}; +void copy(Owner& owner) { Owner dst = std::move(owner); } +"#, + ); + assert_reference_target(&p, &a, "copy", "Owner::Owner", false); +} + +#[test] +fn defaulted_move_checks_each_shared_subobject_layout_once() { + let mut source = String::from("struct N0 { char data; };\n"); + for depth in 1..=28 { + let child = depth - 1; + source.push_str(&format!("struct N{depth} {{ N{child} left, right; }};\n")); + } + source.push_str( + "struct Owner { + N28 member; + Owner(const Owner&) {} + Owner(Owner&&) = default; + }; + void run(Owner& owner) { Owner dst = std::move(owner); }", + ); + let started = std::time::Instant::now(); + let (p, a) = analyze(&source); + assert!( + started.elapsed() < std::time::Duration::from_secs(10), + "repeated subobject layout checks took {:?}", + started.elapsed() + ); + assert_edge(&p, &a, "run", "std::move"); + assert!(!has_any_edge(&p, &a, "run", "Owner::Owner")); +} + +#[test] +fn const_subobjects_need_a_viable_copy_to_use_a_defaulted_move() { + let (p, a) = analyze( + r#" +int value; +struct Member { int&& reference; }; +struct Owner { + const Member member; + Owner(const Owner&) : member{static_cast(value)} {} + Owner(Owner&&) = default; +}; +struct Movable { + Member member; + Movable(const Movable&) : member{static_cast(value)} {} + Movable(Movable&&) = default; +}; +void copy(Owner& owner) { Owner dst = std::move(owner); } +void move(Movable& owner) { Movable dst = std::move(owner); } +"#, + ); + assert_reference_target(&p, &a, "copy", "Owner::Owner", false); + assert!(!has_any_edge(&p, &a, "move", "Movable::Movable")); +} + +#[test] +fn volatile_class_subobjects_can_delete_a_defaulted_move() { + let (p, a) = analyze( + r#" +struct Member { int n; }; +struct Owner { + volatile Member member; + Owner(const Owner&) : member{} {} + Owner(Owner&&) = default; +}; +struct ArrayOwner { + Member volatile members[2]; + ArrayOwner(const ArrayOwner&) : members{} {} + ArrayOwner(ArrayOwner&&) = default; +}; +struct Movable { + volatile Member* pointer; + volatile int scalar; + Movable(const Movable&) : pointer{}, scalar{} {} + Movable(Movable&&) = default; +}; +void copy(Owner& owner) { Owner dst = std::move(owner); } +void copy_array(ArrayOwner& owner) { ArrayOwner dst = std::move(owner); } +void move(Movable& owner) { Movable dst = std::move(owner); } +"#, + ); + assert_reference_target(&p, &a, "copy", "Owner::Owner", false); + assert_reference_target(&p, &a, "copy_array", "ArrayOwner::ArrayOwner", false); + assert!(!has_any_edge(&p, &a, "move", "Movable::Movable")); +} + +#[test] +fn volatile_class_aliases_can_delete_a_defaulted_move() { + let (p, a) = analyze( + r#" +struct Member { int n; }; +using V = volatile Member; +typedef V Alias; +using Pointer = V*; +struct Owner { + V member; + Owner(const Owner&) : member{} {} + Owner(Owner&&) = default; +}; +struct ArrayOwner { + Alias members[2]; + ArrayOwner(const ArrayOwner&) : members{} {} + ArrayOwner(ArrayOwner&&) = default; +}; +struct Movable { + Pointer pointer; + Movable(const Movable&) : pointer{} {} + Movable(Movable&&) = default; +}; +void copy(Owner& owner) { Owner dst = std::move(owner); } +void copy_array(ArrayOwner& owner) { ArrayOwner dst = std::move(owner); } +void move(Movable& owner) { Movable dst = std::move(owner); } +"#, + ); + assert_reference_target(&p, &a, "copy", "Owner::Owner", false); + assert_reference_target(&p, &a, "copy_array", "ArrayOwner::ArrayOwner", false); + assert!(!has_any_edge(&p, &a, "move", "Movable::Movable")); +} + +#[test] +fn copy_assignment_can_suppress_a_subobject_move() { + let (p, a) = analyze( + r#" +int value; +struct Member { + int&& ref; + Member& operator=(const Member&) = delete; +}; +struct Owner { + Member member; + Owner(const Owner&) : member{static_cast(value)} {} + Owner(Owner&&) = default; +}; +struct Copyable { + int n; + Copyable& operator=(const Copyable&) = delete; +}; +struct Movable { + Copyable member; + Movable(const Movable&) : member{} {} + Movable(Movable&&) = default; +}; +void copy(Owner& owner) { Owner dst = std::move(owner); } +void move(Movable& owner) { Movable dst = std::move(owner); } +"#, + ); + assert_reference_target(&p, &a, "copy", "Owner::Owner", false); + assert!(!has_any_edge(&p, &a, "move", "Movable::Movable")); +} + +#[test] +fn dependent_forwarding_references_preserve_decltype_and_compound_glvalue_candidates() { + let (p, a) = analyze( + r#" +struct S { + S(const S&) {} + S(S&&) {} + void call() & {} + void call() && {} +}; +void sink(S&) {} +void sink(S&&) {} +template void named(T&& x, S& s) { + std::forward(s).call(); + sink(std::forward(s)); +} +void abbreviated(auto&& x, S& s) { + std::forward(s).call(); + sink(std::forward(s)); +} +template void comma(S& s) { + S copy = (0, std::forward(s)); +} +template void conditional(bool choose, S& s, S& other) { + S copy = choose ? std::forward(s) : std::move(other); +} +"#, + ); + for (caller, callee) in [ + ("named", "S::call"), + ("named", "sink"), + ("abbreviated", "S::call"), + ("abbreviated", "sink"), + ("comma", "S::S"), + ("conditional", "S::S"), + ] { + let targets: std::collections::BTreeSet<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == caller && target.name == callee).then( + || { + target.ref_qualifier.or_else(|| { + target + .parameter_references + .first() + .copied() + .flatten() + .map(|reference| reference.rvalue) + }) + }, + ) + }) + .collect(); + assert_eq!( + targets, + [Some(false), Some(true)].into(), + "{caller} -> {callee}" + ); + } +} + +#[test] +fn subscript_of_xvalue_array_collapses_auto_reference_to_rvalue() { + let (p, a) = analyze( + r#" +struct S { void call() & {} void call() && {} }; +void array(S (&items)[2]) { + auto&& r = std::move(items)[0]; + std::forward(r).call(); +} +void pointer(S* items) { + auto&& r = std::move(items)[0]; + std::forward(r).call(); +} +"#, + ); + for (caller, expected) in [("array", true), ("pointer", false)] { + let targets: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == caller && target.name == "S::call") + .then_some(target.ref_qualifier) + }) + .collect(); + assert_eq!(targets, [Some(expected)], "{caller}"); + } +} + +#[test] +fn implicitly_deleted_move_assignment_keeps_the_copy_body() { + let (p, a) = analyze( + r#" +struct M { M& operator=(M&&) = delete; }; +struct S { + M m; + S& operator=(const S&) { return *this; } + S& operator=(S&&) = default; +}; +void deleted_move(S& a, S& b) { a = std::move(b); } +struct Plain { + int field; + Plain& operator=(const Plain&) { return *this; } + Plain& operator=(Plain&&) = default; +}; +void viable_move(Plain& a, Plain& b) { a = std::move(b); } +"#, + ); + assert_reference_target(&p, &a, "deleted_move", "S::operator=", false); + assert!(!has_any_edge(&p, &a, "viable_move", "Plain::operator=")); +} + +#[test] +fn dependent_class_rvalue_reference_preserves_explicit_base_referent() { + let (p, a) = analyze( + r#" +template struct B { + void f() & {} + void f() && {} +}; +template struct D : B { + void f() && {} +}; +template void run(B&& x, D& d) { + std::forward(d).f(); +} +"#, + ); + let targets: Vec<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let target = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == "run" && target.name.ends_with("::f")) + .then_some((target.name.as_str(), target.ref_qualifier)) + }) + .collect(); + assert_eq!(targets, [("B::f", Some(true))]); +} + +#[test] +fn adjusted_array_parameters_have_lvalue_elements() { + let (p, a) = analyze( + r#" +struct S { + S(const S&) {} + S(S&&) {} + void call() & {} + void call() && {} +}; +void one(S items[2]) { + auto&& r = std::move(items)[0]; + std::forward(r).call(); + S copy = std::move(items)[0]; +} +void two(S items[2][3]) { + auto&& r = std::move(items)[0][0]; + std::forward(r).call(); + S copy = std::move(items)[0][0]; +} +"#, + ); + for caller in ["one", "two"] { + assert_reference_target(&p, &a, caller, "S::S", false); + assert_eq!( + method_qualifiers(&p, &a, caller, "S::call"), + [(false, Some(false))] + ); + } +} + +fn method_qualifiers( + program: &Program, + analysis: &AnalysisResult, + caller: &str, + name: &str, +) -> Vec<(bool, Option)> { + let mut qualifiers: Vec<_> = analysis + .call_edges + .iter() + .filter_map(|edge| { + let f = program.symbols.function_by_id(edge.callee)?; + (program.symbols.function(edge.caller).name == caller && f.name == name) + .then_some((f.is_const_member, f.ref_qualifier)) + }) + .collect(); + qualifiers.sort_unstable(); + qualifiers.dedup(); + qualifiers +} + +#[test] +fn projected_unknown_glvalues_retain_both_constructors() { + let (p, a) = analyze( + r#" +struct S { S(const S&) {} S(S&&) {} }; +struct H { S s; }; +template void array(S (&items)[2]) { S copy = std::forward(items)[0]; } +template void choice(S (&items)[2], S& other, bool c) { + S copy = c ? std::forward(items)[0] : other; +} +template void member(H& h) { S copy = std::forward(h).s; } +"#, + ); + for caller in ["array", "choice", "member"] { + let categories: std::collections::BTreeSet<_> = a + .call_edges + .iter() + .filter_map(|edge| { + let f = p.symbols.function_by_id(edge.callee)?; + (p.symbols.function(edge.caller).name == caller && f.name == "S::S") + .then(|| f.parameter_references.first()?.map(|r| r.rvalue)) + .flatten() + }) + .collect(); + assert_eq!(categories, [false, true].into(), "{caller}"); + } +} + +#[test] +fn dependent_member_references_and_forwarding_constness_stay_conservative() { + let (p, a) = analyze( + r#" +struct S { + void call() & {} + void call() && {} + void call() const & {} + void call() const && {} +}; +template struct Traits; +template struct Box { using type = S&; }; +template void traits(typename Traits::type&& x, S& s) { + std::forward(s).call(); +} +template void box(typename Box::type&& x, S& s) { + std::forward(s).call(); +} +template void named(T&& x, const S& s) { + std::forward(s).call(); +} +void abbreviated(auto&& x, const S& s) { + std::forward(s).call(); +} +"#, + ); + for caller in ["traits", "box"] { + assert!( + method_qualifiers(&p, &a, caller, "S::call").contains(&(false, Some(false))), + "{caller}" + ); + } + for caller in ["named", "abbreviated"] { + let qualifiers = method_qualifiers(&p, &a, caller, "S::call"); + assert!( + qualifiers.contains(&(true, Some(false))), + "{caller}: {qualifiers:?}" + ); + assert!( + qualifiers.contains(&(true, Some(true))), + "{caller}: {qualifiers:?}" + ); + } +} + +#[test] +fn incomplete_subobject_assignment_layouts_keep_copy_fallback() { + let (p, a) = analyze( + r#" +struct NoMove { NoMove& operator=(NoMove&&) = delete; }; +template struct Box { T value; }; +struct A { + Box b; + A& operator=(const A&) { return *this; } + A& operator=(A&&) = default; +}; +struct B { + union { int x; NoMove m; }; + B& operator=(const B&) { return *this; } + B& operator=(B&&) = default; +}; +union Variant { int x; NoMove m; }; +struct C { + Variant v; + C& operator=(const C&) { return *this; } + C& operator=(C&&) = default; +}; +void named_union(C& a, C& b) { a = std::move(b); } +void wrapped(A& a, A& b) { a = std::move(b); } +void anonymous(B& a, B& b) { a = std::move(b); } +"#, + ); + assert_reference_target(&p, &a, "wrapped", "A::operator=", false); + assert_reference_target(&p, &a, "anonymous", "B::operator=", false); + assert_reference_target(&p, &a, "named_union", "C::operator=", false); +} + +#[test] +fn member_decltype_and_address_of_keep_chained_result_types() { + let (p, a) = analyze( + r#" +struct L { void left() {} }; +struct R { void right() {} }; +struct M { + L pick() & { return {}; } + R pick() && { return {}; } + L pick() const && { return {}; } +}; +struct H { M value; M& ref; const M fixed; }; +void value(H& h) { std::forward(h.value).pick().right(); } +void reference(H& h) { std::forward(h.ref).pick().left(); } +void constant(H& h) { std::forward(h.fixed).pick().left(); } +L pick(int*&) { return {}; } +R pick(int*&&) { return {}; } +void pointer(int& n) { + auto&& r = &n; + pick(std::forward(r)).right(); +} +"#, + ); + for (caller, expected, rejected) in [ + ("value", "R::right", "L::left"), + ("reference", "L::left", "R::right"), + ("constant", "L::left", "R::right"), + ("pointer", "R::right", "L::left"), + ] { + assert_edge(&p, &a, caller, expected); + assert!(!has_any_edge(&p, &a, caller, rejected)); + } + assert_eq!( + method_qualifiers(&p, &a, "value", "M::pick"), + [(false, Some(true))] + ); + assert_eq!( + method_qualifiers(&p, &a, "reference", "M::pick"), + [(false, Some(false))] + ); + assert_eq!( + method_qualifiers(&p, &a, "constant", "M::pick"), + [(true, Some(true))] + ); + assert_reference_target(&p, &a, "pointer", "pick", true); +} + +#[test] +fn forwarding_member_decltype_preserves_static_and_dependent_references() { + let (p, a) = analyze( + r#" +struct M { + void pick() & {} + void pick() && {} +}; +struct H { + static M& ref; + static M&& rref; + static M value; +}; +void static_reference(H& h) { std::forward(h.ref).pick(); } +void static_rvalue_reference(H& h) { std::forward(h.rref).pick(); } +void static_value(H& h) { std::forward(h.value).pick(); } + +template struct Ref { using type = M&; }; +template struct Dependent { typename Ref::type&& ref; }; +template void dependent(Dependent& h, M& obj) { + std::forward(obj).pick(); +} +"#, + ); + for (caller, rvalue) in [ + ("static_reference", false), + ("static_rvalue_reference", true), + ("static_value", true), + ] { + assert_eq!( + method_qualifiers(&p, &a, caller, "M::pick"), + [(false, Some(rvalue))], + "{caller}" + ); + } + let candidates = method_qualifiers(&p, &a, "dependent", "M::pick"); + assert!(candidates.contains(&(false, Some(false))), "{candidates:?}"); +} diff --git a/crates/trace-cli/tests/it/value_slice.rs b/crates/trace-cli/tests/it/value_slice.rs index 1f8e7d71..47b35226 100644 --- a/crates/trace-cli/tests/it/value_slice.rs +++ b/crates/trace-cli/tests/it/value_slice.rs @@ -2029,3 +2029,71 @@ fn a_declarator_with_brackets_or_an_attribute_declares_its_identifier() { ); } } + +#[test] +fn allocator_return_origins_follow_the_selected_overload() { + let (_dir, _db, conn) = scratch_db(&[( + "alloc.cpp", + "extern \"C\" void* malloc(unsigned long);\n\ + struct Tag {};\n\ + Tag tag;\n\ + Tag* malloc(Tag*, int) { return &tag; }\n\ + void use() {\n\ + void* p;\n\ + p = malloc(8UL);\n\ + p = malloc(&tag, 0);\n\ + }\n", + )]); + let sites: Vec = conn + .prepare( + "SELECT o.line FROM flow_origins o \ + JOIN flow_nodes src ON src.id = o.src_node \ + JOIN flow_nodes dst ON dst.id = o.dst_node \ + JOIN variables src_var ON src_var.id = src.var_id \ + JOIN variables dst_var ON dst_var.id = dst.var_id \ + WHERE o.kind = 'addr_of' AND o.operation = 'return value' \ + AND src_var.name = 'tag' AND dst_var.name = 'p' \ + ORDER BY o.line", + ) + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(Result::unwrap) + .collect(); + assert_eq!(sites, [8]); +} + +#[test] +fn file_scope_allocator_actual_and_return_share_the_initializer_origin() { + let (_dir, _db, conn) = scratch_db(&[( + "alloc.cpp", + "extern \"C\" void* malloc(unsigned long);\n\ + namespace app {\n\ + struct Tag {};\n\ + Tag tag;\n\ + Tag* malloc(Tag* value) { return value; }\n\ + }\n\ + void* p = malloc(&app::tag);\n", + )]); + let sites: Vec<(String, i64, String)> = conn + .prepare( + "SELECT o.operation, o.line, v.name FROM flow_origins o \ + JOIN flow_nodes dst ON dst.id = o.dst_node \ + JOIN variables v ON v.id = dst.var_id \ + WHERE o.kind = 'copy' AND v.name IN ('value', 'p') \ + AND o.operation IN ('argument', 'return value') \ + ORDER BY o.operation", + ) + .unwrap() + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) + .unwrap() + .map(Result::unwrap) + .collect(); + assert_eq!( + sites, + [ + ("argument".into(), 7, "value".into()), + ("return value".into(), 7, "p".into()), + ] + ); +} diff --git a/crates/trace-db/src/dataflow.rs b/crates/trace-db/src/dataflow.rs index 9307deab..c83c1744 100644 --- a/crates/trace-db/src/dataflow.rs +++ b/crates/trace-db/src/dataflow.rs @@ -53,7 +53,13 @@ impl FlowScope { let Some(id) = self.fn_id else { return self.display(); }; - let parameters = if self.parameters.is_empty() && !self.signature.ends_with("()") { + let (storage, _) = trace_ir::split_signature_references(&self.signature); + let (signature, _) = trace_ir::split_signature_template_identity(storage); + let signature = signature + .trim_end_matches(" &") + .trim_end_matches(" &&") + .trim_end_matches(" const"); + let parameters = if self.parameters.is_empty() && !signature.ends_with("()") { "parameters unavailable".into() } else { self.parameters @@ -1776,6 +1782,38 @@ fn step_label(e: &FlowStep, text: bool) -> String { #[cfg(test)] mod tests { use super::*; + #[test] + fn zero_parameter_scope_ignores_signature_metadata() { + let mut scope = FlowScope { + fn_id: Some(FnId(1)), + name: "app::malloc".into(), + location: FlowSite::default(), + signature: String::new(), + target_id: None, + parameters: Vec::new(), + }; + for signature in [ + "app::malloc() ", + "app::malloc()