paralegal_flow/ana/
graph_converter.rs

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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
use super::{path_for_item, src_loc_for_span, SPDGGenerator};
use crate::{
    ann::MarkerAnnotation, desc::*, discover::FnToAnalyze, utils::*, HashMap, HashSet, MarkerCtx,
    Pctx,
};
use flowistry_pdg::{rustc_portable::Location, SourceUse};
use flowistry_pdg_construction::{
    call_tree_visit::{VisitDriver, Visitor},
    determine_async,
    graph::{DepEdge, DepEdgeKind, DepNode, OneHopLocation, PartialGraph},
    utils::{handle_shims, try_monomorphize, try_resolve_function, type_as_fn, ShimResult},
};
use paralegal_spdg::Node;

use rustc_hash::FxHashSet;
use rustc_hir::def_id::DefId;
use rustc_middle::{
    mir,
    ty::{Instance, TyCtxt, TypingEnv},
};

use either::Either;
use flowistry::mir::FlowistryInput;
use petgraph::visit::{IntoNodeReferences, NodeRef};

fn dep_edge_kind_to_edge_kind(kind: DepEdgeKind) -> EdgeKind {
    match kind {
        DepEdgeKind::Control => EdgeKind::Control,
        DepEdgeKind::Data => EdgeKind::Data,
    }
}

#[cfg(debug_assertions)]
fn assert_edge_location_invariant<'tcx, Loc: Eq + std::fmt::Display>(
    tcx: TyCtxt<'tcx>,
    at: Loc,
    body: &mir::Body<'tcx>,
    location: Loc,
    leaf: impl Fn(&Loc) -> GlobalLocation,
) {
    // Normal case. The edge is introduced where the operation happens
    if location == at {
        return;
    }
    // Control flow case. The edge is introduced at the `switchInt`
    if let RichLocation::Location(loc) = leaf(&at).location {
        if leaf(&at).function == leaf(&location).function
            && matches!(
                body.stmt_at(loc),
                Either::Right(mir::Terminator {
                    kind: mir::TerminatorKind::SwitchInt { .. },
                    ..
                })
            )
        {
            return;
        }
    }
    let mut msg = tcx.dcx().struct_span_fatal(
        (body, leaf(&at).location).span(tcx),
        format!(
            "This operation is performed in a different location: {}",
            at
        ),
    );
    msg.span_note(
        (body, leaf(&location).location).span(tcx),
        format!("Expected to originate here: {}", at),
    );
    msg.emit()
}

struct GraphAssembler<'tcx, 'a> {
    // read-only information
    generator: &'a SPDGGenerator<'tcx>,
    is_async: bool,

    // Translation helpers
    /// Translation tables for nodes from local PartialGraphs to the global PDG
    nodes: Vec<Vec<GNode>>,

    // Incrementally built information
    graph: SPDGImpl,
    marker_assignments: HashMap<GNode, HashSet<Identifier>>,
    /// A map of which nodes are of which (marked) type. We build this up during
    /// conversion.
    types: HashMap<GNode, Vec<DefId>>,
    known_def_ids: &'a mut FxHashSet<DefId>,
}

