30. Fixed Point and CIC Filters: the Bridge to VHDL

PySDR computes in floating point throughout, and so have we. But the samples arrive from an ADC as 12- or 16-bit integers, and when the first processing stages move into an FPGA, as PySDR’s introduction notes they usually do in fielded systems, they compute in fixed point: integers with an implied binary point, bit widths chosen per signal, and explicit decisions about rounding and overflow. The C++ model of such a design has one job above all others: produce exactly the same bits as the hardware, so that the VHDL can be tested against it with an equality check instead of a tolerance.

This chapter builds two pieces of that bridge. A fixed-point type whose arithmetic follows the VHDL-2008 fixed_pkg rule for rule, so that its result widths are computed by the C++ compiler exactly as a VHDL designer gets them. And a bit-true model of the CIC decimator, the multiplier-free filter at the front of almost every digital down-converter, whose correctness depends on letting its registers overflow, something C++ only allows if you choose your types deliberately. At the end, the C++ model writes test vectors for a VHDL implementation.

A Fixed-Point Type That Speaks VHDL

In VHDL-2008, sfixed(0 downto -15) is a signed fixed-point number with bits weighted \(2^0\) down to \(2^{-15}\): 16 bits, range \([-1, 1)\), the classic Q1.15 format. The fixed_pkg defines what happens in arithmetic, and its central rule is that operators never lose information. Quoting the package declaration (IEEE fixed_generic_pkg, as shipped with GHDL):

-- sfixed(a downto b) + sfixed(c downto d)
--   = sfixed(maximum(a,c)+1 downto minimum(b,d))
-- sfixed(a downto b) * sfixed(c downto d) = sfixed(a+c+1 downto b+d)

An addition gets one more integer bit, so it cannot overflow; a product gets the full width of both operands. Bits are lost only where the designer says so, in resize, with a rounding style (default fixed_round) and an overflow style (default fixed_saturate).

In C++ the bit positions become template parameters, and the result types become functions of them, computed while compiling (code/include/cppsdr/fixed.hpp):

template <int High, int Low>
class fixed {                        // the twin of sfixed(High downto Low)
    static constexpr int bits = High - Low + 1;
    using storage = /* smallest of int8_t, int16_t, int32_t, int64_t that fits */;
    ...
};

template <int H1, int L1, int H2, int L2>
constexpr auto operator*(fixed<H1, L1> a, fixed<H2, L2> b)
{
    using R = fixed<H1 + H2 + 1, L1 + L2>;
    return R::from_raw(a.raw() * b.raw());   // the integer product *is* the exact result
}

template <int H1, int L1, int H2, int L2>
constexpr auto operator+(fixed<H1, L1> a, fixed<H2, L2> b)
{
    using R = fixed<std::max(H1, H2) + 1, std::min(L1, L2)>;
    // align both operands to the result's LSB, then add
    ...
}

The test checks the sizing rules at compile time, where they belong:

using q15 = fixed<0, -15>;                                   // sfixed(0 downto -15)
static_assert(std::is_same_v<decltype(q15{} * q15{}), fixed<1, -30>>, "sfixed(a+c+1 downto b+d)");
static_assert(std::is_same_v<decltype(q15{} + q15{}), fixed<1, -15>>, "sfixed(max(a,c)+1 downto min(b,d))");
static_assert(std::is_same_v<q15::storage, std::int16_t> && sizeof(fixed<1, -30>) == 4);

Why the extra integer bit in the product? Because \((-1) \cdot (-1) = +1\), which does not fit in \([-1, 1)\). The C++ type can hold it, and the test checks that too.

Rounding and Overflow, Chosen Explicitly

All narrowing goes through resize<High, Low, round_style, overflow_style>, with the same defaults as the VHDL package. Rounding follows the package’s own description of fixed_round: round up if the most significant dropped bit is 1 and either the kept LSB is 1 or any lower dropped bit is 1. That is round-half-to-even, which avoids the small bias that always rounding halves upward accumulates over many operations:

// fixed_pkg: round up if the remainder MSB is 1 and (result LSB is 1 or lower remainder bits are not 0)
r = kept + ((rem & half) && ((kept & 1) || (rem & (half - 1))) ? 1 : 0);

