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
//! FIFO.

use super::*;

/// State for `N`-sized FIFO.
#[derive(Debug, Clone, Copy)]
pub struct FifoS<P: Copy, const N: usize>
where
    [(); clog2(N)]:,
    [(); clog2(N + 1)]:,
{
    /// Inner elements.
    pub inner: Array<P, N>,
    /// Read address.
    pub raddr: U<{ clog2(N) }>,
    /// Write address.
    pub waddr: U<{ clog2(N) }>,
    /// Length.
    pub len: U<{ clog2(N + 1) }>,
}

impl<P: Copy, const N: usize> Default for FifoS<P, N>
where
    [(); clog2(N)]:,
    [(); clog2(N + 1)]:,
{
    fn default() -> Self {
        Self { inner: unsafe { x() }, raddr: U::from(0), waddr: U::from(0), len: U::from(0) }
    }
}

impl<P: Copy, const N: usize> FifoS<P, N>
where
    [(); clog2(N)]:,
    [(); clog2(N + 1)]:,
    [(); clog2(N) + 1]:,
{
    /// Returns the head of the FIFO.
    pub fn head(self) -> HOption<P> {
        if self.len == 0.into_u() {
            None
        } else {
            Some(self.inner[self.raddr])
        }
    }

    /// Returns inner elements with valid bit.
    pub fn inner_with_valid(self) -> Array<HOption<P>, N> {
        range::<N>().map(|i| {
            if i.resize() >= self.len {
                None
            } else {
                Some(self.inner[wrapping_add::<{ clog2(N) }>(self.raddr, i, N.into_u())])
            }
        })
    }
}

impl<P: Copy, R: Copy, const D: Dep> I<VrH<P, R>, D> {
    /// FIFO queue with `N` entries.
    ///
    /// This queue is fully pipelined, which means it can accept a new element every cycle.
    ///
    /// - Payload: If an ingress transfer happens, the ingress payload is enqueued. If an egress transfer happens, the
    ///     egress payload is dequeued. The front (dequeue-side) element is outputted as an egress payload.
    /// - Resolver: The ingress ready signal is true if the queue can accept new elements, i.e. not full. The inner
    ///     value `R` of the resolver is preserved.
    ///
    /// | Interface | Ingress      | Egress       |
    /// | :-------: | ------------ | ------------ |
    /// |  **Fwd**  | `HOption<P>` | `HOption<P>` |
    /// |  **Bwd**  | `Ready<R>`   | `Ready<R>`   |
    pub fn fifo<const N: usize>(self) -> I<VrH<P, R>, { Dep::Helpful }>
    where
        [(); clog2(N) + 1]:,
        [(); clog2(N + 1) + 1]:,
    {
        self.map_resolver_inner::<(R, _)>(|er| er.0).transparent_fifo()
    }
}

impl<const D: Dep, const N: usize, P: Copy, R: Copy> I<VrH<P, (R, FifoS<P, N>)>, D>
where
    [(); clog2(N)]:,
    [(); clog2(N + 1)]:,
{
    /// A variation of [`I::fifo`] that additionally outputs the internal FIFO state to the ingress resolver.
    ///
    /// - Payload: The same behavior as [`I::fifo`].
    /// - Resolver: The same behavior as [`I::fifo`], but additionally the FIFO state `FifoS<P, N>` is outputted.
    ///
    /// | Interface | Ingress                   | Egress       |
    /// | :-------: | ------------------------- | ------------ |
    /// |  **Fwd**  | `HOption<P>`              | `HOption<P>` |
    /// |  **Bwd**  | `Ready<(R, FifoS<P, N>)>` | `Ready<R>`   |
    // TODO: add `flow` and `pipe` parameters.
    // - `flow`: reduce latency when FIFO is empty.
    // If flow bit is valid and FIFO is empty, then ingress payload goes out as egress payload directly.
    // - `pipe`: reduce latency when FIFO is full.
    // If pipe bit is valid and FIFO is full, ingress payload can come in if egress payload goes out.
    // Refer to below link for more details:
    // <https://github.com/chipsalliance/chisel/blob/v3.2.1/src/main/scala/chisel3/util/Decoupled.scala#L235-L246>
    pub fn transparent_fifo(self) -> I<VrH<P, R>, { Dep::Helpful }>
    where
        [(); clog2(N) + 1]:,
        [(); clog2(N + 1) + 1]:,
    {
        self.multi_headed_transparent_fifo().map_resolver_inner(|r| (r, U::from(1))).filter_map(|s| {
            if s.len == 0.into_u() {
                None
            } else {
                Some(s.inner[s.raddr])
            }
        })
    }

    /// A variation of [`I::transparent_fifo`] that outputs the FIFO state instead of the front element as the egress payload,
    /// and takes an additional egress resolver signal representing how many elements will be popped.
    ///
    /// - Payload: The same behavior as [`I::transparent_fifo`], but the FIFO state `FifoS<P, N>` is outputted instead.
    /// - Resolver: The same behavior as [`I::transparent_fifo`], but additionally takes a `U<{ clog2(N + 1) }>` that
    ///     represents how many elements to pop.
    ///
    /// | Interface | Ingress                   | Egress                            |
    /// | :-------: | ------------------------- | --------------------------------- |
    /// |  **Fwd**  | `HOption<P>`              | `HOption<FifoS<P, N>>`            |
    /// |  **Bwd**  | `Ready<(R, FifoS<P, N>)>` | `Ready<(R, U<{ clog2(N + 1) }>)>` |
    #[allow(clippy::type_complexity)]
    pub fn multi_headed_transparent_fifo(self) -> I<VrH<FifoS<P, N>, (R, U<{ clog2(N + 1) }>)>, { Dep::Helpful }>
    where
        [(); clog2(N) + 1]:,
        [(); clog2(N + 1) + 1]:,
    {
        unsafe {
            self.fsm::<FifoS<P, N>, { Dep::Helpful }, VrH<FifoS<P, N>, (R, U<{ clog2(N + 1) }>)>>(
                FifoS::default(),
                |ip, er, s| {
                    let FifoS { inner, raddr, waddr, len } = s;
                    let pop = er.inner.1;

                    let empty = len == U::from(0);
                    let full = len == U::from(N);

                    let enq = ip.is_some() && !full;
                    let deq = er.ready && !empty;

                    let ep = Some(s);
                    let ir = Ready::new(!full, (er.inner.0, s));

                    let inner_next = if enq { inner.set(waddr, ip.unwrap()) } else { inner };
                    let len_next = (len + U::from(enq).resize() - if deq { pop.resize() } else { 0.into_u() }).resize();
                    let raddr_next =
                        if deq { wrapping_add::<{ clog2(N) }>(raddr, pop.resize(), N.into_u()) } else { raddr };
                    let waddr_next = if enq { wrapping_inc::<{ clog2(N) }>(waddr, N.into_u()) } else { waddr };

                    let s_next = FifoS { inner: inner_next, raddr: raddr_next, waddr: waddr_next, len: len_next };

                    (ep, ir, s_next)
                },
            )
        }
    }
}