/// Create a global PDG (spanning the entire call tree) starting from the given
/// target function.
pub fn assemble_pdg<'a>(
    generator: &'a SPDGGenerator<'_>,
    known_def_ids: &'a mut FxHashSet<DefId>,
    target: &'a FnToAnalyze,
) -> SPDG {
    let tcx = generator.tcx();

    // Information and body of the provided target function
    let base_body_def_id = target.def_id.to_def_id();
    let base_body = generator
        .pdg_constructor
        .body_cache()
        .try_get(base_body_def_id)
        .unwrap_or_else(|| {
            panic!("INVARIANT VIOLATED: body for local function {base_body_def_id:?} cannot be loaded.",)
        })
        .body();

    let async_state = determine_async(tcx, base_body_def_id, base_body);

    // These will refer to the function we are actually analyzing from, which may
    // be a generator if the target is async.
    let possibly_generator_id =
        async_state.map_or(base_body_def_id, |(generator, ..)| generator.def_id());
    let (possible_generator_instance, k) = generator
        .pdg_constructor
        .create_root_key(possibly_generator_id.expect_local());

    let mut driver = VisitDriver::new(&generator.pdg_constructor, possible_generator_instance, k);
    let mut assembler = GraphAssembler::new(generator, known_def_ids, target.def_id.to_def_id());

    // If the top level function is async we start analysis from the generator
    // instead (because the async function itself is basically empty, it just
    // creates the generator object).
    if let Some((_, loc, ..)) = async_state {
        // If the top-level function is async we place that on the call stack
        // first so it shows up in the call strings that are generated for the
        // nodes.
        driver.with_pushed_stack(
            GlobalLocation {
                function: base_body_def_id,
                location: RichLocation::Location(loc),
            },
            |driver| {
                driver.start(&mut assembler);
            },
        );
        // Using create_root_key might seem weird here but it currently does what
        // we need (resolve the instance)
        let base_instance = generator
            .pdg_constructor
            .create_root_key(base_body_def_id.expect_local())
            .0;
        // Because we actually started the analysis from the generator, we now
        // have to manually sync up the actual arguments to the async function.
        assembler.fix_async_args(base_instance, loc, &mut driver);
    } else {
        driver.start(&mut assembler);
    }
    let return_ = assembler.determine_return();
    let arguments = assembler.determine_arguments();
    let graph = assembler.graph;
    SPDG {
        name: Identifier::new(target.name()),
        path: path_for_item(target.def_id.to_def_id(), tcx),
        id: target.def_id.to_def_id(),
        graph,
        markers: assembler
            .marker_assignments
            .into_iter()
            .map(|(GNode(node), markers)| (node, markers.into_iter().collect()))
            .collect(),
        arguments,
        return_,
        type_assigns: assembler
            .types
            .into_iter()
            .map(|(GNode(k), v)| (k, Types(v.into())))
            .collect(),
        statistics: Default::default(),
    }
}

impl<'tcx, 'a> GraphAssembler<'tcx, 'a> {
    fn new(
        generator: &'a SPDGGenerator<'tcx>,
        known_def_ids: &'a mut FxHashSet<DefId>,
        def_id: DefId,
    ) -> Self {
        let is_async = entrypoint_is_async(
            generator.pdg_constructor.body_cache(),
            generator.tcx(),
            def_id,
        );
        Self {
            graph: SPDGImpl::new(),
            nodes: Default::default(),
            marker_assignments: Default::default(),
            known_def_ids,
            types: Default::default(),
            generator,
            is_async,
        }
    }

    /// Add these markers to our marker table we maintain for nodes.
    fn register_markers(&mut self, node: GNode, markers: impl IntoIterator<Item = Identifier>) {
        let mut markers = markers.into_iter().peekable();

        if markers.peek().is_some() {
            self.marker_assignments
                .entry(node)
                .or_default()
                .extend(markers);
        }
    }

    /// Add a node from the current local graph to the global graph. Returns the
    /// global index. If the node was already added, returns the prior index.
    fn add_node<K: Clone>(
        &mut self,
        node: Node,
        vis: &mut VisitDriver<'tcx, '_, K>,
        weight: &DepNode<'tcx, OneHopLocation>,
    ) -> GNode {
        let weight = globalize_node(vis, weight, self.tcx());
        let table = self.nodes.last_mut().unwrap();
        let prior = table[node.index()];
        if GNode(Node::end()) != prior {
            prior
        } else {
            let my_idx = GNode(self.graph.add_node(weight));
            table[node.index()] = my_idx;
            my_idx
        }
    }

    /// Add a node that does not correspond to any local graph. This is only used
    /// when fixing async args.
    fn add_untranslatable_node(
        &mut self,
        place: mir::Place,
        at: CallString,
        span: rustc_span::Span,
    ) -> GNode {
        GNode(self.graph.add_node(NodeInfo {
            at,
            description: format!("{place:?}"),
            span: src_loc_for_span(span, self.tcx()),
            local: place.local.as_u32(),
        }))
    }

