forked from model-checking/kani
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis.rs
More file actions
768 lines (712 loc) · 26.7 KB
/
Copy pathanalysis.rs
File metadata and controls
768 lines (712 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Provide passes that perform intra-function analysis on the crate under compilation
use crate::info;
use csv::WriterBuilder;
use graph_cycles::Cycles;
use petgraph::graph::Graph;
use rustc_middle::ty::TyCtxt;
use rustc_public::mir::mono::Instance;
use rustc_public::mir::visit::{Location, PlaceContext, PlaceRef};
use rustc_public::mir::{
BasicBlock, Body, CastKind, MirVisitor, Mutability, NonDivergingIntrinsic, ProjectionElem,
Rvalue, Safety, Statement, StatementKind, Terminator, TerminatorKind,
};
use rustc_public::rustc_internal;
use rustc_public::ty::{Abi, AdtDef, AdtKind, FnDef, GenericArgs, MirConst, RigidTy, Ty, TyKind};
use rustc_public::visitor::{Visitable, Visitor};
use rustc_public::{CrateDef, CrateItem};
use serde::{Serialize, Serializer, ser::SerializeStruct};
use std::collections::{HashMap, HashSet};
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub struct OverallStats {
/// The key and value of each counter.
pub counters: Vec<(&'static str, usize)>,
/// TODO: Group stats per function.
fn_stats: HashMap<CrateItem, FnStats>,
}
#[derive(Clone, Debug, Serialize)]
struct FnStats {
name: String,
is_unsafe: Option<bool>,
has_unsafe_ops: Option<bool>,
has_unsupported_input: Option<bool>,
has_loop_or_iterator: Option<bool>,
is_public: Option<bool>,
}
impl FnStats {
fn new(fn_item: CrateItem) -> FnStats {
FnStats {
name: fn_item.name(),
is_unsafe: None,
has_unsafe_ops: None,
has_unsupported_input: None,
has_loop_or_iterator: None,
is_public: None,
}
}
}
impl Default for OverallStats {
fn default() -> Self {
Self::new()
}
}
impl OverallStats {
pub fn new() -> OverallStats {
let all_items = rustc_public::all_local_items();
let fn_stats: HashMap<_, _> = all_items
.into_iter()
.filter_map(|item| item.ty().kind().is_fn().then_some((item, FnStats::new(item))))
.collect();
let counters = vec![("total_fns", fn_stats.len())];
OverallStats { counters, fn_stats }
}
pub fn store_csv(&self, base_path: PathBuf, file_stem: &str) {
let filename = format!("{file_stem}_overall");
let mut out_path = base_path.parent().map_or(PathBuf::default(), Path::to_path_buf);
out_path.set_file_name(filename);
dump_csv(out_path, &self.counters);
let filename = format!("{file_stem}_functions");
let mut out_path = base_path.parent().map_or(PathBuf::default(), Path::to_path_buf);
out_path.set_file_name(filename);
dump_csv(out_path, &self.fn_stats.values().collect::<Vec<_>>());
}
/// Iterate over all functions defined in this crate and log generic vs monomorphic.
pub fn generic_fns(&mut self) {
let all_items = rustc_public::all_local_items();
let fn_items =
all_items.into_iter().filter(|item| item.ty().kind().is_fn()).collect::<Vec<_>>();
let (mono_fns, generics) = fn_items
.iter()
.partition::<Vec<&CrateItem>, _>(|fn_item| Instance::try_from(**fn_item).is_ok());
self.counters
.extend_from_slice(&[("generic_fns", generics.len()), ("mono_fns", mono_fns.len())]);
}
/// Iterate over all functions defined in this crate and log safe vs unsafe.
pub fn safe_fns(&mut self, _base_filename: PathBuf) {
let all_items = rustc_public::all_local_items();
let (unsafe_fns, safe_fns) = all_items
.into_iter()
.filter_map(|item| {
let kind = item.ty().kind();
if !kind.is_fn() {
return None;
};
let fn_sig = kind.fn_sig().unwrap();
let is_unsafe = fn_sig.skip_binder().safety == Safety::Unsafe;
self.fn_stats.get_mut(&item).unwrap().is_unsafe = Some(is_unsafe);
Some((item, is_unsafe))
})
.partition::<Vec<(CrateItem, bool)>, _>(|(_, is_unsafe)| *is_unsafe);
self.counters
.extend_from_slice(&[("safe_fns", safe_fns.len()), ("unsafe_fns", unsafe_fns.len())]);
}
/// Iterate over all functions defined in this crate and log the inputs.
pub fn supported_inputs(&mut self, filename: PathBuf) {
let all_items = rustc_public::all_local_items();
let (supported, unsupported) = all_items
.into_iter()
.filter_map(|item| {
let kind = item.ty().kind();
if !kind.is_fn() {
return None;
};
let fn_sig = kind.fn_sig().unwrap();
let props = FnInputProps::new(item.name()).collect(fn_sig.skip_binder().inputs());
self.fn_stats.get_mut(&item).unwrap().has_unsupported_input =
Some(!props.is_supported());
Some(props)
})
.partition::<Vec<_>, _>(|props| props.is_supported());
self.counters.extend_from_slice(&[
("supported_inputs", supported.len()),
("unsupported_inputs", unsupported.len()),
]);
dump_csv(filename, &unsupported);
}
/// Iterate over all functions defined in this crate and log any unsafe operation.
pub fn unsafe_operations(&mut self, filename: PathBuf) {
let all_items = rustc_public::all_local_items();
let (has_unsafe, no_unsafe) = all_items
.into_iter()
.filter_map(|item| {
let kind = item.ty().kind();
if !kind.is_fn() {
return None;
};
let unsafe_ops = FnUnsafeOperations::new(item.name()).collect(&item.expect_body());
let fn_sig = kind.fn_sig().unwrap();
let is_unsafe = fn_sig.skip_binder().safety == Safety::Unsafe;
self.fn_stats.get_mut(&item).unwrap().has_unsafe_ops =
Some(unsafe_ops.has_unsafe());
Some((is_unsafe, unsafe_ops))
})
.partition::<Vec<_>, _>(|(_, props)| props.has_unsafe());
self.counters.extend_from_slice(&[
("has_unsafe_ops", has_unsafe.len()),
("no_unsafe_ops", no_unsafe.len()),
("safe_abstractions", has_unsafe.iter().filter(|(is_unsafe, _)| !is_unsafe).count()),
]);
dump_csv(filename, &has_unsafe.into_iter().map(|(_, props)| props).collect::<Vec<_>>());
}
/// Iterate over all functions defined in this crate and log any loop / "hidden" loop.
///
/// A hidden loop is a call to a iterator function that has a loop inside.
pub fn loops(&mut self, filename: PathBuf) {
let all_items = rustc_public::all_local_items();
let (has_loops, no_loops) = all_items
.clone()
.into_iter()
.filter_map(|item| {
let kind = item.ty().kind();
if !kind.is_fn() {
return None;
};
Some(FnLoops::new(item.name()).collect(&item.expect_body()))
})
.partition::<Vec<_>, _>(|props| props.has_loops());
let (has_iterators, no_iterators) = all_items
.clone()
.into_iter()
.filter_map(|item| {
let kind = item.ty().kind();
if !kind.is_fn() {
return None;
};
Some(FnLoops::new(item.name()).collect(&item.expect_body()))
})
.partition::<Vec<_>, _>(|props| props.has_iterators());
let (has_either, _) = all_items
.into_iter()
.filter_map(|item| {
let kind = item.ty().kind();
if !kind.is_fn() {
return None;
};
let fn_props = FnLoops::new(item.name()).collect(&item.expect_body());
self.fn_stats.get_mut(&item).unwrap().has_loop_or_iterator =
Some(fn_props.has_iterators() || fn_props.has_loops());
Some(fn_props)
})
.partition::<Vec<_>, _>(|props| props.has_iterators() || props.has_loops());
self.counters.extend_from_slice(&[
("has_loops", has_loops.len()),
("no_loops", no_loops.len()),
("has_iterators", has_iterators.len()),
("no_iterators", no_iterators.len()),
]);
dump_csv(filename, &has_either);
}
/// Create a callgraph for this crate and try to find recursive calls.
pub fn recursion(&mut self, filename: PathBuf) {
let all_items = rustc_public::all_local_items();
let recursions = Recursion::collect(&all_items);
self.counters.extend_from_slice(&[
("with_recursion", recursions.with_recursion.len()),
("recursive_fns", recursions.recursive_fns.len()),
]);
dump_csv(
filename,
&recursions
.with_recursion
.iter()
.map(|def| {
(
def.name(),
if recursions.recursive_fns.contains(def) { "recursive" } else { "" },
)
})
.collect::<Vec<_>>(),
);
}
/// Iterate over all functions defined in this crate and log public vs private
pub fn public_fns(&mut self, tcx: &TyCtxt) {
let all_items = rustc_public::all_local_items();
let (public_fns, private_fns) = all_items
.into_iter()
.filter_map(|item| {
let kind = item.ty().kind();
if !kind.is_fn() {
return None;
};
let int_def_id = rustc_internal::internal(*tcx, item.def_id());
let is_public = tcx.visibility(int_def_id).is_public()
|| tcx.visibility(int_def_id).is_visible_locally();
self.fn_stats.get_mut(&item).unwrap().is_public = Some(is_public);
Some((item, is_public))
})
.partition::<Vec<(CrateItem, bool)>, _>(|(_, is_public)| *is_public);
self.counters.extend_from_slice(&[
("public_fns", public_fns.len()),
("private_fns", private_fns.len()),
]);
}
}
macro_rules! fn_props {
($(#[$attr:meta])*
$vis:vis struct $name:ident {
$(
$(#[$prop_attr:meta])*
$prop:ident,
)+
}) => {
#[derive(Debug)]
$vis struct $name {
fn_name: String,
$($(#[$prop_attr])* $prop: usize,)+
}
impl $name {
$vis const fn num_props() -> usize {
[$(stringify!($prop),)+].len()
}
$vis fn new(fn_name: String) -> Self {
Self { fn_name, $($prop: 0,)+}
}
}
/// Need to manually implement this, since CSV serializer does not support map (i.e.: flatten).
impl Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("FnInputProps", Self::num_props())?;
state.serialize_field("fn_name", &self.fn_name)?;
$(state.serialize_field(stringify!($prop), &self.$prop)?;)+
state.end()
}
}
};
}
fn_props! {
struct FnInputProps {
boxes,
closures,
coroutines,
floats,
fn_defs,
fn_ptrs,
generics,
interior_muts,
raw_ptrs,
recursive_types,
mut_refs,
simd,
unions,
}
}
impl FnInputProps {
pub fn collect(mut self, inputs: &[Ty]) -> FnInputProps {
for input in inputs {
let mut visitor = TypeVisitor { metrics: &mut self, visited: HashSet::new() };
let _ = visitor.visit_ty(input);
}
self
}
pub fn is_supported(&self) -> bool {
(self.closures
+ self.coroutines
+ self.floats
+ self.fn_defs
+ self.fn_ptrs
+ self.interior_muts
+ self.raw_ptrs
+ self.recursive_types
+ self.mut_refs)
== 0
}
}
struct TypeVisitor<'a> {
metrics: &'a mut FnInputProps,
visited: HashSet<Ty>,
}
impl TypeVisitor<'_> {
pub fn visit_variants(&mut self, def: AdtDef, _args: &GenericArgs) -> ControlFlow<()> {
for variant in def.variants_iter() {
for field in variant.fields() {
self.visit_ty(&field.ty())?
}
}
ControlFlow::Continue(())
}
}
impl Visitor for TypeVisitor<'_> {
type Break = ();
fn visit_ty(&mut self, ty: &Ty) -> ControlFlow<Self::Break> {
if self.visited.contains(ty) {
self.metrics.recursive_types += 1;
ControlFlow::Continue(())
} else {
self.visited.insert(*ty);
let kind = ty.kind();
match kind {
TyKind::Alias(..) => {}
TyKind::Param(_) => self.metrics.generics += 1,
TyKind::RigidTy(rigid) => match rigid {
RigidTy::Coroutine(..) => self.metrics.coroutines += 1,
RigidTy::Closure(..) => self.metrics.closures += 1,
RigidTy::FnDef(..) => self.metrics.fn_defs += 1,
RigidTy::FnPtr(..) => self.metrics.fn_ptrs += 1,
RigidTy::Float(..) => self.metrics.floats += 1,
RigidTy::RawPtr(..) => self.metrics.raw_ptrs += 1,
RigidTy::Ref(_, _, Mutability::Mut) => self.metrics.mut_refs += 1,
RigidTy::Adt(def, args) => match def.kind() {
AdtKind::Union => self.metrics.unions += 1,
_ => {
let name = def.name();
if def.is_box() {
self.metrics.boxes += 1;
} else if name.ends_with("UnsafeCell") {
self.metrics.interior_muts += 1;
} else {
self.visit_variants(def, &args)?;
}
}
},
_ => {}
},
kind => unreachable!("Expected rigid type, but found: {kind:?}"),
}
ty.super_visit(self)
}
}
}
pub(crate) fn dump_csv<T: Serialize>(mut out_path: PathBuf, data: &[T]) {
out_path.set_extension("csv");
info(format!("Write file: {out_path:?}"));
let mut writer = WriterBuilder::new().delimiter(b';').from_path(&out_path).unwrap();
for d in data {
writer.serialize(d).unwrap();
}
}
fn_props! {
pub struct FnUnsafeOperations {
inline_assembly,
/// Dereference a raw pointer.
/// This is also counted when we access a static variable since it gets translated to a raw pointer.
unsafe_dereference,
/// Call an unsafe function or method including C-FFI.
unsafe_call,
/// Access or modify a mutable static variable.
unsafe_static_access,
/// Access fields of unions.
unsafe_union_access,
/// Invoke external functions (this is a subset of `unsafe_call`.
extern_call,
/// Transmute operations.
transmute,
/// Cast raw pointer to reference.
unsafe_cast,
}
}
impl FnUnsafeOperations {
pub fn collect(self, body: &Body) -> FnUnsafeOperations {
let mut visitor = BodyVisitor { props: self, body };
visitor.visit_body(body);
visitor.props
}
pub fn has_unsafe(&self) -> bool {
(self.inline_assembly
+ self.unsafe_static_access
+ self.unsafe_dereference
+ self.unsafe_union_access
+ self.unsafe_call)
> 0
}
}
struct BodyVisitor<'a> {
props: FnUnsafeOperations,
body: &'a Body,
}
impl MirVisitor for BodyVisitor<'_> {
fn visit_terminator(&mut self, term: &Terminator, location: Location) {
match &term.kind {
TerminatorKind::Call { func, .. } => {
let TyKind::RigidTy(RigidTy::FnDef(fn_def, _)) =
func.ty(self.body.locals()).unwrap().kind()
else {
return self.super_terminator(term, location);
};
let fn_sig = fn_def.fn_sig().skip_binder();
if fn_sig.safety == Safety::Unsafe {
self.props.unsafe_call += 1;
if !matches!(fn_sig.abi, Abi::Rust | Abi::RustCold | Abi::RustCall)
&& !fn_def.has_body()
{
self.props.extern_call += 1;
}
}
}
TerminatorKind::InlineAsm { .. } => self.props.inline_assembly += 1,
_ => { /* safe */ }
}
self.super_terminator(term, location)
}
fn visit_rvalue(&mut self, rvalue: &Rvalue, location: Location) {
if let Rvalue::Cast(cast_kind, operand, ty) = rvalue {
match cast_kind {
CastKind::Transmute => {
self.props.transmute += 1;
}
_ => {
let operand_ty = operand.ty(self.body.locals()).unwrap();
if ty.kind().is_ref() && operand_ty.kind().is_raw_ptr() {
self.props.unsafe_cast += 1;
}
}
}
};
self.super_rvalue(rvalue, location);
}
fn visit_statement(&mut self, stmt: &Statement, location: Location) {
if matches!(
&stmt.kind,
StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(_))
) {
// Treat this as invoking the copy intrinsic.
self.props.unsafe_call += 1;
}
self.super_statement(stmt, location)
}
fn visit_projection_elem(
&mut self,
place: PlaceRef,
elem: &ProjectionElem,
ptx: PlaceContext,
location: Location,
) {
match elem {
ProjectionElem::Deref => {
if place.ty(self.body.locals()).unwrap().kind().is_raw_ptr() {
self.props.unsafe_dereference += 1;
}
}
ProjectionElem::Field(_, ty) => {
if ty.kind().is_union() {
self.props.unsafe_union_access += 1;
}
}
ProjectionElem::Downcast(_) => {}
ProjectionElem::OpaqueCast(_) => {}
ProjectionElem::Index(_)
| ProjectionElem::ConstantIndex { .. }
| ProjectionElem::Subslice { .. } => { /* safe */ }
}
self.super_projection_elem(elem, ptx, location)
}
fn visit_mir_const(&mut self, constant: &MirConst, location: Location) {
if constant.ty().kind().is_raw_ptr() {
self.props.unsafe_static_access += 1;
}
self.super_mir_const(constant, location)
}
}
fn_props! {
struct FnLoops {
iterators,
loops,
// TODO: Collect nested loops.
nested_loops,
}
}
impl FnLoops {
pub fn collect(self, body: &Body) -> FnLoops {
let mut visitor =
IteratorVisitor { props: self, body, graph: Vec::new(), current_bbidx: 0 };
visitor.visit_body(body);
visitor.props
}
pub fn has_loops(&self) -> bool {
(self.loops + self.nested_loops) > 0
}
pub fn has_iterators(&self) -> bool {
(self.iterators) > 0
}
}
/// Try to find hidden loops by looking for calls to Iterator functions that has a loop in them.
///
/// Note that this will not find a loop, if the iterator is called inside a closure.
/// Run with -C opt-level 2 to help with this issue (i.e.: inline).
struct IteratorVisitor<'a> {
props: FnLoops,
body: &'a Body,
graph: Vec<(u32, u32)>,
current_bbidx: u32,
}
impl MirVisitor for IteratorVisitor<'_> {
fn visit_body(&mut self, body: &Body) {
// First visit the body to build the control flow graph
self.super_body(body);
// Build the petgraph from the adj vec
let g = Graph::<(), ()>::from_edges(self.graph.clone());
self.props.loops += g.cycles().len();
}
fn visit_basic_block(&mut self, bb: &BasicBlock) {
self.current_bbidx = self.body.blocks.iter().position(|b| *b == *bb).unwrap() as u32;
self.super_basic_block(bb);
}
fn visit_terminator(&mut self, term: &Terminator, location: Location) {
// Add edges between basic block into the adj table
let successors = term.kind.successors();
for target in successors {
self.graph.push((self.current_bbidx, target as u32));
}
if let TerminatorKind::Call { func, .. } = &term.kind {
let kind = func.ty(self.body.locals()).unwrap().kind();
// Check if the target is a visited block.
// Check if the call is an iterator function that contains loops.
if let TyKind::RigidTy(RigidTy::FnDef(def, _)) = kind {
let fullname = def.name();
let names = fullname.split("::").collect::<Vec<_>>();
if let [.., s_last, last] = names.as_slice()
&& *s_last == "Iterator"
&& [
"for_each",
"collect",
"advance_by",
"all",
"any",
"partition",
"partition_in_place",
"fold",
"try_fold",
"spec_fold",
"spec_try_fold",
"try_for_each",
"for_each",
"try_reduce",
"reduce",
"find",
"find_map",
"try_find",
"position",
"rposition",
"nth",
"count",
"last",
"find",
]
.contains(last)
{
self.props.iterators += 1;
}
}
}
self.super_terminator(term, location)
}
}
#[derive(Debug, Default)]
struct Recursion {
/// Collect the functions that may lead to a recursion loop.
/// I.e., for the following control flow graph:
/// ```dot
/// A -> B
/// B -> C
/// C -> [B, D]
/// ```
/// this field value would contain A, B, and C since they can all lead to a recursion.
with_recursion: HashSet<FnDef>,
/// Collect the functions that are part of a recursion loop.
/// For the following control flow graph:
/// ```dot
/// A -> [B, C]
/// B -> B
/// C -> D
/// D -> [C, E]
/// ```
/// The recursive functions would be B, C, and D.
recursive_fns: HashSet<FnDef>,
}
impl Recursion {
pub fn collect<'a>(items: impl IntoIterator<Item = &'a CrateItem>) -> Recursion {
let call_graph = items
.into_iter()
.filter_map(|item| {
if let TyKind::RigidTy(RigidTy::FnDef(def, _)) = item.ty().kind() {
let body = item.expect_body();
let mut visitor = FnCallVisitor { body: &body, fns: vec![] };
visitor.visit_body(&body);
Some((def, visitor.fns))
} else {
None
}
})
.collect::<HashMap<_, _>>();
let mut recursions = Recursion::default();
recursions.analyze(call_graph);
recursions
}
/// DFS post-order traversal to collect all loops in our control flow graph.
/// We only include direct call recursions which can only happen within a crate.
///
/// # How it works
///
/// Given a call graph, [(fn_def, [fn_def]*)]*, enqueue all existing nodes together with the
/// graph distance.
/// Keep track of the current path and the visiting status of each node.
/// For those that we have visited once, store whether a loop is reachable from them.
fn analyze(&mut self, call_graph: HashMap<FnDef, Vec<FnDef>>) {
#[derive(Copy, Clone, PartialEq, Eq)]
enum Status {
ToVisit,
Visiting,
Visited,
}
let mut visit_status = HashMap::<FnDef, Status>::new();
let mut queue: Vec<_> = call_graph.keys().map(|node| (*node, 0)).collect();
let mut path: Vec<FnDef> = vec![];
while let Some((next, level)) = queue.last().copied() {
match visit_status.get(&next).unwrap_or(&Status::ToVisit) {
Status::ToVisit => {
assert_eq!(path.len(), level);
path.push(next);
visit_status.insert(next, Status::Visiting);
let next_level = level + 1;
if let Some(callees) = call_graph.get(&next) {
queue.extend(callees.iter().map(|callee| (*callee, next_level)));
}
}
Status::Visiting => {
if level < path.len() {
// We have visited all callees in this node.
visit_status.insert(next, Status::Visited);
path.pop();
} else {
// Found a loop.
let mut in_loop = false;
for def in &path {
in_loop |= *def == next;
if in_loop {
self.recursive_fns.insert(*def);
}
self.with_recursion.insert(*def);
}
}
queue.pop();
}
Status::Visited => {
queue.pop();
if self.with_recursion.contains(&next) {
self.with_recursion.extend(&path);
}
}
}
}
}
}
pub struct FnCallVisitor<'a> {
pub body: &'a Body,
pub fns: Vec<FnDef>,
}
impl MirVisitor for FnCallVisitor<'_> {
fn visit_terminator(&mut self, term: &Terminator, location: Location) {
if let TerminatorKind::Call { func, .. } = &term.kind {
let kind = func.ty(self.body.locals()).unwrap().kind();
if let TyKind::RigidTy(RigidTy::FnDef(def, _)) = kind {
self.fns.push(def);
}
}
self.super_terminator(term, location)
}
}