 ! These need to be numbered so that the same instruction
 ! will get distinct nodes if it occurs multiple times
 TUPLE: node
+    precedes-data precedes-control
     number insn precedes follows
     children parent
     registers parent-index ;

    node insn>> temp-vregs length +
    dup node (>>registers) ;

: data-dependence? ( to from -- ? )
    ! If this takes lots of time, then refactor code
    ! so that nodes store their data dependences
    [ insn>> ] bi@
    [ uses-vregs ] [ defs-vreg ] bi*
    swap member? ;

DEFER: follow-tree

: maybe-cut-node ( node -- ? )
    ! If this node has multiple successors
    ! then it needs to be made into the head of a new tree
    [ precedes>> assoc-size 1 = dup ] keep
    '[ _ dup , follow-tree ] when ;

: follow-tree ( node -- )
    ! This is bogus: it misses nodes that aren't reachable
    ! from the roots because of a control dependence
    dup dup follows>> values
    [ data-dependence? ] with filter
    [ parent>> not ] filter
    [ maybe-cut-node ] filter
    
    [ [ >>parent drop ] with each ]
    [ >>children drop ] 2bi ;

: attach-parent ( node -- )
    drop ;

: make-trees ( -- trees )
    nodes get
    [ [ attach-parent ] each ]
    [ [ parent>> not ] filter ] bi ;

ERROR: node-missing-parent trees nodes ;

        node-number counter >>number
        swap >>insn
        H{ } clone >>precedes
        H{ } clone >>precedes-data
        H{ } clone >>precedes-control
        H{ } clone >>follows ;

: ready? ( node -- ? ) precedes>> assoc-empty? ;