    fn ctx(&self) -> &Pctx<'tcx> {
        &self.generator.ctx
    }

    fn tcx(&self) -> TyCtxt<'tcx> {
        self.ctx().tcx()
    }

    fn marker_ctx(&self) -> &MarkerCtx<'tcx> {
        self.generator.marker_ctx()
    }

    /// Fetch annotations item identified by this `id`.
    ///
    /// The callback is used to filter out annotations where the "refinement"
    /// doesn't match. The idea is that the caller of this function knows
    /// whether they are looking for annotations on an argument or return of a
    /// function identified by this `id` or on a type and the callback should be
    /// used to enforce this.
    fn register_annotations_for_function(
        &mut self,
        node: GNode,
        function: DefId,
        mut filter: impl FnMut(&MarkerAnnotation) -> bool,
    ) {
        let parent = get_parent(self.tcx(), function);
        let marker_ctx = self.marker_ctx().clone();
        self.register_markers(
            node,
            marker_ctx
                .combined_markers(function)
                .chain(
                    parent
                        .into_iter()
                        .flat_map(|parent| marker_ctx.combined_markers(parent)),
                )
                .filter(|ann| filter(ann))
                .map(|ann| ann.marker),
        );
        self.known_def_ids.extend(parent);
    }

    /// Check if this node is of a marked type and register that type.
    fn handle_node_types<K: Clone>(
        &mut self,
        node: GNode,
        at: &OneHopLocation,
        place: mir::Place<'tcx>,
        span: rustc_span::Span,
        vis: &VisitDriver<'tcx, '_, K>,
    ) {
        trace!("Checking types for node {node:?} ({:?})", place);

        let tcx = self.tcx();
        let function = vis.current_function();

        // So actually we're going to check the base place only, because
        // Flowistry sometimes tracks subplaces instead but we want the marker
        // from the base place.
        let (base_place, projections) =
            if self.entrypoint_is_async() && place.local.as_u32() == 1 && at.in_child.is_none() {
                if place.projection.is_empty() {
                    return;
                }
                let (base_project, rest) = place.projection.split_first().unwrap();
                // in the case of targeting the top-level async closure (e.g. async args)
                // we'll keep the first projection.
                (
                    mir::Place {
                        local: place.local,
                        projection: self.tcx().mk_place_elems(&[*base_project]),
                    },
                    rest,
                )
            } else {
                (place.local.into(), place.projection.as_slice())
            };
        trace!("Using base place {base_place:?} with projections {projections:?}");

        let resolution = vis.current_function();

        // Thread through each caller to recover generic arguments
        let body = self
            .generator
            .pdg_constructor
            .body_cache()
            .get(function.def_id())
            .body();
        let raw_ty = base_place.ty(body, tcx);
        let base_ty = try_monomorphize(
            resolution,
            tcx,
            TypingEnv::fully_monomorphized(),
            &raw_ty,
            span,
        )
        .unwrap();

        self.handle_node_types_helper(node, base_ty, projections);
    }

    /// Adds the markers for all levels of projection on this node. For the
    /// final projection we add all markers from that type (deep markers), for
    /// others we only add the shallow markers.
    fn handle_node_types_helper(
        &mut self,
        node: GNode,
        mut base_ty: mir::tcx::PlaceTy<'tcx>,
        projections: &[mir::PlaceElem<'tcx>],
    ) {
        trace!("Has place type {base_ty:?}");
        let mut node_types = HashSet::new();
        for proj in projections {
            node_types.extend(self.type_is_marked(base_ty, false));
            base_ty = base_ty.projection_ty(self.tcx(), *proj);
        }
        node_types.extend(self.type_is_marked(base_ty, true));
        self.known_def_ids.extend(node_types.iter().copied());
        let tcx = self.tcx();
        if !node_types.is_empty() {
            self.types.entry(node).or_default().extend(
                node_types
                    .iter()
                    .filter(|t| !tcx.is_coroutine(**t) && !tcx.def_kind(*t).is_fn_like()),
            )
        }
        trace!("Found marked node types {node_types:?}",);
    }

    /// Return the (sub)types of this type that are marked.
    fn type_is_marked(
        &'a self,
        typ: mir::tcx::PlaceTy<'tcx>,
        deep: bool,
    ) -> impl Iterator<Item = TypeId> + 'a {
        if deep {
            Either::Left(self.marker_ctx().deep_type_markers(typ.ty).iter().copied())
        } else {
            Either::Right(self.marker_ctx().shallow_type_markers(typ.ty))
        }
        .map(|(d, _)| d)
    }

    /// Discover and register directly applied markers on this node.
    fn node_annotations<K: Clone>(
        &mut self,
        local_node: Node,
        node: GNode,
        weight: &DepNode<'tcx, OneHopLocation>,
        vis: &VisitDriver<'tcx, '_, K>,
    ) {
        let leaf_loc = weight.at.location;
        let function = vis.current_function();
        let function_id = function.def_id();

        let body = self
            .generator
            .pdg_constructor
            .body_cache()
            .get(function.def_id())
            .body();

        match leaf_loc {
            RichLocation::Start
                if matches!(body.local_kind(weight.place.local), mir::LocalKind::Arg) =>
            {
                let arg_num = weight.place.local.as_u32() - 1;
                self.known_def_ids.extend([function_id]);
                self.register_annotations_for_argument(node, arg_num, function_id);
            }
            RichLocation::End if weight.place.local == mir::RETURN_PLACE => {
                self.known_def_ids.extend([function_id]);
                self.register_annotations_for_return(node, function_id);
            }
            RichLocation::Location(loc) => self.handle_node_annotations_for_regular_location(
                local_node, node, weight, body, loc, vis,
            ),
            _ => (),
        }
    }

    fn register_annotations_for_argument(&mut self, node: GNode, arg_num: u32, function_id: DefId) {
        self.register_annotations_for_function(node, function_id, |ann| {
            ann.refinement.on_argument().contains(arg_num).unwrap()
        });
    }

    fn register_annotations_for_return(&mut self, node: GNode, function_id: DefId) {
        self.register_annotations_for_function(node, function_id, |ann| ann.refinement.on_return());
    }

    /// Helper for `node_annotations` to handle the case where the node is at a `RichLocation::Location`.
    fn handle_node_annotations_for_regular_location<K: Clone>(
        &mut self,
        local_node: Node,
        node: GNode,
        weight: &DepNode<'tcx, OneHopLocation>,
        body: &mir::Body<'tcx>,
        loc: Location,
        vis: &VisitDriver<'tcx, '_, K>,
    ) {
        let function = vis.current_function();
        let function_id = function.def_id();
        let crate::Either::Right(
            term @ mir::Terminator {
                kind: mir::TerminatorKind::Call { func, .. },
                ..
            },
        ) = body.stmt_at(loc)
        else {
            return;
        };
        debug!("Assigning markers to {:?}", term.kind);
        let param_env = TypingEnv::post_analysis(self.tcx(), function.def_id());
        let func =
            try_monomorphize(function, self.tcx(), param_env, func, term.source_info.span).unwrap();
        let Some(funcc) = func.constant() else {
            self.generator.ctx.maybe_span_err(
                weight.span,
                "SOUNDNESS: Cannot determine markers for function call",
            );
            return;
        };
        let (inst, args) = type_as_fn(self.tcx(), ty_of_const(funcc)).unwrap();
        let f = if let Some(inst) = try_resolve_function(
            self.tcx(),
            inst,
            TypingEnv::post_analysis(self.tcx(), function_id),
            args,
        ) {
            match handle_shims(inst, self.tcx(), param_env, weight.span) {
                ShimResult::IsHandledShim { instance, .. } => instance,
                ShimResult::IsNotShim => inst,
                ShimResult::IsNonHandleableShim => {
                    self.ctx().maybe_span_err(
                        weight.span,
                        "SOUNDNESS: Cannot determine markers for shim usage",
                    );
                    return;
                }
            }
            .def_id()
        } else {
            debug!("Could not resolve {inst:?} properly during marker assignment");
            inst
        };

        self.known_def_ids.extend(Some(f));

        let graph = vis.current_graph();

        // Question: Could a function with no input produce an
        // output that has aliases? E.g. could some place, where the
        // local portion isn't the local from the destination of
        // this function call be affected/modified by this call? If
        // so, that location would also need to have this marker
        // attached
        //
        // Also yikes. This should have better detection of whether
        // a place is (part of) a function return

        let mut is_return_use = false;
        let mut has_no_data_edges = true;

        for eref in graph.raw().edges_directed(local_node, petgraph::Outgoing) {
            let SourceUse::Argument(arg) = eref.weight().source_use else {
                continue;
            };
            self.register_annotations_for_function(node, f, |ann| {
                ann.refinement.on_argument().contains(arg as u32).unwrap()
            });
        }
        for eref in graph.raw().edges_directed(local_node, petgraph::Incoming) {
            if eref.weight().kind == DepEdgeKind::Data {
                has_no_data_edges = false;
                let at = eref.weight().at.clone();
                #[cfg(debug_assertions)]
                assert_edge_location_invariant(
                    self.tcx(),
                    at.clone(),
                    body,
                    weight.at.clone(),
                    |at| GlobalLocation {
                        function: function.def_id(),
                        location: at.location,
                    },
                );
                if weight.at == at && eref.weight().target_use.is_return() {
                    is_return_use = true;
                }
            }
        }
        let needs_return_markers = has_no_data_edges | is_return_use;

        if needs_return_markers {
            self.register_annotations_for_function(node, f, |ann| ann.refinement.on_return());
        }
    }

    /// Determine the set if nodes corresponding to the inputs to the
    /// entrypoint. The order is guaranteed to be the same as the source-level
    /// function declaration.
    fn determine_arguments(&self) -> Box<[Node]> {
        let mut g_nodes: Vec<_> = self
            .graph
            .node_references()
            .filter(|n| {
                let at = n.weight().at;
                let is_candidate =
                    matches!(self.try_as_root(at), Some(l) if l.location == RichLocation::Start);
                is_candidate
            })
            .collect();

        g_nodes.sort_by_key(|(_, i)| i.local);

        g_nodes.into_iter().map(|(n, _)| n).collect()
    }

    /// Try to find the node corresponding to the values returned from this
    /// controller.
    ///
    /// TODO: Include mutable inputs
    fn determine_return(&self) -> Box<[Node]> {
        // In async functions
        self.graph
            .node_references()
            .filter(|n| {
                let weight = n.weight();
                let at = weight.at;
                matches!(self.try_as_root(at), Some(l) if l.location == RichLocation::End)
            })
            .map(|n| n.id())
            .collect()
    }

    /// Similar to `CallString::is_at_root`, but takes into account top-level
    /// async functions
    fn try_as_root(&self, at: CallString) -> Option<GlobalLocation> {
        at.is_at_root().then(|| at.leaf())
    }

    /// Is the top-level function (entrypoint) an `async fn`
    fn entrypoint_is_async(&self) -> bool {
        self.is_async
    }

    /// When we analyze an async function (as entry point), we actually start
    /// the analysis from the generator, since the async function itself is
    /// mostly empty. However the arguments to the generator are not the same as
    /// for the async function. It is the generator object that basically
    /// tuples together the arguments to the original async function. (And as a
    /// second argument there's a context object.)
    ///
    /// This function adds nodes for the original async function's arguments and
    /// connects them to the fields of the generator object to establish the flows.
    fn fix_async_args<K: Clone + std::hash::Hash + Eq>(
        &mut self,
        instance: Instance<'tcx>,
        loc: Location,
        driver: &mut VisitDriver<'tcx, 'a, K>,
    ) {
        let def_id = instance.def_id();
        self.known_def_ids.extend([def_id]);
        let tcx = self.generator.tcx();
        let base_body = self
            .generator
            .pdg_constructor
            .body_cache()
            .try_get(def_id)
            .unwrap_or_else(|| {
                panic!("INVARIANT VIOLATED: body for local function {def_id:?} cannot be loaded.",)
            })
            .body();
        let pgraph = driver.current_graph_as_rc();

        // New nodes for arguments and return place
        let args_as_nodes = base_body
            .args_iter()
            .map(|arg| {
                self.add_untranslatable_node(
                    arg.into(),
                    driver.globalize_location(&RichLocation::Start.into()),
                    base_body.local_decls[arg].source_info.span,
                )
            })
            .collect::<Vec<_>>();
        let return_node = self.add_untranslatable_node(
            mir::RETURN_PLACE.into(),
            driver.globalize_location(&RichLocation::End.into()),
            base_body.local_decls[mir::RETURN_PLACE].source_info.span,
        );

        let mono_ty = |local| {
            let decl = &base_body.local_decls[local];
            mir::tcx::PlaceTy::from_ty(
                try_monomorphize(
                    instance,
                    tcx,
                    TypingEnv::fully_monomorphized(),
                    &decl.ty,
                    decl.source_info.span,
                )
                .unwrap(),
            )
        };

        // Register the new nodes and add potential markers
        for (arg_num, a) in args_as_nodes.iter().enumerate() {
            self.register_annotations_for_argument(*a, arg_num as u32, def_id);
            let local = mir::Local::from_usize(arg_num + 1);
            self.handle_node_types_helper(*a, mono_ty(local), &[]);
        }
        self.register_annotations_for_return(return_node, def_id);
        let local = mir::RETURN_PLACE;
        self.handle_node_types_helper(return_node, mono_ty(local), &[]);

        // Establish connections to existing nodes
        let generator_loc = RichLocation::Location(loc);
        let transition_at = CallString::new(&[GlobalLocation {
            location: generator_loc,
            function: def_id,
        }]);
        for (nidx, n) in pgraph.iter_nodes() {
            if n.place.local.as_u32() == 1 && n.at.location == RichLocation::Start {
                let ridx = self.translate_node(nidx);
                let Some(mir::ProjectionElem::Field(id, _)) = n.place.projection.first() else {
                    tcx.dcx().span_err(
                        n.span,
                        format!("Expected field projection on async generator in {def_id:?}, found {:?}", n.place),
                    );
                    continue;
                };

                let arg = args_as_nodes[id.as_usize()];
                self.graph.add_edge(
                    arg.to_index(),
                    ridx.to_index(),
                    EdgeInfo {
                        kind: EdgeKind::Data,
                        at: transition_at,
                        source_use: SourceUse::Argument(id.as_u32() as u8),
                        target_use: TargetUse::Assign,
                    },
                );
            } else if n.place.local == mir::RETURN_PLACE {
                let ridx = self.translate_node(nidx);
                self.graph.add_edge(
                    ridx.to_index(),
                    return_node.to_index(),
                    EdgeInfo {
                        kind: EdgeKind::Data,
                        at: transition_at,
                        source_use: SourceUse::Operand,
                        target_use: TargetUse::Return,
                    },
                );
            }
        }
    }

    /// Translate a node from the current local graph to the global graph.
    fn translate_node(&self, node: Node) -> GNode {
        self.translate_node_in(node, self.nodes.len() - 1)
    }

    /// Translate a node from a specific local graph to the global graph.
    fn translate_node_in(&self, node: Node, index: usize) -> GNode {
        let idx = self.nodes[index][node.index()];
        assert_ne!(idx.to_index(), Node::end(), "Node {node:?} is unknown");
        idx
    }

    fn with_new_translation_table<R>(&mut self, size: usize, f: impl FnOnce(&mut Self) -> R) -> R {
        self.nodes.push(vec![GNode(Node::end()); size]);
        let result = f(self);
        if self.nodes.len() != 1 {
            // Yuck. In oder to still be able to fix up the async args we let
            // the bottom translation table remain.
            assert_eq!(self.nodes.pop().unwrap().len(), size);
        }
        result
    }
}