static_assert(resize<2, -2>(fixed<0, -3>::from_raw(5)).raw() == 2);    // 2.5 LSB -> 2
static_assert(resize<2, -2>(fixed<0, -3>::from_raw(7)).raw() == 4);    // 3.5 LSB -> 4
static_assert(resize<2, -2>(fixed<0, -3>::from_raw(-5)).raw() == -2);  // -2.5 LSB -> -2

kept comes from r >> drop. Shifting a negative signed integer right was implementation-defined before C++20; C++20 made two’s complement the only representation and >> an arithmetic shift, so this is now the portable way to drop bits, and it rounds towards minus infinity, exactly like dropping bits from a two’s complement vector in hardware. That is also what round_style::truncate gives you. (These rounding tests initially failed for a good reason: we had written the target as fixed<0, -2>, whose range ends at 0.75, and 3.5 LSB = 0.875 saturated as it should. The type was right and the test was wrong.)

Overflow is the second choice. overflow_style::saturate clamps to the largest representable value, which is what you want for signals; overflow_style::wrap keeps the low bits and sign-extends, which is what plain hardware adders do, and, as the next section shows, sometimes exactly what you want.

CIC Filters: Overflow on Purpose

A CIC (cascaded integrator-comb) decimator, introduced by Hogenauer in 1981 (IEEE Trans. ASSP, vol. 29, no. 2), reduces the sample rate by a factor \(R\) without a single multiplier. It consists of \(N\) integrators running at the input rate, a decimator, and \(N\) combs (differences with delay \(M\)) at the output rate. Its response is that of \(N\) cascaded moving sums of length \(RM\), a crude but cheap low-pass that is usually followed by a short FIR filter at the lower rate. It is the reason that the first, fastest stage of a digital down-converter fits into an FPGA at all.

The integrators are the strange part: an integrator fed with a constant grows without bound, so its register will overflow. Hogenauer’s insight is that this does not matter. If all registers use modular (two’s complement) arithmetic and are at least

\[B_{\text{reg}} = B_{\text{in}} + \lceil N \log_2(RM) \rceil\]

bits wide, the combs subtract out every wrap-around and the output is exact. Read the formula as: the filter’s DC gain is \((RM)^N\), and the registers need room for the input times that gain.

This is where C++ needs care. The natural type for a signed register is int32_t, but signed overflow is undefined behavior in C++: the optimizer may assume it never happens and generate code that does something else entirely (Pikus, The Art of Writing Efficient Programs, chapter 11). Unsigned arithmetic, on the other hand, is defined to wrap modulo \(2^n\). So the model computes in std::uint64_t and masks every result to exactly the register width of the hardware (code/include/cppsdr/cic.hpp):

template <unsigned N, unsigned R, unsigned M, unsigned InBits,
          unsigned Width = InBits + cic_bit_growth(N, R, M)>   // Hogenauer's minimum by default
class cic_decimator {
public:
    static constexpr std::uint64_t mask = (std::uint64_t{1} << Width) - 1;   // (Width < 64)

    std::size_t process(std::span<const std::int32_t> in, std::span<std::int64_t> out)
    {
        std::size_t n_out = 0;
        for (std::int32_t x : in) {
            std::uint64_t v = std::uint64_t(std::int64_t(x)) & mask;  // two's complement, Width bits
            for (auto& acc : integ_) v = acc = (acc + v) & mask;       // N integrators, modulo 2^Width
            if (++phase_ < R) continue;
            phase_ = 0;
            for (unsigned k = 0; k < N; ++k) {                       // N combs at the low rate
                auto& d = delay_[k];
                const std::uint64_t old = d[pos_];
                d[pos_] = v;
                v = (v - old) & mask;
            }
            pos_ = (pos_ + 1) % M;
            out[n_out++] = sign_extend(v);
        }
        return n_out;
    }
    ...
};

The register width is a template parameter with Hogenauer’s formula as its default, computed by a constexpr function with integers only (the number of bits needed for \((RM)^N\)), so the compiler checks it: static_assert(cic_decimator<4, 16, 1, 16>::register_bits == 32). The last step, sign_extend, turns the Width-bit pattern back into a signed number with a left shift and an arithmetic right shift, again well-defined since C++20.