impl<const D: Dep, const N: usize, P: Copy> I<VrH<P, FifoS<P, N>>, D>
where
    [(); clog2(N)]:,
    [(); clog2(N + 1)]:,
{
    /// A variation of [`I::transparent_fifo`] that has valid-ready egress interface.
    ///
    /// - Payload: The same behavior as [`I::transparent_fifo`].
    /// - Resolver: The same behavior as [`I::transparent_fifo`], but unnecessary unit type is removed in the ingress
    ///     resolver signal.
    ///
    /// | Interface | Ingress              | Egress       |
    /// | :-------: | -------------------- | ------------ |
    /// |  **Fwd**  | `HOption<P>`         | `HOption<P>` |
    /// |  **Bwd**  | `Ready<FifoS<P, N>>` | `Ready<()>`  |
    pub fn transparent_fifo(self) -> Vr<P>
    where
        [(); clog2(N) + 1]:,
        [(); clog2(N + 1) + 1]:,
    {
        self.multi_headed_transparent_fifo().map_resolver_inner(|_| U::from(1)).filter_map(|s| {
            if s.len == 0.into_u() {
                None
            } else {
                Some(s.inner[s.raddr])
            }
        })
    }

    /// A variation of [`I::multi_headed_transparent_fifo`] that has valid-ready egress interface.
    ///
    /// - Payload: The same behavior as [`I::multi_headed_transparent_fifo`].
    /// - Resolver: The same behavior as [`I::multi_headed_transparent_fifo`], but unnecessary unit type is removed in
    ///     the ingress resolver signal.
    ///
    /// | Interface | Ingress               | Egress                       |
    /// | :-------: | --------------------- | ---------------------------- |
    /// |  **Fwd**  | `HOption<P>`          | `HOption<FifoS<P, N>>`       |
    /// |  **Bwd**  | `Ready<FifoS<P, N>>`  | `Ready<U<{ clog2(N + 1) }>>` |
    #[allow(clippy::type_complexity)]
    pub fn multi_headed_transparent_fifo(self) -> I<VrH<FifoS<P, N>, U<{ clog2(N + 1) }>>, { Dep::Helpful }>
    where
        [(); clog2(N) + 1]:,
        [(); clog2(N + 1) + 1]:,
    {
        unsafe {
            self.fsm::<FifoS<P, N>, { Dep::Helpful }, VrH<FifoS<P, N>, U<{ clog2(N + 1) }>>>(
                FifoS::default(),
                |ip, er, s| {
                    let FifoS { inner, raddr, waddr, len } = s;
                    let pop = er.inner;

                    let empty = len == U::from(0);
                    let full = len == U::from(N);

                    let enq = ip.is_some() && !full;
                    let deq = er.ready && !empty;

                    let ep = Some(s);
                    let ir = Ready::new(!full, s);

                    let inner_next = if enq { inner.set(waddr, ip.unwrap()) } else { inner };
                    let len_next = (len + U::from(enq).resize() - if deq { pop.resize() } else { 0.into_u() }).resize();
                    let raddr_next =
                        if deq { wrapping_add::<{ clog2(N) }>(raddr, pop.resize(), N.into_u()) } else { raddr };
                    let waddr_next = if enq { wrapping_inc::<{ clog2(N) }>(waddr, N.into_u()) } else { waddr };

                    let s_next = FifoS { inner: inner_next, raddr: raddr_next, waddr: waddr_next, len: len_next };

                    (ep, ir, s_next)
                },
            )
        }
    }
}