fn globalize_node<'tcx, K: Clone>(
    vis: &mut VisitDriver<'tcx, '_, K>,
    node: &DepNode<'tcx, OneHopLocation>,
    tcx: TyCtxt<'tcx>,
) -> NodeInfo {
    let at = vis.globalize_location(&node.at);
    NodeInfo {
        at,
        description: format!("{:?}", node.place),
        span: src_loc_for_span(node.span, tcx),
        local: node.place.local.as_u32(),
    }
}

fn globalize_edge<K: Clone>(
    vis: &mut VisitDriver<'_, '_, K>,
    edge: &DepEdge<OneHopLocation>,
) -> EdgeInfo {
    let at = vis.globalize_location(&edge.at);
    EdgeInfo {
        kind: dep_edge_kind_to_edge_kind(edge.kind),
        at,
        source_use: edge.source_use,
        target_use: edge.target_use,
    }
}

/// A newtype for indices into the global graph. This type exists because under
/// the hood local and global graphs use the same index types which makes it
/// very easy to mistake them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GNode(petgraph::graph::NodeIndex);

impl GNode {
    fn to_index(self) -> petgraph::graph::NodeIndex {
        self.0
    }
}

impl<'tcx, K: std::hash::Hash + Eq + Clone> Visitor<'tcx, K> for GraphAssembler<'tcx, '_> {
    fn visit_parent_connection(
        &mut self,
        _vis: &mut VisitDriver<'tcx, '_, K>,
        in_caller: Node,
        in_this: Node,
        _is_at_start: bool,
    ) {
        let [parent_table, this_table] = self.nodes.last_chunk_mut().unwrap();
        this_table[in_this.index()] = parent_table[in_caller.index()]
    }

