// fir_hls.cpp // FIR filter written for high-level synthesis (AMD Vitis HLS pragma syntax). // NOT SYNTHESISED HERE: no HLS tool was run on this file. It is compiled as // ordinary C++17 by test_fir_hls.py and checked bit for bit against a NumPy // model. A C++ compiler ignores the HLS pragmas. Under -Wall -Werror, clang // needs -Wno-unknown-pragmas for them and -Wno-unused-label for the loop // labels, which only name the loops for the HLS tool. #include "fir_hls.hpp" // 31-tap low-pass, firwin (Hamming), cutoff 6 kHz at fs = 48 kHz, Q1.15. // Identical to the default COEFS of fir_transposed.sv in lesson 15. static const coef_t COEF[NTAPS] = { -39, -67, -68, 0, 156, 324, 327, 0, -621, -1189, -1139, 0, 2249, 5022, 7322, 8216, 7322, 5022, 2249, 0, -1139, -1189, -621, 0, 327, 324, 156, 0, -68, -67, -39}; // Round half up at bit FRAC-1, shift right by FRAC, saturate to 16 bits. // The right shift of a negative value is arithmetic in clang, gcc and HLS // tools (and guaranteed from C++20 on). static sample_t round_sat(acc_t acc) { acc_t y = (acc + (acc_t(1) << (FRAC - 1))) >> FRAC; if (y > 32767) y = 32767; if (y < -32768) y = -32768; return static_cast(y); } void fir_hls(const sample_t in[MAX_LEN], sample_t out[MAX_LEN], int len, int clear) { #pragma HLS interface mode=m_axi port=in #pragma HLS interface mode=m_axi port=out #pragma HLS interface mode=s_axilite port=len #pragma HLS interface mode=s_axilite port=clear #pragma HLS interface mode=s_axilite port=return static sample_t shift_reg[NTAPS]; // filter state, kept between calls #pragma HLS array_partition variable=shift_reg type=complete if (clear) { CLEAR: for (int k = 0; k < NTAPS; k++) { #pragma HLS unroll shift_reg[k] = 0; } } if (len > MAX_LEN) len = MAX_LEN; SAMPLES: for (int n = 0; n < len; n++) { #pragma HLS pipeline II=1 const sample_t x = in[n]; acc_t acc = 0; TAPS: for (int k = NTAPS - 1; k > 0; k--) { #pragma HLS unroll shift_reg[k] = shift_reg[k - 1]; // shift the delay line acc += acc_t(shift_reg[k]) * COEF[k]; // multiply-accumulate } shift_reg[0] = x; acc += acc_t(x) * COEF[0]; out[n] = round_sat(acc); } }