The test feeds 100 000 full-scale random 16-bit samples through the CIC, in blocks, and compares with a direct computation of \(N\) moving sums in 64-bit integers that never overflow. The results are identical, although the 32-bit integrators wrap around constantly. Then the interesting experiment: the same filter with 31-bit registers, one bit less than Hogenauer’s bound. On the random data it is still exact, because random data never comes close to full scale. Feeding it the worst case instead, a constant \(-32768\), the correct output is \(-32768 \cdot 16^4 = -2^{31}\), which needs all 32 bits; the 31-bit version outputs 0. The bound is tight, and random test data would never have shown it. Test vectors for hardware need deliberate corner cases.

The Same CIC in VHDL

Here is the hardware twin (code/vhdl/cic_decimator.vhd). It uses numeric_std’s signed type, whose + on operands of equal width also wraps around, so the modular arithmetic comes for free:

elsif in_valid = '1' then
  v := resize(in_data, W);
  for k in 0 to N - 1 loop
    v := integ(k) + v;                 -- wraps modulo 2**W
    integ(k) <= v;
  end loop;
  if phase = R - 1 then
    phase <= 0;
    for k in 0 to N - 1 loop           -- combs at the low rate
      delay(k) <= v;
      v := v - delay(k);
    end loop;
    out_data  <= v;
    out_valid <= '1';
  else
    phase <= phase + 1;
  end if;
end if;

Compare it with the C++: the same loops, the same order, the same widths. That is the point of a bit-true model. The VHDL is written for clarity, with the \(N\) integrator additions chained within one clock cycle; a real design at hundreds of MHz would pipeline them, which changes the latency but not the output values.

The bridge is the test bench. code/examples/cic_vectors.cpp runs the C++ model on 32 000 input samples, starting with full-scale DC (the worst case from above) followed by random data, and writes cic_in.txt and cic_out.txt. The VHDL test bench (code/vhdl/tb_cic_decimator.vhd) reads the input file, drives the design, and compares every output with the C++ value using assert ... severity failure. The VHDL files analyze without errors with the open-source simulator nvc in VHDL-2008 mode. We have not run the simulation for this edition of the book; to do so:

cd code && ./build/cic_vectors testdata
nvc --std=2008 -a vhdl/cic_decimator.vhd vhdl/tb_cic_decimator.vhd \
    -e tb_cic_decimator -gVECTOR_DIR=testdata -r

Making the Workflow Stick

The pattern generalizes to any block that moves into hardware:

  1. Write the C++ model with exactly the hardware’s widths, rounding and overflow behavior, using types that make those choices explicit (fixed<High, Low>, resize with named policies, unsigned arithmetic for anything that must wrap).

  2. Test the model against a floating-point or wide-integer reference: does the fixed-point design do what the algorithm intends? Include the worst cases, not just random data.

  3. Let the model write test vectors, and make the HDL test bench compare bit for bit.

The C++ model then plays the role that PySDR’s Python plays for the algorithm: it is the executable specification, and it runs a thousand times faster than an HDL simulation, so the expensive exploration happens in C++ and the HDL simulation only has to confirm. Vendor tools follow the same idea; AMD’s Vitis HLS ships ap_fixed, a fixed-point C++ type with similar rounding and overflow modes, for exactly this purpose.

Key Takeaways

  • A fixed-point type whose template parameters are the VHDL bit positions lets the C++ compiler compute result widths with the same rules as fixed_pkg: lossless + and *, narrowing only in resize.

  • Make rounding and overflow explicit policies. fixed_round is round-half-to-even; C++20 guarantees that >> on signed values is an arithmetic shift (round towards minus infinity).

  • Signed overflow is undefined behavior in C++. For registers that must wrap, such as CIC integrators or phase accumulators, compute in unsigned types and mask to the hardware width.

  • Hogenauer’s register width \(B_{in} + \lceil N\log_2(RM) \rceil\) is tight, and only worst-case inputs show it.

  • Let the C++ model write the test vectors and the HDL test bench compare every bit.