    fn visit_node(
        &mut self,
        vis: &mut VisitDriver<'tcx, '_, K>,
        k: Node,
        node: &DepNode<'tcx, OneHopLocation>,
    ) {
        let is_in_child = node.at.in_child.is_some();
        let idx = self.add_node(k, vis, node);
        if !is_in_child {
            self.node_annotations(k, idx, node, vis);
            self.handle_node_types(idx, &node.at, node.place, node.span, vis);
        }
    }

    fn visit_edge(
        &mut self,
        vis: &mut VisitDriver<'tcx, '_, K>,
        src: Node,
        dst: Node,
        kind: &DepEdge<OneHopLocation>,
    ) {
        let src = self.translate_node(src);
        let dst = self.translate_node(dst);
        let new_kind = globalize_edge(vis, kind);
        self.graph
            .add_edge(src.to_index(), dst.to_index(), new_kind);
    }

    fn visit_partial_graph(
        &mut self,
        vis: &mut VisitDriver<'tcx, '_, K>,
        graph: &PartialGraph<'tcx, K>,
    ) {
        self.with_new_translation_table(graph.node_count(), |slf: &mut Self| {
            trace!(
                "Visiting partial graph {:?}",
                slf.tcx().def_path_str(graph.def_id())
            );
            vis.visit_partial_graph(slf, graph);
        })
    }

    fn visit_ctrl_edge(
        &mut self,
        _vis: &mut VisitDriver<'tcx, '_, K>,
        index: usize,
        src: Node,
        dst: Node,
        edge: &DepEdge<CallString>,
    ) {
        let src = self.translate_node_in(src, index);
        let dst = self.translate_node(dst);
        self.graph.add_edge(
            src.to_index(),
            dst.to_index(),
            EdgeInfo {
                kind: dep_edge_kind_to_edge_kind(edge.kind),
                at: edge.at,
                source_use: edge.source_use,
                target_use: edge.target_use,
            },
        );
    }
}