text
stringlengths
41
20k
#ifndef IPS_FILTER_LT_MODEL_HPP #define IPS_FILTER_LT_MODEL_HPP #ifdef IPS_DEBUG_EN #include <iostream> #endif // IPS_DEBUG_ENi #ifdef IPS_DUMP_EN #include <sstream> #endif // IPS_DUMP_EN #include <systemc.h> #ifdef USING_TLM_TB_EN #include "ips_filter_defines.hpp" #endif // USING_TLM_TB_EN /** * @brief Filter module. * It takes care of filtering a image/kernel using a median filter or an * equivalent convolution like: * | 1/N^2 ... 1/N^2 | | img(row - N/2, col - N/2) ... img(row + N/2, col + N/2) | * img(row, col) = | ... ... .... | * | ... ... ... | * | 1/N^2 ... 1/N^2 | | img(row + N/2, col - N/2) ... img(row + N/2, col + N/2) | * * @tparam IN - data type of the inputs * @tparam OUT - data type of the outputs * @tparam N - size of the kernel */ template <typename IN = sc_uint<8>, typename OUT = sc_uint<8>, uint8_t N = 3> SC_MODULE(Filter) { protected: //----------------------------Internal Variables---------------------------- #ifdef IPS_DUMP_EN sc_trace_file* wf; #endif // IPS_DUMP_EN OUT* img_window_tmp; OUT* kernel; OUT* result_ptr; // Event to trigger the filter execution sc_event event; //-----------------------------Internal Methods----------------------------- void exec_filter(); void init(); public: /** * @brief Default constructor for Filter */ SC_HAS_PROCESS(Filter); #ifdef IPS_DUMP_EN /** * @brief Construct a new Filter object * * @param name - name of the module * @param wf - waveform file pointer */ Filter(sc_core::sc_module_name name, sc_core::sc_trace_file* wf) : sc_core::sc_module(name), wf(wf) #else /** * @brief Construct a new Filter object * * @param name - name of the module */ Filter(sc_core::sc_module_name name) : sc_core::sc_module(name) #endif // IPS_DUMP_EN { // Calling this method by default since it is no time consumer // It is assumed that this kernel is already loaded in the model // Kernel does not change after synthesis SC_METHOD(init); // Thread waiting for the request SC_THREAD(exec_filter); } //---------------------------------Methods--------------------------------- void filter(IN* img_window, OUT* result); }; /** * @brief Execute the image filtering * */ template <typename IN, typename OUT, uint8_t N> void Filter<IN, OUT, N>::exec_filter() { size_t i; size_t j; while (true) { // Wait to peform the convolution wait(this->event); // Default value for the result depending on the output datatype *(this->result_ptr) = static_cast<OUT >(0); // Perform the convolution for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) *(this->result_ptr) += this->kernel[i * N + j] * this->img_window_tmp[i * N + j]; } } /** * @brief Filtering image * * @param img_window - image window to filter * @param result - resultant pixel */ template <typename IN, typename OUT, uint8_t N> void Filter<IN, OUT, N>::filter(IN* img_window, OUT* result) { size_t i; size_t j; // Default value for the result depending on the output datatype this->result_ptr = result; // Perform the convolution for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) this->img_window_tmp[i * N + j] = static_cast<OUT >(img_window[i * N + j]); this->event.notify(DELAY_TIME, SC_NS); } /** * @brief Initializes a kernel of N x N with default value of 1 / (N^2) * */ template <typename IN, typename OUT, uint8_t N> void Filter<IN, OUT, N>::init() { // Init a kernel of N x N with default value of 1 / (N * N) this->kernel = new OUT[N * N]; std::fill_n(this->kernel, N * N, static_cast<OUT >(1) / static_cast<OUT > (N * N)); // Init image window of N x N with default value of 1 / (N * N) this->img_window_tmp = new OUT[N * N]; #ifdef IPS_DEBUG_EN // Print the initialized kernel SC_REPORT_INFO(this->name(), "init result"); size_t i, j; for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { std::cout << "[" << this->kernel[i * N + j] << "]"; #ifdef IPS_DUMP_EN // Adding the signals to the waveform std::ostringstream var_name; var_name << "kernel_" << i << "_" << j; sc_trace(this->wf, this->kernel[i * N + j], var_name.str()); #endif // IPS_DUMP_EN } std::cout << std::endl; } #else #ifdef IPS_DUMP_EN size_t i, j; for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { // Adding the signals to the waveform std::ostringstream var_name; var_name << "kernel_" << i << "_" << j; sc_trace(this->wf, this->kernel[i * N + j], var_name.str()); } } #endif // IPS_DUMP_EN #endif // IPS_DEBUG_EN } #endif // IPS_FILTER_LT_MODEL_HPP
#ifdef EDGE_DETECTOR_AT_EN #ifndef SOBEL_EDGE_DETECTOR_HPP #define SOBEL_EDGE_DETECTOR_HPP #include <systemc.h> #include "address_map.hpp" SC_MODULE(Edge_Detector) { #ifndef USING_TLM_TB_EN sc_inout<sc_uint<64>> data; sc_in<sc_uint<24>> address; #else sc_uint<64> data; sc_uint<64> address; #endif // USING_TLM_TB_EN const double delay_full_adder_1_bit = 0.361; const double delay_full_adder = delay_full_adder_1_bit * 16; const double delay_multiplier = 9.82; const sc_int<16> sobelGradientX[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}; const sc_int<16> sobelGradientY[3][3] = {{-1, -2, -1}, { 0, 0, 0}, { 1, 2, 1}}; sc_int<16> localWindow[3][3]; sc_int<16> resultSobelGradientX; sc_int<16> resultSobelGradientY; sc_int<16> localMultX[3][3]; sc_int<16> localMultY[3][3]; sc_event gotLocalWindow; sc_event rd_t, wr_t; sc_event mult_x, mult_y, sum_x, sum_y; SC_CTOR(Edge_Detector) { SC_THREAD(wr); SC_THREAD(rd); SC_THREAD(compute_sobel_gradient_x); SC_THREAD(compute_sobel_gradient_y); SC_THREAD(perform_mult_gradient_x); SC_THREAD(perform_mult_gradient_y); SC_THREAD(perform_sum_gradient_x); SC_THREAD(perform_sum_gradient_y); } virtual void write(); virtual void read(); virtual void wr(); void rd(); void compute_sobel_gradient_x(); void compute_sobel_gradient_y(); void perform_mult_gradient_x(); void perform_mult_gradient_y(); void perform_sum_gradient_x(); void perform_sum_gradient_y(); }; #endif // SOBEL_EDGE_DETECTOR_HPP #endif // EDGE_DETECTOR_AT_EN
#ifndef RGB2GRAY_TLM_HPP #define RGB2GRAY_TLM_HPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "rgb2gray_pv_model.hpp" #include "../src/img_target.cpp" //Extended Unification TLM struct rgb2gray_tlm : public Rgb2Gray, public img_target { rgb2gray_tlm(sc_module_name name) : Rgb2Gray((std::string(name) + "_HW_block").c_str()), img_target((std::string(name) + "_target").c_str()) { #ifdef DISABLE_RGB_DEBUG this->use_prints = false; #endif //DISABLE_RGB_DEBUG checkprintenableimgtar(use_prints); } //Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); }; #endif // RGB2GRAY_TLM_HPP
#ifndef IPS_FILTER_LT_MODEL_HPP #define IPS_FILTER_LT_MODEL_HPP #ifdef IPS_DEBUG_EN #include <iostream> #endif // IPS_DEBUG_ENi #ifdef IPS_DUMP_EN #include <sstream> #endif // IPS_DUMP_EN #include <systemc.h> #define IPS_FILTER_KERNEL_SIZE 3 #define DELAY_TIME (IPS_FILTER_KERNEL_SIZE * IPS_FILTER_KERNEL_SIZE * 1) + 4 + 2 + 1 /** * @brief Filter module. * It takes care of filtering a image/kernel using a median filter or an * equivalent convolution like: * | 1/N^2 ... 1/N^2 | | img(row - N/2, col - N/2) ... img(row + N/2, col + N/2) | * img(row, col) = | ... ... .... | * | ... ... ... | * | 1/N^2 ... 1/N^2 | | img(row + N/2, col - N/2) ... img(row + N/2, col + N/2) | * * @tparam IN - data type of the inputs * @tparam OUT - data type of the outputs * @tparam N - size of the kernel */ template <typename IN = sc_uint<8>, typename OUT = sc_uint<8>, uint8_t N = 3> SC_MODULE(Filter) { protected: //----------------------------Internal Variables---------------------------- #ifdef IPS_DUMP_EN sc_trace_file* wf; #endif // IPS_DUMP_EN OUT* img_window_tmp; OUT* kernel; OUT* result_ptr; // Event to trigger the filter execution sc_event event; //-----------------------------Internal Methods----------------------------- void exec_filter(); void init(); public: /** * @brief Default constructor for Filter */ SC_HAS_PROCESS(Filter); #ifdef IPS_DUMP_EN /** * @brief Construct a new Filter object * * @param name - name of the module * @param wf - waveform file pointer */ Filter(sc_core::sc_module_name name, sc_core::sc_trace_file* wf) : sc_core::sc_module(name), wf(wf) #else /** * @brief Construct a new Filter object * * @param name - name of the module */ Filter(sc_core::sc_module_name name) : sc_core::sc_module(name) #endif // IPS_DUMP_EN { // Calling this method by default since it is no time consumer // It is assumed that this kernel is already loaded in the model // Kernel does not change after synthesis SC_METHOD(init); // Thread waiting for the request SC_THREAD(exec_filter); } //---------------------------------Methods--------------------------------- void filter(IN* img_window, OUT* result); }; /** * @brief Execute the image filtering * */ template <typename IN, typename OUT, uint8_t N> void Filter<IN, OUT, N>::exec_filter() { size_t i; size_t j; while (true) { // Wait to peform the convolution wait(this->event); // Default value for the result depending on the output datatype *(this->result_ptr) = static_cast<OUT >(0); // Perform the convolution for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) *(this->result_ptr) += this->kernel[i * N + j] * this->img_window_tmp[i * N + j]; } } /** * @brief Filtering image * * @param img_window - image window to filter * @param result - resultant pixel */ template <typename IN, typename OUT, uint8_t N> void Filter<IN, OUT, N>::filter(IN* img_window, OUT* result) { size_t i; size_t j; // Default value for the result depending on the output datatype this->result_ptr = result; // Perform the convolution for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) this->img_window_tmp[i * N + j] = static_cast<OUT >(img_window[i * N + j]); this->event.notify(DELAY_TIME, SC_NS); } /** * @brief Initializes a kernel of N x N with default value of 1 / (N^2) * */ template <typename IN, typename OUT, uint8_t N> void Filter<IN, OUT, N>::init() { // Init a kernel of N x N with default value of 1 / (N * N) this->kernel = new OUT[N * N]; std::fill_n(this->kernel, N * N, static_cast<OUT >(1) / static_cast<OUT > (N * N)); // Init image window of N x N with default value of 1 / (N * N) this->img_window_tmp = new OUT[N * N]; #ifdef IPS_DEBUG_EN // Print the initialized kernel SC_REPORT_INFO(this->name(), "init result"); size_t i, j; for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { std::cout << "[" << this->kernel[i * N + j] << "]"; #ifdef IPS_DUMP_EN // Adding the signals to the waveform std::ostringstream var_name; var_name << "kernel_" << i << "_" << j; sc_trace(this->wf, this->kernel[i * N + j], var_name.str()); #endif // IPS_DUMP_EN } std::cout << std::endl; } #else #ifdef IPS_DUMP_EN size_t i, j; for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { // Adding the signals to the waveform std::ostringstream var_name; var_name << "kernel_" << i << "_" << j; sc_trace(this->wf, this->kernel[i * N + j], var_name.str()); } } #endif // IPS_DUMP_EN #endif // IPS_DEBUG_EN } #endif // IPS_FILTER_LT_MODEL_HPP
#ifndef IPS_FILTER_TLM_HPP #define IPS_FILTER_TLM_HPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include "ips_filter_lt_model.hpp" #include "../src/img_target.cpp" #include "important_defines.hpp" //Extended Unification TLM struct ips_filter_tlm : public Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>, public img_target { SC_CTOR(ips_filter_tlm): Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>(Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>::name()), img_target(img_target::name()) { set_mem_attributes(IMG_FILTER_KERNEL_ADDRESS_LO, IMG_FILTER_KERNEL_SIZE+IMG_FILTER_OUTPUT_SIZE); } //Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); IPS_IN_TYPE_TB img_window[IPS_FILTER_KERNEL_SIZE * IPS_FILTER_KERNEL_SIZE]; IPS_OUT_TYPE_TB img_result; }; #endif // IPS_FILTER_TLM_HPP
/* * @ASCK */ #include <systemc.h> SC_MODULE (WB) { sc_in_clk clk; sc_in <sc_int<8>> prev_alu_result; sc_in <sc_int<8>> prev_mem_result; sc_in <bool> prev_WbMux; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_alu_result; sc_out <sc_int<8>> next_mem_result; sc_out <bool> next_WbMux; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (WB){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_alu_result.write(prev_alu_result.read()); next_mem_result.write(prev_mem_result.read()); next_WbMux.write(prev_WbMux.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
/* Copyright 2017 Columbia University, SLD Group */ // // tb.h - Robert Margelli // Testbench header file. // #ifndef __TB__H #define __TB__H #include <time.h> #include <systemc.h> #include "cynw_flex_channels.h" #include <esc.h> #include "hl5_datatypes.hpp" #include "globals.hpp" #include "defines.hpp" SC_MODULE(tb) { public: // Declaration of clock and reset parameters sc_in < bool > clk; sc_in < bool > rst; // End of simulation signal. sc_in < bool > program_end; // Fetch enable signal. sc_out < bool > fetch_en; // CPU Reset sc_out < bool > cpu_rst; // Entry point sc_out < unsigned > entry_point; // TODO: removeme // sc_in < bool > main_start; // sc_in < bool > main_end; // Instruction counters sc_in < long int > icount; sc_in < long int > j_icount; sc_in < long int > b_icount; sc_in < long int > m_icount; sc_in < long int > o_icount; sc_uint<XLEN> *imem; sc_uint<XLEN> *dmem; SC_HAS_PROCESS(tb); tb(sc_module_name name, sc_uint<XLEN> imem[ICACHE_SIZE], sc_uint<XLEN> dmem[DCACHE_SIZE]) : clk("clk") , rst("rst") , program_end("program_end") , fetch_en("fetch_en") , cpu_rst("cpu_rst") , entry_point("entry_point") // , main_start("main_start") // , main_end("main_end") , icount("icount") , j_icount("j_icount") , b_icount("b_icount") , m_icount("m_icount") , o_icount("o_icount") , imem(imem) , dmem(dmem) { SC_CTHREAD(source, clk.pos()); reset_signal_is(rst, 0); SC_CTHREAD(sink, clk.pos()); reset_signal_is(rst, 0); } void source(); void sink(); double exec_start; // double exec_main_start; }; #endif
// Copyright (c) 2011-2024 Columbia University, System Level Design Group // SPDX-License-Identifier: MIT #ifndef __ESP_SYSTEMC_HPP__ #define __ESP_SYSTEMC_HPP__ // Fixed point #if defined(SC_FIXED_POINT) || defined(SC_FIXED_POINT_FAST) // Using SystemC fixed point #define SC_INCLUDE_FX #include <systemc.h> #else // Using cynw fixed point (default) #include <systemc.h> #include <cynw_fixed.h> #endif // Channels #ifdef __CARGO__ // Using CARGO flex channels #include <flex_channels.hpp> #else // Using cynw flex channels (default) #include <cynw_flex_channels.h> #endif #endif // __ESP_SYSTEMC_HPP__
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _Tripleur_ #define _Tripleur_ #include "systemc.h" #include <cstdint> SC_MODULE(Tripleur) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_int<8> > e; sc_fifo_out< sc_int<8> > s1; sc_fifo_out< sc_int<8> > s2; sc_fifo_out< sc_int<8> > s3; SC_CTOR(Tripleur) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: void do_gen( ) { while ( true ) { const uint8_t data = e.read(); s1.write( data ); s2.write( data ); s3.write( data ); } } }; #endif
/* Copyright 2017 Columbia University, SLD Group */ // // system.h - Robert Margelli // Top-level model header file. // Instantiates the CPU, TB, IMEM, DMEM. // #ifndef SYSTEM_H_INCLUDED #define SYSTEM_H_INCLUDED #include <systemc.h> #include "cynw_flex_channels.h" #include "hl5_datatypes.hpp" #include "defines.hpp" #include "globals.hpp" #include "hl5_wrap.h" #include "tb.hpp" SC_MODULE(TOP) { public: // Clock and reset sc_in<bool> clk; sc_in<bool> rst; // End of simulation signal. sc_signal < bool > program_end; // Fetch enable signal. sc_signal < bool > fetch_en; // CPU Reset sc_signal < bool > cpu_rst; // Entry point sc_signal < unsigned > entry_point; // TODO: removeme // sc_signal < bool > main_start; // sc_signal < bool > main_end; // Instruction counters sc_signal < long int > icount; sc_signal < long int > j_icount; sc_signal < long int > b_icount; sc_signal < long int > m_icount; sc_signal < long int > o_icount; // Cache modeled as arryas sc_uint<XLEN> imem[ICACHE_SIZE]; sc_uint<XLEN> dmem[DCACHE_SIZE]; /* The testbench, DUT, IMEM and DMEM modules. */ tb *m_tb; hl5_wrapper *m_dut; SC_CTOR(TOP) : clk("clk") , rst("rst") , program_end("program_end") , fetch_en("fetch_en") , cpu_rst("cpu_rst") , entry_point("entry_point") { m_tb = new tb("tb", imem, dmem); m_dut = new hl5_wrapper("dut", imem, dmem); // Connect the design module m_dut->clk(clk); m_dut->rst(cpu_rst); m_dut->entry_point(entry_point); m_dut->program_end(program_end); m_dut->fetch_en(fetch_en); // m_dut->main_start(main_start); // m_dut->main_end(main_end); m_dut->icount(icount); m_dut->j_icount(j_icount); m_dut->b_icount(b_icount); m_dut->m_icount(m_icount); m_dut->o_icount(o_icount); // Connect the testbench m_tb->clk(clk); m_tb->rst(rst); m_tb->cpu_rst(cpu_rst); m_tb->entry_point(entry_point); m_tb->program_end(program_end); m_tb->fetch_en(fetch_en); // m_tb->main_start(main_start); // m_tb->main_end(main_end); m_tb->icount(icount); m_tb->j_icount(j_icount); m_tb->b_icount(b_icount); m_tb->m_icount(m_icount); m_tb->o_icount(o_icount); } ~TOP() { delete m_tb; delete m_dut; delete imem; delete dmem; } }; #endif // SYSTEM_H_INCLUDED
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _ModuleCompute_ #define _ModuleCompute_ #include "systemc.h" #include <cstdint> SC_MODULE(ModuleCompute) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_int <8> > e; sc_fifo_out< sc_uint<8> > s; SC_CTOR(ModuleCompute) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: /* template< int XW, int OW, bool OS > void ac_sqrt( ac_int<XW,false> x, ac_int<OW,OS> &sqrt ) { const int RW = (XW+1)/2; // masks used only to hint synthesis on precision ac_int<RW+2, false> mask_d = 0; ac_int<RW+2, false> d = 0; ac_int<RW, false> r = 0; ac_int<2*RW, false> z = x; // needs to pick 2 bits of z for each iteration starting from // the 2 MSB bits. Inside loop, z will be shifted left by 2 each // iteration. The bits of interest are always on the same // position (z_shift+1 downto z_shift) unsigned int z_shift = (RW-1)*2; for (int i = RW-1; i >= 0; i--) { r <<= 1; mask_d = (mask_d << 2) | 0x3; d = mask_d & (d << 2) | ((z >> z_shift) & 0x3 ); ac_int<RW+2, false> t = (ac_int<RW+2, false>)(d - (( ((ac_int<RW+1, false>)r) << 1) | 0x1)); if ( !t[RW+1] ) { // since t is unsigned, look at MSB r |= 0x1; d = mask_d & t; } z <<= 2; } sqrt = r; } */ unsigned short int_sqrt32(unsigned short x) { unsigned char res = 0; unsigned char add = 0x80; // 32b = 0x8000 int i; for(i = 0; i < 8; i++) // 32b = 16 { unsigned char temp = res | add; unsigned short g2 = temp * temp; if (x >= g2) { res = temp; } add >>=1; } return res; } void do_gen( ) { while ( true ) { //#pragma HLS PIPELINE enable_flush #if 0 float breal = e.read(); float bimag = e.read(); float resul = sqrt( breal * breal + bimag * bimag); s.write( (sc_uint<8>)resul ); #else const sc_int < 8> breal = e.read(); const sc_int < 8> bimag = e.read(); const sc_uint<16> rr = (breal * breal); const sc_uint<16> ii = (bimag * bimag); sc_uint< 8> rc = int_sqrt32( rr + ii); s.write( rc ); #endif } } }; #endif
#include <systemc.h> #include <systemc-ams.h> #include <config.hpp> #define ${sensor_name}_VREF ${vref} SCA_TDF_MODULE(Sensor_${sensor_name}_power) { //Data from Functional Instance sca_tdf::sc_in <int> func_signal; //Data to Power Bus sca_tdf::sca_out <double> voltage_state; sca_tdf::sca_out <double> current_state; SCA_CTOR(Sensor_${sensor_name}_power): func_signal("State_of_Power_From_Functional"), voltage_state("Voltage_trace_to_Power_Bus"), current_state("Current_trace_to_Power_Bus") {} void set_attributes(); void initialize(); void processing(); Sensor_${sensor_name}_power(){} };
#ifdef EDGE_DETECTOR_LT_EN #ifndef SOBEL_EDGE_DETECTOR_HPP #define SOBEL_EDGE_DETECTOR_HPP #include <systemc.h> SC_MODULE(Edge_Detector) { int localWindow[3][3]; const int sobelGradientX[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}; const int sobelGradientY[3][3] = {{-1, -2, -1}, { 0, 0, 0}, { 1, 2, 1}}; int resultSobelGradientX; int resultSobelGradientY; sc_event gotLocalWindow, finishedSobelGradientX, finishedSobelGradientY; SC_CTOR(Edge_Detector) { SC_THREAD(compute_sobel_gradient_x); SC_THREAD(compute_sobel_gradient_y); } void set_local_window(int window[3][3]); void compute_sobel_gradient_x(); void compute_sobel_gradient_y(); int obtain_sobel_gradient_x(); int obtain_sobel_gradient_y(); }; #endif // SOBEL_EDGE_DETECTOR_HPP #endif // EDGE_DETECTOR_LT_EN
/***************************************************************************\ * * * ___ ___ ___ ___ * / /\ / /\ / /\ / /\ * / /:/ / /::\ / /::\ / /::\ * / /:/ / /:/\:\ / /:/\:\ / /:/\:\ * / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/ * / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/ * /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/ * \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/ * \ \:\ \ \:\ \ \:\ \ \:\ * \ \ \ \ \:\ \ \:\ \ \:\ * \__\/ \__\/ \__\/ \__\/ * * * * * This file is part of TRAP. * * TRAP is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * or see <http://www.gnu.org/licenses/>. * * * * (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com * \***************************************************************************/ #ifndef PROFINFO_HPP #define PROFINFO_HPP #include <string> #include <systemc.h> namespace trap{ ///Represents all the profiling data which can be ///associated with a single assembly instruction struct ProfInstruction{ ///Name of the assembly instruction (MOV, ADD ...) std::string name; ///Number of times this instruction is called unsigned long long numCalls; ///Total number of instructions executed static unsigned long long numTotalCalls; ///Total time spent in executing the instruction sc_time time; ///dump these information to a string, in the command separated values (CVS) format std::string printCsv(); ///Prints the description of the informations which describe an instruction, in the command separated values (CVS) format static std::string printCsvHeader(); ///Prints the summary of all the executed instructions, in the command separated values (CVS) format static std::string printCsvSummary(); ///Empty constructor, performs the initialization of the statistics ProfInstruction(); }; ///Represents all the profiling data which can be ///associated with a single function struct ProfFunction{ ///Address of the function unsigned int address; ///Name of the function std::string name; ///Number of times this function is called unsigned long long numCalls; ///Total number of function calls static unsigned long long numTotalCalls; ///The number of assembly instructions executed in total inside the function unsigned long long totalNumInstr; ///The number of assembly instructions executed exclusively inside the function unsigned long long exclNumInstr; ///Total time spent in the function sc_time totalTime; ///Time spent exclusively in the function sc_time exclTime; ///Used to coorectly keep track of the increment of the time, instruction count, etc. ///in recursive functions bool alreadyExamined; ///dump these information to a string, in the command separated values (CVS) format std::string printCsv(); ///Prints the description of the informations which describe a function, in the command separated values (CVS) format static std::string printCsvHeader(); ///Empty constructor, performs the initialization of the statistics ProfFunction(); }; } #endif
// Copyright (c) 2011-2021 Columbia University, System Level Design Group // SPDX-License-Identifier: Apache-2.0 #ifndef __GEMM_ACCELERATOR_CONF_INFO_HPP__ #define __GEMM_ACCELERATOR_CONF_INFO_HPP__ #include <systemc.h> // // Configuration parameters for the accelerator. // class conf_info_t { public: // // constructors // conf_info_t() { /* <<--ctor-->> */ this->gemm_m = 64; this->gemm_n = 64; this->gemm_k = 64; } conf_info_t( /* <<--ctor-args-->> */ int32_t gemm_m, int32_t gemm_n, int32_t gemm_k ) { /* <<--ctor-custom-->> */ this->gemm_m = gemm_m; this->gemm_n = gemm_n; this->gemm_k = gemm_k; } // equals operator inline bool operator==(const conf_info_t &rhs) const { /* <<--eq-->> */ if (gemm_m != rhs.gemm_m) return false; if (gemm_n != rhs.gemm_n) return false; if (gemm_k != rhs.gemm_k) return false; return true; } // assignment operator inline conf_info_t& operator=(const conf_info_t& other) { /* <<--assign-->> */ gemm_m = other.gemm_m; gemm_n = other.gemm_n; gemm_k = other.gemm_k; return *this; } // VCD dumping function friend void sc_trace(sc_trace_file *tf, const conf_info_t &v, const std::string &NAME) {} // redirection operator friend ostream& operator << (ostream& os, conf_info_t const &conf_info) { os << "{"; /* <<--print-->> */ os << "gemm_m = " << conf_info.gemm_m << ", "; os << "gemm_n = " << conf_info.gemm_n << ", "; os << "gemm_k = " << conf_info.gemm_k << ""; os << "}"; return os; } /* <<--params-->> */ int32_t gemm_m; int32_t gemm_n; int32_t gemm_k; }; #endif // __GEMM_ACCELERATOR_CONF_INFO_HPP__
#ifndef IMG_RECEIVER_TLM_HPP #define IMG_RECEIVER_TLM_HPP #include <systemc.h> #include "img_receiver.hpp" #include "../src/img_target.cpp" #include "address_map.hpp" struct img_receiver_tlm: public img_receiver, public img_target { img_receiver_tlm(sc_module_name name) : img_receiver((std::string(name) + "_receiver").c_str()), img_target((std::string(name) + "_target").c_str()) { set_mem_attributes(IMG_INPUT_ADDRESS_LO, IMG_INPUT_SIZE); } //Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); }; #endif // IMG_RECEIVER_TLM_HPP
/* * Copyright (c) 2010 TIMA Laboratory * * This file is part of Rabbits. * * Rabbits is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Rabbits is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Rabbits. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #include <system_init.h> #include <systemc.h> #include <abstract_noc.h> #include <interconnect_master.h> #include <../../qemu/qemu-0.9.1/qemu_systemc.h> #include <qemu_wrapper.h> #include <qemu_cpu_wrapper.h> #include <qemu_wrapper_cts.h> #include <interconnect.h> #include <sram_device.h> #include <dbf_device.h> #include <framebuffer_device.h> #include <timer_device.h> #include <tty_serial_device.h> #include <sem_device.h> #include <mem_device.h> #include <sl_block_device.h> #include <qemu_imported.h> #include <qemu_wrapper_cts.h> #ifndef O_BINARY #define O_BINARY 0 #endif unsigned long no_frames_to_simulate = 0; mem_device *ram = NULL; interconnect *onoc = NULL; slave_device *slaves[50]; int nslaves = 0; init_struct is; int sc_main (int argc, char ** argv) { int i; memset (&is, 0, sizeof (init_struct)); is.cpu_family = "arm"; is.cpu_model = NULL; is.kernel_filename = NULL; is.initrd_filename = NULL; is.no_cpus = 4; is.ramsize = 256 * 1024 * 1024; parse_cmdline (argc, argv, &is); if (check_init (&is) != 0) return 1; fb_reset_t fb_res_stat = { /* .fb_start = */ 0, /* .fb_w = */ 0, /* .fb_h = */ 0, /* .fb_mode = */ NONE, /* .fb_display_on_warp = */ 0, }; //slaves ram = new mem_device ("dynamic", is.ramsize + 0x1000); sram_device *sram = new sram_device ("sram", 0x800000); tty_serial_device *tty = new tty_serial_device ("tty"); sem_device *sem = new sem_device ("sem", 0x100000); fb_device *fb = new fb_device("fb", is.no_cpus, &fb_res_stat); dbf_device *dbf = new dbf_device("DBF", is.no_cpus + 1/* , nslaves + 1*/); sl_block_device *bl = new sl_block_device("block", is.no_cpus + 2, NULL, 1); timer_device *timers[1]; int ntimers = sizeof (timers) / sizeof (timer_device *); slaves[nslaves++] = ram; // 0 slaves[nslaves++] = sram; // 1 slaves[nslaves++] = fb->get_slave(); // 2 slaves[nslaves++] = tty; // 3 slaves[nslaves++] = sem; // 4 slaves[nslaves++] = bl->get_slave(); // 5 for (i = 0; i < ntimers; i++){ char buf[20]; sprintf (buf, "timer_%d", i); timers[i] = new timer_device (buf); slaves[nslaves++] = timers[i]; // 6 + i } int no_irqs = ntimers + 3; /* timers + TTY + FB + DBF */ int int_cpu_mask [] = {1, 1, 1, 1, 0, 0}; sc_signal<bool> *wires_irq_qemu = new sc_signal<bool>[no_irqs]; for (i = 0; i < ntimers; i++) timers[i]->irq(wires_irq_qemu[i]); tty->irq_line(wires_irq_qemu[ntimers]); fb->irq(wires_irq_qemu[ntimers + 1]); dbf->irq(wires_irq_qemu[ntimers + 2]); //interconnect onoc = new interconnect ("interconnect", is.no_cpus + 3, /* masters: CPUs + FB + DBF + BL*/ nslaves + 1); /* slaves: ... */ for (i = 0; i < nslaves; i++) onoc->connect_slave_64 (i, slaves[i]->get_port, slaves[i]->put_port); onoc->connect_slave_64(nslaves, dbf->get_port, dbf->put_port); arm_load_kernel (&is); //masters qemu_wrapper qemu1 ("QEMU1", 0, no_irqs, int_cpu_mask, is.no_cpus, is.cpu_family, is.cpu_model, is.ramsize); qemu1.add_map(0xA0000000, 0x20000000); // (base address, size) qemu1.set_base_address (QEMU_ADDR_BASE); for(i = 0; i < no_irqs; i++) qemu1.interrupt_ports[i] (wires_irq_qemu[i]); for(i = 0; i < is.no_cpus; i++) onoc->connect_master_64 (i, qemu1.get_cpu(i)->put_port, qemu1.get_cpu(i)->get_port); if(is.gdb_port > 0){ qemu1.m_qemu_import.gdb_srv_start_and_wait(qemu1.m_qemu_instance, is.gdb_port); //qemu1.set_unblocking_write (0); } /* Master : FrameBuffer */ onoc->connect_master_64(is.no_cpus, fb->get_master()->put_port, fb->get_master()->get_port); /* Master : H264 DBF */ onoc->connect_master_64(is.no_cpus + 1, dbf->master_put_port, dbf->master_get_port); /* Block device*/ sc_signal<bool> bl_irq_wire; bl->irq (bl_irq_wire); onoc->connect_master_64(is.no_cpus + 2, bl->get_master()->put_port, bl->get_master()->get_port); sc_start (); return 0; } void invalidate_address (unsigned long addr, int slave_id, unsigned long offset_slave, int src_id) { int i, first_node_id; unsigned long taddr; qemu_wrapper *qw; for (i = 0; i < qemu_wrapper::s_nwrappers; i++) { qw = qemu_wrapper::s_wrappers[i]; first_node_id = qw->m_cpus[0]->m_node_id; if (src_id >= first_node_id && src_id < first_node_id + qw->m_ncpu) { qw->invalidate_address (addr, src_id - first_node_id); } else { if (onoc->get_master (first_node_id)->get_liniar_address ( slave_id, offset_slave, taddr)) { qw->invalidate_address (taddr, -1); } } } } int systemc_load_image (const char *file, unsigned long ofs) { if (file == NULL) return -1; int fd, img_size, size; fd = open (file, O_RDONLY | O_BINARY); if (fd < 0) return -1; img_size = lseek (fd, 0, SEEK_END); if (img_size + ofs > ram->get_size ()) { printf ("%s - RAM size < %s size + %lx\n", __FUNCTION__, file, ofs); close(fd); exit (1); } lseek (fd, 0, SEEK_SET); size = img_size; if (read (fd, ram->get_mem () + ofs, size) != size) { printf ("Error reading file (%s) in function %s.\n", file, __FUNCTION__); close(fd); exit (1); } close (fd); return img_size; } unsigned char* systemc_get_sram_mem_addr () { return ram->get_mem (); } extern "C" { unsigned char dummy_for_invalid_address[256]; struct mem_exclusive_t {unsigned long addr; int cpus;} mem_exclusive[100]; int no_mem_exclusive = 0; #define idx_to_bit(idx) (1 << (idx)) void memory_mark_exclusive (int cpu, unsigned long addr) { mem_exclusive_t *entry; int i; addr &= 0xFFFFFFFC; for (i = 0; i < no_mem_exclusive; i++) { entry = &mem_exclusive[i]; if (entry->addr == addr) { entry->cpus |= idx_to_bit(cpu); return; } } entry = &mem_exclusive[no_mem_exclusive]; entry->addr = addr; entry->cpus = idx_to_bit(cpu); no_mem_exclusive++; } static int delete_entry(int i) { for (; i < no_mem_exclusive - 1; i++) { mem_exclusive[i].addr = mem_exclusive[i + 1].addr; mem_exclusive[i].cpus = mem_exclusive[i + 1].cpus; } no_mem_exclusive--; } int memory_test_exclusive (int cpu, unsigned long addr) { int i; addr &= 0xFFFFFFFC; for (i = 0; i < no_mem_exclusive; i++) { mem_exclusive_t *entry = &mem_exclusive[i]; if (entry->addr == addr) { if (entry->cpus & idx_to_bit(cpu)) { delete_entry(i); return 0; } break; } } return 1; } void memory_clear_exclusive (int cpu, unsigned long addr) { int i; addr &= 0xFFFFFFFC; for (i = 0; i < no_mem_exclusive; i++) { mem_exclusive_t *entry = &mem_exclusive[i]; if (entry->addr == addr) { delete_entry(i); return; } } } unsigned char *systemc_get_mem_addr (qemu_cpu_wrapper_t *qw, unsigned long addr) { int slave_id = onoc->get_master (qw->m_node_id)->get_slave_id_for_mem_addr (addr); if (slave_id == -1) return dummy_for_invalid_address; return slaves[slave_id]->get_mem () + addr; } } /* * Vim standard variables * vim:set ts=4 expandtab tw=80 cindent syntax=c: * * Emacs standard variables * Local Variables: * mode: c * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: nil * End: */
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #pragma once #define SC_INCLUDE_FX #include <systemc.h> //#if __RTL_SIMULATION__ //#include "cnn_rtl_wrapper.h" //#else //#include "hwcore/cnn/cnn.h" //#endif #include "hwcore/cnn/cnn.h" #include "hwcore/hf/helperlib.h" #include "hwcore/pipes/pipes.h" #if __RTL_SIMULATION__ //#include "DMA_performance_tester_rtl_wrapper.h" //#else //#include "DMA_generic_performance_tester.hpp" #endif SC_MODULE(mon_CNN) { sc_in<bool> clk; sc_out<bool> reset; sc_fifo_in<hwcore::pipes::sc_data_stream_t<OUTPUT_WIDTH> > data_in; SC_CTOR_DEFAULT(mon_CNN) { SC_CTHREAD(mon_thread, clk.pos()); // sensitive << clk; } void mon_thread() { reset.write(true); wait(); wait(); wait(); wait(); wait(); wait(); wait(); reset.write(false); for (int i = 0; i < 20; i++) wait(); int counter = 1; int last_count = 1; sc_fixed<DATA_W, DATA_P> value = -1.0; sc_fixed<DATA_W, DATA_P> value_inc = 0.123; sc_fixed<DATA_W, DATA_P> Win[16 * 16]; sc_fixed<DATA_W, DATA_P> Xin[16 * 16]; for (int wIdx = 0; wIdx < 16 * 16; wIdx++) { Win[wIdx] = value; value += value_inc; if (value > 1.0) { value = -1.0; } } for (int xIdx = 0; xIdx < 16 * 16; xIdx++) { Xin[xIdx] = value; value += value_inc; if (value > 1.0) { value = -1.0; } } sc_fixed<DATA_W, DATA_P> Y_golden[16 * 16]; for (int a = 0; a < 16; a++) { for (int b = 0; b < 16; b++) { sc_fixed<DATA_W, DATA_P> tmp = 0; for (int wi = 0; wi < 16; wi++) { tmp += Win[wi + (b * 16)] * Xin[(a * 16) + wi]; } Y_golden[(a * 16) + b] = tmp; } } sc_fixed<DATA_W, DATA_P> Y[16 * 16]; hwcore::pipes::sc_data_stream_t<OUTPUT_WIDTH> tmp; for (int a = 0; a < 16; a++) { for (int b = 0; b < 16 / OUTPUT_BW_N; b++) { tmp = data_in.read(); sc_fixed<DATA_W, DATA_P> data_in[OUTPUT_BW_N]; tmp.getDataFixed<DATA_W, DATA_P, OUTPUT_BW_N>(data_in); for (int i = 0; i < OUTPUT_BW_N; i++) { Y[(a * 16) + (b * OUTPUT_BW_N) + i] = data_in[i]; HLS_DEBUG(1, 1, 0, "got knew value: ") std::cout << " |--> " << data_in[i].to_float() << " index nr: " << counter << " tlast? " << tmp.tlast.to_int() << std::endl << std::flush; counter++; } } } bool ok = true; if (tmp.tlast.to_int() != 1) { ok = false; std::cout << "error - missing tlast!!!" << std::endl << std::flush; } for (int i = 0; i < 16 * 16; i++) { std::cout << "[ " << i << " ] Y = " << Y[i].to_float() << std::endl << std::flush; // " == Y_golden = " << Y_golden[i].to_float() << std::endl << std::flush; /* if(Y[i]!=Y_golden[i]) { std::cout << "error not equal!!!" << std::endl << std::flush; ok = false; }*/ } HLS_DEBUG(1, 1, 0, "Simulation done"); if (!ok) { HLS_DEBUG(1, 1, 0, "Simulation done - with errors!!!"); } sc_stop(); } }; SC_MODULE(wave_CNN) { SC_MODULE_CLK_RESET_SIGNAL; sc_fifo_out<hwcore::pipes::sc_data_stream_t<INPUT_WIDTH> > data_out; sc_out<sc_uint<16 + 1> > weight_ctrl; //, data_ctrl; sc_out<sc_uint<16 + 1> > weight_ctrl_replay; sc_out<sc_uint<16 + 1> > ctrl_row_size_pkg; sc_out<sc_uint<16 + 1> > ctrl_window_size; sc_out<sc_uint<16 + 1> > ctrl_depth; sc_out<sc_uint<16 + 1> > ctrl_stride; sc_out<sc_uint<16 + 1> > ctrl_replay; sc_out<sc_uint<1 + 1> > ctrl_channel; sc_out<sc_uint<16 + 1> > ctrl_row_N; sc_in<sc_uint<1> > ready; template <class interface, typename T> void do_cmd(interface & itf, T value) { while (ready.read() == 0) { wait(); } itf.write((value << 1) | 0b01); while (ready.read() == 1) { wait(); } while (ready.read() == 0) { wait(); } itf.write(0); wait(); } SC_CTOR_DEFAULT(wave_CNN) { SC_CTHREAD(wave_thread, clk.pos()); SC_CTHREAD(sending_ctrls, clk.pos()); } void sending_ctrls() { wait(); while (reset.read()) { wait(); } for (int i = 0; i < 20; i++) wait(); ctrl_channel.write(0); ctrl_row_N.write(0); weight_ctrl.write(0); // data_ctrl.write(0); do_cmd(ctrl_channel, 0); do_cmd(ctrl_row_N, 16 / INPUT_BW_N); do_cmd(weight_ctrl, hwcore::pipes::sc_stream_buffer<>::ctrls::newset); do_cmd(ctrl_depth, 1); do_cmd(ctrl_replay, 1); do_cmd(ctrl_stride, 0); do_cmd(ctrl_row_size_pkg, 1024); do_cmd(ctrl_window_size, 1); for (int a = 0; a < 16; a++) { do_cmd(ctrl_channel, 1); do_cmd(weight_ctrl, hwcore::pipes::sc_stream_buffer<>::ctrls::reapeat); // do_cmd(data_ctrl,hwcore::pipes::sc_stream_buffer<>::ctrls::newset); } while (true) { wait(); } } void wave_thread() { // sending dummy weights. wait(); while (reset.read()) { wait(); } for (int i = 0; i < 15; i++) wait(); sc_fixed<DATA_W, DATA_P> value = -1.0; sc_fixed<DATA_W, DATA_P> value_inc = 0.123; HLS_DEBUG(1, 1, 0, "sending data -- weights!----------------------"); sc_fixed<DATA_W, DATA_P> Win[16 * 16]; sc_fixed<DATA_W, DATA_P> Xin[16 * 16]; for (int wIdx = 0; wIdx < 16 * 16; wIdx++) { Win[wIdx] = value; value += value_inc; if (value > 1.0) { value = -1.0; } } for (int xIdx = 0; xIdx < 16 * 16; xIdx++) { Xin[xIdx] = value; value += value_inc; if (value > 1.0) { value = -1.0; } } for (int a = 0; a < (16 * 16) / INPUT_BW_N; a++) { hwcore::pipes::sc_data_stream_t<INPUT_WIDTH> tmp; tmp.setDataFixed<DATA_W, DATA_P, INPUT_BW_N>(&Win[a * INPUT_BW_N]); tmp.setKeep(); if (a == ((16 * 16) / INPUT_BW_N) - 1) { tmp.tlast = 1; HLS_DEBUG(1, 1, 0, "sending data -- TLAST!----------------------"); } else { tmp.tlast = 0; } HLS_DEBUG(1, 1, 5, "sending data -- %s", tmp.data.to_string().c_str()); data_out.write(tmp); } // sending input data HLS_DEBUG(1, 1, 0, "sending data -- Input!----------------------"); for (int a = 0; a < 16; a++) { for (int i = 0; i < 16 / INPUT_BW_N; i++) { hwcore::pipes::sc_data_stream_t<INPUT_WIDTH> tmp; tmp.setDataFixed<DATA_W, DATA_P, INPUT_BW_N>(&Xin[(i * INPUT_BW_N) + (a * 16)]); tmp.setKeep(); if (a == (16) - 1 && i == (16 / INPUT_BW_N) - 1) { tmp.tlast = 1; HLS_DEBUG(1, 1, 0, "sending Input data -- TLAST!----------------------"); } else { tmp.tlast = 0; } HLS_DEBUG(1, 1, 5, "sending Input data -- %s", tmp.data.to_string().c_str()); data_out.write(tmp); } } /*HLS_DEBUG(1,1,0,"sending data -- Firing!----------------------"); data_ctrl.write(hwcore::pipes::sc_stream_buffer<>::ctrls::reapeat);*/ while (true) { wait(); } } }; SC_MODULE(tb_CNN) { #if __RTL_SIMULATION__ // DMA_performance_tester_rtl_wrapper u1; #else // DMA_performance_tester u1; #endif sc_clock clk; sc_signal<bool> reset; wave_CNN wave; sc_fifo<hwcore::pipes::sc_data_stream_t<INPUT_WIDTH> > wave_2_u1; sc_signal<sc_uint<31 + 1> > weight_ctrl; //, data_ctrl; sc_signal<sc_uint<16 + 1> > ctrl_row_size_pkg; sc_signal<sc_uint<16 + 1> > ctrl_window_size; sc_signal<sc_uint<16 + 1> > ctrl_depth; sc_signal<sc_uint<16 + 1> > ctrl_stride; sc_signal<sc_uint<16 + 1> > ctrl_replay; sc_signal<sc_uint<1 + 1> > ctrl_channel; sc_signal<sc_uint<16 + 1> > ctrl_row_N; sc_signal<sc_uint<1> > ready; // sc_fifo<hwcore::pipes::sc_data_stream_t<16> > wave_2_u1; ::cnn cnn_u1; // hwcore::cnn::top_cnn<16,8,1,1,16,16> cnn_u1; sc_fifo<hwcore::pipes::sc_data_stream_t<OUTPUT_WIDTH> > u1_2_mon; mon_CNN mon; sc_trace_file *tracePtr; SC_CTOR_DEFAULT(tb_CNN) : SC_INST(wave), SC_INST(cnn_u1), SC_INST(mon), clk("clk", sc_time(10, SC_NS)) { SC_MODULE_LINK(wave); SC_MODULE_LINK(mon); SC_MODULE_LINK(cnn_u1); wave.ctrl_row_size_pkg(ctrl_row_size_pkg); wave.ctrl_window_size(ctrl_window_size); wave.ctrl_depth(ctrl_depth); wave.ctrl_stride(ctrl_stride); wave.ctrl_replay(ctrl_replay); wave.ready(ready); wave.data_out(wave_2_u1); // wave.data_ctrl(data_ctrl); wave.weight_ctrl(weight_ctrl); wave.ctrl_row_N(ctrl_row_N); wave.ctrl_channel(ctrl_channel); cnn_u1.ready(ready); cnn_u1.ctrl_row_size_pkg(ctrl_row_size_pkg); cnn_u1.ctrl_window_size(ctrl_window_size); cnn_u1.ctrl_depth(ctrl_depth); cnn_u1.ctrl_stride(ctrl_stride); cnn_u1.ctrl_replay(ctrl_replay); cnn_u1.ctrl_row_N(ctrl_row_N); cnn_u1.weight_ctrls(weight_ctrl); // cnn_u1.data_ctrls(data_ctrl); cnn_u1.ctrl_channel(ctrl_channel); cnn_u1.data_sink(wave_2_u1); cnn_u1.data_source(u1_2_mon); mon.data_in(u1_2_mon); tracePtr = sc_create_vcd_trace_file("tb_CNN"); trace(tracePtr); } inline void trace(sc_trace_file * trace) { SC_TRACE_ADD(clk); SC_TRACE_ADD(reset); SC_TRACE_ADD_MODULE(wave_2_u1); SC_TRACE_ADD_MODULE(data_ctrl); SC_TRACE_ADD_MODULE(weight_ctrl); SC_TRACE_ADD_MODULE(ctrl_row_N); SC_TRACE_ADD_MODULE(ctrl_channel); SC_TRACE_ADD_MODULE(cnn_u1); SC_TRACE_ADD_MODULE(u1_2_mon); } virtual ~tb_CNN() { sc_close_vcd_trace_file(tracePtr); } }; /*{ #define SC_FIFO_IN_TRANSACTOR_ADD_SIGNALS(portName,width,if_type)\ sc_signal<if_type > dma_sink_dout;\ sc_signal< sc_logic > portName##_read;\ sc_signal< sc_logic > portName##_empty_n;\ sc_signal< sc_lv<width> > portName##_0_dout\ sc_signal< sc_logic > portName##_0_read;\ sc_signal< sc_lv<1> > portName##_1_dout;\ sc_signal< sc_logic > portName##_1_read;\ sc_signal< sc_lv<width/8> > portName##_2_dout; #define SC_FIFO_IN_TRANSACTOR_ADD(inst,portName,id)\ inst.portName##_##id##_empty_n(portName##_empty_n);\ inst.portName##_##id##_read(portName##_read);\ inst.portName##_##id##_dout(portName##_dout_0); #define SC_FIFO_IN_TRANSACTOR_CREATE(inst,portName, width, if_type, fifo) \ SC_FIFO_in_transactor<0, if_type >* portName##_inFifo_tr = new SC_FIFO_in_transactor<0, if_type >(#portName"_inFifo_tr", AESL_ResetType::active_high_sync);\ portName##_inFifo_tr->rst(reset);\ portName##_inFifo_tr->FifoIn(fifo);\ portName##_inFifo_tr->clock(clk);\ portName##_inFifo_tr->if_empty_n(portName##_empty_n);\ portName##_inFifo_tr->if_read(portName##_read);\ portName##_inFifo_tr->if_dout(portName##_dout);\ SC_FIFO_IN_TRANSACTOR_ADD(cnn_u1,data_sink,0);\ SC_FIFO_IN_TRANSACTOR_ADD(cnn_u1,data_sink,1);\ SC_FIFO_IN_TRANSACTOR_ADD(cnn_u1,data_sink,2);\ portName##_dout_0.write((sc_lv<width>)(portName##_dout.read().data));\ portName##_dout_1.write((sc_lv<1>)(portName##_dout.read().tlast));\ portName##_dout_2.write((sc_lv<width/8>)(portName##_dout.read().tkeep)); }*/
#include <systemc.h> /** * @brief jpg_output module. Federico Cruz * It takes the image and compresses it into jpeg format * It is done in 4 parts: * 1. Divides the image in 8x8 pixel blocks; for 8-bit grayscale images the a level shift is done by substracting 128 from each pixel. * 2. Discrete Cosine Transform (DCT) of the 8x8 image. * 3. Each transformed 8x8 block is divided by a quantization value for each block entry. * 4. Each quantized 8x8 block is reordered by a Zig-Zag sequence into a array of size 64. * *5. Entropy compression by variable length encoding (huffman). Used to maximize compression. Not implemented here. */ #define PI 3.1415926535897932384626433832795 #define BLOCK_ROWS 8 #define BLOCK_COLS 8 SC_MODULE(jpg_output) { //-----------Internal variables------------------- // const int Block_rows = 8; // const int Block_cols = 8; double *image; int image_rows = 480; int image_cols = 640; signed char eob = 127; // end of block int quantificator[8][8] = {// quantization table {16, 11, 10, 16, 24, 40, 51, 61}, {12, 12, 14, 19, 26, 58, 60, 55}, {14, 13, 16, 24, 40, 57, 69, 56}, {14, 17, 22, 29, 51, 87, 80, 62}, {18, 22, 37, 56, 68, 109, 103, 77}, {24, 35, 55, 64, 81, 104, 113, 92}, {49, 64, 78, 87, 103, 121, 120, 101}, {72, 92, 95, 98, 112, 100, 103, 99}}; int zigzag_index[64] = {// zigzag table 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63}; // Constructor for compressor SC_HAS_PROCESS(jpg_output); jpg_output(sc_module_name jpg_compressor, int im_rows = 480, int im_cols = 640) : sc_module(jpg_compressor) { if (im_rows % BLOCK_ROWS == 0) { image_rows = im_rows; } else { image_rows = (im_rows / BLOCK_ROWS + 1) * BLOCK_ROWS; } if (im_cols % BLOCK_COLS == 0) { image_cols = im_cols; } else { image_cols = (im_cols / BLOCK_COLS + 1) * BLOCK_COLS; } image = new double[image_rows * image_cols]; // initialize the image matrix to avoid nan for (int i = 0; i < (image_rows * image_cols); i++) { image[i] = 0; } } // End of Constructor //------------Code Starts Here------------------------- void input_pixel(int pixel_value, int row, int col) { double *i_row = &image[row * image_cols]; i_row[col] = double(pixel_value); } void output_pixel(int *Pixel, int row, int col) { double *i_row = &image[row * image_cols]; *Pixel = int(i_row[col]); } void output_byte(signed char *element, int index) { element[index] = image[index]; } void jpeg_compression(int *output_size) { // Level shift for (int i = 0; i < (image_rows * image_cols); i++) { image[i] = image[i] - 128; } int number_of_blocks = image_rows * image_cols / (BLOCK_ROWS * BLOCK_COLS); #ifndef USING_TLM_TB_EN int block_output[number_of_blocks][BLOCK_ROWS * BLOCK_COLS] = {0}; int block_output_size[number_of_blocks] = {0}; #else int **block_output = new int *[number_of_blocks]; int *block_output_size = new int[number_of_blocks]; for (int i = 0; i < number_of_blocks; i++) { block_output[i] = new int[BLOCK_ROWS * BLOCK_COLS]; } for (int i = 0; i < number_of_blocks; i++) { block_output_size[i] = 0; for (int j = 0; j < BLOCK_ROWS * BLOCK_COLS; j++) { block_output[i][j] = 0; } } #endif // USING_TLM_TB_EN int block_counter = 0; *output_size = 0; for (int row = 0; row < image_rows; row += BLOCK_ROWS) { for (int col = 0; col < image_cols; col += BLOCK_COLS) { // Divided the image in 8×8 blocks dct(row, col); quantization(row, col); zigzag(row, col, &block_output_size[block_counter], block_output[block_counter]); *output_size += block_output_size[block_counter] + 1; block_counter++; } } int output_counter = 0; for (int block_index = 0; block_index < number_of_blocks; block_index++) { for (int out_index = 0; out_index < block_output_size[block_index]; out_index++) { image[output_counter] = block_output[block_index][out_index]; output_counter++; } image[output_counter] = eob; output_counter++; } #ifdef USING_TLM_TB_EN for (int i = 0; i < number_of_blocks; i++) { delete[] block_output[i]; } delete[] block_output; delete[] block_output_size; #endif // USING_TLM_TB_EN } void dct(int row_offset, int col_offset) { double cos_table[BLOCK_ROWS][BLOCK_COLS]; // make the cosine table for (int row = 0; row < BLOCK_ROWS; row++) { for (int col = 0; col < BLOCK_COLS; col++) { cos_table[row][col] = cos((((2 * row) + 1) * col * PI) / 16); } } double temp = 0.0; for (int row = row_offset; row < row_offset + BLOCK_ROWS; row++) { double *i_row = &image[row * image_cols]; for (int col = col_offset; col < col_offset + BLOCK_COLS; col++) { // i_row[col] = cos_table[row-row_offset][col-col_offset]; temp = 0.0; for (int x = 0; x < 8; x++) { double *x_row = &image[(x + row_offset) * image_cols]; for (int y = 0; y < 8; y++) { temp += x_row[y + col_offset] * cos_table[x][row - row_offset] * cos_table[y][col - col_offset]; } } if ((row - row_offset == 0) && (col - col_offset == 0)) { temp /= 8.0; } else if (((row - row_offset == 0) && (col - col_offset != 0)) || ((row - row_offset != 0) && (col - col_offset == 0))) { temp /= (4.0 * sqrt(2.0)); } else { temp /= 4.0; } i_row[col] = temp; } } } void quantization(int row_offset, int col_offset) { for (int row = row_offset; row < row_offset + BLOCK_ROWS; row++) { double *i_row = &image[row * image_cols]; for (int col = col_offset; col < col_offset + BLOCK_COLS; col++) { i_row[col] = round(i_row[col] / quantificator[row - row_offset][col - col_offset]); } } } void zigzag(int row_offset, int col_offset, int *block_output_size, int *block_output) { int index_last_non_zero_value = 0; // index to last non-zero in a block zigzag array for (int row = row_offset; row < row_offset + BLOCK_ROWS; row++) { double *i_row = &image[row * image_cols]; for (int col = col_offset; col < col_offset + BLOCK_COLS; col++) { int temp_index = zigzag_index[(row - row_offset) * 8 + (col - col_offset)]; block_output[temp_index] = i_row[col]; if (i_row[col] != 0 && temp_index > index_last_non_zero_value) { index_last_non_zero_value = temp_index + 1; } } } *block_output_size = index_last_non_zero_value; } };
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _Detecteur_ #define _Detecteur_ #include "systemc.h" #include <cstdint> #include "Doubleur_uint.hpp" #include "trames_separ.hpp" #include "Seuil_calc.hpp" // #define _DEBUG_SYNCHRO_ SC_MODULE(Detecteur) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_uint<8> > e; // sc_fifo_in < sc_uint<8> > e2; sc_fifo_out< sc_uint<8> > s; SC_CTOR(Detecteur): s_calc("s_calc"), t_sep("t_sep"), dbl("dbl"), dbl2scalc("dbl2scalc",1024), dbl2tsep("dbl2tsep",1024), detect("detect", 1024) { dbl.clock(clock); dbl.reset(reset); dbl.e(e); dbl.s1(dbl2scalc); dbl.s2(dbl2tsep); s_calc.clock(clock); s_calc.reset(reset); s_calc.e(dbl2scalc); s_calc.detect(detect); t_sep.clock(clock); t_sep.reset(reset); t_sep.e(dbl2tsep); t_sep.detect(detect); t_sep.s(s); } private: Seuil_calc s_calc; trames_separ t_sep; DOUBLEUR_U dbl; sc_fifo< sc_uint<8> > dbl2scalc; sc_fifo< sc_uint<8> > dbl2tsep; sc_fifo <bool> detect; }; #endif
#ifdef RGB2GRAY_PV_EN #ifndef RGB2GRAY_HPP #define RGB2GRAY_HPP #include <systemc.h> SC_MODULE(Rgb2Gray) { unsigned char r; unsigned char g; unsigned char b; unsigned char gray_value; SC_CTOR(Rgb2Gray) { } void set_rgb_pixel(unsigned char r_val, unsigned char g_val, unsigned char b_val); void compute_gray_value(); unsigned char obtain_gray_value(); }; #endif // RGB2GRAY_HPP #endif // RGB2GRAY_PV_EN
#ifndef MEMORY_TLM_HPP #define MEMORY_TLM_HPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "../src/img_target.cpp" #include "address_map.hpp" //Extended Unification TLM struct memory_tlm : public img_target { memory_tlm(sc_module_name name) : img_target((std::string(name) + "_target").c_str()) { mem_array = new unsigned char[MEMORY_SIZE]; #ifdef DISABLE_MEM_DEBUG this->use_prints = false; #endif //DISABLE_MEM_DEBUG checkprintenableimgtar(use_prints); } //Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); void backdoor_write(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); void backdoor_read(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); unsigned char* mem_array; sc_uint<64> mem_data; sc_uint<24> mem_address; sc_uint<1> mem_we; }; #endif // MEMORY_TLM_HPP
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _DownSampling_ #define _DownSampling_ #include "systemc.h" #include <cstdint> #include "constantes.hpp" SC_MODULE(DownSampling) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_uint<8> > e; sc_fifo_out< sc_uint<8> > s; SC_CTOR(DownSampling) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: void do_gen( ) { const uint8_t scale = 2; #if 1 while( true ) { uint32_t sum = e.read(); for(uint32_t j = 1 ; j < scale; j += 1) sum += (uint32_t)e.read(); s.write( sum / scale ); } #else while( true ) { uint32_t tab[scale]; for(uint32_t j = 0; j < scale; j += 1) tab[j] = e.read(); uint32_t sum = 0; for(uint32_t j = 0 ; j < scale; j += 1) sum += tab[j]; for(uint32_t j = 0 ; j < scale; j += 1) printf("%3d ", tab[j]); printf(" => %3d : %3d\n", sum, sum/scale); s.write( sum / scale ); } #endif } }; #endif
#ifndef IMG_TRANSMITER_TLM_HPP #define IMG_TRANSMITER_TLM_HPP #include <systemc.h> #include "img_transmiter.hpp" #include "../src/img_target.cpp" #include "address_map.hpp" struct img_transmiter_tlm: public img_transmiter, public img_target { SC_CTOR(img_transmiter_tlm): img_transmiter(img_transmiter::name()), img_target(img_target::name()) { set_mem_attributes(IMG_OUTPUT_ADDRESS_LO, IMG_OUTPUT_SIZE); } //Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); }; #endif // IMG_TRANSMITER_TLM_HPP
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _BitsToBytes_ #define _BitsToBytes_ #include "systemc.h" #include <cstdint> SC_MODULE(BitsToBytes) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_uint<1> > e; sc_fifo_out< sc_uint<8> > s; SC_CTOR(BitsToBytes) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: void do_gen( ) { #if 1 while ( true ) { uint8_t v = 0; for( uint32_t q = 0; q < 8 ; q += 1 ) { uint8_t E = e.read(); v = (v << 1) | E; } s.write( v ); } #else while ( true ) { uint8_t bits[8]; for( uint32_t q = 0; q < 8 ; q += 1 ) bits[q] = e.read(); uint8_t v = 0; for( uint32_t q = 0; q < 8 ; q += 1 ) { v = (v << 1) | bits[q]; } for( uint32_t q = 0; q < 8 ; q += 1 ) printf("%d", bits[q]); printf(" = 0x%2.2X\n", v); s.write( v ); } #endif } }; #endif
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _Seuil_calc_ #define _Seuil_calc_ #include "systemc.h" #include <cstdint> #include "constantes.hpp" using namespace std; // #define _DEBUG_SYNCHRO_ SC_MODULE(Seuil_calc) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_uint<8> > e; sc_fifo_out <bool> detect; SC_CTOR(Seuil_calc) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: void do_gen( ) { // #ifdef _DEBUG_SYNCHRO_ // uint64_t counter = 0; // detect.write(false); // #endif float buffer[32]; // const int factor = 2 * 2; // PPM modulation + UpSampling(2) #pragma HLS ARRAY_PARTITION variable=buffer complete dim=0 while( true ) { #pragma HLS PIPELINE for (int j = 0; j < 32-1; j += 1) { // #pragma HLS PIPELINE buffer[j] = buffer[j+1]; } buffer[32-1] = e.read(); const float ps = buffer[ 0] + buffer[ 1] + buffer[ 4] + buffer[ 5] + // 2 bits à 1 en PPM buffer[14] + buffer[15] + buffer[18] + buffer[19]; // 2 bits à 0 en PPM float sum = 0.0; for (int j = 0; j < 32; j += 1) { // #pragma HLS PIPELINE const float temp = buffer[j]; const float sqrv = (temp * temp); sum += sqrv; } sum = 8.0f * sum; float res = (ps*ps / sum ); detect.write(res>0.80f); } } }; #endif
#include <systemc.h> #include <config.hpp> SC_MODULE(Functional_bus){ //Input Port sc_core::sc_in <int> request_address; sc_core::sc_in <int> request_data; sc_core::sc_in <bool> flag_from_core; sc_core::sc_in <bool> request_ready; sc_core::sc_in <int> data_input_sensor[NUM_SENSORS]; sc_core::sc_in <bool> go_sensors[NUM_SENSORS]; //Output Port sc_core::sc_out <int> request_value; sc_core::sc_out <bool> request_go; sc_core::sc_out <int> address_out_sensor[NUM_SENSORS]; sc_core::sc_out <int> data_out_sensor[NUM_SENSORS]; sc_core::sc_out <bool> flag_out_sensor[NUM_SENSORS]; sc_core::sc_out <bool> ready_sensor[NUM_SENSORS]; SC_CTOR(Functional_bus): request_address("Address_from_Master_to_Bus"), request_data("Data_from_Master_to_Bus"), flag_from_core("Flag_from_Master_to_Bus"), request_ready("Ready_from_Master_to_Bus"), request_value("Data_from_Bus_to_Master"), request_go("Go_from_Bus_to_Master") { SC_THREAD(processing_data); sensitive << request_ready; for (int i = 0; i < NUM_SENSORS; i++){ sensitive << go_sensors[i]; } } void processing_data(); void response(); void Set_Go(bool flag); void Set_Slave(int address, bool flag); private: int selected_slave = 0; Functional_bus(){} };
//-------------------------------------------------------- //Testbench: Unification //By: Roger Morales Monge //Description: Simple TB for pixel unification modules //-------------------------------------------------------- #ifndef USING_TLM_TB_EN #define STB_IMAGE_IMPLEMENTATION #include "include/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "include/stb_image_write.h" #include <systemc.h> #include <math.h> #ifdef IMG_UNIFICATE_PV_EN #include "unification_pv_model.hpp" #endif // IMG_UNIFICATE_PV_EN int sc_main(int, char*[]) { unsigned char pixel_x, pixel_y; unsigned char pixel_magnitude; int width, height, channels, pixel_count; unsigned char *img_x, *img_y, *img_unificated; //Ref Image pointer unsigned char *img_ref; int error_count; float error_med; img_unification_module unification_U1 ("unification_U1"); // Open VCD file sc_trace_file *wf = sc_create_vcd_trace_file("unification_U1"); wf->set_time_unit(1, SC_NS); // Dump the desired signals sc_trace(wf, pixel_x, "pixel_x"); sc_trace(wf, pixel_y, "pixel_y"); sc_trace(wf, pixel_magnitude, "pixel_magnitude"); // Load Image img_x = stbi_load("../../tools/datagen/src/imgs/car_sobel_x_result.jpg", &width, &height, &channels, 0); img_y = stbi_load("../../tools/datagen/src/imgs/car_sobel_y_result.jpg", &width, &height, &channels, 0); img_ref = stbi_load("../../tools/datagen/src/imgs/car_sobel_combined_result.jpg", &width, &height, &channels, 0); pixel_count = width * height * channels; //Allocate memory for output image img_unificated = (unsigned char *)(malloc(size_t(pixel_count))); if(img_unificated == NULL) { printf("Unable to allocate memory for the output image.\n"); exit(1); } printf("Loaded images X and Y with Width: %0d, Height: %0d, Channels %0d. Total pixel count: %0d", width, height, channels, pixel_count); sc_start(); cout << "@" << sc_time_stamp()<< endl; printf("Combined X and Y images...\n"); //Iterate over image unification_U1.unificate_img(img_x, img_y, img_unificated, pixel_count, channels); printf("Unification finished.\n"); //Compare with reference image error_count = 0; error_med = 0; for(unsigned char *ref = img_ref, *result = img_unificated; ref < img_ref + pixel_count && result< img_unificated + pixel_count; ref+=channels, result+=channels){ //printf("Pixel #%0d, Ref Value: %0d, Result Value: %0d\n", int(ref-img_ref), *ref, *result); error_count += (*ref != *result); error_med += abs(*ref - *result); } error_med /= pixel_count; printf("-----------------------------------\n"); printf("Comparison Results:\n"); printf("Error Count: %0d, Error Rate: %0.2f\n", error_count, (100*(error_count+0.0))/pixel_count); printf("Mean Error Distance: %0.2f\n", error_med); printf("-----------------------------------\n"); //FIXME: Add time measurement cout << "@" << sc_time_stamp() <<" Terminating simulation\n" << endl; //Write output image stbi_write_jpg("./car_unificated.jpg", width, height, channels, img_unificated, 100); sc_close_vcd_trace_file(wf); return 0;// Terminate simulation } #endif // #ifdef USING_TLM_TB_EN
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _BitDecider_ #define _BitDecider_ #include "systemc.h" #include <cstdint> SC_MODULE(BitDecider) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_uint<8> > e; sc_fifo_out< sc_uint<1> > s; SC_CTOR(BitDecider) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: void do_gen( ) { while ( true ) { const uint8_t left = e.read(); const uint8_t right = e.read(); const uint8_t bitv = left > right; #if 0 printf("%3d ? %3d => %d\n", left, right, bitv); #endif s.write( bitv ); } } }; #endif
#include <systemc.h> #include <systemc-ams.h> #include <config.hpp> #define ${sensor_name}_VREF ${vref} SCA_TDF_MODULE(Sensor_${sensor_name}_power) { //Data from Functional Instance sca_tdf::sc_in <int> func_signal; //Data to Power Bus sca_tdf::sca_out <double> voltage_state; sca_tdf::sca_out <double> current_state; SCA_CTOR(Sensor_${sensor_name}_power): func_signal("State_of_Power_From_Functional"), voltage_state("Voltage_trace_to_Power_Bus"), current_state("Current_trace_to_Power_Bus") {} void set_attributes(); void initialize(); void processing(); Sensor_${sensor_name}_power(){} };
#ifdef EDGE_DETECTOR_LT_EN #ifndef SOBEL_EDGE_DETECTOR_HPP #define SOBEL_EDGE_DETECTOR_HPP #include <systemc.h> SC_MODULE(Edge_Detector) { int localWindow[3][3]; const int sobelGradientX[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}; const int sobelGradientY[3][3] = {{-1, -2, -1}, { 0, 0, 0}, { 1, 2, 1}}; int resultSobelGradientX; int resultSobelGradientY; sc_event gotLocalWindow, finishedSobelGradientX, finishedSobelGradientY; SC_CTOR(Edge_Detector) { SC_THREAD(compute_sobel_gradient_x); SC_THREAD(compute_sobel_gradient_y); } void set_local_window(int window[3][3]); void compute_sobel_gradient_x(); void compute_sobel_gradient_y(); int obtain_sobel_gradient_x(); int obtain_sobel_gradient_y(); }; #endif // SOBEL_EDGE_DETECTOR_HPP #endif // EDGE_DETECTOR_LT_EN
/* Copyright 2017 Columbia University, SLD Group */ // memwb.h - Robert Margelli // memory+writeback stage header file. #ifndef __MEMWB__H #define __MEMWB__H #include <systemc.h> #include "cynw_flex_channels.h" #include "defines.hpp" #include "globals.hpp" #include "syn_directives.hpp" #include "hl5_datatypes.hpp" SC_MODULE(memwb) { // FlexChannel initiators get_initiator< exe_out_t > din; put_initiator< mem_out_t > dout; // Clock and reset signals sc_in_clk clk; sc_in<bool> rst; // Enable fetch sc_in<bool> fetch_en; // Used to synchronize writeback with fetch at reset. // Instruction cache pointer to external memory sc_uint<XLEN> *dmem; // Thread prototype void memwb_th(void); // Function prototypes. sc_bv<XLEN> ext_sign_byte(sc_bv<BYTE> read_data); // Sign extend byte read from memory. For LB sc_bv<XLEN> ext_unsign_byte(sc_bv<BYTE> read_data); // Zero extend byte read from memory. For LBU sc_bv<XLEN> ext_sign_halfword(sc_bv<BYTE*2> read_data); // Sign extend half-word read from memory. For LH sc_bv<XLEN> ext_unsign_halfword(sc_bv<BYTE*2> read_data); // Zero extend half-word read from memory. For LHU // Constructor SC_HAS_PROCESS(memwb); memwb(sc_module_name name, sc_uint<XLEN> _dmem[DCACHE_SIZE]) : din("din") , dout("dout") , clk("clk") , rst("rst") , fetch_en("fetch_en") , dmem(_dmem) { SC_CTHREAD(memwb_th, clk.pos()); reset_signal_is(rst, false); din.clk_rst(clk, rst); dout.clk_rst(clk, rst); MAP_DCACHE; } // Member variables exe_out_t input; mem_out_t output; sc_bv<DATA_SIZE> mem_dout; // Temporarily stores the value read from memory with a load instruction }; #endif
#ifndef __RBM_H_ #define __RBM_H_ #include "systemc.h" #include <ctos_flex_channels.h> //This macro includes fixed-point into SystemC #if defined(SC_FIXED_POINT) #define SC_INCLUDE_FX #endif #if defined(__CTOS__) || defined(CTOS_MODEL) || defined(CTOS_SC_FIXED_POINT) #include <ctos_fx/ctos_fx_macros.h> #endif #include <div.hpp> #include "data.hpp" SC_MODULE(rbm) { sc_in<bool> clk; // clock sc_in<bool> rst; // reset // DMA requests interface from memory to device sc_out<u32> rd_index; // array index (offset from base address) sc_out<u32> rd_length; // burst size sc_out<bool> rd_request; // transaction request sc_in<bool> rd_grant; // transaction grant //input data read by load b_get_initiator<u32> data_in; // input // DMA requests interface from device to memory sc_out<u32> wr_index; // array index (offset from base address) sc_out<u32> wr_length; // burst size (in words) sc_out<bool> wr_request; // transaction request sc_in<bool> wr_grant; // transaction grant //output data wrtten by ourput put_initiator<u32> data_out; // output sc_out<bool> done; sc_in<bool> conf_done; //input data by config sc_in<u32> conf_num_hidden; sc_in<u32> conf_num_visible; sc_in<u32> conf_num_users; sc_in<u32> conf_num_loops; sc_in<u32> conf_num_testusers; sc_in<u32> conf_num_movies; void config(); void load(); void store(); void train_rbm(); void predict_rbm(); SC_CTOR(rbm) : clk("clk") , rst("rst") , rd_index("rd_index") , rd_length("rd_length") , rd_request("rd_request") , rd_grant("rd_grant") , data_in("data_in") , wr_index("wr_index") , wr_length("wr_length") , wr_request("wr_request") , wr_grant("wr_grant") , data_out("data_out") , done("done") , conf_done("cond_done") , conf_num_hidden("conf_num_hidden") , conf_num_visible("conf_num_visible") , conf_num_users("conf_num_users") , conf_num_testusers("conf_num_testusers") , conf_num_loops("conf_num_loops") , conf_num_movies("conf_num_movies") { ///config SC_CTHREAD(config, clk.pos()); reset_signal_is(rst, false); ///load SC_CTHREAD(load, clk.pos()); reset_signal_is(rst, false); ///compute SC_CTHREAD(train_rbm, clk.pos()); reset_signal_is(rst, false); set_stack_size(0x500000); SC_CTHREAD(predict_rbm, clk.pos()); reset_signal_is(rst, false); set_stack_size(0x500000); ///store SC_CTHREAD(store, clk.pos()); reset_signal_is(rst, false); ///data channels data_in.clk_rst(clk, rst); data_out.clk_rst(clk, rst); } void activateHiddenUnits_train(bool pingpong, u16 nh, u16 nv); void activateVisibleUnits_train(u16 nh, u16 nv); void activateHiddenUnits_predict(bool pingpong, u16 nh, u16 nv); void activateVisibleUnits_predict(u16 nh, u16 nv); DATA01_D rand_gen(); /// --- memory data structures --- ///input data u8 data[2][NUM_VISIBLE_MAX + 1]; ///temporary bool visible_unit[NUM_VISIBLE_MAX + 1]; bool hidden_unit[NUM_HIDDEN_MAX + 1]; DATA_edge edges[NUM_VISIBLE_MAX + 1][NUM_HIDDEN_MAX + 1]; bool pos[NUM_VISIBLE_MAX + 1][NUM_HIDDEN_MAX + 1];//u16 0/1 bool neg[NUM_VISIBLE_MAX + 1][NUM_HIDDEN_MAX + 1]; DATA_sum_ visibleEnergies[K]; //TODO: maximum 500 k.1 added together, k>0 ///output data bool predict_vector[NUM_VISIBLE_MAX + 1]; u8 predict_result[2][NUM_MOVIE_MAX];//max movies ///random generator numbers u32 mt[N]; /// --- signals --- //Written by config_debayer sc_signal<u16> num_hidden; sc_signal<u16> num_visible; sc_signal<u16> num_users; sc_signal<u16> num_loops; sc_signal<u16> num_testusers; sc_signal<u16> num_movies; sc_signal<bool> init_done; //Written by load_input sc_signal<bool> train_input_done; sc_signal<bool> predict_input_done; //Written by train_rbm sc_signal<bool> train_start; sc_signal<bool> train_done; sc_signal<int32> mti_signal; //Written by predict_rbm sc_signal<bool> predict_start; sc_signal<bool> predict_done; //Written by store_output sc_signal<bool> output_start; sc_signal<bool> output_done; }; #endif
#include<systemc.h> #include<vector> #include "interfaces.hpp" #include<nana/gui/widgets/listbox.hpp> using std::vector; class instruction_queue: public sc_module { public: sc_port<read_if> in; sc_port<write_if_f> out; SC_HAS_PROCESS(instruction_queue); instruction_queue(sc_module_name name, vector<string> inst_q, nana::listbox &instr); void main(); private: unsigned int pc; vector<string> instruct_queue; nana::listbox &instructions; };
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _CRCCheck_ #define _CRCCheck_ #include "systemc.h" #include <cstdint> #include "constantes.hpp" SC_MODULE(CRCCheck) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_uint<8> > e; sc_fifo_out< sc_uint<8> > s; SC_CTOR(CRCCheck) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: void do_gen( ) { cout << "(II) CRCCheck :: START" << endl; sc_uint<8> ibuffer[_BYTE_HEADER_ + _BYTE_PAYLOAD_]; const uint32_t P = 0x82f63b78; while( true ) { uint32_t R = 0; for (uint32_t i = 0; i < _BYTE_HEADER_ + _BYTE_PAYLOAD_; i += 1) { #pragma HLS PIPELINE uint8_t v = e.read(); ibuffer[i] = v; R ^= v; for (uint32_t j = 0; j < 8; ++j) { #pragma HLS UNROLL R = R & 1 ? (R >> 1) ^ P : R >> 1; } } uint8_t crc_t[4]; for (uint32_t i = 0; i < 4; i += 1) crc_t[i] = e.read(); uint32_t crc = 0; for (uint32_t i = 0; i < 4; i += 1) crc = crc << 8 | crc_t[4-1-i]; #if 0 printf("0x%8.8X != 0x%8.8X\n", R, crc); #endif if( crc == R ) { #if 0 printf("(DD) CRC validé...\n"); #endif for (uint32_t i = 0; i < _BYTE_HEADER_ + _BYTE_PAYLOAD_; ++i) { #pragma HLS PIPELINE s.write( ibuffer[i] ); } }else{ // printf("(DD) CRC NON validé !!!\n"); #if 0 printf("0x%2.2X | ", ibuffer[0].to_uint()); printf("0x%2.2X | 0x", ibuffer[1].to_uint()); for (uint32_t i = _BYTE_HEADER_; i < _BYTE_HEADER_ + _BYTE_PAYLOAD_; ++i) printf("%2.2X", ibuffer[i].to_uint()); printf(" | 0x%2.2X%2.2X%2.2X%2.2X ", crc_t[0], crc_t[1], crc_t[2], crc_t[3]); printf("| 0x%8.8X | 0x%8.8X\n", crc, R); exit( 0 ); #endif } } } }; #endif
/***************************************************************************\ * * * ___ ___ ___ ___ * / /\ / /\ / /\ / /\ * / /:/ / /::\ / /::\ / /::\ * / /:/ / /:/\:\ / /:/\:\ / /:/\:\ * / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/ * / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/ * /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/ * \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/ * \ \:\ \ \:\ \ \:\ \ \:\ * \ \ \ \ \:\ \ \:\ \ \:\ * \__\/ \__\/ \__\/ \__\/ * * * * * This file is part of TRAP. * * TRAP is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * or see <http://www.gnu.org/licenses/>. * * * * (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com * \***************************************************************************/ #ifndef MEMORYAT_HPP #define MEMORYAT_HPP #include <systemc.h> #include <tlm.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include <boost/lexical_cast.hpp> #include <string> #include <cstring> #include <trap_utils.hpp> DECLARE_EXTENDED_PHASE(internal_ph); namespace trap{ template<unsigned int N_INITIATORS, unsigned int sockSize> class MemoryAT: public sc_module{ public: tlm_utils::simple_target_socket_tagged<MemoryAT, sockSize> * socket[N_INITIATORS]; MemoryAT(sc_module_name name, unsigned int size, sc_time latency = SC_ZERO_TIME) : sc_module(name), size(size), latency(latency), transId(0), transactionInProgress(false), m_peq(this, &MemoryAT::peq_cb){ for(int i = 0; i < N_INITIATORS; i++){ this->socket[i] = new tlm_utils::simple_target_socket_tagged<MemoryAT, sockSize>(("mem_socket_" + boost::lexical_cast<std::string>(i)).c_str()); this->socket[i]->register_nb_transport_fw(this, &MemoryAT::nb_transport_fw, i); this->socket[i]->register_transport_dbg(this, &MemoryAT::transport_dbg, i); } // Reset memory this->mem = new unsigned char[size]; memset(this->mem, 0, size); end_module(); } ~MemoryAT(){ delete this->mem; for(int i = 0; i < N_INITIATORS; i++){ delete this->socket[i]; } } // TLM-2 non-blocking transport method tlm::tlm_sync_enum nb_transport_fw(int tag, tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay){ sc_dt::uint64 adr = trans.get_address(); unsigned int len = trans.get_data_length(); unsigned char* byt = trans.get_byte_enable_ptr(); unsigned int wid = trans.get_streaming_width(); // Obliged to check the transaction attributes for unsupported features // and to generate the appropriate error response if (byt != 0){ trans.set_response_status(tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE); return tlm::TLM_COMPLETED; } if(adr > this->size){ trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE); std::cerr << "Error requesting address " << std::showbase << std::hex << adr << std::dec << std::endl; return tlm::TLM_COMPLETED; } // Now queue the transaction until the annotated time has elapsed if(phase == tlm::BEGIN_REQ){ while(this->transactionInProgress){ //std::cerr << "waiting for transactionInProgress" << std::endl; wait(this->transactionCompleted); } //std::cerr << "there are no transactionInProgress" << std::endl; this->transactionInProgress = true; } this->transId = tag; m_peq.notify(trans, phase, delay); trans.set_response_status(tlm::TLM_OK_RESPONSE); return tlm::TLM_ACCEPTED; } void peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase){ tlm::tlm_sync_enum status; sc_time delay; switch (phase){ case tlm::BEGIN_REQ: status = send_end_req(trans); break; case tlm::END_RESP: //std::cerr << "tlm::END_RESP in memory peq_cb" << std::endl; this->transactionInProgress = false; this->transactionCompleted.notify(); break; case tlm::END_REQ: case tlm::BEGIN_RESP: SC_REPORT_FATAL("TLM-2", "Illegal transaction phase received by target"); break; default: if (phase == internal_ph){ // Execute the read or write commands tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); unsigned char* ptr = trans.get_data_ptr(); unsigned int len = trans.get_data_length(); if (cmd == tlm::TLM_READ_COMMAND){ memcpy(ptr, &mem[adr], len); } else if(cmd == tlm::TLM_WRITE_COMMAND){ memcpy(&mem[adr], ptr, len); } trans.set_response_status(tlm::TLM_OK_RESPONSE); // Target must honor BEGIN_RESP/END_RESP exclusion rule // i.e. must not send BEGIN_RESP until receiving previous END_RESP or BEGIN_REQ send_response(trans); //std::cerr << "Memory reading address in memory " << std::hex << std::showbase << adr << std::endl; } break; } } tlm::tlm_sync_enum send_end_req(tlm::tlm_generic_payload& trans){ tlm::tlm_sync_enum status; tlm::tlm_phase bw_phase; tlm::tlm_phase int_phase = internal_ph; // Queue the acceptance and the response with the appropriate latency bw_phase = tlm::END_REQ; sc_time zeroDelay = SC_ZERO_TIME; status = (*(this->socket[transId]))->nb_transport_bw(trans, bw_phase, zeroDelay); if (status == tlm::TLM_COMPLETED){ // Transaction aborted by the initiator // (TLM_UPDATED cannot occur at this point in the base protocol, so need not be checked) trans.release(); return status; } // Queue internal event to mark beginning of response m_peq.notify( trans, int_phase, this->latency ); return status; } void send_response(tlm::tlm_generic_payload& trans){ tlm::tlm_sync_enum status; tlm::tlm_phase bw_phase; bw_phase = tlm::BEGIN_RESP; sc_time zeroDelay = SC_ZERO_TIME; status = (*(this->socket[transId]))->nb_transport_bw(trans, bw_phase, zeroDelay); //std::cerr << "response status " << status << std::endl; if (status == tlm::TLM_UPDATED){ // The timing annotation must be honored m_peq.notify(trans, bw_phase, SC_ZERO_TIME); } else if (status == tlm::TLM_COMPLETED){ // The initiator has terminated the transaction trans.release(); } } // TLM-2 debug transaction method unsigned int transport_dbg(int tag, tlm::tlm_generic_payload& trans){ tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); unsigned char* ptr = trans.get_data_ptr(); unsigned int len = trans.get_data_length(); // Calculate the number of bytes to be actually copied unsigned int num_bytes = (len < this->size - adr) ? len : this->size - adr; if(cmd == tlm::TLM_READ_COMMAND){ memcpy(ptr, &mem[adr], num_bytes); } else if(cmd == tlm::TLM_WRITE_COMMAND){ memcpy(&mem[adr], ptr, num_bytes); } return num_bytes; } //Method used to directly write a word into memory; it is mainly used to load the //application program into memory inline void write_byte_dbg(const unsigned int & address, const unsigned char & datum) throw(){ if(address >= this->size){ THROW_ERROR("Address " << std::hex << std::showbase << address << " out of memory"); } this->mem[address] = datum; } private: const sc_time latency; unsigned int size; unsigned char * mem; int transId; bool transactionInProgress; sc_event transactionCompleted; tlm_utils::peq_with_cb_and_phase<MemoryAT> m_peq; }; }; #endif
#ifndef IPS_FILTER_TLM_HPP #define IPS_FILTER_TLM_HPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "ips_filter_lt_model.hpp" #include "../src/img_target.cpp" #include "important_defines.hpp" //Extended Unification TLM struct ips_filter_tlm : public Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>, public img_target { ips_filter_tlm(sc_module_name name) : Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>((std::string(name) + "_HW_block").c_str()), img_target((std::string(name) + "_target").c_str()) { #ifdef DISABLE_FILTER_DEBUG this->use_prints = false; #endif //DISABLE_FILTER_DEBUG checkprintenableimgtar(use_prints); } //Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); IPS_IN_TYPE_TB img_window[IPS_FILTER_KERNEL_SIZE * IPS_FILTER_KERNEL_SIZE]; IPS_OUT_TYPE_TB img_result; }; #endif // IPS_FILTER_TLM_HPP
#include <time.h> #include "systemc.h" #ifndef SC_FAULT_INJECT_HPP #define SC_FAULT_INJECT_HPP /** Representation of variable to be upset. */ struct fault_injectable_variable_t { char *name; // name uint8_t *ptr; // pointer to variable uint32_t size; // size uint32_t rand_threshold; // probability of fault per byte uint32_t fault_count; // fault injection count uint32_t pos_fault_count; // possible fault injection count }; /** Class to inject faults into registered variables. */ class sc_fault_injector; // forward declaration for global singleton class sc_fault_injector { public: /** Global singleton instance. */ static sc_fault_injector injector; /** Initializer specifying output file. */ static void init(double step_size, sc_time_unit time_unit) { injector._step_size = step_size; injector._step_unit = time_unit; } /** Configure maximum and minimum probability bounds. Default is 1.0f and 0.0f. */ static void configure_bounds(float max_prob, float min_prob) { if (max_prob > 1.0f) max_prob = 1.0f; if (min_prob < 0.0f) min_prob = 0.0f; injector._max_prob = max_prob; injector._min_prob = min_prob; } /** * Register a variable for fault injection. * * @param value The variable into which inject faults. * @param prob The probability of fault per byte per simulation step when running `simulate`. In mathematical terms, the total probability looks like: `prob` faults/step / (`_step_size`*`_step_unit` s/step) = `prob` / (`_step_size`*`_step_unit`) faults/s. * @param name The display name of the variable. */ template <class T> static void set_injectable(T& value, float prob = 0.01f, char* name = NULL) { set_injectable_ptr<T>(&value, 1, prob, name); } /** * Register a variable array for fault injection. * * @param value The variable into which inject faults. * @param n The number of variables in the array. * @param prob The probability of fault per byte per simulation step when running `simulate`. In mathematical terms, the total probability looks like: `prob` faults/step / (`_step_size`*`_step_unit` s/step) = `prob` / (`_step_size`*`_step_unit`) faults/s. * @param name The display name of the variable. */ template <class T> static void set_injectable_ptr(T* value, uint32_t n, float prob = 0.01f, char* name = NULL) { // check bounds if (prob > injector._max_prob) prob = injector._max_prob; if (prob < injector._min_prob) prob = injector._min_prob; // generate structure fault_injectable_variable_t registration; registration.name = name; registration.ptr = (uint8_t*)value; registration.size = sizeof(T) * n; registration.rand_threshold = (uint32_t)(prob * (double)((uint32_t)0xffffffff)); // compute integer value for threshold registration.fault_count = 0; registration.pos_fault_count = 0; injector._var_list.push_back(registration); } /** Run the simulation, stepping `_step_size` `_step_unit` before testing for injection. Returns the duration. */ static sc_time simulate(double max_time = -1.0) { srand(time(0)); double time = 0.0; sc_time start_time = sc_time_stamp(); while (injector._enabled) { // simulate a step sc_start(injector._step_size, injector._step_unit); time += injector._step_size; // check if done if ((max_time > 0.0 && time >= max_time) || !sc_pending_activity_at_current_time()) { break; } if (!injector._enabled) continue; // if enabled, inject faults into registration list uint32_t rand_val; uint8_t fault_bit; for (fault_injectable_variable_t &var : injector._var_list) { uint8_t *ptr = var.ptr; uint32_t n_bytes = var.size; while (n_bytes) { // probability of random fault rand_val = (uint32_t)rand(); if (rand_val < var.rand_threshold) { var.pos_fault_count++; // determine which bit to upset fault_bit = rand_val & 0x7; fault_bit = 0b1 << fault_bit; // perform mask if ((uint32_t)rand() & 0x8) { // 50% chance of possible 0 --> 1 fault if (!(*ptr & fault_bit)) var.fault_count++; *ptr |= fault_bit; } else { // 50% chance of possible 1 --> 0 fault if (*ptr & fault_bit) var.fault_count++; *ptr ^= fault_bit; } } // increment counter n_bytes--; ptr++; } //std::cout << var.name << " has a fault count of " << var.fault_count << " and a possible fault count of " << var.pos_fault_count << std::endl; } } // if never started (stepper disabled), run until completion if (time == 0.0) { sc_start(); } sc_time stop_time = sc_time_stamp(); // print report print(); // return duration return stop_time - start_time; } /** Disable tracing. */ static void disable() { injector._enabled = false; } /** Enable tracing. */ static void enable() { injector._enabled = true; } static void print() { uint32_t total_faults = 0; uint32_t total_size = 0; for (fault_injectable_variable_t &var : injector._var_list) { total_faults += var.fault_count; total_size += var.size; } std::cout << "Total of " << total_faults << " faults over " << total_size << " bytes." << std::endl; } private: /** Enable switch. */ bool _enabled = true; /** Bounds. */ float _max_prob = 1.0f; float _min_prob = 0.0f; /** Simulation step size. */ double _step_size = 10; sc_time_unit _step_unit = SC_NS; /** Internal list. */ std::vector<fault_injectable_variable_t> _var_list; }; #endif // SC_FAULT_INJECT_HPP
#ifndef USING_TLM_TB_EN #define int64 systemc_int64 #define uint64 systemc_uint64 #include <systemc.h> #undef int64 #undef uint64 #define int64 opencv_int64 #define uint64 opencv_uint64 #include <opencv2/opencv.hpp> #undef int64 #undef uint64 #include "vga.hpp" // Image path #define IPS_IMG_PATH_TB "../../tools/datagen/src/imgs/car_rgb_noisy_image.jpg" // Main clock frequency in Hz - 25.175 MHz #define CLK_FREQ 25175000 // VGA settings #define H_ACTIVE 640 #define H_FP 16 #define H_SYNC_PULSE 96 #define H_BP 48 #define V_ACTIVE 480 #define V_FP 10 #define V_SYNC_PULSE 2 #define V_BP 33 // Compute the total number of pixels #define TOTAL_VERTICAL (H_ACTIVE + H_FP + H_SYNC_PULSE + H_BP) #define TOTAL_HORIZONTAL (V_ACTIVE + V_FP + V_SYNC_PULSE + V_BP) #define TOTAL_PIXELES (TOTAL_VERTICAL * TOTAL_HORIZONTAL) // Number of bits for ADC, DAC and VGA #define BITS 8 int sc_main(int, char*[]) { // Read image const std::string img_path = IPS_IMG_PATH_TB; cv::Mat read_img = cv::imread(img_path, cv::IMREAD_COLOR); // CV_8UC3 Type: 8-bit unsigned, 3 channels (e.g., for a color image) cv::Mat tx_img; read_img.convertTo(tx_img, CV_8UC3); cv::Mat rx_data(TOTAL_HORIZONTAL, TOTAL_VERTICAL, CV_8UC3); cv::Mat rx_img(tx_img.size(), CV_8UC3); #ifdef IPS_DEBUG_EN std::cout << "Loading image: " << img_path << std::endl; #endif // IPS_DEBUG_EN // Check if the image is loaded successfully if (tx_img.empty()) { std::cerr << "Error: Could not open or find the image!" << std::endl; exit(EXIT_FAILURE); } #ifdef IPS_DEBUG_EN std::cout << "TX image info: "; std::cout << "rows = " << tx_img.rows; std::cout << " cols = " << tx_img.cols; std::cout << " channels = " << tx_img.channels() << std::endl; std::cout << "RX data info: "; std::cout << "rows = " << rx_data.rows; std::cout << " cols = " << rx_data.cols; std::cout << " channels = " << rx_data.channels() << std::endl; std::cout << "RX image info: "; std::cout << "rows = " << rx_img.rows; std::cout << " cols = " << rx_img.cols; std::cout << " channels = " << rx_img.channels() << std::endl; #endif // IPS_DEBUG_EN // Compute the clock time in seconds const double CLK_TIME = 1.0 / static_cast<double>(CLK_FREQ); // Compute the total simulation based on the total amount of pixels in the // screen const double SIM_TIME = CLK_TIME * static_cast<double>(TOTAL_PIXELES); // Signals to use // -- Inputs sc_core::sc_clock clk("clk", CLK_TIME, sc_core::SC_SEC); sc_core::sc_signal<sc_uint<8> > s_tx_red; sc_core::sc_signal<sc_uint<8> > s_tx_green; sc_core::sc_signal<sc_uint<8> > s_tx_blue; // -- Outputs sc_core::sc_signal<bool> s_hsync; sc_core::sc_signal<bool> s_vsync; sc_core::sc_signal<unsigned int> s_h_count; sc_core::sc_signal<unsigned int> s_v_count; sc_core::sc_signal<sc_uint<8> > s_rx_red; sc_core::sc_signal<sc_uint<8> > s_rx_green; sc_core::sc_signal<sc_uint<8> > s_rx_blue; // VGA module instanciation and connections vga< BITS, H_ACTIVE, H_FP, H_SYNC_PULSE, H_BP, V_ACTIVE, V_FP, V_SYNC_PULSE, V_BP > ips_vga("ips_vga"); ips_vga.clk(clk); ips_vga.red(s_tx_red); ips_vga.green(s_tx_green); ips_vga.blue(s_tx_blue); ips_vga.o_hsync(s_hsync); ips_vga.o_vsync(s_vsync); ips_vga.o_h_count(s_h_count); ips_vga.o_v_count(s_v_count); ips_vga.o_red(s_rx_red); ips_vga.o_green(s_rx_green); ips_vga.o_blue(s_rx_blue); // Signals to dump #ifdef IPS_DUMP_EN sc_trace_file* wf = sc_create_vcd_trace_file("ips_vga"); sc_trace(wf, clk, "clk"); sc_trace(wf, s_tx_red, "tx_red"); sc_trace(wf, s_tx_green, "tx_green"); sc_trace(wf, s_tx_blue, "tx_blue"); sc_trace(wf, s_hsync, "hsync"); sc_trace(wf, s_vsync, "vsync"); sc_trace(wf, s_h_count, "h_count"); sc_trace(wf, s_v_count, "v_count"); sc_trace(wf, s_rx_red, "rx_red"); sc_trace(wf, s_rx_green, "rx_green"); sc_trace(wf, s_rx_blue, "rx_blue"); #endif // IPS_DUMP_EN // Start time std::cout << "@" << sc_time_stamp() << std::endl; double total_sim_time = 0.0; while (SIM_TIME > total_sim_time) { const int IMG_ROW = s_v_count.read() - (V_SYNC_PULSE + V_BP); const int IMG_COL = s_h_count.read() - (H_SYNC_PULSE + H_BP); #ifdef IPS_DEBUG_EN std::cout << "TX image: "; std::cout << "row = " << IMG_ROW; std::cout << " col = " << IMG_COL; #endif // IPS_DEBUG_EN if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= V_ACTIVE) || (IMG_COL >= H_ACTIVE)) { s_tx_red.write(0); s_tx_green.write(0); s_tx_blue.write(0); #ifdef IPS_DEBUG_EN std::cout << " dpixel = (0,0,0) " << std::endl; #endif // IPS_DEBUG_EN } else { cv::Vec3b pixel = tx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL, 0); s_tx_red.write(static_cast<sc_uint<8> >(pixel[0])); s_tx_green.write(static_cast<sc_uint<8> >(pixel[1])); s_tx_blue.write(static_cast<sc_uint<8> >(pixel[2])); #ifdef IPS_DEBUG_EN std::cout << " ipixel = (" << static_cast<int>(pixel[0]) << "," << static_cast<int>(pixel[1]) << "," << static_cast<int>(pixel[2]) << ")" << std::endl; #endif // IPS_DEBUG_EN } total_sim_time += CLK_TIME; sc_start(CLK_TIME, sc_core::SC_SEC); if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= V_ACTIVE) || (IMG_COL >= H_ACTIVE)) { cv::Vec3b pixel(0, 0, 0); rx_data.at<cv::Vec3b>(s_v_count.read(), s_h_count.read()) = pixel; } else { cv::Vec3b pixel = cv::Vec3b(s_rx_red.read(), s_rx_green.read(), s_rx_blue.read()); rx_data.at<cv::Vec3b>(s_v_count.read(), s_h_count.read()) = pixel; rx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL) = pixel; } } // End time std::cout << "@" << sc_time_stamp() << std::endl; #ifdef IPS_DUMP_EN sc_close_vcd_trace_file(wf); #endif // IPS_DUMP_EN #ifdef IPS_IMSHOW // Show the images in their respective windows cv::imshow("TX image", tx_img); cv::imshow("RX image", rx_img); // Wait for a key press indefinitely to keep the windows open cv::waitKey(0); #endif // IPS_IMSHOW return 0; } #endif // USING_TLM_TB_EN
// half - IEEE 754-based half-precision floating-point library. // // Copyright (c) 2012-2021 Christian Rau <rauy@users.sourceforge.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // Version 2.2.0 /// \file /// Main header file for half-precision functionality. #ifndef HALF_HALF_HPP #define HALF_HALF_HPP #define HALF_GCC_VERSION (__GNUC__*100+__GNUC_MINOR__) #if defined(__INTEL_COMPILER) #define HALF_ICC_VERSION __INTEL_COMPILER #elif defined(__ICC) #define HALF_ICC_VERSION __ICC #elif defined(__ICL) #define HALF_ICC_VERSION __ICL #else #define HALF_ICC_VERSION 0 #endif // check C++11 language features #if defined(__clang__) // clang #if __has_feature(cxx_static_assert) && !defined(HALF_ENABLE_CPP11_STATIC_ASSERT) #define HALF_ENABLE_CPP11_STATIC_ASSERT 1 #endif #if __has_feature(cxx_constexpr) && !defined(HALF_ENABLE_CPP11_CONSTEXPR) #define HALF_ENABLE_CPP11_CONSTEXPR 1 #endif #if __has_feature(cxx_noexcept) && !defined(HALF_ENABLE_CPP11_NOEXCEPT) #define HALF_ENABLE_CPP11_NOEXCEPT 1 #endif #if __has_feature(cxx_user_literals) && !defined(HALF_ENABLE_CPP11_USER_LITERALS) #define HALF_ENABLE_CPP11_USER_LITERALS 1 #endif #if __has_feature(cxx_thread_local) && !defined(HALF_ENABLE_CPP11_THREAD_LOCAL) #define HALF_ENABLE_CPP11_THREAD_LOCAL 1 #endif #if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && !defined(HALF_ENABLE_CPP11_LONG_LONG) #define HALF_ENABLE_CPP11_LONG_LONG 1 #endif #elif HALF_ICC_VERSION && defined(__INTEL_CXX11_MODE__) // Intel C++ #if HALF_ICC_VERSION >= 1500 && !defined(HALF_ENABLE_CPP11_THREAD_LOCAL) #define HALF_ENABLE_CPP11_THREAD_LOCAL 1 #endif #if HALF_ICC_VERSION >= 1500 && !defined(HALF_ENABLE_CPP11_USER_LITERALS) #define HALF_ENABLE_CPP11_USER_LITERALS 1 #endif #if HALF_ICC_VERSION >= 1400 && !defined(HALF_ENABLE_CPP11_CONSTEXPR) #define HALF_ENABLE_CPP11_CONSTEXPR 1 #endif #if HALF_ICC_VERSION >= 1400 && !defined(HALF_ENABLE_CPP11_NOEXCEPT) #define HALF_ENABLE_CPP11_NOEXCEPT 1 #endif #if HALF_ICC_VERSION >= 1110 && !defined(HALF_ENABLE_CPP11_STATIC_ASSERT) #define HALF_ENABLE_CPP11_STATIC_ASSERT 1 #endif #if HALF_ICC_VERSION >= 1110 && !defined(HALF_ENABLE_CPP11_LONG_LONG) #define HALF_ENABLE_CPP11_LONG_LONG 1 #endif #elif defined(__GNUC__) // gcc #if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L #if HALF_GCC_VERSION >= 408 && !defined(HALF_ENABLE_CPP11_THREAD_LOCAL) #define HALF_ENABLE_CPP11_THREAD_LOCAL 1 #endif #if HALF_GCC_VERSION >= 407 && !defined(HALF_ENABLE_CPP11_USER_LITERALS) #define HALF_ENABLE_CPP11_USER_LITERALS 1 #endif #if HALF_GCC_VERSION >= 406 && !defined(HALF_ENABLE_CPP11_CONSTEXPR) #define HALF_ENABLE_CPP11_CONSTEXPR 1 #endif #if HALF_GCC_VERSION >= 406 && !defined(HALF_ENABLE_CPP11_NOEXCEPT) #define HALF_ENABLE_CPP11_NOEXCEPT 1 #endif #if HALF_GCC_VERSION >= 403 && !defined(HALF_ENABLE_CPP11_STATIC_ASSERT) #define HALF_ENABLE_CPP11_STATIC_ASSERT 1 #endif #if !defined(HALF_ENABLE_CPP11_LONG_LONG) #define HALF_ENABLE_CPP11_LONG_LONG 1 #endif #endif #define HALF_TWOS_COMPLEMENT_INT 1 #elif defined(_MSC_VER) // Visual C++ #if _MSC_VER >= 1900 && !defined(HALF_ENABLE_CPP11_THREAD_LOCAL) #define HALF_ENABLE_CPP11_THREAD_LOCAL 1 #endif #if _MSC_VER >= 1900 && !defined(HALF_ENABLE_CPP11_USER_LITERALS) #define HALF_ENABLE_CPP11_USER_LITERALS 1 #endif #if _MSC_VER >= 1900 && !defined(HALF_ENABLE_CPP11_CONSTEXPR) #define HALF_ENABLE_CPP11_CONSTEXPR 1 #endif #if _MSC_VER >= 1900 && !defined(HALF_ENABLE_CPP11_NOEXCEPT) #define HALF_ENABLE_CPP11_NOEXCEPT 1 #endif #if _MSC_VER >= 1600 && !defined(HALF_ENABLE_CPP11_STATIC_ASSERT) #define HALF_ENABLE_CPP11_STATIC_ASSERT 1 #endif #if _MSC_VER >= 1310 && !defined(HALF_ENABLE_CPP11_LONG_LONG) #define HALF_ENABLE_CPP11_LONG_LONG 1 #endif #define HALF_TWOS_COMPLEMENT_INT 1 #define HALF_POP_WARNINGS 1 #pragma warning(push) #pragma warning(disable : 4099 4127 4146) //struct vs class, constant in if, negative unsigned #endif // check C++11 library features #include <utility> #if defined(_LIBCPP_VERSION) // libc++ #if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103 #ifndef HALF_ENABLE_CPP11_TYPE_TRAITS #define HALF_ENABLE_CPP11_TYPE_TRAITS 1 #endif #ifndef HALF_ENABLE_CPP11_CSTDINT #define HALF_ENABLE_CPP11_CSTDINT 1 #endif #ifndef HALF_ENABLE_CPP11_CMATH #define HALF_ENABLE_CPP11_CMATH 1 #endif #ifndef HALF_ENABLE_CPP11_HASH #define HALF_ENABLE_CPP11_HASH 1 #endif #ifndef HALF_ENABLE_CPP11_CFENV #define HALF_ENABLE_CPP11_CFENV 1 #endif #endif #elif defined(__GLIBCXX__) // libstdc++ #if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103 #ifdef __clang__ #if __GLIBCXX__ >= 20080606 && !defined(HALF_ENABLE_CPP11_TYPE_TRAITS) #define HALF_ENABLE_CPP11_TYPE_TRAITS 1 #endif #if __GLIBCXX__ >= 20080606 && !defined(HALF_ENABLE_CPP11_CSTDINT) #define HALF_ENABLE_CPP11_CSTDINT 1 #endif #if __GLIBCXX__ >= 20080606 && !defined(HALF_ENABLE_CPP11_CMATH) #define HALF_ENABLE_CPP11_CMATH 1 #endif #if __GLIBCXX__ >= 20080606 && !defined(HALF_ENABLE_CPP11_HASH) #define HALF_ENABLE_CPP11_HASH 1 #endif #if __GLIBCXX__ >= 20080606 && !defined(HALF_ENABLE_CPP11_CFENV) #define HALF_ENABLE_CPP11_CFENV 1 #endif #else #if HALF_GCC_VERSION >= 403 && !defined(HALF_ENABLE_CPP11_TYPE_TRAITS) #define HALF_ENABLE_CPP11_TYPE_TRAITS 1 #endif #if HALF_GCC_VERSION >= 403 && !defined(HALF_ENABLE_CPP11_CSTDINT) #define HALF_ENABLE_CPP11_CSTDINT 1 #endif #if HALF_GCC_VERSION >= 403 && !defined(HALF_ENABLE_CPP11_CMATH) #define HALF_ENABLE_CPP11_CMATH 1 #endif #if HALF_GCC_VERSION >= 403 && !defined(HALF_ENABLE_CPP11_HASH) #define HALF_ENABLE_CPP11_HASH 1 #endif #if HALF_GCC_VERSION >= 403 && !defined(HALF_ENABLE_CPP11_CFENV) #define HALF_ENABLE_CPP11_CFENV 1 #endif #endif #endif #elif defined(_CPPLIB_VER) // Dinkumware/Visual C++ #if _CPPLIB_VER >= 520 && !defined(HALF_ENABLE_CPP11_TYPE_TRAITS) #define HALF_ENABLE_CPP11_TYPE_TRAITS 1 #endif #if _CPPLIB_VER >= 520 && !defined(HALF_ENABLE_CPP11_CSTDINT) #define HALF_ENABLE_CPP11_CSTDINT 1 #endif #if _CPPLIB_VER >= 520 && !defined(HALF_ENABLE_CPP11_HASH) #define HALF_ENABLE_CPP11_HASH 1 #endif #if _CPPLIB_VER >= 610 && !defined(HALF_ENABLE_CPP11_CMATH) #define HALF_ENABLE_CPP11_CMATH 1 #endif #if _CPPLIB_VER >= 610 && !defined(HALF_ENABLE_CPP11_CFENV) #define HALF_ENABLE_CPP11_CFENV 1 #endif #endif #undef HALF_GCC_VERSION #undef HALF_ICC_VERSION // any error throwing C++ exceptions? #if defined(HALF_ERRHANDLING_THROW_INVALID) || defined(HALF_ERRHANDLING_THROW_DIVBYZERO) || defined(HALF_ERRHANDLING_THROW_OVERFLOW) || defined(HALF_ERRHANDLING_THROW_UNDERFLOW) || defined(HALF_ERRHANDLING_THROW_INEXACT) #define HALF_ERRHANDLING_THROWS 1 #endif // any error handling enabled? #define HALF_ERRHANDLING (HALF_ERRHANDLING_FLAGS||HALF_ERRHANDLING_ERRNO||HALF_ERRHANDLING_FENV||HALF_ERRHANDLING_THROWS) #if HALF_ERRHANDLING #define HALF_UNUSED_NOERR(name) name #else #define HALF_UNUSED_NOERR(name) #endif // support constexpr #if HALF_ENABLE_CPP11_CONSTEXPR #define HALF_CONSTEXPR constexpr #define HALF_CONSTEXPR_CONST constexpr #if HALF_ERRHANDLING #define HALF_CONSTEXPR_NOERR #else #define HALF_CONSTEXPR_NOERR constexpr #endif #else #define HALF_CONSTEXPR #define HALF_CONSTEXPR_CONST const #define HALF_CONSTEXPR_NOERR #endif // support noexcept #if HALF_ENABLE_CPP11_NOEXCEPT #define HALF_NOEXCEPT noexcept #define HALF_NOTHROW noexcept #else #define HALF_NOEXCEPT #define HALF_NOTHROW throw() #endif // support thread storage #if HALF_ENABLE_CPP11_THREAD_LOCAL #define HALF_THREAD_LOCAL thread_local #else #define HALF_THREAD_LOCAL static #endif #include <utility> #include <algorithm> #include <istream> #include <ostream> #include <limits> #include <stdexcept> #include <climits> #include <cmath> #include <cstring> #include <cstdlib> #include "systemc.h" #if HALF_ENABLE_CPP11_TYPE_TRAITS #include <type_traits> #endif #if HALF_ENABLE_CPP11_CSTDINT #include <cstdint> #endif #if HALF_ERRHANDLING_ERRNO #include <cerrno> #endif #if HALF_ENABLE_CPP11_CFENV #include <cfenv> #endif #if HALF_ENABLE_CPP11_HASH #include <functional> #endif #ifndef HALF_ENABLE_F16C_INTRINSICS /// Enable F16C intruction set intrinsics. /// Defining this to 1 enables the use of [F16C compiler intrinsics](https://en.wikipedia.org/wiki/F16C) for converting between /// half-precision and single-precision values which may result in improved performance. This will not perform additional checks /// for support of the F16C instruction set, so an appropriate target platform is required when enabling this feature. /// /// Unless predefined it will be enabled automatically when the `__F16C__` symbol is defined, which some compilers do on supporting platforms. #define HALF_ENABLE_F16C_INTRINSICS __F16C__ #endif #if HALF_ENABLE_F16C_INTRINSICS #include <immintrin.h> #endif #ifdef HALF_DOXYGEN_ONLY /// Type for internal floating-point computations. /// This can be predefined to a built-in floating-point type (`float`, `double` or `long double`) to override the internal /// half-precision implementation to use this type for computing arithmetic operations and mathematical function (if available). /// This can result in improved performance for arithmetic operators and mathematical functions but might cause results to /// deviate from the specified half-precision rounding mode and inhibits proper detection of half-precision exceptions. #define HALF_ARITHMETIC_TYPE (undefined) /// Enable internal exception flags. /// Defining this to 1 causes operations on half-precision values to raise internal floating-point exception flags according to /// the IEEE 754 standard. These can then be cleared and checked with clearexcept(), testexcept(). #define HALF_ERRHANDLING_FLAGS 0 /// Enable exception propagation to `errno`. /// Defining this to 1 causes operations on half-precision values to propagate floating-point exceptions to /// [errno](https://en.cppreference.com/w/cpp/error/errno) from `<cerrno>`. Specifically this will propagate domain errors as /// [EDOM](https://en.cppreference.com/w/cpp/error/errno_macros) and pole, overflow and underflow errors as /// [ERANGE](https://en.cppreference.com/w/cpp/error/errno_macros). Inexact errors won't be propagated. #define HALF_ERRHANDLING_ERRNO 0 /// Enable exception propagation to built-in floating-point platform. /// Defining this to 1 causes operations on half-precision values to propagate floating-point exceptions to the built-in /// single- and double-precision implementation's exception flags using the /// [C++11 floating-point environment control](https://en.cppreference.com/w/cpp/numeric/fenv) from `<cfenv>`. However, this /// does not work in reverse and single- or double-precision exceptions will not raise the corresponding half-precision /// exception flags, nor will explicitly clearing flags clear the corresponding built-in flags. #define HALF_ERRHANDLING_FENV 0 /// Throw C++ exception on domain errors. /// Defining this to a string literal causes operations on half-precision values to throw a /// [std::domain_error](https://en.cppreference.com/w/cpp/error/domain_error) with the specified message on domain errors. #define HALF_ERRHANDLING_THROW_INVALID (undefined) /// Throw C++ exception on pole errors. /// Defining this to a string literal causes operations on half-precision values to throw a /// [std::domain_error](https://en.cppreference.com/w/cpp/error/domain_error) with the specified message on pole errors. #define HALF_ERRHANDLING_THROW_DIVBYZERO (undefined) /// Throw C++ exception on overflow errors. /// Defining this to a string literal causes operations on half-precision values to throw a /// [std::overflow_error](https://en.cppreference.com/w/cpp/error/overflow_error) with the specified message on overflows. #define HALF_ERRHANDLING_THROW_OVERFLOW (undefined) /// Throw C++ exception on underflow errors. /// Defining this to a string literal causes operations on half-precision values to throw a /// [std::underflow_error](https://en.cppreference.com/w/cpp/error/underflow_error) with the specified message on underflows. #define HALF_ERRHANDLING_THROW_UNDERFLOW (undefined) /// Throw C++ exception on rounding errors. /// Defining this to 1 causes operations on half-precision values to throw a /// [std::range_error](https://en.cppreference.com/w/cpp/error/range_error) with the specified message on general rounding errors. #define HALF_ERRHANDLING_THROW_INEXACT (undefined) #endif #ifndef HALF_ERRHANDLING_OVERFLOW_TO_INEXACT /// Raise INEXACT exception on overflow. /// Defining this to 1 (default) causes overflow errors to automatically raise inexact exceptions in addition. /// These will be raised after any possible handling of the underflow exception. #define HALF_ERRHANDLING_OVERFLOW_TO_INEXACT 1 #endif #ifndef HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT /// Raise INEXACT exception on underflow. /// Defining this to 1 (default) causes underflow errors to automatically raise inexact exceptions in addition. /// These will be raised after any possible handling of the underflow exception. /// /// **Note:** This will actually cause underflow (and the accompanying inexact) exceptions to be raised *only* when the result /// is inexact, while if disabled bare underflow errors will be raised for *any* (possibly exact) subnormal result. #define HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT 1 #endif /// Default rounding mode. /// This specifies the rounding mode used for all conversions between [half](\ref half_float::half)s and more precise types /// (unless using half_cast() and specifying the rounding mode directly) as well as in arithmetic operations and mathematical /// functions. It can be redefined (before including half.hpp) to one of the standard rounding modes using their respective /// constants or the equivalent values of /// [std::float_round_style](https://en.cppreference.com/w/cpp/types/numeric_limits/float_round_style): /// /// `std::float_round_style` | value | rounding /// ---------------------------------|-------|------------------------- /// `std::round_indeterminate` | -1 | fastest /// `std::round_toward_zero` | 0 | toward zero /// `std::round_to_nearest` | 1 | to nearest (default) /// `std::round_toward_infinity` | 2 | toward positive infinity /// `std::round_toward_neg_infinity` | 3 | toward negative infinity /// /// By default this is set to `1` (`std::round_to_nearest`), which rounds results to the nearest representable value. It can even /// be set to [std::numeric_limits<float>::round_style](https://en.cppreference.com/w/cpp/types/numeric_limits/round_style) to synchronize /// the rounding mode with that of the built-in single-precision implementation (which is likely `std::round_to_nearest`, though). #ifndef HALF_ROUND_STYLE #define HALF_ROUND_STYLE 1 // = std::round_to_nearest #endif /// Value signaling overflow. /// In correspondence with `HUGE_VAL[F|L]` from `<cmath>` this symbol expands to a positive value signaling the overflow of an /// operation, in particular it just evaluates to positive infinity. /// /// **See also:** Documentation for [HUGE_VAL](https://en.cppreference.com/w/cpp/numeric/math/HUGE_VAL) #define HUGE_VALH std::numeric_limits<half_float::half>::infinity() /// Fast half-precision fma function. /// This symbol is defined if the fma() function generally executes as fast as, or faster than, a separate /// half-precision multiplication followed by an addition, which is always the case. /// /// **See also:** Documentation for [FP_FAST_FMA](https://en.cppreference.com/w/cpp/numeric/math/fma) #define FP_FAST_FMAH 1 /// Half rounding mode. /// In correspondence with `FLT_ROUNDS` from `<cfloat>` this symbol expands to the rounding mode used for /// half-precision operations. It is an alias for [HALF_ROUND_STYLE](\ref HALF_ROUND_STYLE). /// /// **See also:** Documentation for [FLT_ROUNDS](https://en.cppreference.com/w/cpp/types/climits/FLT_ROUNDS) #define HLF_ROUNDS HALF_ROUND_STYLE #ifndef FP_ILOGB0 #define FP_ILOGB0 INT_MIN #endif #ifndef FP_ILOGBNAN #define FP_ILOGBNAN INT_MAX #endif #ifndef FP_SUBNORMAL #define FP_SUBNORMAL 0 #endif #ifndef FP_ZERO #define FP_ZERO 1 #endif #ifndef FP_NAN #define FP_NAN 2 #endif #ifndef FP_INFINITE #define FP_INFINITE 3 #endif #ifndef FP_NORMAL #define FP_NORMAL 4 #endif #if !HALF_ENABLE_CPP11_CFENV && !defined(FE_ALL_EXCEPT) #define FE_INVALID 0x10 #define FE_DIVBYZERO 0x08 #define FE_OVERFLOW 0x04 #define FE_UNDERFLOW 0x02 #define FE_INEXACT 0x01 #define FE_ALL_EXCEPT (FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW|FE_UNDERFLOW|FE_INEXACT) #endif /// Main namespace for half-precision functionality. /// This namespace contains all the functionality provided by the library. namespace half_float { class half; #if HALF_ENABLE_CPP11_USER_LITERALS /// Library-defined half-precision literals. /// Import this namespace to enable half-precision floating-point literals: /// ~~~~{.cpp} /// using namespace half_float::literal; /// half_float::half = 4.2_h; /// ~~~~ namespace literal { half operator "" _h(long double); } #endif /// \internal /// \brief Implementation details. namespace detail { #if HALF_ENABLE_CPP11_TYPE_TRAITS /// Conditional type. template<bool B,typename T,typename F> struct conditional : std::conditional<B,T,F> {}; /// Helper for tag dispatching. template<bool B> struct bool_type : std::integral_constant<bool,B> {}; using std::true_type; using std::false_type; /// Type traits for floating-point types. template<typename T> struct is_float : std::is_floating_point<T> {}; #else /// Conditional type. template<bool, typename T, typename > struct conditional { typedef T type; }; template<typename T, typename F> struct conditional<false, T, F> { typedef F type; }; /// Helper for tag dispatching. template<bool> struct bool_type { }; typedef bool_type<true> true_type; typedef bool_type<false> false_type; /// Type traits for floating-point types. template<typename > struct is_float: false_type { }; template<typename T> struct is_float<const T> : is_float<T> { }; template<typename T> struct is_float<volatile T> : is_float<T> { }; template<typename T> struct is_float<const volatile T> : is_float<T> { }; template<> struct is_float<float> : true_type { }; template<> struct is_float<double> : true_type { }; template<> struct is_float<long double> : true_type { }; #endif /// Type traits for floating-point bits. template<typename T> struct bits { typedef unsigned char type; }; template<typename T> struct bits<const T> : bits<T> { }; template<typename T> struct bits<volatile T> : bits<T> { }; template<typename T> struct bi
ts<const volatile T> : bits<T> { }; #if HALF_ENABLE_CPP11_CSTDINT /// Unsigned integer of (at least) 16 bits width. typedef std::uint_least16_t uint16; /// Fastest unsigned integer of (at least) 32 bits width. typedef std::uint_fast32_t uint32; /// Fastest signed integer of (at least) 32 bits width. typedef std::int_fast32_t int32; /// Unsigned integer of (at least) 32 bits width. template<> struct bits<float> { typedef std::uint_least32_t type; }; /// Unsigned integer of (at least) 64 bits width. template<> struct bits<double> { typedef std::uint_least64_t type; }; #else /// Unsigned integer of (at least) 16 bits width. typedef unsigned short uint16; /// Fastest unsigned integer of (at least) 32 bits width. typedef unsigned long uint32; /// Fastest unsigned integer of (at least) 32 bits width. typedef long int32; /// Unsigned integer of (at least) 32 bits width. template<> struct bits<float> : conditional< std::numeric_limits<unsigned int>::digits >= 32, unsigned int, unsigned long> { }; #if HALF_ENABLE_CPP11_LONG_LONG /// Unsigned integer of (at least) 64 bits width. template<> struct bits<double> : conditional<std::numeric_limits<unsigned long>::digits>=64,unsigned long,unsigned long long> {}; #else /// Unsigned integer of (at least) 64 bits width. template<> struct bits<double> { typedef unsigned long type; }; #endif #endif #ifdef HALF_ARITHMETIC_TYPE /// Type to use for arithmetic computations and mathematic functions internally. typedef HALF_ARITHMETIC_TYPE internal_t; #endif /// Tag type for binary construction. struct binary_t { }; /// Tag for binary construction. HALF_CONSTEXPR_CONST binary_t binary = binary_t(); /// \name Implementation defined classification and arithmetic /// \{ /// Check for infinity. /// \tparam T argument type (builtin floating-point type) /// \param arg value to query /// \retval true if infinity /// \retval false else template<typename T> bool builtin_isinf(T arg) { #if HALF_ENABLE_CPP11_CMATH return std::isinf(arg); #elif defined(_MSC_VER) return !::_finite(static_cast<double>(arg)) && !::_isnan(static_cast<double>(arg)); #else return arg == std::numeric_limits<T>::infinity() || arg == -std::numeric_limits<T>::infinity(); #endif } /// Check for NaN. /// \tparam T argument type (builtin floating-point type) /// \param arg value to query /// \retval true if not a number /// \retval false else template<typename T> bool builtin_isnan(T arg) { #if HALF_ENABLE_CPP11_CMATH return std::isnan(arg); #elif defined(_MSC_VER) return ::_isnan(static_cast<double>(arg)) != 0; #else return arg != arg; #endif } /// Check sign. /// \tparam T argument type (builtin floating-point type) /// \param arg value to query /// \retval true if signbit set /// \retval false else template<typename T> bool builtin_signbit(T arg) { #if HALF_ENABLE_CPP11_CMATH return std::signbit(arg); #else return arg < T() || (arg == T() && T(1) / arg < T()); #endif } /// Platform-independent sign mask. /// \param arg integer value in two's complement /// \retval -1 if \a arg negative /// \retval 0 if \a arg positive inline uint32 sign_mask(uint32 arg) { static const int N = std::numeric_limits<uint32>::digits - 1; #if HALF_TWOS_COMPLEMENT_INT return static_cast<int32>(arg) >> N; #else return -((arg>>N)&1); #endif } /// Platform-independent arithmetic right shift. /// \param arg integer value in two's complement /// \param i shift amount (at most 31) /// \return \a arg right shifted for \a i bits with possible sign extension inline uint32 arithmetic_shift(uint32 arg, int i) { #if HALF_TWOS_COMPLEMENT_INT return static_cast<int32>(arg) >> i; #else return static_cast<int32>(arg)/(static_cast<int32>(1)<<i) - ((arg>>(std::numeric_limits<uint32>::digits-1))&1); #endif } /// \} /// \name Error handling /// \{ /// Internal exception flags. /// \return reference to global exception flags inline int& errflags() { HALF_THREAD_LOCAL int flags = 0; return flags; } /// Raise floating-point exception. /// \param flags exceptions to raise /// \param cond condition to raise exceptions for inline void raise(int HALF_UNUSED_NOERR(flags), bool HALF_UNUSED_NOERR(cond) = true) { #if HALF_ERRHANDLING if(!cond) return; #if HALF_ERRHANDLING_FLAGS errflags() |= flags; #endif #if HALF_ERRHANDLING_ERRNO if(flags & FE_INVALID) errno = EDOM; else if(flags & (FE_DIVBYZERO|FE_OVERFLOW|FE_UNDERFLOW)) errno = ERANGE; #endif #if HALF_ERRHANDLING_FENV && HALF_ENABLE_CPP11_CFENV std::feraiseexcept(flags); #endif #ifdef HALF_ERRHANDLING_THROW_INVALID if(flags & FE_INVALID) throw std::domain_error(HALF_ERRHANDLING_THROW_INVALID); #endif #ifdef HALF_ERRHANDLING_THROW_DIVBYZERO if(flags & FE_DIVBYZERO) throw std::domain_error(HALF_ERRHANDLING_THROW_DIVBYZERO); #endif #ifdef HALF_ERRHANDLING_THROW_OVERFLOW if(flags & FE_OVERFLOW) throw std::overflow_error(HALF_ERRHANDLING_THROW_OVERFLOW); #endif #ifdef HALF_ERRHANDLING_THROW_UNDERFLOW if(flags & FE_UNDERFLOW) throw std::underflow_error(HALF_ERRHANDLING_THROW_UNDERFLOW); #endif #ifdef HALF_ERRHANDLING_THROW_INEXACT if(flags & FE_INEXACT) throw std::range_error(HALF_ERRHANDLING_THROW_INEXACT); #endif #if HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT if((flags & FE_UNDERFLOW) && !(flags & FE_INEXACT)) raise(FE_INEXACT); #endif #if HALF_ERRHANDLING_OVERFLOW_TO_INEXACT if((flags & FE_OVERFLOW) && !(flags & FE_INEXACT)) raise(FE_INEXACT); #endif #endif } /// Check and signal for any NaN. /// \param x first half-precision value to check /// \param y second half-precision value to check /// \retval true if either \a x or \a y is NaN /// \retval false else /// \exception FE_INVALID if \a x or \a y is NaN inline HALF_CONSTEXPR_NOERR bool compsignal(unsigned int x, unsigned int y) { #if HALF_ERRHANDLING raise(FE_INVALID, (x&0x7FFF)>0x7C00 || (y&0x7FFF)>0x7C00); #endif return (x & 0x7FFF) > 0x7C00 || (y & 0x7FFF) > 0x7C00; } /// Signal and silence signaling NaN. /// \param nan half-precision NaN value /// \return quiet NaN /// \exception FE_INVALID if \a nan is signaling NaN inline HALF_CONSTEXPR_NOERR unsigned int signal(unsigned int nan) { #if HALF_ERRHANDLING raise(FE_INVALID, !(nan&0x200)); #endif return nan | 0x200; } /// Signal and silence signaling NaNs. /// \param x first half-precision value to check /// \param y second half-precision value to check /// \return quiet NaN /// \exception FE_INVALID if \a x or \a y is signaling NaN inline HALF_CONSTEXPR_NOERR unsigned int signal(unsigned int x, unsigned int y) { #if HALF_ERRHANDLING raise(FE_INVALID, ((x&0x7FFF)>0x7C00 && !(x&0x200)) || ((y&0x7FFF)>0x7C00 && !(y&0x200))); #endif return ((x & 0x7FFF) > 0x7C00) ? (x | 0x200) : (y | 0x200); } /// Signal and silence signaling NaNs. /// \param x first half-precision value to check /// \param y second half-precision value to check /// \param z third half-precision value to check /// \return quiet NaN /// \exception FE_INVALID if \a x, \a y or \a z is signaling NaN inline HALF_CONSTEXPR_NOERR unsigned int signal(unsigned int x, unsigned int y, unsigned int z) { #if HALF_ERRHANDLING raise(FE_INVALID, ((x&0x7FFF)>0x7C00 && !(x&0x200)) || ((y&0x7FFF)>0x7C00 && !(y&0x200)) || ((z&0x7FFF)>0x7C00 && !(z&0x200))); #endif return ((x & 0x7FFF) > 0x7C00) ? (x | 0x200) : ((y & 0x7FFF) > 0x7C00) ? (y | 0x200) : (z | 0x200); } /// Select value or signaling NaN. /// \param x preferred half-precision value /// \param y ignored half-precision value except for signaling NaN /// \return \a y if signaling NaN, \a x otherwise /// \exception FE_INVALID if \a y is signaling NaN inline HALF_CONSTEXPR_NOERR unsigned int select(unsigned int x, unsigned int HALF_UNUSED_NOERR(y)) { #if HALF_ERRHANDLING return (((y&0x7FFF)>0x7C00) && !(y&0x200)) ? signal(y) : x; #else return x; #endif } /// Raise domain error and return NaN. /// return quiet NaN /// \exception FE_INVALID inline HALF_CONSTEXPR_NOERR unsigned int invalid() { #if HALF_ERRHANDLING raise(FE_INVALID); #endif return 0x7FFF; } /// Raise pole error and return infinity. /// \param sign half-precision value with sign bit only /// \return half-precision infinity with sign of \a sign /// \exception FE_DIVBYZERO inline HALF_CONSTEXPR_NOERR unsigned int pole(unsigned int sign = 0) { #if HALF_ERRHANDLING raise(FE_DIVBYZERO); #endif return sign | 0x7C00; } /// Check value for underflow. /// \param arg non-zero half-precision value to check /// \return \a arg /// \exception FE_UNDERFLOW if arg is subnormal inline HALF_CONSTEXPR_NOERR unsigned int check_underflow(unsigned int arg) { #if HALF_ERRHANDLING && !HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT raise(FE_UNDERFLOW, !(arg&0x7C00)); #endif return arg; } /// \} /// \name Conversion and rounding /// \{ /// Half-precision overflow. /// \tparam R rounding mode to use /// \param sign half-precision value with sign bit only /// \return rounded overflowing half-precision value /// \exception FE_OVERFLOW template<std::float_round_style R> HALF_CONSTEXPR_NOERR unsigned int overflow( unsigned int sign = 0) { #if HALF_ERRHANDLING raise(FE_OVERFLOW); #endif return (R == std::round_toward_infinity) ? (sign + 0x7C00 - (sign >> 15)) : (R == std::round_toward_neg_infinity) ? (sign + 0x7BFF + (sign >> 15)) : (R == std::round_toward_zero) ? (sign | 0x7BFF) : (sign | 0x7C00); } /// Half-precision underflow. /// \tparam R rounding mode to use /// \param sign half-precision value with sign bit only /// \return rounded underflowing half-precision value /// \exception FE_UNDERFLOW template<std::float_round_style R> HALF_CONSTEXPR_NOERR unsigned int underflow( unsigned int sign = 0) { #if HALF_ERRHANDLING raise(FE_UNDERFLOW); #endif return (R == std::round_toward_infinity) ? (sign + 1 - (sign >> 15)) : (R == std::round_toward_neg_infinity) ? (sign + (sign >> 15)) : sign; } /// Round half-precision number. /// \tparam R rounding mode to use /// \tparam I `true` to always raise INEXACT exception, `false` to raise only for rounded results /// \param value finite half-precision number to round /// \param g guard bit (most significant discarded bit) /// \param s sticky bit (or of all but the most significant discarded bits) /// \return rounded half-precision value /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if value had to be rounded or \a I is `true` template<std::float_round_style R, bool I> HALF_CONSTEXPR_NOERR unsigned int rounded( unsigned int value, int g, int s) { #if HALF_ERRHANDLING value += (R==std::round_to_nearest) ? (g&(s|value)) : (R==std::round_toward_infinity) ? (~(value>>15)&(g|s)) : (R==std::round_toward_neg_infinity) ? ((value>>15)&(g|s)) : 0; if((value&0x7C00) == 0x7C00) raise(FE_OVERFLOW); else if(value & 0x7C00) raise(FE_INEXACT, I || (g|s)!=0); else raise(FE_UNDERFLOW, !(HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT) || I || (g|s)!=0); return value; #else return (R == std::round_to_nearest) ? (value + (g & (s | value))) : (R == std::round_toward_infinity) ? (value + (~(value >> 15) & (g | s))) : (R == std::round_toward_neg_infinity) ? (value + ((value >> 15) & (g | s))) : value; #endif } /// Round half-precision number to nearest integer value. /// \tparam R rounding mode to use /// \tparam E `true` for round to even, `false` for round away from zero /// \tparam I `true` to raise INEXACT exception (if inexact), `false` to never raise it /// \param value half-precision value to round /// \return half-precision bits for nearest integral value /// \exception FE_INVALID for signaling NaN /// \exception FE_INEXACT if value had to be rounded and \a I is `true` template<std::float_round_style R, bool E, bool I> unsigned int integral( unsigned int value) { unsigned int abs = value & 0x7FFF; if (abs < 0x3C00) { raise(FE_INEXACT, I); return ((R == std::round_to_nearest) ? (0x3C00 & -static_cast<unsigned>(abs >= (0x3800 + E))) : (R == std::round_toward_infinity) ? (0x3C00 & -(~(value >> 15) & (abs != 0))) : (R == std::round_toward_neg_infinity) ? (0x3C00 & -static_cast<unsigned>(value > 0x8000)) : 0) | (value & 0x8000); } if (abs >= 0x6400) return (abs > 0x7C00) ? signal(value) : value; unsigned int exp = 25 - (abs >> 10), mask = (1 << exp) - 1; raise(FE_INEXACT, I && (value & mask)); return (( (R == std::round_to_nearest) ? ((1 << (exp - 1)) - (~(value >> exp) & E)) : (R == std::round_toward_infinity) ? (mask & ((value >> 15) - 1)) : (R == std::round_toward_neg_infinity) ? (mask & -(value >> 15)) : 0) + value) & ~mask; } /// Convert fixed point to half-precision floating-point. /// \tparam R rounding mode to use /// \tparam F number of fractional bits in [11,31] /// \tparam S `true` for signed, `false` for unsigned /// \tparam N `true` for additional normalization step, `false` if already normalized to 1.F /// \tparam I `true` to always raise INEXACT exception, `false` to raise only for rounded results /// \param m mantissa in Q1.F fixed point format /// \param exp biased exponent - 1 /// \param sign half-precision value with sign bit only /// \param s sticky bit (or of all but the most significant already discarded bits) /// \return value converted to half-precision /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if value had to be rounded or \a I is `true` template<std::float_round_style R, unsigned int F, bool S, bool N, bool I> unsigned int fixed2half( uint32 m, int exp = 14, unsigned int sign = 0, int s = 0) { if (S) { uint32 msign = sign_mask(m); m = (m ^ msign) - msign; sign = msign & 0x8000; } if (N) for (; m < (static_cast<uint32>(1) << F) && exp; m <<= 1, --exp) ; else if (exp < 0) return rounded<R, I>(sign + (m >> (F - 10 - exp)), (m >> (F - 11 - exp)) & 1, s | ((m & ((static_cast<uint32>(1) << (F - 11 - exp)) - 1)) != 0)); return rounded<R, I>(sign + (exp << 10) + (m >> (F - 10)), (m >> (F - 11)) & 1, s | ((m & ((static_cast<uint32>(1) << (F - 11)) - 1)) != 0)); } /// Convert IEEE single-precision to half-precision. /// Credit for this goes to [Jeroen van der Zijp](ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf). /// \tparam R rounding mode to use /// \param value single-precision value to convert /// \return rounded half-precision value /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if value had to be rounded template<std::float_round_style R> unsigned int float2half_impl(float value, true_type) { #if HALF_ENABLE_F16C_INTRINSICS return _mm_cvtsi128_si32(_mm_cvtps_ph(_mm_set_ss(value), (R==std::round_to_nearest) ? _MM_FROUND_TO_NEAREST_INT : (R==std::round_toward_zero) ? _MM_FROUND_TO_ZERO : (R==std::round_toward_infinity) ? _MM_FROUND_TO_POS_INF : (R==std::round_toward_neg_infinity) ? _MM_FROUND_TO_NEG_INF : _MM_FROUND_CUR_DIRECTION)); #else bits<float>::type fbits; std::memcpy(&fbits, &value, sizeof(float)); #if 1 unsigned int sign = (fbits >> 16) & 0x8000; fbits &= 0x7FFFFFFF; if (fbits >= 0x7F800000) return sign | 0x7C00 | ((fbits > 0x7F800000) ? (0x200 | ((fbits >> 13) & 0x3FF)) : 0); if (fbits >= 0x47800000) return overflow<R>(sign); if (fbits >= 0x38800000) return rounded<R, false>( sign | (((fbits >> 23) - 112) << 10) | ((fbits >> 13) & 0x3FF), (fbits >> 12) & 1, (fbits & 0xFFF) != 0); if (fbits >= 0x33000000) { int i = 125 - (fbits >> 23); fbits = (fbits & 0x7FFFFF) | 0x800000; return rounded<R, false>(sign | (fbits >> (i + 1)), (fbits >> i) & 1, (fbits & ((static_cast<uint32>(1) << i) - 1)) != 0); } if (fbits != 0) return underflow<R>(sign); return sign; #else static const uint16 base_table[512] = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x0C00, 0x1000, 0x1400, 0x1800, 0x1C00, 0x2000, 0x2400, 0x2800, 0x2C00, 0x3000, 0x3400, 0x3800, 0x3C00, 0x4000, 0x4400, 0x4800, 0x4C00, 0x5000, 0x5400, 0x5800, 0x5C00, 0x6000, 0x6400, 0x6800, 0x6C00, 0x7000, 0x7400, 0x7800, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7BFF, 0x7C00, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8001, 0x8002, 0x8004, 0x8008, 0x8010, 0x8020, 0x8040, 0x8080, 0x8100, 0x8200, 0x8400, 0x8800, 0x8C00, 0x9000, 0x9400, 0x9800, 0x9C00, 0xA000, 0xA400, 0xA800, 0xAC00, 0xB000, 0xB400, 0xB800, 0xBC00, 0xC000, 0xC400, 0xC800, 0xCC00, 0xD000, 0xD400, 0xD800, 0xDC00, 0xE000, 0xE400, 0xE800, 0xEC00, 0xF000, 0xF400, 0xF800, 0xFBFF, 0xFBFF,
0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFBFF, 0xFC00 }; static const unsigned char shift_table[256] = { 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 13 }; int sexp = fbits >> 23, exp = sexp & 0xFF, i = shift_table[exp]; fbits &= 0x7FFFFF; uint32 m = (fbits|((exp!=0)<<23)) & -static_cast<uint32>(exp!=0xFF); return rounded<R,false>(base_table[sexp]+(fbits>>i), (m>>(i-1))&1, (((static_cast<uint32>(1)<<(i-1))-1)&m)!=0); #endif #endif } /// Convert IEEE double-precision to half-precision. /// \tparam R rounding mode to use /// \param value double-precision value to convert /// \return rounded half-precision value /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if value had to be rounded template<std::float_round_style R> unsigned int float2half_impl(double value, true_type) { #if HALF_ENABLE_F16C_INTRINSICS if(R == std::round_indeterminate) return _mm_cvtsi128_si32(_mm_cvtps_ph(_mm_cvtpd_ps(_mm_set_sd(value)), _MM_FROUND_CUR_DIRECTION)); #endif bits<double>::type dbits; std::memcpy(&dbits, &value, sizeof(double)); uint32 hi = dbits >> 32, lo = dbits & 0xFFFFFFFF; unsigned int sign = (hi >> 16) & 0x8000; hi &= 0x7FFFFFFF; if (hi >= 0x7FF00000) return sign | 0x7C00 | ((dbits & 0xFFFFFFFFFFFFF) ? (0x200 | ((hi >> 10) & 0x3FF)) : 0); if (hi >= 0x40F00000) return overflow<R>(sign); if (hi >= 0x3F100000) return rounded<R, false>( sign | (((hi >> 20) - 1008) << 10) | ((hi >> 10) & 0x3FF), (hi >> 9) & 1, ((hi & 0x1FF) | lo) != 0); if (hi >= 0x3E600000) { int i = 1018 - (hi >> 20); hi = (hi & 0xFFFFF) | 0x100000; return rounded<R, false>(sign | (hi >> (i + 1)), (hi >> i) & 1, ((hi & ((static_cast<uint32>(1) << i) - 1)) | lo) != 0); } if ((hi | lo) != 0) return underflow<R>(sign); return sign; } /// Convert non-IEEE floating-point to half-precision. /// \tparam R rounding mode to use /// \tparam T source type (builtin floating-point type) /// \param value floating-point value to convert /// \return rounded half-precision value /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if value had to be rounded template<std::float_round_style R, typename T> unsigned int float2half_impl( T value, ...) { unsigned int hbits = static_cast<unsigned>(builtin_signbit(value)) << 15; if (value == T()) return hbits; if (builtin_isnan(value)) return hbits | 0x7FFF; if (builtin_isinf(value)) return hbits | 0x7C00; int exp; std::frexp(value, &exp); if (exp > 16) return overflow<R>(hbits); if (exp < -13) value = std::ldexp(value, 25); else { value = std::ldexp(value, 12 - exp); hbits |= ((exp + 13) << 10); } T ival, frac = std::modf(value, &ival); int m = std::abs(static_cast<int>(ival)); return rounded<R, false>(hbits + (m >> 1), m & 1, frac != T()); } /// Convert floating-point to half-precision. /// \tparam R rounding mode to use /// \tparam T source type (builtin floating-point type) /// \param value floating-point value to convert /// \return rounded half-precision value /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if value had to be rounded template<std::float_round_style R, typename T> unsigned int float2half( T value) { return float2half_impl<R>(value, bool_type< std::numeric_limits<T>::is_iec559 && sizeof(typename bits<T>::type) == sizeof(T)>()); } /// Convert integer to half-precision floating-point. /// \tparam R rounding mode to use /// \tparam T type to convert (builtin integer type) /// \param value integral value to convert /// \return rounded half-precision value /// \exception FE_OVERFLOW on overflows /// \exception FE_INEXACT if value had to be rounded template<std::float_round_style R, typename T> unsigned int int2half(T value) { unsigned int bits = static_cast<unsigned>(value < 0) << 15; if (!value) return bits; if (bits) value = -value; if (value > 0xFFFF) return overflow<R>(bits); unsigned int m = static_cast<unsigned int>(value), exp = 24; for (; m < 0x400; m <<= 1, --exp) ; for (; m > 0x7FF; m >>= 1, ++exp) ; bits |= (exp << 10) + m; return (exp > 24) ? rounded<R, false>(bits, (value >> (exp - 25)) & 1, (((1 << (exp - 25)) - 1) & value) != 0) : bits; } /// Convert half-precision to IEEE single-precision. /// Credit for this goes to [Jeroen van der Zijp](ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf). /// \param value half-precision value to convert /// \return single-precision value inline float half2float_impl(unsigned int value, float, true_type) { #if HALF_ENABLE_F16C_INTRINSICS return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(value))); #else #if 0 bits<float>::type fbits = static_cast<bits<float>::type>(value&0x8000) << 16; int abs = value & 0x7FFF; if(abs) { fbits |= 0x38000000 << static_cast<unsigned>(abs>=0x7C00); for(; abs<0x400; abs<<=1,fbits-=0x800000) ; fbits += static_cast<bits<float>::type>(abs) << 13; } #else static const bits<float>::type mantissa_table[2048] = { 0x00000000, 0x33800000, 0x34000000, 0x34400000, 0x34800000, 0x34A00000, 0x34C00000, 0x34E00000, 0x35000000, 0x35100000, 0x35200000, 0x35300000, 0x35400000, 0x35500000, 0x35600000, 0x35700000, 0x35800000, 0x35880000, 0x35900000, 0x35980000, 0x35A00000, 0x35A80000, 0x35B00000, 0x35B80000, 0x35C00000, 0x35C80000, 0x35D00000, 0x35D80000, 0x35E00000, 0x35E80000, 0x35F00000, 0x35F80000, 0x36000000, 0x36040000, 0x36080000, 0x360C0000, 0x36100000, 0x36140000, 0x36180000, 0x361C0000, 0x36200000, 0x36240000, 0x36280000, 0x362C0000, 0x36300000, 0x36340000, 0x36380000, 0x363C0000, 0x36400000, 0x36440000, 0x36480000, 0x364C0000, 0x36500000, 0x36540000, 0x36580000, 0x365C0000, 0x36600000, 0x36640000, 0x36680000, 0x366C0000, 0x36700000, 0x36740000, 0x36780000, 0x367C0000, 0x36800000, 0x36820000, 0x36840000, 0x36860000, 0x36880000, 0x368A0000, 0x368C0000, 0x368E0000, 0x36900000, 0x36920000, 0x36940000, 0x36960000, 0x36980000, 0x369A0000, 0x369C0000, 0x369E0000, 0x36A00000, 0x36A20000, 0x36A40000, 0x36A60000, 0x36A80000, 0x36AA0000, 0x36AC0000, 0x36AE0000, 0x36B00000, 0x36B20000, 0x36B40000, 0x36B60000, 0x36B80000, 0x36BA0000, 0x36BC0000, 0x36BE0000, 0x36C00000, 0x36C20000, 0x36C40000, 0x36C60000, 0x36C80000, 0x36CA0000, 0x36CC0000, 0x36CE0000, 0x36D00000, 0x36D20000, 0x36D40000, 0x36D60000, 0x36D80000, 0x36DA0000, 0x36DC0000, 0x36DE0000, 0x36E00000, 0x36E20000, 0x36E40000, 0x36E60000, 0x36E80000, 0x36EA0000, 0x36EC0000, 0x36EE0000, 0x36F00000, 0x36F20000, 0x36F40000, 0x36F60000, 0x36F80000, 0x36FA0000, 0x36FC0000, 0x36FE0000, 0x37000000, 0x37010000, 0x37020000, 0x37030000, 0x37040000, 0x37050000, 0x37060000, 0x37070000, 0x37080000, 0x37090000, 0x370A0000, 0x370B0000, 0x370C0000, 0x370D0000, 0x370E0000, 0x370F0000, 0x37100000, 0x37110000, 0x37120000, 0x37130000, 0x37140000, 0x37150000, 0x37160000, 0x37170000, 0x37180000, 0x37190000, 0x371A0000, 0x371B0000, 0x371C0000, 0x371D0000, 0x371E0000, 0x371F0000, 0x37200000, 0x37210000, 0x37220000, 0x37230000, 0x37240000, 0x37250000, 0x37260000, 0x37270000, 0x37280000, 0x37290000, 0x372A0000, 0x372B0000, 0x372C0000, 0x372D0000, 0x372E0000, 0x372F0000, 0x37300000, 0x37310000, 0x37320000, 0x37330000, 0x37340000, 0x37350000, 0x37360000, 0x37370000, 0x37380000, 0x37390000, 0x373A0000, 0x373B0000, 0x373C0000, 0x373D0000, 0x373E0000, 0x373F0000, 0x37400000, 0x37410000, 0x37420000, 0x37430000, 0x37440000, 0x37450000, 0x37460000, 0x37470000, 0x37480000, 0x37490000, 0x374A0000, 0x374B0000, 0x374C0000, 0x374D0000, 0x374E0000, 0x374F0000, 0x37500000, 0x37510000, 0x37520000, 0x37530000, 0x37540000, 0x37550000, 0x37560000, 0x37570000, 0x37580000, 0x37590000, 0x375A0000, 0x375B0000, 0x375C0000, 0x375D0000, 0x375E0000, 0x375F0000, 0x37600000, 0x37610000, 0x37620000, 0x37630000, 0x37640000, 0x37650000, 0x37660000, 0x37670000, 0x37680000, 0x37690000, 0x376A0000, 0x376B0000, 0x376C0000, 0x376D0000, 0x376E0000, 0x376F0000, 0x37700000, 0x37710000, 0x37720000, 0x37730000, 0x37740000, 0x37750000, 0x37760000, 0x37770000, 0x37780000, 0x37790000, 0x377A0000, 0x377B0000, 0x377C0000, 0x377D0000, 0x377E0000, 0x377F0000, 0x37800000, 0x37808000, 0x37810000, 0x37818000, 0x37820000, 0x37828000, 0x37830000, 0x37838000, 0x37840000, 0x37848000, 0x37850000, 0x37858000, 0x37860000, 0x37868000, 0x37870000, 0x37878000, 0x37880000, 0x37888000, 0x37890000, 0x37898000, 0x378A0000, 0x378A8000, 0x378B0000, 0x378B8000, 0x378C0000, 0x378C8000, 0x378D0000, 0x378D8000, 0x378E0000, 0x378E8000, 0x378F0000, 0x378F8000, 0x37900000, 0x37908000, 0x37910000, 0x37918000, 0x37920000, 0x37928000, 0x37930000, 0x37938000, 0x37940000, 0x37948000, 0x37950000, 0x37958000, 0x37960000, 0x37968000, 0x37970000, 0x37978000, 0x37980000, 0x37988000, 0x37990000, 0x37998000, 0x379A0000, 0x379A8000, 0x379B0000, 0x379B8000, 0x379C0000, 0x379C8000, 0x379D0000, 0x379D8000, 0x379E0000, 0x379E8000, 0x379F0000, 0x379F8000, 0x37A00000, 0x37A08000, 0x37A10000, 0x37A18000, 0x37A20000, 0x37A28000, 0x37A30000, 0x37A38000, 0x37A40000, 0x37A48000, 0x37A50000, 0x37A58000, 0x37A60000, 0x37A68000, 0x37A70000, 0x37A78000, 0x37A80000, 0x37A88000, 0x37A90000, 0x37A98000, 0x37AA0000, 0x37AA8000, 0x37AB0000, 0x37AB8000, 0x37AC0000, 0x37AC8000, 0x37AD0000, 0x37AD8000, 0x37AE0000, 0x37AE8000, 0x37AF0000, 0x37AF8000, 0x37B00000, 0x37B08000, 0x37B10000, 0x37B18000, 0x37B20000, 0x37B28000, 0x37B30000, 0x37B38000, 0x37B40000, 0x37B48000, 0x37B50000, 0x37B58000, 0x37B60000, 0x37B68000, 0x37B70000, 0x37B78000, 0x37B80000, 0x37B88000, 0x37B90000, 0x37B98000, 0x37BA0000, 0x37BA8000, 0x37BB0000, 0x37BB8000, 0x37BC0000, 0x37BC8000, 0x37BD0000, 0x37BD8000, 0x37BE0000, 0x37BE8000, 0x37BF0000, 0x37BF8000, 0x37C00000, 0x37C08000, 0x37C10000, 0x37C18000, 0x37C20000, 0x37C28000, 0x37C30000, 0x37C38000, 0x37C40000, 0x37C48000, 0x37C50000, 0x37C58000, 0x37C60000, 0x37C68000, 0x37C70000, 0x37C78000, 0x37C80000, 0x37C88000, 0x37C90000, 0x37C98000, 0x37CA0000, 0x37CA8000, 0x37CB0000, 0x37CB8000, 0x37CC0000, 0x37CC8000, 0x37CD0000, 0x37CD8000, 0x37CE0000, 0x37CE8000, 0x37CF0000, 0x37CF8000, 0x37D00000, 0x37D08000, 0x37D10000, 0x37D18000, 0x37D20000, 0x37D28000, 0x37D30000, 0x37D38000, 0x37D40000, 0x37D48000, 0x37D50000, 0x37D58000, 0x37D60000, 0x37D68000, 0x37D70000, 0x37D78000, 0x37D80000, 0x37D88000, 0x37D90000, 0x37D98000, 0x37DA0000, 0x37DA8000, 0x37DB0000, 0x37DB8000, 0x37DC0000, 0x37DC8000, 0x37DD0000, 0x37DD8000, 0x37DE0000, 0x37DE8000, 0x37DF0000, 0x37DF8000, 0x37E00000, 0x37E08000, 0x37E10000, 0x37E18000, 0x37E20000, 0x37E28000, 0x37E30000, 0x37E38000, 0x37E40000, 0x37E48000, 0x37E50000, 0x37E58000, 0x37E60000, 0x37E68000, 0x37E70000, 0x37E78000, 0x37E80000, 0x37E88000, 0x37E90000, 0x37E98000, 0x37EA0000, 0x37EA8000, 0x37EB0000, 0x37EB8000, 0x37EC0000, 0x37EC8000, 0x37ED0000, 0x37ED8000, 0x37EE0000, 0x37EE8000, 0x37EF0000, 0x37EF8000, 0x37F00000, 0x37F08000, 0x37F10000, 0x37F18000, 0x37F20000, 0x37F28000, 0x37F30000, 0x37F38000, 0x37F40000, 0x37F48000, 0x37F50000, 0x37F58000, 0x37F60000, 0x37F68000, 0x37F70000, 0x37F78000, 0x37F80000, 0x37F88000, 0x37F90000, 0x37F98000, 0x37FA0000, 0x37FA8000, 0x37FB0000, 0x37FB8000, 0x37FC0000, 0x37FC8000, 0x37FD0000, 0x37FD8000, 0x37FE0000, 0x37FE8000, 0x37FF0000, 0x37FF8000, 0x38000000, 0x38004000, 0x38008000, 0x3800C000, 0x38010000, 0x38014000, 0x38018000, 0x3801C000, 0x38020000, 0x38024000, 0x38028000, 0x3802C000, 0x38030000, 0x38034000, 0x38038000, 0x3803C000, 0x38040000, 0x38044000, 0x38048000, 0x3804C000, 0x38050000, 0x38054000, 0x38058000, 0x3805C000, 0x38060000, 0x38064000, 0x38068000, 0x3806C000, 0x38070000, 0x38074000, 0x38078000, 0x3807C000, 0x38080000, 0x38084000, 0x38088000, 0x3808C000, 0x38090000, 0x38094000, 0x38098000, 0x3809C000, 0x380A0000, 0x380A4000, 0x380A8000, 0x380AC000, 0x380B0000, 0x380B4000, 0x380B8000, 0x380BC000, 0x380C0000, 0x380C4000, 0x380C8000, 0x380CC000, 0x380D0000, 0x380D4000, 0x380D8000, 0x380DC000, 0x380E0000, 0x380E4000, 0x380E8000, 0x380EC000, 0x380F0000, 0x380F4000, 0x380F8000, 0x380FC000, 0x38100000, 0x38104000, 0x38108000, 0x3810C000, 0x38110000, 0x38114000, 0x38118000, 0x3811C000, 0x38120000, 0x38124000, 0x38128000, 0x3812C000, 0x38130000, 0x38134000, 0x38138000, 0x3813C000, 0x38140000, 0x38144000, 0x38148000, 0x3814C000, 0x38150000, 0x38154000, 0x38158000, 0x3815C000, 0x38160000, 0x38164000, 0x38168000, 0x3816C000, 0x38170000, 0x38174000, 0x38178000, 0x3817C000, 0x38180000, 0x38184000, 0x38188000, 0x3818C000, 0x38190000, 0x38194000, 0x38198000, 0x3819C000, 0x381A0000, 0x381A4000, 0x381A8000, 0x381AC000, 0x381B0000, 0x381B4000, 0x381B8000, 0x381BC000, 0x381C0000, 0x381C4000, 0x381C8000, 0x381CC000, 0x381D0000, 0x381D4000, 0x381D8000, 0x381DC000, 0x381E0000, 0x381E4000, 0x381E8000, 0x381EC000, 0x381F0000, 0x381F4000, 0x381F8000, 0x381FC000, 0x38200000, 0x38204000, 0x38208000, 0x3820C000, 0x38210000, 0x38214000, 0x38218000, 0x3821C000, 0x38220000, 0x38224000, 0x38228000, 0x3822C000, 0x38230000, 0x38234000, 0x38238000, 0x3823C000, 0x38240000, 0x38244000, 0x38248000, 0x3824C000, 0x38250000, 0x38254000, 0x38258000, 0x3825C000, 0x38260000, 0x38264000, 0x38268000, 0x3826C000, 0x38270000, 0x38274000, 0x38278000, 0x3827C000, 0x38280000, 0x38284000, 0x38288000, 0x3828C000, 0x38290000, 0x38294000, 0x38298000, 0x3829C000, 0x382A0000, 0x382A4000, 0x382A8000, 0x382AC000, 0x382B0000, 0x382B4000, 0x382B8000, 0x382BC000, 0x382C0000, 0x382C4000, 0x382C8000, 0x382CC000, 0x382D0000, 0x382D4000, 0x382D8000, 0x382DC000, 0x382E0000, 0x382E4000, 0x382E8000, 0x382EC000, 0x382F0000, 0x382F4000, 0x382F8000, 0x382FC000, 0x38300000, 0x38304000, 0x38308000, 0x3830C000, 0x38310000, 0x38314000, 0x38318000, 0x3831C000, 0x38320000, 0x38324000, 0x38328000, 0x3832C000, 0x38330000, 0x38334000, 0x38338000, 0x3833C000, 0x38340000, 0x38344000, 0x38348000, 0x3834C000, 0x38350000, 0x38354000, 0x38358000, 0x3835C000, 0x38360000, 0x38364000, 0x38368000, 0x3836C000, 0x38370000, 0x38374000, 0x38378000, 0x3837C000, 0x38380000, 0x38384000, 0x38388000, 0x3838C000, 0x38390000, 0x38394000, 0x38398000, 0x3839C000, 0x383A0000, 0x383A4000, 0x383A8000, 0x383AC000, 0x383B0000, 0x383B4000, 0x383B8000, 0x383BC000, 0x383C0000, 0x383C4000, 0x383C8000, 0x383CC000, 0x383D0000, 0x383D4000, 0x383D8000, 0x383DC000, 0x383E0000, 0x383E4000, 0x383E8000, 0x383EC000, 0x383F0000, 0x383F4000, 0x383F8000, 0x383FC000, 0x38400000, 0x38404000, 0x38408000, 0x3840C000, 0x38410000, 0x38414000, 0x38418000, 0x3841C000, 0x38420000, 0x38424000, 0x38428000, 0x3842C000, 0x38430000, 0x38434000, 0x38438000, 0x3843C000, 0x38440000, 0x38444000, 0x38448000, 0x3844C000, 0x38450000, 0x38454000, 0x38458000, 0x3845C000, 0x38460000, 0x38464000, 0x38468000, 0x3846C000, 0x38470000, 0x38474000, 0x38478000, 0x3847C000, 0x38480000, 0x38484000, 0x38488000, 0x3848C000, 0x38490000, 0x38494000, 0x38498000, 0x3849C000, 0x384A0000, 0x384A4000, 0x384A8000, 0x384AC000, 0x384B0000, 0x384B4000, 0x384B8000, 0x384BC000, 0x384C0000, 0x384C4000, 0x384C8000, 0x384CC000, 0x384D0000, 0x384D4000, 0x384D8000, 0x384DC000, 0x384E0000, 0x384E4000, 0x384E8000, 0x384EC000, 0x384F0000, 0x384F4000, 0x384F8000, 0x384FC000, 0x38500000, 0x38504000, 0x38508000, 0x3850C000, 0x38510000, 0x38514000, 0x38518000, 0x3851C000, 0x38520000, 0x38524000, 0x38528000, 0x3852C000, 0x38530000, 0x38534000, 0x38538000, 0x3853C000, 0x38540000, 0x38544000, 0x38548000, 0x3854C000, 0x38550000, 0x38554000, 0x38558000, 0x3855C000, 0x38560000, 0x38564000, 0x38568000, 0x3856C000, 0x38570000, 0x38574000, 0x38578000, 0x3857C000, 0x38580000, 0x38584000, 0x38588000, 0x3858C000, 0x38590000, 0x38594000, 0x38598000, 0x3859C000, 0x385A0000, 0x385A4000, 0x385A8
000, 0x385AC000, 0x385B0000, 0x385B4000, 0x385B8000, 0x385BC000, 0x385C0000, 0x385C4000, 0x385C8000, 0x385CC000, 0x385D0000, 0x385D4000, 0x385D8000, 0x385DC000, 0x385E0000, 0x385E4000, 0x385E8000, 0x385EC000, 0x385F0000, 0x385F4000, 0x385F8000, 0x385FC000, 0x38600000, 0x38604000, 0x38608000, 0x3860C000, 0x38610000, 0x38614000, 0x38618000, 0x3861C000, 0x38620000, 0x38624000, 0x38628000, 0x3862C000, 0x38630000, 0x38634000, 0x38638000, 0x3863C000, 0x38640000, 0x38644000, 0x38648000, 0x3864C000, 0x38650000, 0x38654000, 0x38658000, 0x3865C000, 0x38660000, 0x38664000, 0x38668000, 0x3866C000, 0x38670000, 0x38674000, 0x38678000, 0x3867C000, 0x38680000, 0x38684000, 0x38688000, 0x3868C000, 0x38690000, 0x38694000, 0x38698000, 0x3869C000, 0x386A0000, 0x386A4000, 0x386A8000, 0x386AC000, 0x386B0000, 0x386B4000, 0x386B8000, 0x386BC000, 0x386C0000, 0x386C4000, 0x386C8000, 0x386CC000, 0x386D0000, 0x386D4000, 0x386D8000, 0x386DC000, 0x386E0000, 0x386E4000, 0x386E8000, 0x386EC000, 0x386F0000, 0x386F4000, 0x386F8000, 0x386FC000, 0x38700000, 0x38704000, 0x38708000, 0x3870C000, 0x38710000, 0x38714000, 0x38718000, 0x3871C000, 0x38720000, 0x38724000, 0x38728000, 0x3872C000, 0x38730000, 0x38734000, 0x38738000, 0x3873C000, 0x38740000, 0x38744000, 0x38748000, 0x3874C000, 0x38750000, 0x38754000, 0x38758000, 0x3875C000, 0x38760000, 0x38764000, 0x38768000, 0x3876C000, 0x38770000, 0x38774000, 0x38778000, 0x3877C000, 0x38780000, 0x38784000, 0x38788000, 0x3878C000, 0x38790000, 0x38794000, 0x38798000, 0x3879C000, 0x387A0000, 0x387A4000, 0x387A8000, 0x387AC000, 0x387B0000, 0x387B4000, 0x387B8000, 0x387BC000, 0x387C0000, 0x387C4000, 0x387C8000, 0x387CC000, 0x387D0000, 0x387D4000, 0x387D8000, 0x387DC000, 0x387E0000, 0x387E4000, 0x387E8000, 0x387EC000, 0x387F0000, 0x387F4000, 0x387F8000, 0x387FC000, 0x38000000, 0x38002000, 0x38004000, 0x38006000, 0x38008000, 0x3800A000, 0x3800C000, 0x3800E000, 0x38010000, 0x38012000, 0x38014000, 0x38016000, 0x38018000, 0x3801A000, 0x3801C000, 0x3801E000, 0x38020000, 0x38022000, 0x38024000, 0x38026000, 0x38028000, 0x3802A000, 0x3802C000, 0x3802E000, 0x38030000, 0x38032000, 0x38034000, 0x38036000, 0x38038000, 0x3803A000, 0x3803C000, 0x3803E000, 0x38040000, 0x38042000, 0x38044000, 0x38046000, 0x38048000, 0x3804A000, 0x3804C000, 0x3804E000, 0x38050000, 0x38052000, 0x38054000, 0x38056000, 0x38058000, 0x3805A000, 0x3805C000, 0x3805E000, 0x38060000, 0x38062000, 0x38064000, 0x38066000, 0x38068000, 0x3806A000, 0x3806C000, 0x3806E000, 0x38070000, 0x38072000, 0x38074000, 0x38076000, 0x38078000, 0x3807A000, 0x3807C000, 0x3807E000, 0x38080000, 0x38082000, 0x38084000, 0x38086000, 0x38088000, 0x3808A000, 0x3808C000, 0x3808E000, 0x38090000, 0x38092000, 0x38094000, 0x38096000, 0x38098000, 0x3809A000, 0x3809C000, 0x3809E000, 0x380A0000, 0x380A2000, 0x380A4000, 0x380A6000, 0x380A8000, 0x380AA000, 0x380AC000, 0x380AE000, 0x380B0000, 0x380B2000, 0x380B4000, 0x380B6000, 0x380B8000, 0x380BA000, 0x380BC000, 0x380BE000, 0x380C0000, 0x380C2000, 0x380C4000, 0x380C6000, 0x380C8000, 0x380CA000, 0x380CC000, 0x380CE000, 0x380D0000, 0x380D2000, 0x380D4000, 0x380D6000, 0x380D8000, 0x380DA000, 0x380DC000, 0x380DE000, 0x380E0000, 0x380E2000, 0x380E4000, 0x380E6000, 0x380E8000, 0x380EA000, 0x380EC000, 0x380EE000, 0x380F0000, 0x380F2000, 0x380F4000, 0x380F6000, 0x380F8000, 0x380FA000, 0x380FC000, 0x380FE000, 0x38100000, 0x38102000, 0x38104000, 0x38106000, 0x38108000, 0x3810A000, 0x3810C000, 0x3810E000, 0x38110000, 0x38112000, 0x38114000, 0x38116000, 0x38118000, 0x3811A000, 0x3811C000, 0x3811E000, 0x38120000, 0x38122000, 0x38124000, 0x38126000, 0x38128000, 0x3812A000, 0x3812C000, 0x3812E000, 0x38130000, 0x38132000, 0x38134000, 0x38136000, 0x38138000, 0x3813A000, 0x3813C000, 0x3813E000, 0x38140000, 0x38142000, 0x38144000, 0x38146000, 0x38148000, 0x3814A000, 0x3814C000, 0x3814E000, 0x38150000, 0x38152000, 0x38154000, 0x38156000, 0x38158000, 0x3815A000, 0x3815C000, 0x3815E000, 0x38160000, 0x38162000, 0x38164000, 0x38166000, 0x38168000, 0x3816A000, 0x3816C000, 0x3816E000, 0x38170000, 0x38172000, 0x38174000, 0x38176000, 0x38178000, 0x3817A000, 0x3817C000, 0x3817E000, 0x38180000, 0x38182000, 0x38184000, 0x38186000, 0x38188000, 0x3818A000, 0x3818C000, 0x3818E000, 0x38190000, 0x38192000, 0x38194000, 0x38196000, 0x38198000, 0x3819A000, 0x3819C000, 0x3819E000, 0x381A0000, 0x381A2000, 0x381A4000, 0x381A6000, 0x381A8000, 0x381AA000, 0x381AC000, 0x381AE000, 0x381B0000, 0x381B2000, 0x381B4000, 0x381B6000, 0x381B8000, 0x381BA000, 0x381BC000, 0x381BE000, 0x381C0000, 0x381C2000, 0x381C4000, 0x381C6000, 0x381C8000, 0x381CA000, 0x381CC000, 0x381CE000, 0x381D0000, 0x381D2000, 0x381D4000, 0x381D6000, 0x381D8000, 0x381DA000, 0x381DC000, 0x381DE000, 0x381E0000, 0x381E2000, 0x381E4000, 0x381E6000, 0x381E8000, 0x381EA000, 0x381EC000, 0x381EE000, 0x381F0000, 0x381F2000, 0x381F4000, 0x381F6000, 0x381F8000, 0x381FA000, 0x381FC000, 0x381FE000, 0x38200000, 0x38202000, 0x38204000, 0x38206000, 0x38208000, 0x3820A000, 0x3820C000, 0x3820E000, 0x38210000, 0x38212000, 0x38214000, 0x38216000, 0x38218000, 0x3821A000, 0x3821C000, 0x3821E000, 0x38220000, 0x38222000, 0x38224000, 0x38226000, 0x38228000, 0x3822A000, 0x3822C000, 0x3822E000, 0x38230000, 0x38232000, 0x38234000, 0x38236000, 0x38238000, 0x3823A000, 0x3823C000, 0x3823E000, 0x38240000, 0x38242000, 0x38244000, 0x38246000, 0x38248000, 0x3824A000, 0x3824C000, 0x3824E000, 0x38250000, 0x38252000, 0x38254000, 0x38256000, 0x38258000, 0x3825A000, 0x3825C000, 0x3825E000, 0x38260000, 0x38262000, 0x38264000, 0x38266000, 0x38268000, 0x3826A000, 0x3826C000, 0x3826E000, 0x38270000, 0x38272000, 0x38274000, 0x38276000, 0x38278000, 0x3827A000, 0x3827C000, 0x3827E000, 0x38280000, 0x38282000, 0x38284000, 0x38286000, 0x38288000, 0x3828A000, 0x3828C000, 0x3828E000, 0x38290000, 0x38292000, 0x38294000, 0x38296000, 0x38298000, 0x3829A000, 0x3829C000, 0x3829E000, 0x382A0000, 0x382A2000, 0x382A4000, 0x382A6000, 0x382A8000, 0x382AA000, 0x382AC000, 0x382AE000, 0x382B0000, 0x382B2000, 0x382B4000, 0x382B6000, 0x382B8000, 0x382BA000, 0x382BC000, 0x382BE000, 0x382C0000, 0x382C2000, 0x382C4000, 0x382C6000, 0x382C8000, 0x382CA000, 0x382CC000, 0x382CE000, 0x382D0000, 0x382D2000, 0x382D4000, 0x382D6000, 0x382D8000, 0x382DA000, 0x382DC000, 0x382DE000, 0x382E0000, 0x382E2000, 0x382E4000, 0x382E6000, 0x382E8000, 0x382EA000, 0x382EC000, 0x382EE000, 0x382F0000, 0x382F2000, 0x382F4000, 0x382F6000, 0x382F8000, 0x382FA000, 0x382FC000, 0x382FE000, 0x38300000, 0x38302000, 0x38304000, 0x38306000, 0x38308000, 0x3830A000, 0x3830C000, 0x3830E000, 0x38310000, 0x38312000, 0x38314000, 0x38316000, 0x38318000, 0x3831A000, 0x3831C000, 0x3831E000, 0x38320000, 0x38322000, 0x38324000, 0x38326000, 0x38328000, 0x3832A000, 0x3832C000, 0x3832E000, 0x38330000, 0x38332000, 0x38334000, 0x38336000, 0x38338000, 0x3833A000, 0x3833C000, 0x3833E000, 0x38340000, 0x38342000, 0x38344000, 0x38346000, 0x38348000, 0x3834A000, 0x3834C000, 0x3834E000, 0x38350000, 0x38352000, 0x38354000, 0x38356000, 0x38358000, 0x3835A000, 0x3835C000, 0x3835E000, 0x38360000, 0x38362000, 0x38364000, 0x38366000, 0x38368000, 0x3836A000, 0x3836C000, 0x3836E000, 0x38370000, 0x38372000, 0x38374000, 0x38376000, 0x38378000, 0x3837A000, 0x3837C000, 0x3837E000, 0x38380000, 0x38382000, 0x38384000, 0x38386000, 0x38388000, 0x3838A000, 0x3838C000, 0x3838E000, 0x38390000, 0x38392000, 0x38394000, 0x38396000, 0x38398000, 0x3839A000, 0x3839C000, 0x3839E000, 0x383A0000, 0x383A2000, 0x383A4000, 0x383A6000, 0x383A8000, 0x383AA000, 0x383AC000, 0x383AE000, 0x383B0000, 0x383B2000, 0x383B4000, 0x383B6000, 0x383B8000, 0x383BA000, 0x383BC000, 0x383BE000, 0x383C0000, 0x383C2000, 0x383C4000, 0x383C6000, 0x383C8000, 0x383CA000, 0x383CC000, 0x383CE000, 0x383D0000, 0x383D2000, 0x383D4000, 0x383D6000, 0x383D8000, 0x383DA000, 0x383DC000, 0x383DE000, 0x383E0000, 0x383E2000, 0x383E4000, 0x383E6000, 0x383E8000, 0x383EA000, 0x383EC000, 0x383EE000, 0x383F0000, 0x383F2000, 0x383F4000, 0x383F6000, 0x383F8000, 0x383FA000, 0x383FC000, 0x383FE000, 0x38400000, 0x38402000, 0x38404000, 0x38406000, 0x38408000, 0x3840A000, 0x3840C000, 0x3840E000, 0x38410000, 0x38412000, 0x38414000, 0x38416000, 0x38418000, 0x3841A000, 0x3841C000, 0x3841E000, 0x38420000, 0x38422000, 0x38424000, 0x38426000, 0x38428000, 0x3842A000, 0x3842C000, 0x3842E000, 0x38430000, 0x38432000, 0x38434000, 0x38436000, 0x38438000, 0x3843A000, 0x3843C000, 0x3843E000, 0x38440000, 0x38442000, 0x38444000, 0x38446000, 0x38448000, 0x3844A000, 0x3844C000, 0x3844E000, 0x38450000, 0x38452000, 0x38454000, 0x38456000, 0x38458000, 0x3845A000, 0x3845C000, 0x3845E000, 0x38460000, 0x38462000, 0x38464000, 0x38466000, 0x38468000, 0x3846A000, 0x3846C000, 0x3846E000, 0x38470000, 0x38472000, 0x38474000, 0x38476000, 0x38478000, 0x3847A000, 0x3847C000, 0x3847E000, 0x38480000, 0x38482000, 0x38484000, 0x38486000, 0x38488000, 0x3848A000, 0x3848C000, 0x3848E000, 0x38490000, 0x38492000, 0x38494000, 0x38496000, 0x38498000, 0x3849A000, 0x3849C000, 0x3849E000, 0x384A0000, 0x384A2000, 0x384A4000, 0x384A6000, 0x384A8000, 0x384AA000, 0x384AC000, 0x384AE000, 0x384B0000, 0x384B2000, 0x384B4000, 0x384B6000, 0x384B8000, 0x384BA000, 0x384BC000, 0x384BE000, 0x384C0000, 0x384C2000, 0x384C4000, 0x384C6000, 0x384C8000, 0x384CA000, 0x384CC000, 0x384CE000, 0x384D0000, 0x384D2000, 0x384D4000, 0x384D6000, 0x384D8000, 0x384DA000, 0x384DC000, 0x384DE000, 0x384E0000, 0x384E2000, 0x384E4000, 0x384E6000, 0x384E8000, 0x384EA000, 0x384EC000, 0x384EE000, 0x384F0000, 0x384F2000, 0x384F4000, 0x384F6000, 0x384F8000, 0x384FA000, 0x384FC000, 0x384FE000, 0x38500000, 0x38502000, 0x38504000, 0x38506000, 0x38508000, 0x3850A000, 0x3850C000, 0x3850E000, 0x38510000, 0x38512000, 0x38514000, 0x38516000, 0x38518000, 0x3851A000, 0x3851C000, 0x3851E000, 0x38520000, 0x38522000, 0x38524000, 0x38526000, 0x38528000, 0x3852A000, 0x3852C000, 0x3852E000, 0x38530000, 0x38532000, 0x38534000, 0x38536000, 0x38538000, 0x3853A000, 0x3853C000, 0x3853E000, 0x38540000, 0x38542000, 0x38544000, 0x38546000, 0x38548000, 0x3854A000, 0x3854C000, 0x3854E000, 0x38550000, 0x38552000, 0x38554000, 0x38556000, 0x38558000, 0x3855A000, 0x3855C000, 0x3855E000, 0x38560000, 0x38562000, 0x38564000, 0x38566000, 0x38568000, 0x3856A000, 0x3856C000, 0x3856E000, 0x38570000, 0x38572000, 0x38574000, 0x38576000, 0x38578000, 0x3857A000, 0x3857C000, 0x3857E000, 0x38580000, 0x38582000, 0x38584000, 0x38586000, 0x38588000, 0x3858A000, 0x3858C000, 0x3858E000, 0x38590000, 0x38592000, 0x38594000, 0x38596000, 0x38598000, 0x3859A000, 0x3859C000, 0x3859E000, 0x385A0000, 0x385A2000, 0x385A4000, 0x385A6000, 0x385A8000, 0x385AA000, 0x385AC000, 0x385AE000, 0x385B0000, 0x385B2000, 0x385B4000, 0x385B6000, 0x385B8000, 0x385BA000, 0x385BC000, 0x385BE000, 0x385C0000, 0x385C2000, 0x385C4000, 0x385C6000, 0x385C8000, 0x385CA000, 0x385CC000, 0x385CE000, 0x385D0000, 0x385D2000, 0x385D4000, 0x385D6000, 0x385D8000, 0x385DA000, 0x385DC000, 0x385DE000, 0x385E0000, 0x385E2000, 0x385E4000, 0x385E6000, 0x385E8000, 0x385EA000, 0x385EC000, 0x385EE000, 0x385F0000, 0x385F2000, 0x385F4000, 0x385F6000, 0x385F8000, 0x385FA000, 0x385FC000, 0x385FE000, 0x38600000, 0x38602000, 0x38604000, 0x38606000, 0x38608000, 0x3860A000, 0x3860C000, 0x3860E000, 0x38610000, 0x38612000, 0x38614000, 0x38616000, 0x38618000, 0x3861A000, 0x3861C000, 0x3861E000, 0x38620000, 0x38622000, 0x38624000, 0x38626000, 0x38628000, 0x3862A000, 0x3862C000, 0x3862E000, 0x38630000, 0x38632000, 0x38634000, 0x38636000, 0x38638000, 0x3863A000, 0x3863C000, 0x3863E000, 0x38640000, 0x38642000, 0x38644000, 0x38646000, 0x38648000, 0x3864A000, 0x3864C000, 0x3864E000, 0x38650000, 0x38652000, 0x38654000, 0x38656000, 0x38658000, 0x3865A000, 0x3865C000, 0x3865E000, 0x38660000, 0x38662000, 0x38664000, 0x38666000, 0x38668000, 0x3866A000, 0x3866C000, 0x3866E000, 0x38670000, 0x38672000, 0x38674000, 0x38676000, 0x38678000, 0x3867A000, 0x3867C000, 0x3867E000, 0x38680000, 0x38682000, 0x38684000, 0x38686000, 0x38688000, 0x3868A000, 0x3868C000, 0x3868E000, 0x38690000, 0x38692000, 0x38694000, 0x38696000, 0x38698000, 0x3869A000, 0x3869C000, 0x3869E000, 0x386A0000, 0x386A2000, 0x386A4000, 0x386A6000, 0x386A8000, 0x386AA000, 0x386AC000, 0x386AE000, 0x386B0000, 0x386B2000, 0x386B4000, 0x386B6000, 0x386B8000, 0x386BA000, 0x386BC000, 0x386BE000, 0x386C0000, 0x386C2000, 0x386C4000, 0x386C6000, 0x386C8000, 0x386CA000, 0x386CC000, 0x386CE000, 0x386D0000, 0x386D2000, 0x386D4000, 0x386D6000, 0x386D8000, 0x386DA000, 0x386DC000, 0x386DE000, 0x386E0000, 0x386E2000, 0x386E4000, 0x386E6000, 0x386E8000, 0x386EA000, 0x386EC000, 0x386EE000, 0x386F0000, 0x386F2000, 0x386F4000, 0x386F6000, 0x386F8000, 0x386FA000, 0x386FC000, 0x386FE000, 0x38700000, 0x38702000, 0x38704000, 0x38706000, 0x38708000, 0x3870A000, 0x3870C000, 0x3870E000, 0x38710000, 0x38712000, 0x38714000, 0x38716000, 0x38718000, 0x3871A000, 0x3871C000, 0x3871E000, 0x38720000, 0x38722000, 0x38724000, 0x38726000, 0x38728000, 0x3872A000, 0x3872C000, 0x3872E000, 0x38730000, 0x38732000, 0x38734000, 0x38736000, 0x38738000, 0x3873A000, 0x3873C000, 0x3873E000, 0x38740000, 0x38742000, 0x38744000, 0x38746000, 0x38748000, 0x3874A000, 0x3874C000, 0x3874E000, 0x38750000, 0x38752000, 0x38754000, 0x38756000, 0x38758000, 0x3875A000, 0x3875C000, 0x3875E000, 0x38760000, 0x38762000, 0x38764000, 0x38766000, 0x38768000, 0x3876A000, 0x3876C000, 0x3876E000, 0x38770000, 0x38772000, 0x38774000, 0x38776000, 0x38778000, 0x3877A000, 0x3877C000, 0x3877E000, 0x38780000, 0x38782000, 0x38784000, 0x38786000, 0x38788000, 0x3878A000, 0x3878C000, 0x3878E000, 0x38790000, 0x38792000, 0x38794000, 0x38796000, 0x38798000, 0x3879A000, 0x3879C000, 0x3879E000, 0x387A0000, 0x387A2000, 0x387A4000, 0x387A6000, 0x387A8000, 0x387AA000, 0x387AC000, 0x387AE000, 0x387B0000, 0x387B2000, 0x387B4000, 0x387B6000, 0x387B8000, 0x387BA000, 0x387BC000, 0x387BE000, 0x387C0000, 0x387C2000, 0x387C4000, 0x387C6000, 0x387C8000, 0x387CA000, 0x387CC000, 0x387CE000, 0x387D0000, 0x387D2000, 0x387D4000, 0x387D6000, 0x387D8000, 0x387DA000, 0x387DC000, 0x387DE000, 0x387E0000, 0x387E2000, 0x387E4000, 0x387E6000, 0x387E8000, 0x387EA000, 0x387EC000, 0x387EE000, 0x387F0000, 0x387F2000, 0x387F4000, 0x387F6000, 0x387F8000, 0x387FA000, 0x387FC000, 0x387FE000 }; static const bits<float>::type exponent_table[64] = { 0x00000000, 0x00800000, 0x01000000, 0x01800000, 0x02000000, 0x02800000, 0x03000000, 0x03800000, 0x04000000, 0x04800000, 0x05000000, 0x05800000, 0x06000000, 0x06800000, 0x07000000, 0x07800000, 0x08000000, 0x08800000, 0x09000000, 0x09800000, 0x0A000000, 0x0A800000, 0x0B000000, 0x0B800000, 0x0C000000, 0x0C800000, 0x0D000000, 0x0D800000, 0x0E000000, 0x0E800000, 0x0F000000, 0x47800000, 0x80000000, 0x80800000, 0x81000000, 0x81800000, 0x82000000, 0x82800000, 0x83000000, 0x83800000, 0x84000000, 0x84800000, 0x85000000, 0x85800000, 0x86000000, 0x86800000, 0x87000000, 0x87800000, 0x88000000, 0x88800000, 0x89000000, 0x89800000, 0x8A000000, 0x8A800000, 0x8B000000, 0x8B800000, 0x8C000000, 0x8C800000, 0x8D000000, 0x8D800000, 0x8E000000, 0x8E800000, 0x8F000000, 0xC7800000 }; static const unsigned short offset_table[64] = { 0, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 0, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024 }; bits<float>::type fbits = mantissa_table[offset_table[value >> 10] + (value & 0x3FF)] + exponent_table[value >> 10]; #endif float out; std::memcpy(&out, &fbits, sizeof(float)); return out; #endif } /// Convert half-precision to IEEE double-precision. /// \param value half-precision value to convert /// \return double-precision value inline double half2float_impl(unsigned int value, double, true_type) { #if HALF_ENABLE_F16C_INTRINSICS return _mm_cvtsd_f64(_mm_cvtps_pd(_mm_cvtph_ps(_mm_cvtsi32_si128(value)))); #else uint32 hi = static_cast<uint32>(value & 0x8000) << 16; unsigned int abs = value & 0x7FFF; if (abs) { hi |= 0x3F000000 << static_cast<unsigned>(abs >= 0x7C00); for (; abs < 0x400; abs <<= 1, hi -= 0x100000) ; hi += static_cast<uint32>(abs) << 10; } bits<double>::type dbits = static_cast<bits<double>::type>(hi) << 32; double out; std::memcpy(&out, &dbits, sizeof(double)); return out; #endif } /// Convert half-precision to non-IEEE floating-point. /// \tparam T type to convert to (builtin integer type) /// \param value half-precision value to convert /// \return floating-point value template<typename T> T half2float_impl(unsigned int value, T, ...) { T out; unsigned int abs = value & 0x7FFF; if (abs > 0x7C00) out = (std::numeric_limits<T>::has_signaling_NaN && !(abs & 0x200)) ? std::numeric_limits<T>::signaling_NaN() : std::numeric_limits<T>::has_quiet_NaN ? std::numeric_limits<T>::quiet_NaN() : T();
else if (abs == 0x7C00) out = std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity() : std::numeric_limits<T>::max(); else if (abs > 0x3FF) out = std::ldexp(static_cast<T>((abs & 0x3FF) | 0x400), (abs >> 10) - 25); else out = std::ldexp(static_cast<T>(abs), -24); return (value & 0x8000) ? -out : out; } /// Convert half-precision to floating-point. /// \tparam T type to convert to (builtin integer type) /// \param value half-precision value to convert /// \return floating-point value template<typename T> T half2float(unsigned int value) { return half2float_impl(value, T(), bool_type< std::numeric_limits<T>::is_iec559 && sizeof(typename bits<T>::type) == sizeof(T)>()); } /// Convert half-precision floating-point to integer. /// \tparam R rounding mode to use /// \tparam E `true` for round to even, `false` for round away from zero /// \tparam I `true` to raise INEXACT exception (if inexact), `false` to never raise it /// \tparam T type to convert to (buitlin integer type with at least 16 bits precision, excluding any implicit sign bits) /// \param value half-precision value to convert /// \return rounded integer value /// \exception FE_INVALID if value is not representable in type \a T /// \exception FE_INEXACT if value had to be rounded and \a I is `true` template<std::float_round_style R, bool E, bool I, typename T> T half2int( unsigned int value) { unsigned int abs = value & 0x7FFF; if (abs >= 0x7C00) { raise(FE_INVALID); return (value & 0x8000) ? std::numeric_limits<T>::min() : std::numeric_limits<T>::max(); } if (abs < 0x3800) { raise(FE_INEXACT, I); return (R == std::round_toward_infinity) ? T(~(value >> 15) & (abs != 0)) : (R == std::round_toward_neg_infinity) ? -T(value > 0x8000) : T(); } int exp = 25 - (abs >> 10); unsigned int m = (value & 0x3FF) | 0x400; int32 i = static_cast<int32>( (exp <= 0) ? (m << -exp) : ((m + ((R == std::round_to_nearest) ? ((1 << (exp - 1)) - (~(m >> exp) & E)) : (R == std::round_toward_infinity) ? (((1 << exp) - 1) & ((value >> 15) - 1)) : (R == std::round_toward_neg_infinity) ? (((1 << exp) - 1) & -(value >> 15)) : 0)) >> exp)); if ((!std::numeric_limits<T>::is_signed && (value & 0x8000)) || (std::numeric_limits<T>::digits < 16 && ((value & 0x8000) ? (-i < std::numeric_limits<T>::min()) : (i > std::numeric_limits<T>::max())))) raise(FE_INVALID); else if (I && exp > 0 && (m & ((1 << exp) - 1))) raise(FE_INEXACT); return static_cast<T>((value & 0x8000) ? -i : i); } /// \} /// \name Mathematics /// \{ /// upper part of 64-bit multiplication. /// \tparam R rounding mode to use /// \param x first factor /// \param y second factor /// \return upper 32 bit of \a x * \a y template<std::float_round_style R> uint32 mulhi(uint32 x, uint32 y) { uint32 xy = (x >> 16) * (y & 0xFFFF), yx = (x & 0xFFFF) * (y >> 16), c = (xy & 0xFFFF) + (yx & 0xFFFF) + (((x & 0xFFFF) * (y & 0xFFFF)) >> 16); return (x >> 16) * (y >> 16) + (xy >> 16) + (yx >> 16) + (c >> 16) + ((R == std::round_to_nearest) ? ((c >> 15) & 1) : (R == std::round_toward_infinity) ? ((c & 0xFFFF) != 0) : 0); } /// 64-bit multiplication. /// \param x first factor /// \param y second factor /// \return upper 32 bit of \a x * \a y rounded to nearest inline uint32 multiply64(uint32 x, uint32 y) { #if HALF_ENABLE_CPP11_LONG_LONG return static_cast<uint32>((static_cast<unsigned long long>(x)*static_cast<unsigned long long>(y)+0x80000000)>>32); #else return mulhi<std::round_to_nearest>(x, y); #endif } /// 64-bit division. /// \param x upper 32 bit of dividend /// \param y divisor /// \param s variable to store sticky bit for rounding /// \return (\a x << 32) / \a y inline uint32 divide64(uint32 x, uint32 y, int &s) { #if HALF_ENABLE_CPP11_LONG_LONG unsigned long long xx = static_cast<unsigned long long>(x) << 32; return s = (xx%y!=0), static_cast<uint32>(xx/y); #else y >>= 1; uint32 rem = x, div = 0; for (unsigned int i = 0; i < 32; ++i) { div <<= 1; if (rem >= y) { rem -= y; div |= 1; } rem <<= 1; } return s = rem > 1, div; #endif } /// Half precision positive modulus. /// \tparam Q `true` to compute full quotient, `false` else /// \tparam R `true` to compute signed remainder, `false` for positive remainder /// \param x first operand as positive finite half-precision value /// \param y second operand as positive finite half-precision value /// \param quo adress to store quotient at, `nullptr` if \a Q `false` /// \return modulus of \a x / \a y template<bool Q, bool R> unsigned int mod(unsigned int x, unsigned int y, int *quo = NULL) { unsigned int q = 0; if (x > y) { int absx = x, absy = y, expx = 0, expy = 0; for (; absx < 0x400; absx <<= 1, --expx) ; for (; absy < 0x400; absy <<= 1, --expy) ; expx += absx >> 10; expy += absy >> 10; int mx = (absx & 0x3FF) | 0x400, my = (absy & 0x3FF) | 0x400; for (int d = expx - expy; d; --d) { if (!Q && mx == my) return 0; if (mx >= my) { mx -= my; q += Q; } mx <<= 1; q <<= static_cast<int>(Q); } if (!Q && mx == my) return 0; if (mx >= my) { mx -= my; ++q; } if (Q) { q &= (1 << (std::numeric_limits<int>::digits - 1)) - 1; if (!mx) return *quo = q, 0; } for (; mx < 0x400; mx <<= 1, --expy) ; x = (expy > 0) ? ((expy << 10) | (mx & 0x3FF)) : (mx >> (1 - expy)); } if (R) { unsigned int a, b; if (y < 0x800) { a = (x < 0x400) ? (x << 1) : (x + 0x400); b = y; } else { a = x; b = y - 0x400; } if (a > b || (a == b && (q & 1))) { int exp = (y >> 10) + (y <= 0x3FF), d = exp - (x >> 10) - (x <= 0x3FF); int m = (((y & 0x3FF) | ((y > 0x3FF) << 10)) << 1) - (((x & 0x3FF) | ((x > 0x3FF) << 10)) << (1 - d)); for (; m < 0x800 && exp > 1; m <<= 1, --exp) ; x = 0x8000 + ((exp - 1) << 10) + (m >> 1); q += Q; } } if (Q) *quo = q; return x; } /// Fixed point square root. /// \tparam F number of fractional bits /// \param r radicand in Q1.F fixed point format /// \param exp exponent /// \return square root as Q1.F/2 template<unsigned int F> uint32 sqrt(uint32 &r, int &exp) { int i = exp & 1; r <<= i; exp = (exp - i) / 2; uint32 m = 0; for (uint32 bit = static_cast<uint32>(1) << F; bit; bit >>= 2) { if (r < m + bit) m >>= 1; else { r -= m + bit; m = (m >> 1) + bit; } } return m; } /// Fixed point binary exponential. /// This uses the BKM algorithm in E-mode. /// \param m exponent in [0,1) as Q0.31 /// \param n number of iterations (at most 32) /// \return 2 ^ \a m as Q1.31 inline uint32 exp2(uint32 m, unsigned int n = 32) { static const uint32 logs[] = { 0x80000000, 0x4AE00D1D, 0x2934F098, 0x15C01A3A, 0x0B31FB7D, 0x05AEB4DD, 0x02DCF2D1, 0x016FE50B, 0x00B84E23, 0x005C3E10, 0x002E24CA, 0x001713D6, 0x000B8A47, 0x0005C53B, 0x0002E2A3, 0x00017153, 0x0000B8AA, 0x00005C55, 0x00002E2B, 0x00001715, 0x00000B8B, 0x000005C5, 0x000002E3, 0x00000171, 0x000000B9, 0x0000005C, 0x0000002E, 0x00000017, 0x0000000C, 0x00000006, 0x00000003, 0x00000001 }; if (!m) return 0x80000000; uint32 mx = 0x80000000, my = 0; for (unsigned int i = 1; i < n; ++i) { uint32 mz = my + logs[i]; if (mz <= m) { my = mz; mx += mx >> i; } } return mx; } /// Fixed point binary logarithm. /// This uses the BKM algorithm in L-mode. /// \param m mantissa in [1,2) as Q1.30 /// \param n number of iterations (at most 32) /// \return log2(\a m) as Q0.31 inline uint32 log2(uint32 m, unsigned int n = 32) { static const uint32 logs[] = { 0x80000000, 0x4AE00D1D, 0x2934F098, 0x15C01A3A, 0x0B31FB7D, 0x05AEB4DD, 0x02DCF2D1, 0x016FE50B, 0x00B84E23, 0x005C3E10, 0x002E24CA, 0x001713D6, 0x000B8A47, 0x0005C53B, 0x0002E2A3, 0x00017153, 0x0000B8AA, 0x00005C55, 0x00002E2B, 0x00001715, 0x00000B8B, 0x000005C5, 0x000002E3, 0x00000171, 0x000000B9, 0x0000005C, 0x0000002E, 0x00000017, 0x0000000C, 0x00000006, 0x00000003, 0x00000001 }; if (m == 0x40000000) return 0; uint32 mx = 0x40000000, my = 0; for (unsigned int i = 1; i < n; ++i) { uint32 mz = mx + (mx >> i); if (mz <= m) { mx = mz; my += logs[i]; } } return my; } /// Fixed point sine and cosine. /// This uses the CORDIC algorithm in rotation mode. /// \param mz angle in [-pi/2,pi/2] as Q1.30 /// \param n number of iterations (at most 31) /// \return sine and cosine of \a mz as Q1.30 inline std::pair<uint32, uint32> sincos(uint32 mz, unsigned int n = 31) { static const uint32 angles[] = { 0x3243F6A9, 0x1DAC6705, 0x0FADBAFD, 0x07F56EA7, 0x03FEAB77, 0x01FFD55C, 0x00FFFAAB, 0x007FFF55, 0x003FFFEB, 0x001FFFFD, 0x00100000, 0x00080000, 0x00040000, 0x00020000, 0x00010000, 0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400, 0x00000200, 0x00000100, 0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008, 0x00000004, 0x00000002, 0x00000001 }; uint32 mx = 0x26DD3B6A, my = 0; for (unsigned int i = 0; i < n; ++i) { uint32 sign = sign_mask(mz); uint32 tx = mx - (arithmetic_shift(my, i) ^ sign) + sign; uint32 ty = my + (arithmetic_shift(mx, i) ^ sign) - sign; mx = tx; my = ty; mz -= (angles[i] ^ sign) - sign; } return std::make_pair(my, mx); } /// Fixed point arc tangent. /// This uses the CORDIC algorithm in vectoring mode. /// \param my y coordinate as Q0.30 /// \param mx x coordinate as Q0.30 /// \param n number of iterations (at most 31) /// \return arc tangent of \a my / \a mx as Q1.30 inline uint32 atan2(uint32 my, uint32 mx, unsigned int n = 31) { static const uint32 angles[] = { 0x3243F6A9, 0x1DAC6705, 0x0FADBAFD, 0x07F56EA7, 0x03FEAB77, 0x01FFD55C, 0x00FFFAAB, 0x007FFF55, 0x003FFFEB, 0x001FFFFD, 0x00100000, 0x00080000, 0x00040000, 0x00020000, 0x00010000, 0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400, 0x00000200, 0x00000100, 0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008, 0x00000004, 0x00000002, 0x00000001 }; uint32 mz = 0; for (unsigned int i = 0; i < n; ++i) { uint32 sign = sign_mask(my); uint32 tx = mx + (arithmetic_shift(my, i) ^ sign) - sign; uint32 ty = my - (arithmetic_shift(mx, i) ^ sign) + sign; mx = tx; my = ty; mz += (angles[i] ^ sign) - sign; } return mz; } /// Reduce argument for trigonometric functions. /// \param abs half-precision floating-point value /// \param k value to take quarter period /// \return \a abs reduced to [-pi/4,pi/4] as Q0.30 inline uint32 angle_arg(unsigned int abs, int &k) { uint32 m = (abs & 0x3FF) | ((abs > 0x3FF) << 10); int exp = (abs >> 10) + (abs <= 0x3FF) - 15; if (abs < 0x3A48) return k = 0, m << (exp + 20); #if HALF_ENABLE_CPP11_LONG_LONG unsigned long long y = m * 0xA2F9836E4E442, mask = (1ULL<<(62-exp)) - 1, yi = (y+(mask>>1)) & ~mask, f = y - yi; uint32 sign = -static_cast<uint32>(f>>63); k = static_cast<int>(yi>>(62-exp)); return (multiply64(static_cast<uint32>((sign ? -f : f)>>(31-exp)), 0xC90FDAA2)^sign) - sign; #else uint32 yh = m * 0xA2F98 + mulhi<std::round_toward_zero>(m, 0x36E4E442), yl = (m * 0x36E4E442) & 0xFFFFFFFF; uint32 mask = (static_cast<uint32>(1) << (30 - exp)) - 1, yi = (yh + (mask >> 1)) & ~mask, sign = -static_cast<uint32>(yi > yh); k = static_cast<int>(yi >> (30 - exp)); uint32 fh = (yh ^ sign) + (yi ^ ~sign) - ~sign, fl = (yl ^ sign) - sign; return (multiply64( (exp > -1) ? (((fh << (1 + exp)) & 0xFFFFFFFF) | ((fl & 0xFFFFFFFF) >> (31 - exp))) : fh, 0xC90FDAA2) ^ sign) - sign; #endif } /// Get arguments for atan2 function. /// \param abs half-precision floating-point value /// \return \a abs and sqrt(1 - \a abs^2) as Q0.30 inline std::pair<uint32, uint32> atan2_args(unsigned int abs) { int exp = -15; for (; abs < 0x400; abs <<= 1, --exp) ; exp += abs >> 10; uint32 my = ((abs & 0x3FF) | 0x400) << 5, r = my * my; int rexp = 2 * exp; r = 0x40000000 - ((rexp > -31) ? ((r >> -rexp) | ((r & ((static_cast<uint32>(1) << -rexp) - 1)) != 0)) : 1); for (rexp = 0; r < 0x40000000; r <<= 1, --rexp) ; uint32 mx = sqrt<30>(r, rexp); int d = exp - rexp; if (d < 0) return std::make_pair( (d < -14) ? ((my >> (-d - 14)) + ((my >> (-d - 15)) & 1)) : (my << (14 + d)), (mx << 14) + (r << 13) / mx); if (d > 0) return std::make_pair(my << 14, (d > 14) ? ((mx >> (d - 14)) + ((mx >> (d - 15)) & 1)) : ((d == 14) ? mx : ((mx << (14 - d)) + (r << (13 - d)) / mx))); return std::make_pair(my << 13, (mx << 13) + (r << 12) / mx); } /// Get exponentials for hyperbolic computation /// \param abs half-precision floating-point value /// \param exp variable to take unbiased exponent of larger result /// \param n number of BKM iterations (at most 32) /// \return exp(abs) and exp(-\a abs) as Q1.31 with same exponent inline std::pair<uint32, uint32> hyperbolic_args(unsigned int abs, int &exp, unsigned int n = 32) { uint32 mx = detail::multiply64( static_cast<uint32>((abs & 0x3FF) + ((abs > 0x3FF) << 10)) << 21, 0xB8AA3B29), my; int e = (abs >> 10) + (abs <= 0x3FF); if (e < 14) { exp = 0; mx >>= 14 - e; } else { exp = mx >> (45 - e); mx = (mx << (e - 14)) & 0x7FFFFFFF; } mx = exp2(mx, n); int d = exp << 1, s; if (mx > 0x80000000) { my = divide64(0x80000000, mx, s); my |= s; ++d; } else my = mx; return std::make_pair(mx, (d < 31) ? ((my >> d) | ((my & ((static_cast<uint32>(1) << d) - 1)) != 0)) : 1); } /// Postprocessing for binary exponential. /// \tparam R rounding mode to use /// \param m fractional part of as Q0.31 /// \param exp absolute value of unbiased exponent /// \param esign sign of actual exponent /// \param sign sign bit of result /// \param n number of BKM iterations (at most 32) /// \return value converted to half-precision /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if value had to be rounded or \a I is `true` template<std::float_round_style R> unsigned int exp2_post(uint32 m, int exp, bool esign, unsigned int sign = 0, unsigned int n = 32) { if (esign) { exp = -exp - (m != 0); if (exp < -25) return underflow<R>(sign); else if (exp == -25) return rounded<R, false>(sign, 1, m != 0); } else if (exp > 15) return overflow<R>(sign); if (!m) return sign | (((exp += 15) > 0) ? (exp << 10) : check_underflow(0x200 >> -exp)); m = exp2(m, n); int s = 0; if (esign) m = divide64(0x80000000, m, s); return fixed2half<R, 31, false, false, true>(m, exp + 14, sign, s); } /// Postprocessing for binary logarithm. /// \tparam R rounding mode to use /// \tparam L logarithm for base transformation as Q1.31 /// \param m fractional part of logarithm as Q0.31 /// \param ilog signed integer part of logarithm /// \param exp biased exponent of result /// \param sign sign bit of result /// \return value base-transformed and converted to half-precision /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if no other exception occurred template<std::float_round_style R, uint32 L> unsigned int log2_post(uint32 m, int ilog, int exp, unsigned int sign = 0) { uint32 msign = sign_mask(ilog); m = (((static_cast<uint32>(ilog) << 27) + (m >> 4)) ^ msign) - msign; if (!m) return 0; for (; m < 0x80000000; m <<= 1, --exp) ; int i = m >= L, s; exp += i; m >>= 1 + i; sign ^= msign & 0x8000; if (exp < -11) return underflow<R>(sign); m = divide64(m, L, s); return fixed2half<R, 30, false, false, true>(m, exp, sign, 1); } /// Hypotenuse square root and postprocessing. /// \tparam R rounding mode to use /// \param r mantissa as Q2.30 /// \param exp biased exponent /// \return square root converted to half-precision /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if value had to be rounded template<std::float_round_style R> unsigned int hypot_post(uint32 r, int exp) { int i = r >> 31; if ((exp += i) > 46) return overflow<R>(); if (exp < -34) return underflow<R>(); r = (r >> i) | (r & i); uint32 m = sqrt<30>(r, exp += 15); return fixed2half<R, 15, false, false, false>(m, exp - 1, 0, r != 0); } /// Division and postprocessing for tangents. /// \tparam R rounding mode to use /// \param my dividend as Q1.31 /// \param mx divisor as Q1.31 /// \param exp biased exponent of result /// \param sign sign bit of result /// \return quotient converted to half-precision /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if no other exception occurred template<std::float_round_style R> unsigned int tangent_post(uint32 my, uint32 mx, int exp, unsigned int sign = 0) { int i = my >= mx, s; exp += i; if (exp > 29) return overflow<R>(sign); if (exp < -11) return underflow<R>(sign); uint32 m = divide64(my >> (i + 1), mx, s); return fixed2half<R, 30, false, false, true>(m, exp, sign, s); } /// Area function and postprocessing. /// This computes the value directly in Q2.30 using the representation `asinh|acosh(x) = log(x+sqrt(x^2+|-1))`. /// \tparam R rounding mode to use /// \tparam S `true` for asinh, `false` for acosh /// \param arg half-precision argument /// \return asinh|acosh(\a arg) converted to half-precision /// \exception FE_OVERFL
OW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if no other exception occurred template<std::float_round_style R, bool S> unsigned int area(unsigned int arg) { int abs = arg & 0x7FFF, expx = (abs >> 10) + (abs <= 0x3FF) - 15, expy = -15, ilog, i; uint32 mx = static_cast<uint32>((abs & 0x3FF) | ((abs > 0x3FF) << 10)) << 20, my, r; for (; abs < 0x400; abs <<= 1, --expy) ; expy += abs >> 10; r = ((abs & 0x3FF) | 0x400) << 5; r *= r; i = r >> 31; expy = 2 * expy + i; r >>= i; if (S) { if (expy < 0) { r = 0x40000000 + ((expy > -30) ? ((r >> -expy) | ((r & ((static_cast<uint32>(1) << -expy) - 1)) != 0)) : 1); expy = 0; } else { r += 0x40000000 >> expy; i = r >> 31; r = (r >> i) | (r & i); expy += i; } } else { r -= 0x40000000 >> expy; for (; r < 0x40000000; r <<= 1, --expy) ; } my = sqrt<30>(r, expy); my = (my << 15) + (r << 14) / my; if (S) { mx >>= expy - expx; ilog = expy; } else { my >>= expx - expy; ilog = expx; } my += mx; i = my >> 31; static const int G = S && (R == std::round_to_nearest); return log2_post<R, 0xB8AA3B2A>(log2(my >> i, 26 + S + G) + (G << 3), ilog + i, 17, arg & (static_cast<unsigned>(S) << 15)); } /// Class for 1.31 unsigned floating-point computation struct f31 { /// Constructor. /// \param mant mantissa as 1.31 /// \param e exponent HALF_CONSTEXPR f31(uint32 mant, int e) : m(mant), exp(e) { } /// Constructor. /// \param abs unsigned half-precision value f31(unsigned int abs) : exp(-15) { for (; abs < 0x400; abs <<= 1, --exp) ; m = static_cast<uint32>((abs & 0x3FF) | 0x400) << 21; exp += (abs >> 10); } /// Addition operator. /// \param a first operand /// \param b second operand /// \return \a a + \a b friend f31 operator+(f31 a, f31 b) { if (b.exp > a.exp) std::swap(a, b); int d = a.exp - b.exp; uint32 m = a.m + ((d < 32) ? (b.m >> d) : 0); int i = (m & 0xFFFFFFFF) < a.m; return f31(((m + i) >> i) | 0x80000000, a.exp + i); } /// Subtraction operator. /// \param a first operand /// \param b second operand /// \return \a a - \a b friend f31 operator-(f31 a, f31 b) { int d = a.exp - b.exp, exp = a.exp; uint32 m = a.m - ((d < 32) ? (b.m >> d) : 0); if (!m) return f31(0, -32); for (; m < 0x80000000; m <<= 1, --exp) ; return f31(m, exp); } /// Multiplication operator. /// \param a first operand /// \param b second operand /// \return \a a * \a b friend f31 operator*(f31 a, f31 b) { uint32 m = multiply64(a.m, b.m); int i = m >> 31; return f31(m << (1 - i), a.exp + b.exp + i); } /// Division operator. /// \param a first operand /// \param b second operand /// \return \a a / \a b friend f31 operator/(f31 a, f31 b) { int i = a.m >= b.m, s; uint32 m = divide64((a.m + i) >> i, b.m, s); return f31(m, a.exp - b.exp + i - 1); } uint32 m; ///< mantissa as 1.31. int exp; ///< exponent. }; /// Error function and postprocessing. /// This computes the value directly in Q1.31 using the approximations given /// [here](https://en.wikipedia.org/wiki/Error_function#Approximation_with_elementary_functions). /// \tparam R rounding mode to use /// \tparam C `true` for comlementary error function, `false` else /// \param arg half-precision function argument /// \return approximated value of error function in half-precision /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if no other exception occurred template<std::float_round_style R, bool C> unsigned int erf(unsigned int arg) { unsigned int abs = arg & 0x7FFF, sign = arg & 0x8000; f31 x(abs), x2 = x * x * f31(0xB8AA3B29, 0), t = f31(0x80000000, 0) / (f31(0x80000000, 0) + f31(0xA7BA054A, -2) * x), t2 = t * t; f31 e = ((f31(0x87DC2213, 0) * t2 + f31(0xB5F0E2AE, 0)) * t2 + f31(0x82790637, -2) - (f31(0xBA00E2B8, 0) * t2 + f31(0x91A98E62, -2)) * t) * t / ((x2.exp < 0) ? f31(exp2((x2.exp > -32) ? (x2.m >> -x2.exp) : 0, 30), 0) : f31(exp2((x2.m << x2.exp) & 0x7FFFFFFF, 22), x2.m >> (31 - x2.exp))); return (!C || sign) ? fixed2half<R, 31, false, true, true>( 0x80000000 - (e.m >> (C - e.exp)), 14 + C, sign & (C - 1U)) : (e.exp < -25) ? underflow<R>() : fixed2half<R, 30, false, false, true>(e.m >> 1, e.exp + 14, 0, e.m & 1); } /// Gamma function and postprocessing. /// This approximates the value of either the gamma function or its logarithm directly in Q1.31. /// \tparam R rounding mode to use /// \tparam L `true` for lograithm of gamma function, `false` for gamma function /// \param arg half-precision floating-point value /// \return lgamma/tgamma(\a arg) in half-precision /// \exception FE_OVERFLOW on overflows /// \exception FE_UNDERFLOW on underflows /// \exception FE_INEXACT if \a arg is not a positive integer template<std::float_round_style R, bool L> unsigned int gamma( unsigned int arg) { /* static const double p[] ={ 2.50662827563479526904, 225.525584619175212544, -268.295973841304927459, 80.9030806934622512966, -5.00757863970517583837, 0.0114684895434781459556 }; double t = arg + 4.65, s = p[0]; for(unsigned int i=0; i<5; ++i) s += p[i+1] / (arg+i); return std::log(s) + (arg-0.5)*std::log(t) - t; */static const f31 pi(0xC90FDAA2, 1), lbe(0xB8AA3B29, 0); unsigned int abs = arg & 0x7FFF, sign = arg & 0x8000; bool bsign = sign != 0; f31 z(abs), x = sign ? (z + f31(0x80000000, 0)) : z, t = x + f31(0x94CCCCCD, 2), s = f31(0xA06C9901, 1) + f31(0xBBE654E2, -7) / (x + f31(0x80000000, 2)) + f31(0xA1CE6098, 6) / (x + f31(0x80000000, 1)) + f31(0xE1868CB7, 7) / x - f31(0x8625E279, 8) / (x + f31(0x80000000, 0)) - f31(0xA03E158F, 2) / (x + f31(0xC0000000, 1)); int i = (s.exp >= 2) + (s.exp >= 4) + (s.exp >= 8) + (s.exp >= 16); s = f31( (static_cast<uint32>(s.exp) << (31 - i)) + (log2(s.m >> 1, 28) >> i), i) / lbe; if (x.exp != -1 || x.m != 0x80000000) { i = (t.exp >= 2) + (t.exp >= 4) + (t.exp >= 8); f31 l = f31( (static_cast<uint32>(t.exp) << (31 - i)) + (log2(t.m >> 1, 30) >> i), i) / lbe; s = (x.exp < -1) ? (s - (f31(0x80000000, -1) - x) * l) : (s + (x - f31(0x80000000, -1)) * l); } s = x.exp ? (s - t) : (t - s); if (bsign) { if (z.exp >= 0) { sign &= (L | ((z.m >> (31 - z.exp)) & 1)) - 1; for (z = f31((z.m << (1 + z.exp)) & 0xFFFFFFFF, -1); z.m < 0x80000000; z.m <<= 1, --z.exp) ; } if (z.exp == -1) z = f31(0x80000000, 0) - z; if (z.exp < -1) { z = z * pi; z.m = sincos(z.m >> (1 - z.exp), 30).first; for (z.exp = 1; z.m < 0x80000000; z.m <<= 1, --z.exp) ; } else z = f31(0x80000000, 0); } if (L) { if (bsign) { f31 l(0x92868247, 0); if (z.exp < 0) { uint32 m = log2((z.m + 1) >> 1, 27); z = f31(-((static_cast<uint32>(z.exp) << 26) + (m >> 5)), 5); for (; z.m < 0x80000000; z.m <<= 1, --z.exp) ; l = l + z / lbe; } sign = static_cast<unsigned>(x.exp && (l.exp < s.exp || (l.exp == s.exp && l.m < s.m))) << 15; s = sign ? (s - l) : x.exp ? (l - s) : (l + s); } else { sign = static_cast<unsigned>(x.exp == 0) << 15; if (s.exp < -24) return underflow<R>(sign); if (s.exp > 15) return overflow<R>(sign); } } else { s = s * lbe; uint32 m; if (s.exp < 0) { m = s.m >> -s.exp; s.exp = 0; } else { m = (s.m << s.exp) & 0x7FFFFFFF; s.exp = (s.m >> (31 - s.exp)); } s.m = exp2(m, 27); if (!x.exp) s = f31(0x80000000, 0) / s; if (bsign) { if (z.exp < 0) s = s * z; s = pi / s; if (s.exp < -24) return underflow<R>(sign); } else if (z.exp > 0 && !(z.m & ((1 << (31 - z.exp)) - 1))) return ((s.exp + 14) << 10) + (s.m >> 21); if (s.exp > 15) return overflow<R>(sign); } return fixed2half<R, 31, false, false, true>(s.m, s.exp + 14, sign); } /// \} template<typename, typename, std::float_round_style> struct half_caster; } /// Half-precision floating-point type. /// This class implements an IEEE-conformant half-precision floating-point type with the usual arithmetic /// operators and conversions. It is implicitly convertible to single-precision floating-point, which makes artihmetic /// expressions and functions with mixed-type operands to be of the most precise operand type. /// /// According to the C++98/03 definition, the half type is not a POD type. But according to C++11's less strict and /// extended definitions it is both a standard layout type and a trivially copyable type (even if not a POD type), which /// means it can be standard-conformantly copied using raw binary copies. But in this context some more words about the /// actual size of the type. Although the half is representing an IEEE 16-bit type, it does not neccessarily have to be of /// exactly 16-bits size. But on any reasonable implementation the actual binary representation of this type will most /// probably not ivolve any additional "magic" or padding beyond the simple binary representation of the underlying 16-bit /// IEEE number, even if not strictly guaranteed by the standard. But even then it only has an actual size of 16 bits if /// your C++ implementation supports an unsigned integer type of exactly 16 bits width. But this should be the case on /// nearly any reasonable platform. /// /// So if your C++ implementation is not totally exotic or imposes special alignment requirements, it is a reasonable /// assumption that the data of a half is just comprised of the 2 bytes of the underlying IEEE representation. class half { public: /// \name Construction and assignment /// \{ /// Default constructor. /// This initializes the half to 0. Although this does not match the builtin types' default-initialization semantics /// and may be less efficient than no initialization, it is needed to provide proper value-initialization semantics. HALF_CONSTEXPR half() HALF_NOEXCEPT : data_() {} /// Conversion constructor. /// \param rhs float to convert /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding explicit half(float rhs) : data_(static_cast<detail::uint16>(detail::float2half<round_style>(rhs))) {} /// Conversion to single-precision. /// \return single precision value representing expression value operator float() const {return detail::half2float<float>(data_);} /// Assignment operator. /// \param rhs single-precision value to copy from /// \return reference to this half /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding half& operator=(float rhs) {data_ = static_cast<detail::uint16>(detail::float2half<round_style>(rhs)); return *this;} /// \} /// \name Arithmetic updates /// \{ /// Arithmetic assignment. /// \tparam T type of concrete half expression /// \param rhs half expression to add /// \return reference to this half /// \exception FE_... according to operator+(half,half) half& operator+=(half rhs) {return *this = *this + rhs;} /// Arithmetic assignment. /// \tparam T type of concrete half expression /// \param rhs half expression to subtract /// \return reference to this half /// \exception FE_... according to operator-(half,half) half& operator-=(half rhs) {return *this = *this - rhs;} /// Arithmetic assignment. /// \tparam T type of concrete half expression /// \param rhs half expression to multiply with /// \return reference to this half /// \exception FE_... according to operator*(half,half) half& operator*=(half rhs) {return *this = *this * rhs;} /// Arithmetic assignment. /// \tparam T type of concrete half expression /// \param rhs half expression to divide by /// \return reference to this half /// \exception FE_... according to operator/(half,half) half& operator/=(half rhs) {return *this = *this / rhs;} /// Arithmetic assignment. /// \param rhs single-precision value to add /// \return reference to this half /// \exception FE_... according to operator=() half& operator+=(float rhs) {return *this = *this + rhs;} /// Arithmetic assignment. /// \param rhs single-precision value to subtract /// \return reference to this half /// \exception FE_... according to operator=() half& operator-=(float rhs) {return *this = *this - rhs;} /// Arithmetic assignment. /// \param rhs single-precision value to multiply with /// \return reference to this half /// \exception FE_... according to operator=() half& operator*=(float rhs) {return *this = *this * rhs;} /// Arithmetic assignment. /// \param rhs single-precision value to divide by /// \return reference to this half /// \exception FE_... according to operator=() half& operator/=(float rhs) {return *this = *this / rhs;} /// \} /// \name Increment and decrement /// \{ /// Prefix increment. /// \return incremented half value /// \exception FE_... according to operator+(half,half) half& operator++() {return *this = *this + half(detail::binary, 0x3C00);} /// Prefix decrement. /// \return decremented half value /// \exception FE_... according to operator-(half,half) half& operator--() {return *this = *this + half(detail::binary, 0xBC00);} /// Postfix increment. /// \return non-incremented half value /// \exception FE_... according to operator+(half,half) half operator++(int) {half out(*this); ++*this; return out;} /// Postfix decrement. /// \return non-decremented half value /// \exception FE_... according to operator-(half,half) half operator--(int) {half out(*this); --*this; return out;} /// \} /// Integration (rough) into SystemC inline friend void sc_trace(sc_trace_file *tf, const half &h, const std::string &name) { sc_trace(tf, h.data_, name); } /// Constructor. RMM: moved from private to public /// \param bits binary representation to set half to HALF_CONSTEXPR half(detail::binary_t, unsigned int bits) HALF_NOEXCEPT : data_(static_cast<detail::uint16>(bits)) {} /// RMML: added this for getting the bit word uint16_t bin_word() {return (uint16_t) data_;} private: /// Rounding mode to use static const std::float_round_style round_style = (std::float_round_style)(HALF_ROUND_STYLE); // /// Constructor. // /// \param bits binary representation to set half to // HALF_CONSTEXPR half(detail::binary_t, unsigned int bits) HALF_NOEXCEPT : data_(static_cast<detail::uint16>(bits)) {} /// Internal binary representation detail::uint16 data_; #ifndef HALF_DOXYGEN_ONLY friend HALF_CONSTEXPR_NOERR bool operator==(half, half); friend HALF_CONSTEXPR_NOERR bool operator!=(half, half); friend HALF_CONSTEXPR_NOERR bool operator<(half, half); friend HALF_CONSTEXPR_NOERR bool operator>(half, half); friend HALF_CONSTEXPR_NOERR bool operator<=(half, half); friend HALF_CONSTEXPR_NOERR bool operator>=(half, half); friend HALF_CONSTEXPR half operator-(half); friend half operator+(half, half); friend half operator-(half, half); friend half operator*(half, half); friend half operator/(half, half); template<typename charT,typename traits> friend std::basic_ostream<charT,traits>& operator<<(std::basic_ostream<charT,traits>&, half); template<typename charT,typename traits> friend std::basic_istream<charT,traits>& operator>>(std::basic_istream<charT,traits>&, half&); friend HALF_CONSTEXPR half fabs(half); friend half fmod(half, half); friend half remainder(half, half); friend half remquo(half, half, int*); friend half fma(half, half, half); friend HALF_CONSTEXPR_NOERR half fmax(half, half); friend HALF_CONSTEXPR_NOERR half fmin(half, half); friend half fdim(half, half); friend half nanh(const char*); friend half exp(half); friend half exp2(half); friend half expm1(half); friend half log(half); friend half log10(half); friend half log2(half); friend half log1p(half); friend half sqrt(half); friend half rsqrt(half); friend half cbrt(half); friend half hypot(half, half); friend half hypot(half, half, half); friend half pow(half, half); friend void sincos(half, half*, half*); friend half sin(half); friend half cos(half); friend half tan(half); friend half asin(half); friend half acos(half); friend half atan(half); friend half atan2(half, half); friend half sinh(half); friend half cosh(half); friend half tanh(half); friend half asinh(half); friend half acosh(half); friend half atanh(half); friend half erf(half); friend half erfc(half); friend half lgamma(half); friend half tgamma(half); friend half ceil(half); friend half floor(half); friend half trunc(half); friend half round(half); friend long lround(half); friend half rint(half); friend long lrint(half); friend half nearbyint(half); #ifdef HALF_ENABLE_CPP11_LONG_LONG friend long long llround(half); friend long long llrint(half); #endif friend half frexp(half, int*); friend half scalbln(half, long); friend half modf(half, half*); friend int ilogb(half); friend half logb(half); friend half nextafter(half, half); friend half nexttoward(half, long double); friend HALF_CONSTEXPR half copysign(half, half); friend HALF_CONSTEXPR int fpclassify(half); friend HALF_CONSTEXPR bool isfinite(half); friend HALF_CONSTEXPR bool isinf(half); friend HALF_CONSTEXPR bool isnan(half); friend HALF_CONSTEXPR bool isnormal(half); friend HALF_CONSTEXPR bool signbit(half); friend HALF_CONSTEXPR bool isgreater(half, half); friend HALF_CONSTEXPR bool isgreaterequal(half, half); friend HALF_CONSTEXPR bool isless(half, half); friend HALF_CONSTEXPR bool islessequal(half, half); friend HALF_CONSTEXPR bool islessgreater(half, half); template<typename,typename,std::float_round_style> friend struct detail::half_caster; friend class std::numeric_limits<half>; #if HALF_ENABLE_CPP11_HASH friend struct std::hash<half>; #endif #if HALF_ENABLE_CPP11_USER_LITERALS friend half literal::operator "" _h(long double); #endif #endif }; #if HALF_ENABLE_CPP11_USER_LITERALS namesp
ace literal { /// Half literal. /// While this returns a properly rounded half-precision value, half literals can unfortunately not be constant /// expressions due to rather involved conversions. So don't expect this to be a literal literal without involving /// conversion operations at runtime. It is a convenience feature, not a performance optimization. /// \param value literal value /// \return half with of given value (possibly rounded) /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half operator "" _h(long double value) {return half(detail::binary, detail::float2half<half::round_style>(value));} } #endif namespace detail { /// Helper class for half casts. /// This class template has to be specialized for all valid cast arguments to define an appropriate static /// `cast` member function and a corresponding `type` member denoting its return type. /// \tparam T destination type /// \tparam U source type /// \tparam R rounding mode to use template<typename T, typename U, std::float_round_style R = (std::float_round_style) (HALF_ROUND_STYLE)> struct half_caster { }; template<typename U, std::float_round_style R> struct half_caster<half, U, R> { #if HALF_ENABLE_CPP11_STATIC_ASSERT && HALF_ENABLE_CPP11_TYPE_TRAITS static_assert(std::is_arithmetic<U>::value, "half_cast from non-arithmetic type unsupported"); #endif static half cast(U arg) { return cast_impl(arg, is_float<U>()); } ; private: static half cast_impl(U arg, true_type) { return half(binary, float2half<R>(arg)); } static half cast_impl(U arg, false_type) { return half(binary, int2half<R>(arg)); } }; template<typename T, std::float_round_style R> struct half_caster<T, half, R> { #if HALF_ENABLE_CPP11_STATIC_ASSERT && HALF_ENABLE_CPP11_TYPE_TRAITS static_assert(std::is_arithmetic<T>::value, "half_cast to non-arithmetic type unsupported"); #endif static T cast(half arg) { return cast_impl(arg, is_float<T>()); } private: static T cast_impl(half arg, true_type) { return half2float<T>(arg.data_); } static T cast_impl(half arg, false_type) { return half2int<R, true, true, T>(arg.data_); } }; template<std::float_round_style R> struct half_caster<half, half, R> { static half cast(half arg) { return arg; } }; } } /// Extensions to the C++ standard library. namespace std { /// Numeric limits for half-precision floats. /// **See also:** Documentation for [std::numeric_limits](https://en.cppreference.com/w/cpp/types/numeric_limits) template<> class numeric_limits<half_float::half> { public: /// Is template specialization. static HALF_CONSTEXPR_CONST bool is_specialized = true; /// Supports signed values. static HALF_CONSTEXPR_CONST bool is_signed = true; /// Is not an integer type. static HALF_CONSTEXPR_CONST bool is_integer = false; /// Is not exact. static HALF_CONSTEXPR_CONST bool is_exact = false; /// Doesn't provide modulo arithmetic. static HALF_CONSTEXPR_CONST bool is_modulo = false; /// Has a finite set of values. static HALF_CONSTEXPR_CONST bool is_bounded = true; /// IEEE conformant. static HALF_CONSTEXPR_CONST bool is_iec559 = true; /// Supports infinity. static HALF_CONSTEXPR_CONST bool has_infinity = true; /// Supports quiet NaNs. static HALF_CONSTEXPR_CONST bool has_quiet_NaN = true; /// Supports signaling NaNs. static HALF_CONSTEXPR_CONST bool has_signaling_NaN = true; /// Supports subnormal values. static HALF_CONSTEXPR_CONST float_denorm_style has_denorm = denorm_present; /// Supports no denormalization detection. static HALF_CONSTEXPR_CONST bool has_denorm_loss = false; #if HALF_ERRHANDLING_THROWS static HALF_CONSTEXPR_CONST bool traps = true; #else /// Traps only if [HALF_ERRHANDLING_THROW_...](\ref HALF_ERRHANDLING_THROW_INVALID) is acitvated. static HALF_CONSTEXPR_CONST bool traps = false; #endif /// Does not support no pre-rounding underflow detection. static HALF_CONSTEXPR_CONST bool tinyness_before = false; /// Rounding mode. static HALF_CONSTEXPR_CONST float_round_style round_style = half_float::half::round_style; /// Significant digits. static HALF_CONSTEXPR_CONST int digits = 11; /// Significant decimal digits. static HALF_CONSTEXPR_CONST int digits10 = 3; /// Required decimal digits to represent all possible values. static HALF_CONSTEXPR_CONST int max_digits10 = 5; /// Number base. static HALF_CONSTEXPR_CONST int radix = 2; /// One more than smallest exponent. static HALF_CONSTEXPR_CONST int min_exponent = -13; /// Smallest normalized representable power of 10. static HALF_CONSTEXPR_CONST int min_exponent10 = -4; /// One more than largest exponent static HALF_CONSTEXPR_CONST int max_exponent = 16; /// Largest finitely representable power of 10. static HALF_CONSTEXPR_CONST int max_exponent10 = 4; /// Smallest positive normal value. static HALF_CONSTEXPR half_float::half min() HALF_NOTHROW { return half_float::half(half_float::detail::binary, 0x0400); } /// Smallest finite value. static HALF_CONSTEXPR half_float::half lowest() HALF_NOTHROW { return half_float::half(half_float::detail::binary, 0xFBFF); } /// Largest finite value. static HALF_CONSTEXPR half_float::half max() HALF_NOTHROW { return half_float::half(half_float::detail::binary, 0x7BFF); } /// Difference between 1 and next representable value. static HALF_CONSTEXPR half_float::half epsilon() HALF_NOTHROW { return half_float::half(half_float::detail::binary, 0x1400); } /// Maximum rounding error in ULP (units in the last place). static HALF_CONSTEXPR half_float::half round_error() HALF_NOTHROW { return half_float::half(half_float::detail::binary, (round_style == std::round_to_nearest) ? 0x3800 : 0x3C00); } /// Positive infinity. static HALF_CONSTEXPR half_float::half infinity() HALF_NOTHROW { return half_float::half(half_float::detail::binary, 0x7C00); } /// Quiet NaN. static HALF_CONSTEXPR half_float::half quiet_NaN() HALF_NOTHROW { return half_float::half(half_float::detail::binary, 0x7FFF); } /// Signaling NaN. static HALF_CONSTEXPR half_float::half signaling_NaN() HALF_NOTHROW { return half_float::half(half_float::detail::binary, 0x7DFF); } /// Smallest positive subnormal value. static HALF_CONSTEXPR half_float::half denorm_min() HALF_NOTHROW { return half_float::half(half_float::detail::binary, 0x0001); } }; #if HALF_ENABLE_CPP11_HASH /// Hash function for half-precision floats. /// This is only defined if C++11 `std::hash` is supported and enabled. /// /// **See also:** Documentation for [std::hash](https://en.cppreference.com/w/cpp/utility/hash) template<> struct hash<half_float::half> { /// Type of function argument. typedef half_float::half argument_type; /// Function return type. typedef size_t result_type; /// Compute hash function. /// \param arg half to hash /// \return hash value result_type operator()(argument_type arg) const { return hash<half_float::detail::uint16>()(arg.data_&-static_cast<unsigned>(arg.data_!=0x8000)); } }; #endif } namespace half_float { /// \anchor compop /// \name Comparison operators /// \{ /// Comparison for equality. /// \param x first operand /// \param y second operand /// \retval true if operands equal /// \retval false else /// \exception FE_INVALID if \a x or \a y is NaN inline HALF_CONSTEXPR_NOERR bool operator==(half x, half y) { return !detail::compsignal(x.data_, y.data_) && (x.data_ == y.data_ || !((x.data_ | y.data_) & 0x7FFF)); } /// Comparison for inequality. /// \param x first operand /// \param y second operand /// \retval true if operands not equal /// \retval false else /// \exception FE_INVALID if \a x or \a y is NaN inline HALF_CONSTEXPR_NOERR bool operator!=(half x, half y) { return detail::compsignal(x.data_, y.data_) || (x.data_ != y.data_ && ((x.data_ | y.data_) & 0x7FFF)); } /// Comparison for less than. /// \param x first operand /// \param y second operand /// \retval true if \a x less than \a y /// \retval false else /// \exception FE_INVALID if \a x or \a y is NaN inline HALF_CONSTEXPR_NOERR bool operator<(half x, half y) { return !detail::compsignal(x.data_, y.data_) && ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) < ((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)); } /// Comparison for greater than. /// \param x first operand /// \param y second operand /// \retval true if \a x greater than \a y /// \retval false else /// \exception FE_INVALID if \a x or \a y is NaN inline HALF_CONSTEXPR_NOERR bool operator>(half x, half y) { return !detail::compsignal(x.data_, y.data_) && ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) > ((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)); } /// Comparison for less equal. /// \param x first operand /// \param y second operand /// \retval true if \a x less equal \a y /// \retval false else /// \exception FE_INVALID if \a x or \a y is NaN inline HALF_CONSTEXPR_NOERR bool operator<=(half x, half y) { return !detail::compsignal(x.data_, y.data_) && ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) <= ((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)); } /// Comparison for greater equal. /// \param x first operand /// \param y second operand /// \retval true if \a x greater equal \a y /// \retval false else /// \exception FE_INVALID if \a x or \a y is NaN inline HALF_CONSTEXPR_NOERR bool operator>=(half x, half y) { return !detail::compsignal(x.data_, y.data_) && ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) >= ((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)); } /// \} /// \anchor arithmetics /// \name Arithmetic operators /// \{ /// Identity. /// \param arg operand /// \return unchanged operand inline HALF_CONSTEXPR half operator+(half arg) { return arg; } /// Negation. /// \param arg operand /// \return negated operand inline HALF_CONSTEXPR half operator-(half arg) { return half(detail::binary, arg.data_ ^ 0x8000); } /// Addition. /// This operation is exact to rounding for all rounding modes. /// \param x left operand /// \param y right operand /// \return sum of half expressions /// \exception FE_INVALID if \a x and \a y are infinities with different signs or signaling NaNs /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half operator+(half x, half y) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(detail::half2float<detail::internal_t>(x.data_)+detail::half2float<detail::internal_t>(y.data_))); #else int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF; bool sub = ((x.data_ ^ y.data_) & 0x8000) != 0; if (absx >= 0x7C00 || absy >= 0x7C00) return half(detail::binary, (absx > 0x7C00 || absy > 0x7C00) ? detail::signal(x.data_, y.data_) : (absy != 0x7C00) ? x.data_ : (sub && absx == 0x7C00) ? detail::invalid() : y.data_); if (!absx) return absy ? y : half(detail::binary, (half::round_style == std::round_toward_neg_infinity) ? (x.data_ | y.data_) : (x.data_ & y.data_)); if (!absy) return x; unsigned int sign = ((sub && absy > absx) ? y.data_ : x.data_) & 0x8000; if (absy > absx) std::swap(absx, absy); int exp = (absx >> 10) + (absx <= 0x3FF), d = exp - (absy >> 10) - (absy <= 0x3FF), mx = ((absx & 0x3FF) | ((absx > 0x3FF) << 10)) << 3, my; if (d < 13) { my = ((absy & 0x3FF) | ((absy > 0x3FF) << 10)) << 3; my = (my >> d) | ((my & ((1 << d) - 1)) != 0); } else my = 1; if (sub) { if (!(mx -= my)) return half(detail::binary, static_cast<unsigned>(half::round_style == std::round_toward_neg_infinity) << 15); for (; mx < 0x2000 && exp > 1; mx <<= 1, --exp) ; } else { mx += my; int i = mx >> 14; if ((exp += i) > 30) return half(detail::binary, detail::overflow<half::round_style>(sign)); mx = (mx >> i) | (mx & i); } return half(detail::binary, detail::rounded<half::round_style, false>( sign + ((exp - 1) << 10) + (mx >> 3), (mx >> 2) & 1, (mx & 0x3) != 0)); #endif } /// Subtraction. /// This operation is exact to rounding for all rounding modes. /// \param x left operand /// \param y right operand /// \return difference of half expressions /// \exception FE_INVALID if \a x and \a y are infinities with equal signs or signaling NaNs /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half operator-(half x, half y) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(detail::half2float<detail::internal_t>(x.data_)-detail::half2float<detail::internal_t>(y.data_))); #else return x + -y; #endif } /// Multiplication. /// This operation is exact to rounding for all rounding modes. /// \param x left operand /// \param y right operand /// \return product of half expressions /// \exception FE_INVALID if multiplying 0 with infinity or if \a x or \a y is signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half operator*(half x, half y) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(detail::half2float<detail::internal_t>(x.data_)*detail::half2float<detail::internal_t>(y.data_))); #else int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, exp = -16; unsigned int sign = (x.data_ ^ y.data_) & 0x8000; if (absx >= 0x7C00 || absy >= 0x7C00) return half(detail::binary, (absx > 0x7C00 || absy > 0x7C00) ? detail::signal(x.data_, y.data_) : ((absx == 0x7C00 && !absy) || (absy == 0x7C00 && !absx)) ? detail::invalid() : (sign | 0x7C00)); if (!absx || !absy) return half(detail::binary, sign); for (; absx < 0x400; absx <<= 1, --exp) ; for (; absy < 0x400; absy <<= 1, --exp) ; detail::uint32 m = static_cast<detail::uint32>((absx & 0x3FF) | 0x400) * static_cast<detail::uint32>((absy & 0x3FF) | 0x400); int i = m >> 21, s = m & i; exp += (absx >> 10) + (absy >> 10) + i; if (exp > 29) return half(detail::binary, detail::overflow<half::round_style>(sign)); else if (exp < -11) return half(detail::binary, detail::underflow<half::round_style>(sign)); return half(detail::binary, detail::fixed2half<half::round_style, 20, false, false, false>( m >> i, exp, sign, s)); #endif } /// Division. /// This operation is exact to rounding for all rounding modes. /// \param x left operand /// \param y right operand /// \return quotient of half expressions /// \exception FE_INVALID if dividing 0s or infinities with each other or if \a x or \a y is signaling NaN /// \exception FE_DIVBYZERO if dividing finite value by 0 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half operator/(half x, half y) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(detail::half2float<detail::internal_t>(x.data_)/detail::half2float<detail::internal_t>(y.data_))); #else int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, exp = 14; unsigned int sign = (x.data_ ^ y.data_) & 0x8000; if (absx >= 0x7C00 || absy >= 0x7C00) return half(detail::binary, (absx > 0x7C00 || absy > 0x7C00) ? detail::signal(x.data_, y.data_) : (absx == absy) ? detail::invalid() : (sign | ((absx == 0x7C00) ? 0x7C00 : 0))); if (!absx) return half(detail::binary, absy ? sign : detail::invalid()); if (!absy) return half(detail::binary, detail::pole(sign)); for (; absx < 0x400; absx <<= 1, --exp) ; for (; absy < 0x400; absy <<= 1, ++exp) ; detail::uint32 mx = (absx & 0x3FF) | 0x400, my = (absy & 0x3FF) | 0x400; int i = mx < my; exp += (absx >> 10) - (absy >> 10) - i; if (exp > 29) return half(detail::binary, detail::overflow<half::round_style>(sign)); else if (exp < -11) return half(detail::binary, detail::underflow<half::round_style>(sign)); mx <<= 12 + i; my <<= 1; return half(detail::binary, detail::fixed2half<half::round_style, 11, false, false, false>( mx / my, exp, sign, mx % my != 0)); #endif } /// \} /// \anchor streaming /// \name Input and output /// \{ /// Output operator. /// This uses the built-in functionality for streaming out floating-point numbers. /// \param out output stream to write into /// \param arg half expression to write /// \return reference to output stream template<typename charT, typename traits> std::basic_ostream<charT, traits>& operator<<( std::basic_ostream<charT, traits> &out, half arg) { #ifdef HALF_ARITHMETIC_TYPE return out << detail::half2float<detail::internal_t>(arg.data_); #else return out << detail::half2float<float>(arg.data_); #endif } /// Input operator. /// This uses the built-in functionality for streaming in floating-point numbers, specifically double precision floating /// point numbers (unless overridden with [HALF_ARITHMETIC_TYPE](\ref HALF_ARITHMETIC_TYPE)). So the input string is first /// rounded to double precision using the underlying platform's current floating-point rounding mode before being rounded /// to half-precision using the library's half-precision rounding mode. /// \param in input stream to read from /// \param arg half to read into /// \return reference to input stream /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding template<typename charT, typename traits> std::basic_istream<charT, traits>& operator>>( std::basic_istream<charT, traits> &in, half &arg) { #ifdef HALF_ARITHMETIC_TYPE detail::internal_t f; #else double f; #endif if (in >> f) arg.data_ = detail::float2half<half::round_style>(f); return in; } /// \} /// \anchor basic /// \name Basic mathematical operations /// \{ /// Absolute value. /// **See also:** Documentation for [std::fabs](https://en.cppreference.com/w/cpp/numeric/math/fabs). /// \param arg operand /// \return absolute value of \a arg inline HALF_CONSTEXPR half fabs(half arg) { return half(detail::binary, arg.data_ & 0x7FFF); } /// Absolute value. /// **See also:** Documentation for [std::abs](https://en.cppreference.com/w/cpp/numeric/math/fabs). /// \param arg operand /// \return absolute value of \a arg inline HALF_CONSTEXPR half abs(half arg) { return fabs(arg); } /// Remainder of division. /// **See also:** Documentation for [std::fmod](https://en.cppreference.com/w/cpp/numeric/math/fmod). /// \param x first operand /// \param y
second operand /// \return remainder of floating-point division. /// \exception FE_INVALID if \a x is infinite or \a y is 0 or if \a x or \a y is signaling NaN inline half fmod(half x, half y) { unsigned int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, sign = x.data_ & 0x8000; if (absx >= 0x7C00 || absy >= 0x7C00) return half(detail::binary, (absx > 0x7C00 || absy > 0x7C00) ? detail::signal(x.data_, y.data_) : (absx == 0x7C00) ? detail::invalid() : x.data_); if (!absy) return half(detail::binary, detail::invalid()); if (!absx) return x; if (absx == absy) return half(detail::binary, sign); return half(detail::binary, sign | detail::mod<false, false>(absx, absy)); } /// Remainder of division. /// **See also:** Documentation for [std::remainder](https://en.cppreference.com/w/cpp/numeric/math/remainder). /// \param x first operand /// \param y second operand /// \return remainder of floating-point division. /// \exception FE_INVALID if \a x is infinite or \a y is 0 or if \a x or \a y is signaling NaN inline half remainder(half x, half y) { unsigned int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, sign = x.data_ & 0x8000; if (absx >= 0x7C00 || absy >= 0x7C00) return half(detail::binary, (absx > 0x7C00 || absy > 0x7C00) ? detail::signal(x.data_, y.data_) : (absx == 0x7C00) ? detail::invalid() : x.data_); if (!absy) return half(detail::binary, detail::invalid()); if (absx == absy) return half(detail::binary, sign); return half(detail::binary, sign ^ detail::mod<false, true>(absx, absy)); } /// Remainder of division. /// **See also:** Documentation for [std::remquo](https://en.cppreference.com/w/cpp/numeric/math/remquo). /// \param x first operand /// \param y second operand /// \param quo address to store some bits of quotient at /// \return remainder of floating-point division. /// \exception FE_INVALID if \a x is infinite or \a y is 0 or if \a x or \a y is signaling NaN inline half remquo(half x, half y, int *quo) { unsigned int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, value = x.data_ & 0x8000; if (absx >= 0x7C00 || absy >= 0x7C00) return half(detail::binary, (absx > 0x7C00 || absy > 0x7C00) ? detail::signal(x.data_, y.data_) : (absx == 0x7C00) ? detail::invalid() : (*quo = 0, x.data_)); if (!absy) return half(detail::binary, detail::invalid()); bool qsign = ((value ^ y.data_) & 0x8000) != 0; int q = 1; if (absx != absy) value ^= detail::mod<true, true>(absx, absy, &q); return *quo = qsign ? -q : q, half(detail::binary, value); } /// Fused multiply add. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::fma](https://en.cppreference.com/w/cpp/numeric/math/fma). /// \param x first operand /// \param y second operand /// \param z third operand /// \return ( \a x * \a y ) + \a z rounded as one operation. /// \exception FE_INVALID according to operator*() and operator+() unless any argument is a quiet NaN and no argument is a signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding the final addition inline half fma(half x, half y, half z) { #ifdef HALF_ARITHMETIC_TYPE detail::internal_t fx = detail::half2float<detail::internal_t>(x.data_), fy = detail::half2float<detail::internal_t>(y.data_), fz = detail::half2float<detail::internal_t>(z.data_); #if HALF_ENABLE_CPP11_CMATH && FP_FAST_FMA return half(detail::binary, detail::float2half<half::round_style>(std::fma(fx, fy, fz))); #else return half(detail::binary, detail::float2half<half::round_style>(fx*fy+fz)); #endif #else int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, absz = z.data_ & 0x7FFF, exp = -15; unsigned int sign = (x.data_ ^ y.data_) & 0x8000; bool sub = ((sign ^ z.data_) & 0x8000) != 0; if (absx >= 0x7C00 || absy >= 0x7C00 || absz >= 0x7C00) return (absx > 0x7C00 || absy > 0x7C00 || absz > 0x7C00) ? half(detail::binary, detail::signal(x.data_, y.data_, z.data_)) : (absx == 0x7C00) ? half(detail::binary, (!absy || (sub && absz == 0x7C00)) ? detail::invalid() : (sign | 0x7C00)) : (absy == 0x7C00) ? half(detail::binary, (!absx || (sub && absz == 0x7C00)) ? detail::invalid() : (sign | 0x7C00)) : z; if (!absx || !absy) return absz ? z : half(detail::binary, (half::round_style == std::round_toward_neg_infinity) ? (z.data_ | sign) : (z.data_ & sign)); for (; absx < 0x400; absx <<= 1, --exp) ; for (; absy < 0x400; absy <<= 1, --exp) ; detail::uint32 m = static_cast<detail::uint32>((absx & 0x3FF) | 0x400) * static_cast<detail::uint32>((absy & 0x3FF) | 0x400); int i = m >> 21; exp += (absx >> 10) + (absy >> 10) + i; m <<= 3 - i; if (absz) { int expz = 0; for (; absz < 0x400; absz <<= 1, --expz) ; expz += absz >> 10; detail::uint32 mz = static_cast<detail::uint32>((absz & 0x3FF) | 0x400) << 13; if (expz > exp || (expz == exp && mz > m)) { std::swap(m, mz); std::swap(exp, expz); if (sub) sign = z.data_ & 0x8000; } int d = exp - expz; mz = (d < 23) ? ((mz >> d) | ((mz & ((static_cast<detail::uint32>(1) << d) - 1)) != 0)) : 1; if (sub) { m = m - mz; if (!m) return half(detail::binary, static_cast<unsigned>(half::round_style == std::round_toward_neg_infinity) << 15); for (; m < 0x800000; m <<= 1, --exp) ; } else { m += mz; i = m >> 24; m = (m >> i) | (m & i); exp += i; } } if (exp > 30) return half(detail::binary, detail::overflow<half::round_style>(sign)); else if (exp < -10) return half(detail::binary, detail::underflow<half::round_style>(sign)); return half(detail::binary, detail::fixed2half<half::round_style, 23, false, false, false>(m, exp - 1, sign)); #endif } /// Maximum of half expressions. /// **See also:** Documentation for [std::fmax](https://en.cppreference.com/w/cpp/numeric/math/fmax). /// \param x first operand /// \param y second operand /// \return maximum of operands, ignoring quiet NaNs /// \exception FE_INVALID if \a x or \a y is signaling NaN inline HALF_CONSTEXPR_NOERR half fmax(half x, half y) { return half(detail::binary, (!isnan(y) && (isnan(x) || (x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) < (y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))))) ? detail::select(y.data_, x.data_) : detail::select(x.data_, y.data_)); } /// Minimum of half expressions. /// **See also:** Documentation for [std::fmin](https://en.cppreference.com/w/cpp/numeric/math/fmin). /// \param x first operand /// \param y second operand /// \return minimum of operands, ignoring quiet NaNs /// \exception FE_INVALID if \a x or \a y is signaling NaN inline HALF_CONSTEXPR_NOERR half fmin(half x, half y) { return half(detail::binary, (!isnan(y) && (isnan(x) || (x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) > (y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))))) ? detail::select(y.data_, x.data_) : detail::select(x.data_, y.data_)); } /// Positive difference. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::fdim](https://en.cppreference.com/w/cpp/numeric/math/fdim). /// \param x first operand /// \param y second operand /// \return \a x - \a y or 0 if difference negative /// \exception FE_... according to operator-(half,half) inline half fdim(half x, half y) { if (isnan(x) || isnan(y)) return half(detail::binary, detail::signal(x.data_, y.data_)); return (x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) <= (y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) ? half(detail::binary, 0) : (x - y); } /// Get NaN value. /// **See also:** Documentation for [std::nan](https://en.cppreference.com/w/cpp/numeric/math/nan). /// \param arg string code /// \return quiet NaN inline half nanh(const char *arg) { unsigned int value = 0x7FFF; while (*arg) value ^= static_cast<unsigned>(*arg++) & 0xFF; return half(detail::binary, value); } /// \} /// \anchor exponential /// \name Exponential functions /// \{ /// Exponential function. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::exp](https://en.cppreference.com/w/cpp/numeric/math/exp). /// \param arg function argument /// \return e raised to \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half exp(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::exp(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, e = (abs >> 10) + (abs <= 0x3FF), exp; if (!abs) return half(detail::binary, 0x3C00); if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? (0x7C00 & ((arg.data_ >> 15) - 1U)) : detail::signal(arg.data_)); if (abs >= 0x4C80) return half(detail::binary, (arg.data_ & 0x8000) ? detail::underflow<half::round_style>() : detail::overflow<half::round_style>()); detail::uint32 m = detail::multiply64( static_cast<detail::uint32>((abs & 0x3FF) + ((abs > 0x3FF) << 10)) << 21, 0xB8AA3B29); if (e < 14) { exp = 0; m >>= 14 - e; } else { exp = m >> (45 - e); m = (m << (e - 14)) & 0x7FFFFFFF; } return half(detail::binary, detail::exp2_post<half::round_style>(m, exp, (arg.data_ & 0x8000) != 0, 0, 26)); #endif } /// Binary exponential. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::exp2](https://en.cppreference.com/w/cpp/numeric/math/exp2). /// \param arg function argument /// \return 2 raised to \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half exp2(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::exp2(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, e = (abs >> 10) + (abs <= 0x3FF), exp = (abs & 0x3FF) + ((abs > 0x3FF) << 10); if (!abs) return half(detail::binary, 0x3C00); if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? (0x7C00 & ((arg.data_ >> 15) - 1U)) : detail::signal(arg.data_)); if (abs >= 0x4E40) return half(detail::binary, (arg.data_ & 0x8000) ? detail::underflow<half::round_style>() : detail::overflow<half::round_style>()); return half(detail::binary, detail::exp2_post<half::round_style>( (static_cast<detail::uint32>(exp) << (6 + e)) & 0x7FFFFFFF, exp >> (25 - e), (arg.data_ & 0x8000) != 0, 0, 28)); #endif } /// Exponential minus one. /// This function may be 1 ULP off the correctly rounded exact result in <0.05% of inputs for `std::round_to_nearest` /// and in <1% of inputs for any other rounding mode. /// /// **See also:** Documentation for [std::expm1](https://en.cppreference.com/w/cpp/numeric/math/expm1). /// \param arg function argument /// \return e raised to \a arg and subtracted by 1 /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half expm1(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::expm1(detail::half2float<detail::internal_t>(arg.data_)))); #else unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000, e = (abs >> 10) + (abs <= 0x3FF), exp; if (!abs) return arg; if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? (0x7C00 + (sign >> 1)) : detail::signal(arg.data_)); if (abs >= 0x4A00) return half(detail::binary, (arg.data_ & 0x8000) ? detail::rounded<half::round_style, true>(0xBBFF, 1, 1) : detail::overflow<half::round_style>()); detail::uint32 m = detail::multiply64( static_cast<detail::uint32>((abs & 0x3FF) + ((abs > 0x3FF) << 10)) << 21, 0xB8AA3B29); if (e < 14) { exp = 0; m >>= 14 - e; } else { exp = m >> (45 - e); m = (m << (e - 14)) & 0x7FFFFFFF; } m = detail::exp2(m); if (sign) { int s = 0; if (m > 0x80000000) { ++exp; m = detail::divide64(0x80000000, m, s); } m = 0x80000000 - ((m >> exp) | ((m & ((static_cast<detail::uint32>(1) << exp) - 1)) != 0) | s); exp = 0; } else m -= (exp < 31) ? (0x80000000 >> exp) : 1; for (exp += 14; m < 0x80000000 && exp; m <<= 1, --exp) ; if (exp > 29) return half(detail::binary, detail::overflow<half::round_style>()); return half(detail::binary, detail::rounded<half::round_style, true>( sign + (exp << 10) + (m >> 21), (m >> 20) & 1, (m & 0xFFFFF) != 0)); #endif } /// Natural logarithm. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::log](https://en.cppreference.com/w/cpp/numeric/math/log). /// \param arg function argument /// \return logarithm of \a arg to base e /// \exception FE_INVALID for signaling NaN or negative argument /// \exception FE_DIVBYZERO for 0 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half log(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::log(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp = -15; if (!abs) return half(detail::binary, detail::pole(0x8000)); if (arg.data_ & 0x8000) return half(detail::binary, (arg.data_ <= 0xFC00) ? detail::invalid() : detail::signal(arg.data_)); if (abs >= 0x7C00) return (abs == 0x7C00) ? arg : half(detail::binary, detail::signal(arg.data_)); for (; abs < 0x400; abs <<= 1, --exp) ; exp += abs >> 10; return half(detail::binary, detail::log2_post<half::round_style, 0xB8AA3B2A>( detail::log2( static_cast<detail::uint32>((abs & 0x3FF) | 0x400) << 20, 27) + 8, exp, 17)); #endif } /// Common logarithm. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::log10](https://en.cppreference.com/w/cpp/numeric/math/log10). /// \param arg function argument /// \return logarithm of \a arg to base 10 /// \exception FE_INVALID for signaling NaN or negative argument /// \exception FE_DIVBYZERO for 0 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half log10(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::log10(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp = -15; if (!abs) return half(detail::binary, detail::pole(0x8000)); if (arg.data_ & 0x8000) return half(detail::binary, (arg.data_ <= 0xFC00) ? detail::invalid() : detail::signal(arg.data_)); if (abs >= 0x7C00) return (abs == 0x7C00) ? arg : half(detail::binary, detail::signal(arg.data_)); switch (abs) { case 0x4900: return half(detail::binary, 0x3C00); case 0x5640: return half(detail::binary, 0x4000); case 0x63D0: return half(detail::binary, 0x4200); case 0x70E2: return half(detail::binary, 0x4400); } for (; abs < 0x400; abs <<= 1, --exp) ; exp += abs >> 10; return half(detail::binary, detail::log2_post<half::round_style, 0xD49A784C>( detail::log2( static_cast<detail::uint32>((abs & 0x3FF) | 0x400) << 20, 27) + 8, exp, 16)); #endif } /// Binary logarithm. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::log2](https://en.cppreference.com/w/cpp/numeric/math/log2). /// \param arg function argument /// \return logarithm of \a arg to base 2 /// \exception FE_INVALID for signaling NaN or negative argument /// \exception FE_DIVBYZERO for 0 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half log2(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::log2(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp = -15, s = 0; if (!abs) return half(detail::binary, detail::pole(0x8000)); if (arg.data_ & 0x8000) return half(detail::binary, (arg.data_ <= 0xFC00) ? detail::invalid() : detail::signal(arg.data_)); if (abs >= 0x7C00) return (abs == 0x7C00) ? arg : half(detail::binary, detail::signal(arg.data_)); if (abs == 0x3C00) return half(detail::binary, 0); for (; abs < 0x400; abs <<= 1, --exp) ; exp += (abs >> 10); if (!(abs & 0x3FF)) { unsigned int value = static_cast<unsigned>(exp < 0) << 15, m = std::abs( exp) << 6; for (exp = 18; m < 0x400; m <<= 1, --exp) ; return half(detail::binary, value + (exp << 10) + m); } detail::uint32 ilog = exp, sign = detail::sign_mask(ilog), m = (((ilog << 27) + (detail::log2( static_cast<detail::uint32>((abs & 0x3FF) | 0x400) << 20, 28) >> 4)) ^ sign) - sign; if (!m) return half(d
etail::binary, 0); for (exp = 14; m < 0x8000000 && exp; m <<= 1, --exp) ; for (; m > 0xFFFFFFF; m >>= 1, ++exp) s |= m & 1; return half(detail::binary, detail::fixed2half<half::round_style, 27, false, false, true>(m, exp, sign & 0x8000, s)); #endif } /// Natural logarithm plus one. /// This function may be 1 ULP off the correctly rounded exact result in <0.05% of inputs for `std::round_to_nearest` /// and in ~1% of inputs for any other rounding mode. /// /// **See also:** Documentation for [std::log1p](https://en.cppreference.com/w/cpp/numeric/math/log1p). /// \param arg function argument /// \return logarithm of \a arg plus 1 to base e /// \exception FE_INVALID for signaling NaN or argument <-1 /// \exception FE_DIVBYZERO for -1 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half log1p(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::log1p(detail::half2float<detail::internal_t>(arg.data_)))); #else if (arg.data_ >= 0xBC00) return half(detail::binary, (arg.data_ == 0xBC00) ? detail::pole(0x8000) : (arg.data_ <= 0xFC00) ? detail::invalid() : detail::signal(arg.data_)); int abs = arg.data_ & 0x7FFF, exp = -15; if (!abs || abs >= 0x7C00) return (abs > 0x7C00) ? half(detail::binary, detail::signal(arg.data_)) : arg; for (; abs < 0x400; abs <<= 1, --exp) ; exp += abs >> 10; detail::uint32 m = static_cast<detail::uint32>((abs & 0x3FF) | 0x400) << 20; if (arg.data_ & 0x8000) { m = 0x40000000 - (m >> -exp); for (exp = 0; m < 0x40000000; m <<= 1, --exp) ; } else { if (exp < 0) { m = 0x40000000 + (m >> -exp); exp = 0; } else { m += 0x40000000 >> exp; int i = m >> 31; m >>= i; exp += i; } } return half(detail::binary, detail::log2_post<half::round_style, 0xB8AA3B2A>(detail::log2(m), exp, 17)); #endif } /// \} /// \anchor power /// \name Power functions /// \{ /// Square root. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::sqrt](https://en.cppreference.com/w/cpp/numeric/math/sqrt). /// \param arg function argument /// \return square root of \a arg /// \exception FE_INVALID for signaling NaN and negative arguments /// \exception FE_INEXACT according to rounding inline half sqrt(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::sqrt(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp = 15; if (!abs || arg.data_ >= 0x7C00) return half(detail::binary, (abs > 0x7C00) ? detail::signal(arg.data_) : (arg.data_ > 0x8000) ? detail::invalid() : arg.data_); for (; abs < 0x400; abs <<= 1, --exp) ; detail::uint32 r = static_cast<detail::uint32>((abs & 0x3FF) | 0x400) << 10, m = detail::sqrt<20>(r, exp += abs >> 10); return half(detail::binary, detail::rounded<half::round_style, false>((exp << 10) + (m & 0x3FF), r > m, r != 0)); #endif } /// Inverse square root. /// This function is exact to rounding for all rounding modes and thus generally more accurate than directly computing /// 1 / sqrt(\a arg) in half-precision, in addition to also being faster. /// \param arg function argument /// \return reciprocal of square root of \a arg /// \exception FE_INVALID for signaling NaN and negative arguments /// \exception FE_INEXACT according to rounding inline half rsqrt(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(detail::internal_t(1)/std::sqrt(detail::half2float<detail::internal_t>(arg.data_)))); #else unsigned int abs = arg.data_ & 0x7FFF, bias = 0x4000; if (!abs || arg.data_ >= 0x7C00) return half(detail::binary, (abs > 0x7C00) ? detail::signal(arg.data_) : (arg.data_ > 0x8000) ? detail::invalid() : !abs ? detail::pole(arg.data_ & 0x8000) : 0); for (; abs < 0x400; abs <<= 1, bias -= 0x400) ; unsigned int frac = (abs += bias) & 0x7FF; if (frac == 0x400) return half(detail::binary, 0x7A00 - (abs >> 1)); if ((half::round_style == std::round_to_nearest && (frac == 0x3FE || frac == 0x76C)) || (half::round_style != std::round_to_nearest && (frac == 0x15A || frac == 0x3FC || frac == 0x401 || frac == 0x402 || frac == 0x67B))) return pow(arg, half(detail::binary, 0xB800)); detail::uint32 f = 0x17376 - abs, mx = (abs & 0x3FF) | 0x400, my = ((f >> 1) & 0x3FF) | 0x400, mz = my * my; int expy = (f >> 11) - 31, expx = 32 - (abs >> 10), i = mz >> 21; for (mz = 0x60000000 - (((mz >> i) * mx) >> (expx - 2 * expy - i)); mz < 0x40000000; mz <<= 1, --expy) ; i = (my *= mz >> 10) >> 31; expy += i; my = (my >> (20 + i)) + 1; i = (mz = my * my) >> 21; for (mz = 0x60000000 - (((mz >> i) * mx) >> (expx - 2 * expy - i)); mz < 0x40000000; mz <<= 1, --expy) ; i = (my *= (mz >> 10) + 1) >> 31; return half(detail::binary, detail::fixed2half<half::round_style, 30, false, false, true>( my >> i, expy + i + 14)); #endif } /// Cubic root. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::cbrt](https://en.cppreference.com/w/cpp/numeric/math/cbrt). /// \param arg function argument /// \return cubic root of \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_INEXACT according to rounding inline half cbrt(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::cbrt(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp = -15; if (!abs || abs == 0x3C00 || abs >= 0x7C00) return (abs > 0x7C00) ? half(detail::binary, detail::signal(arg.data_)) : arg; for (; abs < 0x400; abs <<= 1, --exp) ; detail::uint32 ilog = exp + (abs >> 10), sign = detail::sign_mask(ilog), f, m = (((ilog << 27) + (detail::log2( static_cast<detail::uint32>((abs & 0x3FF) | 0x400) << 20, 24) >> 4)) ^ sign) - sign; for (exp = 2; m < 0x80000000; m <<= 1, --exp) ; m = detail::multiply64(m, 0xAAAAAAAB); int i = m >> 31, s; exp += i; m <<= 1 - i; if (exp < 0) { f = m >> -exp; exp = 0; } else { f = (m << exp) & 0x7FFFFFFF; exp = m >> (31 - exp); } m = detail::exp2(f, (half::round_style == std::round_to_nearest) ? 29 : 26); if (sign) { if (m > 0x80000000) { m = detail::divide64(0x80000000, m, s); ++exp; } exp = -exp; } return half(detail::binary, (half::round_style == std::round_to_nearest) ? detail::fixed2half<half::round_style, 31, false, false, false>(m, exp + 14, arg.data_ & 0x8000) : detail::fixed2half<half::round_style, 23, false, false, false>((m + 0x80) >> 8, exp + 14, arg.data_ & 0x8000)); #endif } /// Hypotenuse function. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::hypot](https://en.cppreference.com/w/cpp/numeric/math/hypot). /// \param x first argument /// \param y second argument /// \return square root of sum of squares without internal over- or underflows /// \exception FE_INVALID if \a x or \a y is signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding of the final square root inline half hypot(half x, half y) { #ifdef HALF_ARITHMETIC_TYPE detail::internal_t fx = detail::half2float<detail::internal_t>(x.data_), fy = detail::half2float<detail::internal_t>(y.data_); #if HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::hypot(fx, fy))); #else return half(detail::binary, detail::float2half<half::round_style>(std::sqrt(fx*fx+fy*fy))); #endif #else int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, expx = 0, expy = 0; if (absx >= 0x7C00 || absy >= 0x7C00) return half(detail::binary, (absx == 0x7C00) ? detail::select(0x7C00, y.data_) : (absy == 0x7C00) ? detail::select(0x7C00, x.data_) : detail::signal(x.data_, y.data_)); if (!absx) return half(detail::binary, absy ? detail::check_underflow(absy) : 0); if (!absy) return half(detail::binary, detail::check_underflow(absx)); if (absy > absx) std::swap(absx, absy); for (; absx < 0x400; absx <<= 1, --expx) ; for (; absy < 0x400; absy <<= 1, --expy) ; detail::uint32 mx = (absx & 0x3FF) | 0x400, my = (absy & 0x3FF) | 0x400; mx *= mx; my *= my; int ix = mx >> 21, iy = my >> 21; expx = 2 * (expx + (absx >> 10)) - 15 + ix; expy = 2 * (expy + (absy >> 10)) - 15 + iy; mx <<= 10 - ix; my <<= 10 - iy; int d = expx - expy; my = (d < 30) ? ((my >> d) | ((my & ((static_cast<detail::uint32>(1) << d) - 1)) != 0)) : 1; return half(detail::binary, detail::hypot_post<half::round_style>(mx + my, expx)); #endif } /// Hypotenuse function. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::hypot](https://en.cppreference.com/w/cpp/numeric/math/hypot). /// \param x first argument /// \param y second argument /// \param z third argument /// \return square root of sum of squares without internal over- or underflows /// \exception FE_INVALID if \a x, \a y or \a z is signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding of the final square root inline half hypot(half x, half y, half z) { #ifdef HALF_ARITHMETIC_TYPE detail::internal_t fx = detail::half2float<detail::internal_t>(x.data_), fy = detail::half2float<detail::internal_t>(y.data_), fz = detail::half2float<detail::internal_t>(z.data_); return half(detail::binary, detail::float2half<half::round_style>(std::sqrt(fx*fx+fy*fy+fz*fz))); #else int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, absz = z.data_ & 0x7FFF, expx = 0, expy = 0, expz = 0; if (!absx) return hypot(y, z); if (!absy) return hypot(x, z); if (!absz) return hypot(x, y); if (absx >= 0x7C00 || absy >= 0x7C00 || absz >= 0x7C00) return half(detail::binary, (absx == 0x7C00) ? detail::select(0x7C00, detail::select(y.data_, z.data_)) : (absy == 0x7C00) ? detail::select(0x7C00, detail::select(x.data_, z.data_)) : (absz == 0x7C00) ? detail::select(0x7C00, detail::select(x.data_, y.data_)) : detail::signal(x.data_, y.data_, z.data_)); if (absz > absy) std::swap(absy, absz); if (absy > absx) std::swap(absx, absy); if (absz > absy) std::swap(absy, absz); for (; absx < 0x400; absx <<= 1, --expx) ; for (; absy < 0x400; absy <<= 1, --expy) ; for (; absz < 0x400; absz <<= 1, --expz) ; detail::uint32 mx = (absx & 0x3FF) | 0x400, my = (absy & 0x3FF) | 0x400, mz = (absz & 0x3FF) | 0x400; mx *= mx; my *= my; mz *= mz; int ix = mx >> 21, iy = my >> 21, iz = mz >> 21; expx = 2 * (expx + (absx >> 10)) - 15 + ix; expy = 2 * (expy + (absy >> 10)) - 15 + iy; expz = 2 * (expz + (absz >> 10)) - 15 + iz; mx <<= 10 - ix; my <<= 10 - iy; mz <<= 10 - iz; int d = expy - expz; mz = (d < 30) ? ((mz >> d) | ((mz & ((static_cast<detail::uint32>(1) << d) - 1)) != 0)) : 1; my += mz; if (my & 0x80000000) { my = (my >> 1) | (my & 1); if (++expy > expx) { std::swap(mx, my); std::swap(expx, expy); } } d = expx - expy; my = (d < 30) ? ((my >> d) | ((my & ((static_cast<detail::uint32>(1) << d) - 1)) != 0)) : 1; return half(detail::binary, detail::hypot_post<half::round_style>(mx + my, expx)); #endif } /// Power function. /// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in ~0.00025% of inputs. /// /// **See also:** Documentation for [std::pow](https://en.cppreference.com/w/cpp/numeric/math/pow). /// \param x base /// \param y exponent /// \return \a x raised to \a y /// \exception FE_INVALID if \a x or \a y is signaling NaN or if \a x is finite an negative and \a y is finite and not integral /// \exception FE_DIVBYZERO if \a x is 0 and \a y is negative /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half pow(half x, half y) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::pow(detail::half2float<detail::internal_t>(x.data_), detail::half2float<detail::internal_t>(y.data_)))); #else int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, exp = -15; if (!absy || x.data_ == 0x3C00) return half(detail::binary, detail::select(0x3C00, (x.data_ == 0x3C00) ? y.data_ : x.data_)); bool is_int = absy >= 0x6400 || (absy >= 0x3C00 && !(absy & ((1 << (25 - (absy >> 10))) - 1))); unsigned int sign = x.data_ & (static_cast<unsigned>((absy < 0x6800) && is_int && ((absy >> (25 - (absy >> 10))) & 1)) << 15); if (absx >= 0x7C00 || absy >= 0x7C00) return half(detail::binary, (absx > 0x7C00 || absy > 0x7C00) ? detail::signal(x.data_, y.data_) : (absy == 0x7C00) ? ((absx == 0x3C00) ? 0x3C00 : (!absx && y.data_ == 0xFC00) ? detail::pole() : (0x7C00 & -((y.data_ >> 15) ^ (absx > 0x3C00)))) : (sign | (0x7C00 & ((y.data_ >> 15) - 1U)))); if (!absx) return half(detail::binary, (y.data_ & 0x8000) ? detail::pole(sign) : sign); if ((x.data_ & 0x8000) && !is_int) return half(detail::binary, detail::invalid()); if (x.data_ == 0xBC00) return half(detail::binary, sign | 0x3C00); switch (y.data_) { case 0x3800: return sqrt(x); case 0x3C00: return half(detail::binary, detail::check_underflow(x.data_)); case 0x4000: return x * x; case 0xBC00: return half(detail::binary, 0x3C00) / x; } for (; absx < 0x400; absx <<= 1, --exp) ; detail::uint32 ilog = exp + (absx >> 10), msign = detail::sign_mask(ilog), f, m = (((ilog << 27) + ((detail::log2( static_cast<detail::uint32>((absx & 0x3FF) | 0x400) << 20) + 8) >> 4)) ^ msign) - msign; for (exp = -11; m < 0x80000000; m <<= 1, --exp) ; for (; absy < 0x400; absy <<= 1, --exp) ; m = detail::multiply64(m, static_cast<detail::uint32>((absy & 0x3FF) | 0x400) << 21); int i = m >> 31; exp += (absy >> 10) + i; m <<= 1 - i; if (exp < 0) { f = m >> -exp; exp = 0; } else { f = (m << exp) & 0x7FFFFFFF; exp = m >> (31 - exp); } return half(detail::binary, detail::exp2_post<half::round_style>(f, exp, ((msign & 1) ^ (y.data_ >> 15)) != 0, sign)); #endif } /// \} /// \anchor trigonometric /// \name Trigonometric functions /// \{ /// Compute sine and cosine simultaneously. /// This returns the same results as sin() and cos() but is faster than calling each function individually. /// /// This function is exact to rounding for all rounding modes. /// \param arg function argument /// \param sin variable to take sine of \a arg /// \param cos variable to take cosine of \a arg /// \exception FE_INVALID for signaling NaN or infinity /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline void sincos(half arg, half *sin, half *cos) { #ifdef HALF_ARITHMETIC_TYPE detail::internal_t f = detail::half2float<detail::internal_t>(arg.data_); *sin = half(detail::binary, detail::float2half<half::round_style>(std::sin(f))); *cos = half(detail::binary, detail::float2half<half::round_style>(std::cos(f))); #else int abs = arg.data_ & 0x7FFF, sign = arg.data_ >> 15, k; if (abs >= 0x7C00) *sin = *cos = half(detail::binary, (abs == 0x7C00) ? detail::invalid() : detail::signal(arg.data_)); else if (!abs) { *sin = arg; *cos = half(detail::binary, 0x3C00); } else if (abs < 0x2500) { *sin = half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ - 1, 1, 1)); *cos = half(detail::binary, detail::rounded<half::round_style, true>(0x3BFF, 1, 1)); } else { if (half::round_style != std::round_to_nearest) { switch (abs) { case 0x48B7: *sin = half(detail::binary, detail::rounded<half::round_style, true>( (~arg.data_ & 0x8000) | 0x1D07, 1, 1)); *cos = half(detail::binary, detail::rounded<half::round_style, true>(0xBBFF, 1, 1)); return; case 0x598C: *sin = half(detail::binary, detail::rounded<half::round_style, true>( (arg.data_ & 0x8000) | 0x3BFF, 1, 1)); *cos = half(detail::binary, detail::rounded<half::round_style, true>(0x80FC, 1, 1)); return; case 0x6A64: *sin = half(detail::binary, detail::rounded<half::round_style, true>( (~arg.data_ & 0x8000) | 0x3BFE, 1, 1)); *cos = half(detail::binary, detail::rounded<half::round_style, true>(0x27FF, 1, 1)); return; case 0x6D8C: *sin = half(detail::binary, detail::rounded<half::round_style, true>( (arg.data_ & 0x8000) | 0x0FE6, 1, 1)); *cos = half(detail::binary, detail::rounded<half::round_style, true>(0x3BFF, 1, 1)); return; } } std::pair<detail::uint32, detail::uint32> sc = detail::sincos( detail::angle_arg(abs, k), 28); switch (k & 3) { case 1: sc = std::make_pair(sc.second, -sc.first); break; case 2: sc = std::make_pair(-sc.first, -sc.second); break; case
3: sc = std::make_pair(-sc.second, sc.first); break; } *sin = half(detail::binary, detail::fixed2half<half::round_style, 30, true, true, true>( (sc.first ^ -static_cast<detail::uint32>(sign)) + sign)); *cos = half(detail::binary, detail::fixed2half<half::round_style, 30, true, true, true>( sc.second)); } #endif } /// Sine function. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::sin](https://en.cppreference.com/w/cpp/numeric/math/sin). /// \param arg function argument /// \return sine value of \a arg /// \exception FE_INVALID for signaling NaN or infinity /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half sin(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::sin(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, k; if (!abs) return arg; if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? detail::invalid() : detail::signal(arg.data_)); if (abs < 0x2900) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ - 1, 1, 1)); if (half::round_style != std::round_to_nearest) switch (abs) { case 0x48B7: return half(detail::binary, detail::rounded<half::round_style, true>( (~arg.data_ & 0x8000) | 0x1D07, 1, 1)); case 0x6A64: return half(detail::binary, detail::rounded<half::round_style, true>( (~arg.data_ & 0x8000) | 0x3BFE, 1, 1)); case 0x6D8C: return half(detail::binary, detail::rounded<half::round_style, true>( (arg.data_ & 0x8000) | 0x0FE6, 1, 1)); } std::pair<detail::uint32, detail::uint32> sc = detail::sincos( detail::angle_arg(abs, k), 28); detail::uint32 sign = -static_cast<detail::uint32>(((k >> 1) & 1) ^ (arg.data_ >> 15)); return half(detail::binary, detail::fixed2half<half::round_style, 30, true, true, true>( (((k & 1) ? sc.second : sc.first) ^ sign) - sign)); #endif } /// Cosine function. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::cos](https://en.cppreference.com/w/cpp/numeric/math/cos). /// \param arg function argument /// \return cosine value of \a arg /// \exception FE_INVALID for signaling NaN or infinity /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half cos(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::cos(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, k; if (!abs) return half(detail::binary, 0x3C00); if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? detail::invalid() : detail::signal(arg.data_)); if (abs < 0x2500) return half(detail::binary, detail::rounded<half::round_style, true>(0x3BFF, 1, 1)); if (half::round_style != std::round_to_nearest && abs == 0x598C) return half(detail::binary, detail::rounded<half::round_style, true>(0x80FC, 1, 1)); std::pair<detail::uint32, detail::uint32> sc = detail::sincos( detail::angle_arg(abs, k), 28); detail::uint32 sign = -static_cast<detail::uint32>(((k >> 1) ^ k) & 1); return half(detail::binary, detail::fixed2half<half::round_style, 30, true, true, true>( (((k & 1) ? sc.first : sc.second) ^ sign) - sign)); #endif } /// Tangent function. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::tan](https://en.cppreference.com/w/cpp/numeric/math/tan). /// \param arg function argument /// \return tangent value of \a arg /// \exception FE_INVALID for signaling NaN or infinity /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half tan(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::tan(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp = 13, k; if (!abs) return arg; if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? detail::invalid() : detail::signal(arg.data_)); if (abs < 0x2700) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_, 0, 1)); if (half::round_style != std::round_to_nearest) switch (abs) { case 0x658C: return half(detail::binary, detail::rounded<half::round_style, true>( (arg.data_ & 0x8000) | 0x07E6, 1, 1)); case 0x7330: return half(detail::binary, detail::rounded<half::round_style, true>( (~arg.data_ & 0x8000) | 0x4B62, 1, 1)); } std::pair<detail::uint32, detail::uint32> sc = detail::sincos( detail::angle_arg(abs, k), 30); if (k & 1) sc = std::make_pair(-sc.second, sc.first); detail::uint32 signy = detail::sign_mask(sc.first), signx = detail::sign_mask(sc.second); detail::uint32 my = (sc.first ^ signy) - signy, mx = (sc.second ^ signx) - signx; for (; my < 0x80000000; my <<= 1, --exp) ; for (; mx < 0x80000000; mx <<= 1, ++exp) ; return half(detail::binary, detail::tangent_post<half::round_style>(my, mx, exp, (signy ^ signx ^ arg.data_) & 0x8000)); #endif } /// Arc sine. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::asin](https://en.cppreference.com/w/cpp/numeric/math/asin). /// \param arg function argument /// \return arc sine value of \a arg /// \exception FE_INVALID for signaling NaN or if abs(\a arg) > 1 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half asin(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::asin(detail::half2float<detail::internal_t>(arg.data_)))); #else unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000; if (!abs) return arg; if (abs >= 0x3C00) return half(detail::binary, (abs > 0x7C00) ? detail::signal(arg.data_) : (abs > 0x3C00) ? detail::invalid() : detail::rounded<half::round_style, true>(sign | 0x3E48, 0, 1)); if (abs < 0x2900) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_, 0, 1)); if (half::round_style != std::round_to_nearest && (abs == 0x2B44 || abs == 0x2DC3)) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ + 1, 1, 1)); std::pair<detail::uint32, detail::uint32> sc = detail::atan2_args(abs); detail::uint32 m = detail::atan2(sc.first, sc.second, (half::round_style == std::round_to_nearest) ? 27 : 26); return half(detail::binary, detail::fixed2half<half::round_style, 30, false, true, true>(m, 14, sign)); #endif } /// Arc cosine function. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::acos](https://en.cppreference.com/w/cpp/numeric/math/acos). /// \param arg function argument /// \return arc cosine value of \a arg /// \exception FE_INVALID for signaling NaN or if abs(\a arg) > 1 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half acos(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::acos(detail::half2float<detail::internal_t>(arg.data_)))); #else unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ >> 15; if (!abs) return half(detail::binary, detail::rounded<half::round_style, true>(0x3E48, 0, 1)); if (abs >= 0x3C00) return half(detail::binary, (abs > 0x7C00) ? detail::signal(arg.data_) : (abs > 0x3C00) ? detail::invalid() : sign ? detail::rounded<half::round_style, true>(0x4248, 0, 1) : 0); std::pair<detail::uint32, detail::uint32> cs = detail::atan2_args(abs); detail::uint32 m = detail::atan2(cs.second, cs.first, 28); return half(detail::binary, detail::fixed2half<half::round_style, 31, false, true, true>( sign ? (0xC90FDAA2 - m) : m, 15, 0, sign)); #endif } /// Arc tangent function. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::atan](https://en.cppreference.com/w/cpp/numeric/math/atan). /// \param arg function argument /// \return arc tangent value of \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half atan(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::atan(detail::half2float<detail::internal_t>(arg.data_)))); #else unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000; if (!abs) return arg; if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? detail::rounded<half::round_style, true>(sign | 0x3E48, 0, 1) : detail::signal(arg.data_)); if (abs <= 0x2700) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ - 1, 1, 1)); int exp = (abs >> 10) + (abs <= 0x3FF); detail::uint32 my = (abs & 0x3FF) | ((abs > 0x3FF) << 10); detail::uint32 m = (exp > 15) ? detail::atan2(my << 19, 0x20000000 >> (exp - 15), (half::round_style == std::round_to_nearest) ? 26 : 24) : detail::atan2(my << (exp + 4), 0x20000000, (half::round_style == std::round_to_nearest) ? 30 : 28); return half(detail::binary, detail::fixed2half<half::round_style, 30, false, true, true>(m, 14, sign)); #endif } /// Arc tangent function. /// This function may be 1 ULP off the correctly rounded exact result in ~0.005% of inputs for `std::round_to_nearest`, /// in ~0.1% of inputs for `std::round_toward_zero` and in ~0.02% of inputs for any other rounding mode. /// /// **See also:** Documentation for [std::atan2](https://en.cppreference.com/w/cpp/numeric/math/atan2). /// \param y numerator /// \param x denominator /// \return arc tangent value /// \exception FE_INVALID if \a x or \a y is signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half atan2(half y, half x) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::atan2(detail::half2float<detail::internal_t>(y.data_), detail::half2float<detail::internal_t>(x.data_)))); #else unsigned int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, signx = x.data_ >> 15, signy = y.data_ & 0x8000; if (absx >= 0x7C00 || absy >= 0x7C00) { if (absx > 0x7C00 || absy > 0x7C00) return half(detail::binary, detail::signal(x.data_, y.data_)); if (absy == 0x7C00) return half(detail::binary, (absx < 0x7C00) ? detail::rounded<half::round_style, true>( signy | 0x3E48, 0, 1) : signx ? detail::rounded<half::round_style, true>( signy | 0x40B6, 0, 1) : detail::rounded<half::round_style, true>( signy | 0x3A48, 0, 1)); return (x.data_ == 0x7C00) ? half(detail::binary, signy) : half(detail::binary, detail::rounded<half::round_style, true>(signy | 0x4248, 0, 1)); } if (!absy) return signx ? half(detail::binary, detail::rounded<half::round_style, true>(signy | 0x4248, 0, 1)) : y; if (!absx) return half(detail::binary, detail::rounded<half::round_style, true>(signy | 0x3E48, 0, 1)); int d = (absy >> 10) + (absy <= 0x3FF) - (absx >> 10) - (absx <= 0x3FF); if (d > (signx ? 18 : 12)) return half(detail::binary, detail::rounded<half::round_style, true>(signy | 0x3E48, 0, 1)); if (signx && d < -11) return half(detail::binary, detail::rounded<half::round_style, true>(signy | 0x4248, 0, 1)); if (!signx && d < ((half::round_style == std::round_toward_zero) ? -15 : -9)) { for (; absy < 0x400; absy <<= 1, --d) ; detail::uint32 mx = ((absx << 1) & 0x7FF) | 0x800, my = ((absy << 1) & 0x7FF) | 0x800; int i = my < mx; d -= i; if (d < -25) return half(detail::binary, detail::underflow<half::round_style>(signy)); my <<= 11 + i; return half(detail::binary, detail::fixed2half<half::round_style, 11, false, false, true>( my / mx, d + 14, signy, my % mx != 0)); } detail::uint32 m = detail::atan2( ((absy & 0x3FF) | ((absy > 0x3FF) << 10)) << (19 + ((d < 0) ? d : (d > 0) ? 0 : -1)), ((absx & 0x3FF) | ((absx > 0x3FF) << 10)) << (19 - ((d > 0) ? d : (d < 0) ? 0 : 1))); return half(detail::binary, detail::fixed2half<half::round_style, 31, false, true, true>( signx ? (0xC90FDAA2 - m) : m, 15, signy, signx)); #endif } /// \} /// \anchor hyperbolic /// \name Hyperbolic functions /// \{ /// Hyperbolic sine. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::sinh](https://en.cppreference.com/w/cpp/numeric/math/sinh). /// \param arg function argument /// \return hyperbolic sine value of \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half sinh(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::sinh(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp; if (!abs || abs >= 0x7C00) return (abs > 0x7C00) ? half(detail::binary, detail::signal(arg.data_)) : arg; if (abs <= 0x2900) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_, 0, 1)); std::pair<detail::uint32, detail::uint32> mm = detail::hyperbolic_args(abs, exp, (half::round_style == std::round_to_nearest) ? 29 : 27); detail::uint32 m = mm.first - mm.second; for (exp += 13; m < 0x80000000 && exp; m <<= 1, --exp) ; unsigned int sign = arg.data_ & 0x8000; if (exp > 29) return half(detail::binary, detail::overflow<half::round_style>(sign)); return half(detail::binary, detail::fixed2half<half::round_style, 31, false, false, true>(m, exp, sign)); #endif } /// Hyperbolic cosine. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::cosh](https://en.cppreference.com/w/cpp/numeric/math/cosh). /// \param arg function argument /// \return hyperbolic cosine value of \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half cosh(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::cosh(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp; if (!abs) return half(detail::binary, 0x3C00); if (abs >= 0x7C00) return half(detail::binary, (abs > 0x7C00) ? detail::signal(arg.data_) : 0x7C00); std::pair<detail::uint32, detail::uint32> mm = detail::hyperbolic_args(abs, exp, (half::round_style == std::round_to_nearest) ? 23 : 26); detail::uint32 m = mm.first + mm.second, i = (~m & 0xFFFFFFFF) >> 31; m = (m >> i) | (m & i) | 0x80000000; if ((exp += 13 + i) > 29) return half(detail::binary, detail::overflow<half::round_style>()); return half(detail::binary, detail::fixed2half<half::round_style, 31, false, false, true>(m, exp)); #endif } /// Hyperbolic tangent. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::tanh](https://en.cppreference.com/w/cpp/numeric/math/tanh). /// \param arg function argument /// \return hyperbolic tangent value of \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half tanh(half arg) { #ifdef HALF_ARITHMETIC_TYPE return half(detail::binary, detail::float2half<half::round_style>(std::tanh(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp; if (!abs) return arg; if (abs >= 0x7C00) return half(detail::binary, (abs > 0x7C00) ? detail::signal(arg.data_) : (arg.data_ - 0x4000)); if (abs >= 0x4500) return half(detail::binary, detail::rounded<half::round_style, true>( (arg.data_ & 0x8000) | 0x3BFF, 1, 1)); if (abs < 0x2700) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ - 1, 1, 1)); if (half::round_style != std::round_to_nearest && abs == 0x2D3F) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ - 3, 0, 1)); std::pair<detail::uint32, detail::uint32> mm = detail::hyperbolic_args(abs, exp, 27); detail::uint32 my = mm.first - mm.second - (half::round_style != std::round_to_nearest), mx = mm.first + mm.second, i = (~mx & 0xFFFFFFFF) >> 31; for (exp = 13; my < 0x80000000; my <<= 1, --exp) ; mx = (mx >> i) | 0x80000000; return half(detail::binary, detail::tangent_post<half::round_style>(my, mx, exp - i, arg.data_ & 0x8000)); #endif } /// Hyperbolic area sine. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::asinh](https://en.cppreference.com/w/cpp/numeric/math/asinh). /// \param arg function argument /// \return area sine value of \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half asinh(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::asinh(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF; if (!abs || abs >= 0x7C00) return (abs > 0x7C00) ?
half(detail::binary, detail::signal(arg.data_)) : arg; if (abs <= 0x2900) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ - 1, 1, 1)); if (half::round_style != std::round_to_nearest) switch (abs) { case 0x32D4: return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ - 13, 1, 1)); case 0x3B5B: return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_ - 197, 1, 1)); } return half(detail::binary, detail::area<half::round_style, true>(arg.data_)); #endif } /// Hyperbolic area cosine. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::acosh](https://en.cppreference.com/w/cpp/numeric/math/acosh). /// \param arg function argument /// \return area cosine value of \a arg /// \exception FE_INVALID for signaling NaN or arguments <1 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half acosh(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::acosh(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF; if ((arg.data_ & 0x8000) || abs < 0x3C00) return half(detail::binary, (abs <= 0x7C00) ? detail::invalid() : detail::signal(arg.data_)); if (abs == 0x3C00) return half(detail::binary, 0); if (arg.data_ >= 0x7C00) return (abs > 0x7C00) ? half(detail::binary, detail::signal(arg.data_)) : arg; return half(detail::binary, detail::area<half::round_style, false>(arg.data_)); #endif } /// Hyperbolic area tangent. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::atanh](https://en.cppreference.com/w/cpp/numeric/math/atanh). /// \param arg function argument /// \return area tangent value of \a arg /// \exception FE_INVALID for signaling NaN or if abs(\a arg) > 1 /// \exception FE_DIVBYZERO for +/-1 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half atanh(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::atanh(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF, exp = 0; if (!abs) return arg; if (abs >= 0x3C00) return half(detail::binary, (abs == 0x3C00) ? detail::pole(arg.data_ & 0x8000) : (abs <= 0x7C00) ? detail::invalid() : detail::signal(arg.data_)); if (abs < 0x2700) return half(detail::binary, detail::rounded<half::round_style, true>(arg.data_, 0, 1)); detail::uint32 m = static_cast<detail::uint32>((abs & 0x3FF) | ((abs > 0x3FF) << 10)) << ((abs >> 10) + (abs <= 0x3FF) + 6), my = 0x80000000 + m, mx = 0x80000000 - m; for (; mx < 0x80000000; mx <<= 1, ++exp) ; int i = my >= mx, s; return half(detail::binary, detail::log2_post<half::round_style, 0xB8AA3B2A>( detail::log2((detail::divide64(my >> i, mx, s) + 1) >> 1, 27) + 0x10, exp + i - 1, 16, arg.data_ & 0x8000)); #endif } /// \} /// \anchor special /// \name Error and gamma functions /// \{ /// Error function. /// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in <0.5% of inputs. /// /// **See also:** Documentation for [std::erf](https://en.cppreference.com/w/cpp/numeric/math/erf). /// \param arg function argument /// \return error function value of \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half erf(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::erf(detail::half2float<detail::internal_t>(arg.data_)))); #else unsigned int abs = arg.data_ & 0x7FFF; if (!abs || abs >= 0x7C00) return (abs >= 0x7C00) ? half(detail::binary, (abs == 0x7C00) ? (arg.data_ - 0x4000) : detail::signal(arg.data_)) : arg; if (abs >= 0x4200) return half(detail::binary, detail::rounded<half::round_style, true>( (arg.data_ & 0x8000) | 0x3BFF, 1, 1)); return half(detail::binary, detail::erf<half::round_style, false>(arg.data_)); #endif } /// Complementary error function. /// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in <0.5% of inputs. /// /// **See also:** Documentation for [std::erfc](https://en.cppreference.com/w/cpp/numeric/math/erfc). /// \param arg function argument /// \return 1 minus error function value of \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half erfc(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::erfc(detail::half2float<detail::internal_t>(arg.data_)))); #else unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000; if (abs >= 0x7C00) return (abs >= 0x7C00) ? half(detail::binary, (abs == 0x7C00) ? (sign >> 1) : detail::signal(arg.data_)) : arg; if (!abs) return half(detail::binary, 0x3C00); if (abs >= 0x4400) return half(detail::binary, detail::rounded<half::round_style, true>( (sign >> 1) - (sign >> 15), sign >> 15, 1)); return half(detail::binary, detail::erf<half::round_style, true>(arg.data_)); #endif } /// Natural logarithm of gamma function. /// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in ~0.025% of inputs. /// /// **See also:** Documentation for [std::lgamma](https://en.cppreference.com/w/cpp/numeric/math/lgamma). /// \param arg function argument /// \return natural logarith of gamma function for \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_DIVBYZERO for 0 or negative integer arguments /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half lgamma(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::lgamma(detail::half2float<detail::internal_t>(arg.data_)))); #else int abs = arg.data_ & 0x7FFF; if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? 0x7C00 : detail::signal(arg.data_)); if (!abs || arg.data_ >= 0xE400 || (arg.data_ >= 0xBC00 && !(abs & ((1 << (25 - (abs >> 10))) - 1)))) return half(detail::binary, detail::pole()); if (arg.data_ == 0x3C00 || arg.data_ == 0x4000) return half(detail::binary, 0); return half(detail::binary, detail::gamma<half::round_style, true>(arg.data_)); #endif } /// Gamma function. /// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in <0.25% of inputs. /// /// **See also:** Documentation for [std::tgamma](https://en.cppreference.com/w/cpp/numeric/math/tgamma). /// \param arg function argument /// \return gamma function value of \a arg /// \exception FE_INVALID for signaling NaN, negative infinity or negative integer arguments /// \exception FE_DIVBYZERO for 0 /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half tgamma(half arg) { #if defined(HALF_ARITHMETIC_TYPE) && HALF_ENABLE_CPP11_CMATH return half(detail::binary, detail::float2half<half::round_style>(std::tgamma(detail::half2float<detail::internal_t>(arg.data_)))); #else unsigned int abs = arg.data_ & 0x7FFF; if (!abs) return half(detail::binary, detail::pole(arg.data_)); if (abs >= 0x7C00) return (arg.data_ == 0x7C00) ? arg : half(detail::binary, detail::signal(arg.data_)); if (arg.data_ >= 0xE400 || (arg.data_ >= 0xBC00 && !(abs & ((1 << (25 - (abs >> 10))) - 1)))) return half(detail::binary, detail::invalid()); if (arg.data_ >= 0xCA80) return half(detail::binary, detail::underflow<half::round_style>( (1 - ((abs >> (25 - (abs >> 10))) & 1)) << 15)); if (arg.data_ <= 0x100 || (arg.data_ >= 0x4900 && arg.data_ < 0x8000)) return half(detail::binary, detail::overflow<half::round_style>()); if (arg.data_ == 0x3C00) return arg; return half(detail::binary, detail::gamma<half::round_style, false>(arg.data_)); #endif } /// \} /// \anchor rounding /// \name Rounding /// \{ /// Nearest integer not less than half value. /// **See also:** Documentation for [std::ceil](https://en.cppreference.com/w/cpp/numeric/math/ceil). /// \param arg half to round /// \return nearest integer not less than \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_INEXACT if value had to be rounded inline half ceil(half arg) { return half(detail::binary, detail::integral<std::round_toward_infinity, true, true>(arg.data_)); } /// Nearest integer not greater than half value. /// **See also:** Documentation for [std::floor](https://en.cppreference.com/w/cpp/numeric/math/floor). /// \param arg half to round /// \return nearest integer not greater than \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_INEXACT if value had to be rounded inline half floor(half arg) { return half(detail::binary, detail::integral<std::round_toward_neg_infinity, true, true>( arg.data_)); } /// Nearest integer not greater in magnitude than half value. /// **See also:** Documentation for [std::trunc](https://en.cppreference.com/w/cpp/numeric/math/trunc). /// \param arg half to round /// \return nearest integer not greater in magnitude than \a arg /// \exception FE_INVALID for signaling NaN /// \exception FE_INEXACT if value had to be rounded inline half trunc(half arg) { return half(detail::binary, detail::integral<std::round_toward_zero, true, true>(arg.data_)); } /// Nearest integer. /// **See also:** Documentation for [std::round](https://en.cppreference.com/w/cpp/numeric/math/round). /// \param arg half to round /// \return nearest integer, rounded away from zero in half-way cases /// \exception FE_INVALID for signaling NaN /// \exception FE_INEXACT if value had to be rounded inline half round(half arg) { return half(detail::binary, detail::integral<std::round_to_nearest, false, true>(arg.data_)); } /// Nearest integer. /// **See also:** Documentation for [std::lround](https://en.cppreference.com/w/cpp/numeric/math/round). /// \param arg half to round /// \return nearest integer, rounded away from zero in half-way cases /// \exception FE_INVALID if value is not representable as `long` inline long lround(half arg) { return detail::half2int<std::round_to_nearest, false, false, long>( arg.data_); } /// Nearest integer using half's internal rounding mode. /// **See also:** Documentation for [std::rint](https://en.cppreference.com/w/cpp/numeric/math/rint). /// \param arg half expression to round /// \return nearest integer using default rounding mode /// \exception FE_INVALID for signaling NaN /// \exception FE_INEXACT if value had to be rounded inline half rint(half arg) { return half(detail::binary, detail::integral<half::round_style, true, true>(arg.data_)); } /// Nearest integer using half's internal rounding mode. /// **See also:** Documentation for [std::lrint](https://en.cppreference.com/w/cpp/numeric/math/rint). /// \param arg half expression to round /// \return nearest integer using default rounding mode /// \exception FE_INVALID if value is not representable as `long` /// \exception FE_INEXACT if value had to be rounded inline long lrint(half arg) { return detail::half2int<half::round_style, true, true, long>(arg.data_); } /// Nearest integer using half's internal rounding mode. /// **See also:** Documentation for [std::nearbyint](https://en.cppreference.com/w/cpp/numeric/math/nearbyint). /// \param arg half expression to round /// \return nearest integer using default rounding mode /// \exception FE_INVALID for signaling NaN inline half nearbyint(half arg) { return half(detail::binary, detail::integral<half::round_style, true, false>(arg.data_)); } #if HALF_ENABLE_CPP11_LONG_LONG /// Nearest integer. /// **See also:** Documentation for [std::llround](https://en.cppreference.com/w/cpp/numeric/math/round). /// \param arg half to round /// \return nearest integer, rounded away from zero in half-way cases /// \exception FE_INVALID if value is not representable as `long long` inline long long llround(half arg) { return detail::half2int<std::round_to_nearest,false,false,long long>(arg.data_); } /// Nearest integer using half's internal rounding mode. /// **See also:** Documentation for [std::llrint](https://en.cppreference.com/w/cpp/numeric/math/rint). /// \param arg half expression to round /// \return nearest integer using default rounding mode /// \exception FE_INVALID if value is not representable as `long long` /// \exception FE_INEXACT if value had to be rounded inline long long llrint(half arg) { return detail::half2int<half::round_style,true,true,long long>(arg.data_); } #endif /// \} /// \anchor float /// \name Floating point manipulation /// \{ /// Decompress floating-point number. /// **See also:** Documentation for [std::frexp](https://en.cppreference.com/w/cpp/numeric/math/frexp). /// \param arg number to decompress /// \param exp address to store exponent at /// \return significant in range [0.5, 1) /// \exception FE_INVALID for signaling NaN inline half frexp(half arg, int *exp) { *exp = 0; unsigned int abs = arg.data_ & 0x7FFF; if (abs >= 0x7C00 || !abs) return (abs > 0x7C00) ? half(detail::binary, detail::signal(arg.data_)) : arg; for (; abs < 0x400; abs <<= 1, --*exp) ; *exp += (abs >> 10) - 14; return half(detail::binary, (arg.data_ & 0x8000) | 0x3800 | (abs & 0x3FF)); } /// Multiply by power of two. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::scalbln](https://en.cppreference.com/w/cpp/numeric/math/scalbn). /// \param arg number to modify /// \param exp power of two to multiply with /// \return \a arg multplied by 2 raised to \a exp /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half scalbln(half arg, long exp) { unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000; if (abs >= 0x7C00 || !abs) return (abs > 0x7C00) ? half(detail::binary, detail::signal(arg.data_)) : arg; for (; abs < 0x400; abs <<= 1, --exp) ; exp += abs >> 10; if (exp > 30) return half(detail::binary, detail::overflow<half::round_style>(sign)); else if (exp < -10) return half(detail::binary, detail::underflow<half::round_style>(sign)); else if (exp > 0) return half(detail::binary, sign | (exp << 10) | (abs & 0x3FF)); unsigned int m = (abs & 0x3FF) | 0x400; return half(detail::binary, detail::rounded<half::round_style, false>(sign | (m >> (1 - exp)), (m >> -exp) & 1, (m & ((1 << -exp) - 1)) != 0)); } /// Multiply by power of two. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::scalbn](https://en.cppreference.com/w/cpp/numeric/math/scalbn). /// \param arg number to modify /// \param exp power of two to multiply with /// \return \a arg multplied by 2 raised to \a exp /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half scalbn(half arg, int exp) { return scalbln(arg, exp); } /// Multiply by power of two. /// This function is exact to rounding for all rounding modes. /// /// **See also:** Documentation for [std::ldexp](https://en.cppreference.com/w/cpp/numeric/math/ldexp). /// \param arg number to modify /// \param exp power of two to multiply with /// \return \a arg multplied by 2 raised to \a exp /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding inline half ldexp(half arg, int exp) { return scalbln(arg, exp); } /// Extract integer and fractional parts. /// **See also:** Documentation for [std::modf](https://en.cppreference.com/w/cpp/numeric/math/modf). /// \param arg number to decompress /// \param iptr address to store integer part at /// \return fractional part /// \exception FE_INVALID for signaling NaN inline half modf(half arg, half *iptr) { unsigned int abs = arg.data_ & 0x7FFF; if (abs > 0x7C00) { arg = half(detail::binary, detail::signal(arg.data_)); return *iptr = arg, arg; } if (abs >= 0x6400) return *iptr = arg, half(detail::binary, arg.data_ & 0x8000); if (abs < 0x3C00) return iptr->data_ = arg.data_ & 0x8000, arg; unsigned int exp = abs >> 10, mask = (1 << (25 - exp)) - 1, m = arg.data_ & mask; iptr->data_ = arg.data_ & ~mask; if (!m) return half(detail::binary, arg.data_ & 0x8000); for (; m < 0x400; m <<= 1, --exp) ; return half(detail::binary, (arg.data_ & 0x8000) | (exp << 10) | (m & 0x3FF)); } /// Extract exponent. /// **See also:** Documentation for [std::ilogb](https://en.cppreference.com/w/cpp/numeric/math/ilogb). /// \param arg number to query /// \return floating-point exponent /// \retval FP_ILOGB0 for zero /// \retval FP_ILOGBNAN for NaN /// \retval INT_MAX for infinity /// \exception FE_INVALID for 0 or infinite values inline int ilogb(half arg) { int abs = arg.data_ & 0x7FFF, exp; if (!abs || abs >= 0x7C00) { detail::raise(FE_INVALID); return !abs ? FP_ILOGB0 : (abs == 0x7C00) ? INT_MAX : FP_ILOGBNAN; } for (exp = (abs >> 10) - 15; abs < 0x200; abs <<= 1, --exp) ; return exp; } /// Extract exponent. /// **See also:** Documentation for [std::logb](https://en.cppreference.com/w/cpp/numeric/math/logb). /// \param arg number to query /// \return floating-point exponent /// \exception FE_INVALID for signaling NaN /// \exception FE_DIVBYZERO for 0 inline half logb(half arg) { int abs = arg.data_ & 0x7FFF, exp; if (!abs) return half(detail::binary, detail::pole(0x8000)); if (abs >= 0x7C00) return half(detail::binary, (abs == 0x7C00) ? 0x7C00 : detail::signal(arg.data_)); for (exp = (abs >> 10) - 15; abs < 0x200; abs <<= 1, --exp) ; unsigned int value = static_cast<unsigned>(exp < 0) << 15; if (exp) { unsigned int m = std::abs(exp) << 6; for (exp = 18; m < 0x400; m <<= 1, --exp) ; value |= (exp << 10) + m; } return half(detail::binary, value); } /// Next representable value. /// **See also:** Documentation for [std::nextafter](https://en.cppreference.com/w/cpp/numeric/math/nextafter). /// \param from value to compute next representable value for /// \param to direction towards which to compute next value /// \return next representable value after \a from in direction towards \a to /// \exception FE_INVALID for
signaling NaN /// \exception FE_OVERFLOW for infinite result from finite argument /// \exception FE_UNDERFLOW for subnormal result inline half nextafter(half from, half to) { int fabs = from.data_ & 0x7FFF, tabs = to.data_ & 0x7FFF; if (fabs > 0x7C00 || tabs > 0x7C00) return half(detail::binary, detail::signal(from.data_, to.data_)); if (from.data_ == to.data_ || !(fabs | tabs)) return to; if (!fabs) { detail::raise(FE_UNDERFLOW, !HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT); return half(detail::binary, (to.data_ & 0x8000) + 1); } unsigned int out = from.data_ + (((from.data_ >> 15) ^ static_cast<unsigned>((from.data_ ^ (0x8000 | (0x8000 - (from.data_ >> 15)))) < (to.data_ ^ (0x8000 | (0x8000 - (to.data_ >> 15)))))) << 1) - 1; detail::raise(FE_OVERFLOW, fabs < 0x7C00 && (out & 0x7C00) == 0x7C00); detail::raise(FE_UNDERFLOW, !HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT && (out & 0x7C00) < 0x400); return half(detail::binary, out); } /// Next representable value. /// **See also:** Documentation for [std::nexttoward](https://en.cppreference.com/w/cpp/numeric/math/nexttoward). /// \param from value to compute next representable value for /// \param to direction towards which to compute next value /// \return next representable value after \a from in direction towards \a to /// \exception FE_INVALID for signaling NaN /// \exception FE_OVERFLOW for infinite result from finite argument /// \exception FE_UNDERFLOW for subnormal result inline half nexttoward(half from, long double to) { int fabs = from.data_ & 0x7FFF; if (fabs > 0x7C00) return half(detail::binary, detail::signal(from.data_)); long double lfrom = static_cast<long double>(from); if (detail::builtin_isnan(to) || lfrom == to) return half(static_cast<float>(to)); if (!fabs) { detail::raise(FE_UNDERFLOW, !HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT); return half(detail::binary, (static_cast<unsigned>(detail::builtin_signbit(to)) << 15) + 1); } unsigned int out = from.data_ + (((from.data_ >> 15) ^ static_cast<unsigned>(lfrom < to)) << 1) - 1; detail::raise(FE_OVERFLOW, (out & 0x7FFF) == 0x7C00); detail::raise(FE_UNDERFLOW, !HALF_ERRHANDLING_UNDERFLOW_TO_INEXACT && (out & 0x7FFF) < 0x400); return half(detail::binary, out); } /// Take sign. /// **See also:** Documentation for [std::copysign](https://en.cppreference.com/w/cpp/numeric/math/copysign). /// \param x value to change sign for /// \param y value to take sign from /// \return value equal to \a x in magnitude and to \a y in sign inline HALF_CONSTEXPR half copysign(half x, half y) { return half(detail::binary, x.data_ ^ ((x.data_ ^ y.data_) & 0x8000)); } /// \} /// \anchor classification /// \name Floating point classification /// \{ /// Classify floating-point value. /// **See also:** Documentation for [std::fpclassify](https://en.cppreference.com/w/cpp/numeric/math/fpclassify). /// \param arg number to classify /// \retval FP_ZERO for positive and negative zero /// \retval FP_SUBNORMAL for subnormal numbers /// \retval FP_INFINITY for positive and negative infinity /// \retval FP_NAN for NaNs /// \retval FP_NORMAL for all other (normal) values inline HALF_CONSTEXPR int fpclassify(half arg) { return !(arg.data_ & 0x7FFF) ? FP_ZERO : ((arg.data_ & 0x7FFF) < 0x400) ? FP_SUBNORMAL : ((arg.data_ & 0x7FFF) < 0x7C00) ? FP_NORMAL : ((arg.data_ & 0x7FFF) == 0x7C00) ? FP_INFINITE : FP_NAN; } /// Check if finite number. /// **See also:** Documentation for [std::isfinite](https://en.cppreference.com/w/cpp/numeric/math/isfinite). /// \param arg number to check /// \retval true if neither infinity nor NaN /// \retval false else inline HALF_CONSTEXPR bool isfinite(half arg) { return (arg.data_ & 0x7C00) != 0x7C00; } /// Check for infinity. /// **See also:** Documentation for [std::isinf](https://en.cppreference.com/w/cpp/numeric/math/isinf). /// \param arg number to check /// \retval true for positive or negative infinity /// \retval false else inline HALF_CONSTEXPR bool isinf(half arg) { return (arg.data_ & 0x7FFF) == 0x7C00; } /// Check for NaN. /// **See also:** Documentation for [std::isnan](https://en.cppreference.com/w/cpp/numeric/math/isnan). /// \param arg number to check /// \retval true for NaNs /// \retval false else inline HALF_CONSTEXPR bool isnan(half arg) { return (arg.data_ & 0x7FFF) > 0x7C00; } /// Check if normal number. /// **See also:** Documentation for [std::isnormal](https://en.cppreference.com/w/cpp/numeric/math/isnormal). /// \param arg number to check /// \retval true if normal number /// \retval false if either subnormal, zero, infinity or NaN inline HALF_CONSTEXPR bool isnormal(half arg) { return ((arg.data_ & 0x7C00) != 0) & ((arg.data_ & 0x7C00) != 0x7C00); } /// Check sign. /// **See also:** Documentation for [std::signbit](https://en.cppreference.com/w/cpp/numeric/math/signbit). /// \param arg number to check /// \retval true for negative number /// \retval false for positive number inline HALF_CONSTEXPR bool signbit(half arg) { return (arg.data_ & 0x8000) != 0; } /// \} /// \anchor compfunc /// \name Comparison /// \{ /// Quiet comparison for greater than. /// **See also:** Documentation for [std::isgreater](https://en.cppreference.com/w/cpp/numeric/math/isgreater). /// \param x first operand /// \param y second operand /// \retval true if \a x greater than \a y /// \retval false else inline HALF_CONSTEXPR bool isgreater(half x, half y) { return ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) > ((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)) && !isnan(x) && !isnan(y); } /// Quiet comparison for greater equal. /// **See also:** Documentation for [std::isgreaterequal](https://en.cppreference.com/w/cpp/numeric/math/isgreaterequal). /// \param x first operand /// \param y second operand /// \retval true if \a x greater equal \a y /// \retval false else inline HALF_CONSTEXPR bool isgreaterequal(half x, half y) { return ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) >= ((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)) && !isnan(x) && !isnan(y); } /// Quiet comparison for less than. /// **See also:** Documentation for [std::isless](https://en.cppreference.com/w/cpp/numeric/math/isless). /// \param x first operand /// \param y second operand /// \retval true if \a x less than \a y /// \retval false else inline HALF_CONSTEXPR bool isless(half x, half y) { return ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) < ((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)) && !isnan(x) && !isnan(y); } /// Quiet comparison for less equal. /// **See also:** Documentation for [std::islessequal](https://en.cppreference.com/w/cpp/numeric/math/islessequal). /// \param x first operand /// \param y second operand /// \retval true if \a x less equal \a y /// \retval false else inline HALF_CONSTEXPR bool islessequal(half x, half y) { return ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) <= ((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)) && !isnan(x) && !isnan(y); } /// Quiet comarison for less or greater. /// **See also:** Documentation for [std::islessgreater](https://en.cppreference.com/w/cpp/numeric/math/islessgreater). /// \param x first operand /// \param y second operand /// \retval true if either less or greater /// \retval false else inline HALF_CONSTEXPR bool islessgreater(half x, half y) { return x.data_ != y.data_ && ((x.data_ | y.data_) & 0x7FFF) && !isnan(x) && !isnan(y); } /// Quiet check if unordered. /// **See also:** Documentation for [std::isunordered](https://en.cppreference.com/w/cpp/numeric/math/isunordered). /// \param x first operand /// \param y second operand /// \retval true if unordered (one or two NaN operands) /// \retval false else inline HALF_CONSTEXPR bool isunordered(half x, half y) { return isnan(x) || isnan(y); } /// \} /// \anchor casting /// \name Casting /// \{ /// Cast to or from half-precision floating-point number. /// This casts between [half](\ref half_float::half) and any built-in arithmetic type. The values are converted /// directly using the default rounding mode, without any roundtrip over `float` that a `static_cast` would otherwise do. /// /// Using this cast with neither of the two types being a [half](\ref half_float::half) or with any of the two types /// not being a built-in arithmetic type (apart from [half](\ref half_float::half), of course) results in a compiler /// error and casting between [half](\ref half_float::half)s returns the argument unmodified. /// \tparam T destination type (half or built-in arithmetic type) /// \tparam U source type (half or built-in arithmetic type) /// \param arg value to cast /// \return \a arg converted to destination type /// \exception FE_INVALID if \a T is integer type and result is not representable as \a T /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding template<typename T, typename U> T half_cast(U arg) { return detail::half_caster<T, U>::cast(arg); } /// Cast to or from half-precision floating-point number. /// This casts between [half](\ref half_float::half) and any built-in arithmetic type. The values are converted /// directly using the specified rounding mode, without any roundtrip over `float` that a `static_cast` would otherwise do. /// /// Using this cast with neither of the two types being a [half](\ref half_float::half) or with any of the two types /// not being a built-in arithmetic type (apart from [half](\ref half_float::half), of course) results in a compiler /// error and casting between [half](\ref half_float::half)s returns the argument unmodified. /// \tparam T destination type (half or built-in arithmetic type) /// \tparam R rounding mode to use. /// \tparam U source type (half or built-in arithmetic type) /// \param arg value to cast /// \return \a arg converted to destination type /// \exception FE_INVALID if \a T is integer type and result is not representable as \a T /// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding template<typename T, std::float_round_style R, typename U> T half_cast(U arg) { return detail::half_caster<T, U, R>::cast(arg); } /// \} /// \} /// \anchor errors /// \name Error handling /// \{ /// Clear exception flags. /// This function works even if [automatic exception flag handling](\ref HALF_ERRHANDLING_FLAGS) is disabled, /// but in that case manual flag management is the only way to raise flags. /// /// **See also:** Documentation for [std::feclearexcept](https://en.cppreference.com/w/cpp/numeric/fenv/feclearexcept). /// \param excepts OR of exceptions to clear /// \retval 0 all selected flags cleared successfully inline int feclearexcept(int excepts) { detail::errflags() &= ~excepts; return 0; } /// Test exception flags. /// This function works even if [automatic exception flag handling](\ref HALF_ERRHANDLING_FLAGS) is disabled, /// but in that case manual flag management is the only way to raise flags. /// /// **See also:** Documentation for [std::fetestexcept](https://en.cppreference.com/w/cpp/numeric/fenv/fetestexcept). /// \param excepts OR of exceptions to test /// \return OR of selected exceptions if raised inline int fetestexcept(int excepts) { return detail::errflags() & excepts; } /// Raise exception flags. /// This raises the specified floating point exceptions and also invokes any additional automatic exception handling as /// configured with the [HALF_ERRHANDLIG_...](\ref HALF_ERRHANDLING_ERRNO) preprocessor symbols. /// This function works even if [automatic exception flag handling](\ref HALF_ERRHANDLING_FLAGS) is disabled, /// but in that case manual flag management is the only way to raise flags. /// /// **See also:** Documentation for [std::feraiseexcept](https://en.cppreference.com/w/cpp/numeric/fenv/feraiseexcept). /// \param excepts OR of exceptions to raise /// \retval 0 all selected exceptions raised successfully inline int feraiseexcept(int excepts) { detail::errflags() |= excepts; detail::raise(excepts); return 0; } /// Save exception flags. /// This function works even if [automatic exception flag handling](\ref HALF_ERRHANDLING_FLAGS) is disabled, /// but in that case manual flag management is the only way to raise flags. /// /// **See also:** Documentation for [std::fegetexceptflag](https://en.cppreference.com/w/cpp/numeric/fenv/feexceptflag). /// \param flagp adress to store flag state at /// \param excepts OR of flags to save /// \retval 0 for success inline int fegetexceptflag(int *flagp, int excepts) { *flagp = detail::errflags() & excepts; return 0; } /// Restore exception flags. /// This only copies the specified exception state (including unset flags) without incurring any additional exception handling. /// This function works even if [automatic exception flag handling](\ref HALF_ERRHANDLING_FLAGS) is disabled, /// but in that case manual flag management is the only way to raise flags. /// /// **See also:** Documentation for [std::fesetexceptflag](https://en.cppreference.com/w/cpp/numeric/fenv/feexceptflag). /// \param flagp adress to take flag state from /// \param excepts OR of flags to restore /// \retval 0 for success inline int fesetexceptflag(const int *flagp, int excepts) { detail::errflags() = (detail::errflags() | (*flagp & excepts)) & (*flagp | ~excepts); return 0; } /// Throw C++ exceptions based on set exception flags. /// This function manually throws a corresponding C++ exception if one of the specified flags is set, /// no matter if automatic throwing (via [HALF_ERRHANDLING_THROW_...](\ref HALF_ERRHANDLING_THROW_INVALID)) is enabled or not. /// This function works even if [automatic exception flag handling](\ref HALF_ERRHANDLING_FLAGS) is disabled, /// but in that case manual flag management is the only way to raise flags. /// \param excepts OR of exceptions to test /// \param msg error message to use for exception description /// \throw std::domain_error if `FE_INVALID` or `FE_DIVBYZERO` is selected and set /// \throw std::overflow_error if `FE_OVERFLOW` is selected and set /// \throw std::underflow_error if `FE_UNDERFLOW` is selected and set /// \throw std::range_error if `FE_INEXACT` is selected and set inline void fethrowexcept(int excepts, const char *msg = "") { excepts &= detail::errflags(); if (excepts & (FE_INVALID | FE_DIVBYZERO)) throw std::domain_error(msg); if (excepts & FE_OVERFLOW) throw std::overflow_error(msg); if (excepts & FE_UNDERFLOW) throw std::underflow_error(msg); if (excepts & FE_INEXACT) throw std::range_error(msg); } /// \} } #undef HALF_UNUSED_NOERR #undef HALF_CONSTEXPR #undef HALF_CONSTEXPR_CONST #undef HALF_CONSTEXPR_NOERR #undef HALF_NOEXCEPT #undef HALF_NOTHROW #undef HALF_THREAD_LOCAL #undef HALF_TWOS_COMPLEMENT_INT #ifdef HALF_POP_WARNINGS #pragma warning(pop) #undef HALF_POP_WARNINGS #endif #endif
#pragma once #include "systemc.hpp" #include "common.hpp" #include <memory> // Forward declarations struct Objector_module; struct Stimulus_module; template<typename T> struct Splitter_module; struct Behavior_module; struct Observer_module; struct Top_module: sc_core::sc_module { std::unique_ptr<Objector_module> objector; std::unique_ptr<Stimulus_module> stimulus; std::unique_ptr<Splitter_module<Data_t>> splitter; std::unique_ptr<Behavior_module> behavior; std::unique_ptr<Observer_module> observer; // Constructor scans command-line and connects everything Top_module( sc_core::sc_module_name ); ~Top_module(); // Open trace file if needed void end_of_elaboration(); // If not nullptr, then return an trace file handle static sc_core::sc_trace_file* trace_file(); private: sc_core::sc_trace_file* m_trace { nullptr }; inline static Top_module* s_self { nullptr }; };
#pragma once #include "systemc.hpp" #include <string> struct Commandline { // Return index if a command-line argument beginning with opt exists; otherwise, zero // Optional index may be used to continue scanning from previous scan (0 => // start from first) inline static size_t has_opt( std::string& opt, int i=0 ) { for( ++i; i < sc_core::sc_argc(); ++i ) { std::string arg{ sc_core::sc_argv()[ i ] }; if( arg.find( opt ) == 0 ) return i; } return 0; } private: [[maybe_unused]]constexpr static char const * const MSGID{ "/Doulos/Example/Commandline" }; };
#pragma once #include<string> #include<systemc.h> using std::string; class write_if_f: virtual public sc_interface { public: virtual void write(string) = 0; virtual void nb_write(string) = 0; }; class read_if_f: virtual public sc_interface { public: virtual void read(string &) = 0; virtual void nb_read(string &) = 0; virtual void notify() = 0; }; class write_if: virtual public sc_interface { public: virtual void write(string) = 0; }; class read_if: virtual public sc_interface { public: virtual void read(string &) = 0; };
/***************************************************************************\ * * * ___ ___ ___ ___ * / /\ / /\ / /\ / /\ * / /:/ / /::\ / /::\ / /::\ * / /:/ / /:/\:\ / /:/\:\ / /:/\:\ * / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/ * / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/ * /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/ * \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/ * \ \:\ \ \:\ \ \:\ \ \:\ * \ \ \ \ \:\ \ \:\ \ \:\ * \__\/ \__\/ \__\/ \__\/ * * * * * This file is part of TRAP. * * TRAP is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * or see <http://www.gnu.org/licenses/>. * * * * (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com * \***************************************************************************/ #ifndef SPARSE_MEMORYAT_HPP #define SPARSE_MEMORYAT_HPP #include <systemc.h> #include <tlm.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include <boost/lexical_cast.hpp> #include <string> #include <cstring> #include <map> #include <trap_utils.hpp> DECLARE_EXTENDED_PHASE(internal_ph); namespace trap{ template<unsigned int N_INITIATORS, unsigned int sockSize> class SparseMemoryAT: public sc_module{ public: tlm_utils::simple_target_socket_tagged<SparseMemoryAT, sockSize> * socket[N_INITIATORS]; SparseMemoryAT(sc_module_name name, unsigned int size, sc_time latency = SC_ZERO_TIME) : sc_module(name), size(size), latency(latency), transId(0), transactionInProgress(false), m_peq(this, &SparseMemoryAT::peq_cb){ for(int i = 0; i < N_INITIATORS; i++){ this->socket[i] = new tlm_utils::simple_target_socket_tagged<SparseMemoryAT, sockSize>(("mem_socket_" + boost::lexical_cast<std::string>(i)).c_str()); this->socket[i]->register_nb_transport_fw(this, &SparseMemoryAT::nb_transport_fw, i); this->socket[i]->register_transport_dbg(this, &SparseMemoryAT::transport_dbg, i); } // Reset memory end_module(); } ~SparseMemoryAT(){ for(int i = 0; i < N_INITIATORS; i++){ delete this->socket[i]; } } // TLM-2 non-blocking transport method tlm::tlm_sync_enum nb_transport_fw(int tag, tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay){ sc_dt::uint64 adr = trans.get_address(); unsigned int len = trans.get_data_length(); unsigned char* byt = trans.get_byte_enable_ptr(); unsigned int wid = trans.get_streaming_width(); // Obliged to check the transaction attributes for unsupported features // and to generate the appropriate error response if (byt != 0){ trans.set_response_status(tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE); return tlm::TLM_COMPLETED; } // Now queue the transaction until the annotated time has elapsed if(phase == tlm::BEGIN_REQ){ while(this->transactionInProgress){ //std::cerr << "waiting for transactionInProgress" << std::endl; wait(this->transactionCompleted); } //std::cerr << "there are no transactionInProgress" << std::endl; this->transactionInProgress = true; } this->transId = tag; m_peq.notify(trans, phase, delay); trans.set_response_status(tlm::TLM_OK_RESPONSE); return tlm::TLM_ACCEPTED; } void peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase){ tlm::tlm_sync_enum status; sc_time delay; switch (phase){ case tlm::BEGIN_REQ: status = send_end_req(trans); break; case tlm::END_RESP: //std::cerr << "tlm::END_RESP in memory peq_cb" << std::endl; this->transactionInProgress = false; this->transactionCompleted.notify(); break; case tlm::END_REQ: case tlm::BEGIN_RESP: SC_REPORT_FATAL("TLM-2", "Illegal transaction phase received by target"); break; default: if (phase == internal_ph){ // Execute the read or write commands tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); unsigned char* ptr = trans.get_data_ptr(); unsigned int len = trans.get_data_length(); if(cmd == tlm::TLM_READ_COMMAND){ for(int i = 0; i < len; i++, ptr++) *ptr = this->mem[adr + i]; } else if(cmd == tlm::TLM_WRITE_COMMAND){ for(int i = 0; i < len; i++, ptr++) this->mem[adr + i] = *ptr; } trans.set_response_status(tlm::TLM_OK_RESPONSE); // Target must honor BEGIN_RESP/END_RESP exclusion rule // i.e. must not send BEGIN_RESP until receiving previous END_RESP or BEGIN_REQ send_response(trans); //std::cerr << "Memory reading address in memory " << std::hex << std::showbase << adr << std::endl; } break; } } tlm::tlm_sync_enum send_end_req(tlm::tlm_generic_payload& trans){ tlm::tlm_sync_enum status; tlm::tlm_phase bw_phase; tlm::tlm_phase int_phase = internal_ph; // Queue the acceptance and the response with the appropriate latency bw_phase = tlm::END_REQ; sc_time zeroDelay = SC_ZERO_TIME; status = (*(this->socket[transId]))->nb_transport_bw(trans, bw_phase, zeroDelay); if (status == tlm::TLM_COMPLETED){ // Transaction aborted by the initiator // (TLM_UPDATED cannot occur at this point in the base protocol, so need not be checked) trans.release(); return status; } // Queue internal event to mark beginning of response m_peq.notify( trans, int_phase, this->latency ); return status; } void send_response(tlm::tlm_generic_payload& trans){ tlm::tlm_sync_enum status; tlm::tlm_phase bw_phase; bw_phase = tlm::BEGIN_RESP; sc_time zeroDelay = SC_ZERO_TIME; status = (*(this->socket[transId]))->nb_transport_bw(trans, bw_phase, zeroDelay); //std::cerr << "response status " << status << std::endl; if (status == tlm::TLM_UPDATED){ // The timing annotation must be honored m_peq.notify(trans, bw_phase, SC_ZERO_TIME); } else if (status == tlm::TLM_COMPLETED){ // The initiator has terminated the transaction trans.release(); } } // TLM-2 debug transaction method unsigned int transport_dbg(int tag, tlm::tlm_generic_payload& trans){ tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); unsigned char* ptr = trans.get_data_ptr(); unsigned int len = trans.get_data_length(); if(cmd == tlm::TLM_READ_COMMAND){ for(int i = 0; i < len; i++, ptr++) *ptr = this->mem[adr + i]; } else if(cmd == tlm::TLM_WRITE_COMMAND){ for(int i = 0; i < len; i++, ptr++) this->mem[adr + i] = *ptr; } return len; } //Method used to directly write a word into memory; it is mainly used to load the //application program into memory inline void write_byte_dbg(const unsigned int & address, const unsigned char & datum) throw(){ this->mem[address] = datum; } private: const sc_time latency; unsigned int size; std::map<unsigned int, unsigned char> mem; int transId; bool transactionInProgress; sc_event transactionCompleted; tlm_utils::peq_with_cb_and_phase<SparseMemoryAT> m_peq; }; }; #endif
#include <iostream> #include <systemc.h> int run_simple_simulation(unsigned long int stack);
#include <systemc.h> #include <config.hpp> SC_MODULE(Functional_bus){ //Input Port sc_core::sc_in <unsigned int> request_address; sc_core::sc_in <uint8_t*> request_data; sc_core::sc_in <bool> flag_from_core; sc_core::sc_in <bool> request_ready; sc_core::sc_in <unsigned int> request_size; sc_core::sc_in <uint8_t*> data_input_sensor[NUM_SENSORS]; sc_core::sc_in <bool> go_sensors[NUM_SENSORS]; //Output Port sc_core::sc_out <uint8_t*> request_value; sc_core::sc_out <bool> request_go; sc_core::sc_out <int> idx_sensor; sc_core::sc_out <unsigned int> address_out_sensor[NUM_SENSORS]; sc_core::sc_out <uint8_t*> data_out_sensor[NUM_SENSORS]; sc_core::sc_out <unsigned int> size_out_sensor[NUM_SENSORS]; sc_core::sc_out <bool> flag_out_sensor[NUM_SENSORS]; sc_core::sc_out <bool> ready_sensor[NUM_SENSORS]; SC_CTOR(Functional_bus): request_address("Address_from_Master_to_Bus"), request_data("Data_from_Master_to_Bus"), flag_from_core("Flag_from_Master_to_Bus"), request_ready("Ready_from_Master_to_Bus"), request_value("Data_from_Bus_to_Master"), request_go("Go_from_Bus_to_Master"), idx_sensor("selected_sensor_from_request") { SC_THREAD(processing_data); sensitive << request_ready; for (int i = 0; i < NUM_SENSORS; i++){ sensitive << go_sensors[i]; } } void processing_data(); void response(); private: int selected_sensor = 0; Functional_bus(){} };
#ifndef IMG_SAVER_TLM_HPP #define IMG_SAVER_TLM_HPP #include <systemc.h> #include "../src/img_target.cpp" #include "address_map.hpp" struct img_saver_tlm: public img_target { img_saver_tlm(sc_module_name name) : img_target((std::string(name) + "_target").c_str()) { set_mem_attributes(IMG_SAVER_ID_ADDRESS_LO, IMG_SAVER_ID_SIZE+IMG_SAVER_START_SIZE); } //Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); int local_id; unsigned char *img_input_ptr; unsigned char *img_inprocess_a_ptr; unsigned char *img_inprocess_b_ptr; unsigned char *img_inprocess_c_ptr; unsigned char *img_inprocess_d_ptr; unsigned char *img_output_ptr; unsigned char *img_output_dec_ptr; }; #endif // IMG_SAVER_TLM_HPP
#ifndef PACKET_GENERATOR_TLM_HPP #define PACKET_GENERATOR_TLM_HPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include <systemc-ams.h> #include "packetGenerator.h" #include "../src/img_target.cpp" #include "address_map.hpp" //Extended Unification TLM struct packetGenerator_tlm : public packetGenerator, public img_target { packetGenerator_tlm(sc_module_name name, bool use_prints_, sca_core::sca_time sample_time) : packetGenerator((std::string(name) + "_AMS_HW_block").c_str(), sample_time), img_target((std::string(name) + "_target").c_str()), tmp_data_length(0) { tmp_data = new unsigned char[IMG_OUTPUT_SIZE]; set_mem_attributes(IMG_OUTPUT_ADDRESS_LO, IMG_OUTPUT_SIZE+IMG_OUTPUT_SIZE_SIZE+IMG_OUTPUT_DONE_SIZE+IMG_OUTPUT_STATUS_SIZE); use_prints = use_prints_; checkprintenableimgtar(use_prints); } //Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address); //Backdoor access to memory void backdoor_write(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address); void backdoor_read(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address); unsigned int tmp_data_length; unsigned char* tmp_data; }; #endif // PACKET_GENERATOR_TLM_HPP
#ifndef IPS_SEQ_ITEM_AMS_HPP #define IPS_SEQ_ITEM_AMS_HPP #define int64 systemc_int64 #define uint64 systemc_uint64 #include <systemc.h> #include <systemc-ams.h> #undef int64 #undef uint64 #define int64 opencv_int64 #define uint64 opencv_uint64 #include <opencv2/opencv.hpp> #undef int64 #undef uint64 // Image path #define IPS_IMG_PATH_TB "../../tools/datagen/src/imgs/car_rgb_noisy_image.jpg" /** * @brief This class is used to generate the data for the AMS test * * @tparam N - the number of output bits of the digital pixel * @tparam H_ACTIVE - output horizontal active video pixels * @tparam H_FP - wait after the display period before the sync * horizontal pulse * @tparam H_SYNC_PULSE - assert HSYNC * @tparam H_BP - wait after the sync horizontal pulse before starting * the next display period * @tparam V_ACTIVE - output vertical active video pixels * @tparam V_FP - wait after the display period before the sync * vertical pulse * @tparam V_SYNC_PULSE - assert VSYNC * @tparam V_BP - wait after the sync vertical pulse before starting * the next display period */ template < unsigned int N = 8, unsigned int H_ACTIVE = 640, unsigned int H_FP = 16, unsigned int H_SYNC_PULSE = 96, unsigned int H_BP = 48, unsigned int V_ACTIVE = 480, unsigned int V_FP = 10, unsigned int V_SYNC_PULSE = 2, unsigned int V_BP = 33 > SC_MODULE(seq_item_ams) { protected: cv::Mat tx_img; public: // Input clock sc_core::sc_in<bool> clk; // Counters sc_core::sc_in<unsigned int> hcount; sc_core::sc_in<unsigned int> vcount; // Output pixel sc_core::sc_out<sc_uint<N> > o_red; sc_core::sc_out<sc_uint<N> > o_green; sc_core::sc_out<sc_uint<N> > o_blue; SC_CTOR(seq_item_ams) { // Read image const std::string img_path = IPS_IMG_PATH_TB; cv::Mat read_img = cv::imread(img_path, cv::IMREAD_COLOR); // CV_8UC3 Type: 8-bit unsigned, 3 channels (e.g., for a color image) read_img.convertTo(this->tx_img, CV_8UC3); #ifdef IPS_DEBUG_EN std::cout << "Loading image: " << img_path << std::endl; #endif // IPS_DEBUG_EN // Check if the image is loaded successfully if (this->tx_img.empty()) { std::cerr << "Error: Could not open or find the image!" << std::endl; exit(EXIT_FAILURE); } #ifdef IPS_DEBUG_EN std::cout << "TX image info: "; std::cout << "rows = " << this->tx_img.rows; std::cout << " cols = " << this->tx_img.cols; std::cout << " channels = " << this->tx_img.channels() << std::endl; #endif // IPS_DEBUG_EN SC_METHOD(run); sensitive << clk.pos(); } void run() { if (this->clk.read()) { const int IMG_ROW = static_cast<int>(this->vcount.read()) - (V_SYNC_PULSE + V_BP); const int IMG_COL = static_cast<int>(this->hcount.read()) - (H_SYNC_PULSE + H_BP); #ifdef IPS_DEBUG_EN std::cout << "TX image: "; std::cout << "row = " << IMG_ROW; std::cout << " col = " << IMG_COL; #endif // IPS_DEBUG_EN if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= static_cast<int>(V_ACTIVE)) || (IMG_COL >= static_cast<int>(H_ACTIVE))) { this->o_red.write(0); this->o_green.write(0); this->o_blue.write(0); #ifdef IPS_DEBUG_EN std::cout << " dpixel = (0,0,0) " << std::endl; #endif // IPS_DEBUG_EN } else { cv::Vec3b pixel = tx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL, 0); this->o_red.write(static_cast<sc_uint<8>>(pixel[0])); this->o_green.write(static_cast<sc_uint<8>>(pixel[1])); this->o_blue.write(static_cast<sc_uint<8>>(pixel[2])); #ifdef IPS_DEBUG_EN std::cout << " ipixel = (" << static_cast<int>(pixel[0]) << "," << static_cast<int>(pixel[1]) << "," << static_cast<int>(pixel[2]) << ")" << std::endl; #endif // IPS_DEBUG_EN } } } }; #endif // IPS_SEQ_ITEM_AMS_HPP
#include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU24 : public rand_obj { randv< sc_bv<2> > op ; randv< sc_uint<24> > a, b ; ALU24() : op(this), a(this), b(this) { constraint ( (op() != 0x0) || ( 16777215 >= a() + b() ) ); constraint ( (op() != 0x1) || ((16777215 >= a() - b()) && (b() <= a()) ) ); constraint ( (op() != 0x2) || ( 16777215 >= a() * b() ) ); constraint ( (op() != 0x3) || ( b() != 0 ) ); } friend std::ostream & operator<< (std::ostream & o, ALU24 const & alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b ; return o; } }; int sc_main (int argc, char** argv) { boost::timer timer; ALU24 c; c.next(); std::cout << "first: " << timer.elapsed() << "\n"; for (int i=0; i<1000; ++i) { c.next(); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
#include<systemc.h> #include<vector> #include "interfaces.hpp" #include<nana/gui/widgets/listbox.hpp> using std::vector; class instruction_queue: public sc_module { public: sc_port<read_if> in; sc_port<write_if_f> out; SC_HAS_PROCESS(instruction_queue); instruction_queue(sc_module_name name, vector<string> inst_q, nana::listbox &instr); void main(); private: unsigned int pc; vector<string> instruct_queue; nana::listbox &instructions; };
#include <time.h> #include "systemc.h" #ifndef SC_FAULT_INJECT_HPP #define SC_FAULT_INJECT_HPP /** Representation of variable to be upset. */ struct fault_injectable_variable_t { char *name; // name uint8_t *ptr; // pointer to variable uint32_t size; // size uint32_t rand_threshold; // probability of fault per byte uint32_t fault_count; // fault injection count uint32_t pos_fault_count; // possible fault injection count }; /** Class to inject faults into registered variables. */ class sc_fault_injector; // forward declaration for global singleton class sc_fault_injector { public: /** Global singleton instance. */ static sc_fault_injector injector; /** Initializer specifying output file. */ static void init(double step_size, sc_time_unit time_unit) { injector._step_size = step_size; injector._step_unit = time_unit; } /** Configure maximum and minimum probability bounds. Default is 1.0f and 0.0f. */ static void configure_bounds(float max_prob, float min_prob) { if (max_prob > 1.0f) max_prob = 1.0f; if (min_prob < 0.0f) min_prob = 0.0f; injector._max_prob = max_prob; injector._min_prob = min_prob; } /** * Register a variable for fault injection. * * @param value The variable into which inject faults. * @param prob The probability of fault per byte per simulation step when running `simulate`. In mathematical terms, the total probability looks like: `prob` faults/step / (`_step_size`*`_step_unit` s/step) = `prob` / (`_step_size`*`_step_unit`) faults/s. * @param name The display name of the variable. */ template <class T> static void set_injectable(T& value, float prob = 0.01f, char* name = NULL) { set_injectable_ptr<T>(&value, 1, prob, name); } /** * Register a variable array for fault injection. * * @param value The variable into which inject faults. * @param n The number of variables in the array. * @param prob The probability of fault per byte per simulation step when running `simulate`. In mathematical terms, the total probability looks like: `prob` faults/step / (`_step_size`*`_step_unit` s/step) = `prob` / (`_step_size`*`_step_unit`) faults/s. * @param name The display name of the variable. */ template <class T> static void set_injectable_ptr(T* value, uint32_t n, float prob = 0.01f, char* name = NULL) { // check bounds if (prob > injector._max_prob) prob = injector._max_prob; if (prob < injector._min_prob) prob = injector._min_prob; // generate structure fault_injectable_variable_t registration; registration.name = name; registration.ptr = (uint8_t*)value; registration.size = sizeof(T) * n; registration.rand_threshold = (uint32_t)(prob * (double)((uint32_t)0xffffffff)); // compute integer value for threshold registration.fault_count = 0; registration.pos_fault_count = 0; injector._var_list.push_back(registration); } /** Run the simulation, stepping `_step_size` `_step_unit` before testing for injection. Returns the duration. */ static sc_time simulate(double max_time = -1.0) { srand(time(0)); double time = 0.0; sc_time start_time = sc_time_stamp(); while (injector._enabled) { // simulate a step sc_start(injector._step_size, injector._step_unit); time += injector._step_size; // check if done if ((max_time > 0.0 && time >= max_time) || !sc_pending_activity_at_current_time()) { break; } if (!injector._enabled) continue; // if enabled, inject faults into registration list uint32_t rand_val; uint8_t fault_bit; for (fault_injectable_variable_t &var : injector._var_list) { uint8_t *ptr = var.ptr; uint32_t n_bytes = var.size; while (n_bytes) { // probability of random fault rand_val = (uint32_t)rand(); if (rand_val < var.rand_threshold) { var.pos_fault_count++; // determine which bit to upset fault_bit = rand_val & 0x7; fault_bit = 0b1 << fault_bit; // perform mask if ((uint32_t)rand() & 0x8) { // 50% chance of possible 0 --> 1 fault if (!(*ptr & fault_bit)) var.fault_count++; *ptr |= fault_bit; } else { // 50% chance of possible 1 --> 0 fault if (*ptr & fault_bit) var.fault_count++; *ptr ^= fault_bit; } } // increment counter n_bytes--; ptr++; } //std::cout << var.name << " has a fault count of " << var.fault_count << " and a possible fault count of " << var.pos_fault_count << std::endl; } } // if never started (stepper disabled), run until completion if (time == 0.0) { sc_start(); } sc_time stop_time = sc_time_stamp(); // print report print(); // return duration return stop_time - start_time; } /** Disable tracing. */ static void disable() { injector._enabled = false; } /** Enable tracing. */ static void enable() { injector._enabled = true; } static void print() { uint32_t total_faults = 0; uint32_t total_size = 0; for (fault_injectable_variable_t &var : injector._var_list) { total_faults += var.fault_count; total_size += var.size; } std::cout << "Total of " << total_faults << " faults over " << total_size << " bytes." << std::endl; } private: /** Enable switch. */ bool _enabled = true; /** Bounds. */ float _max_prob = 1.0f; float _min_prob = 0.0f; /** Simulation step size. */ double _step_size = 10; sc_time_unit _step_unit = SC_NS; /** Internal list. */ std::vector<fault_injectable_variable_t> _var_list; }; #endif // SC_FAULT_INJECT_HPP
#pragma once #include<string> #include<systemc.h> using std::string; class write_if_f: virtual public sc_interface { public: virtual void write(string) = 0; virtual void nb_write(string) = 0; }; class read_if_f: virtual public sc_interface { public: virtual void read(string &) = 0; virtual void nb_read(string &) = 0; virtual void notify() = 0; }; class write_if: virtual public sc_interface { public: virtual void write(string) = 0; }; class read_if: virtual public sc_interface { public: virtual void read(string &) = 0; };
#ifndef TOP_HPP #define TOP_HPP #include <systemc.h> #include "scheduler.hpp" #include "processing_engine.hpp" #include "verbose.hpp" #define CORE_BIND(NAME, INDEX) \ NAME.clk(clk); \ NAME.reset(reset); \ NAME.from_scheduler_instructions(npu_instructions[INDEX]); \ NAME.from_scheduler_weight(npu_weight[INDEX]); \ NAME.from_scheduler_input(npu_input[INDEX]); \ NAME.to_scheduler(npu_output[INDEX]); class top_module : public sc_core::sc_module { public: sc_in<bool> clk; sc_in<bool> reset; // IO sc_fifo_in< sc_uint<64> > dma_config; sc_fifo_in<float> dma_weight; sc_fifo_in<float> dma_input; sc_fifo_out<float> dma_output; sc_fifo<sc_uint<34>> npu_instructions[CORE]; sc_fifo<float> npu_weight[CORE]; sc_fifo<float> npu_input[CORE]; sc_fifo<float> npu_output[CORE]; // Modules scheduler_module mod_scheduler; // Cores #if CORE == 8 processing_engine_module mod_core_1; processing_engine_module mod_core_2; processing_engine_module mod_core_3; processing_engine_module mod_core_4; processing_engine_module mod_core_5; processing_engine_module mod_core_6; processing_engine_module mod_core_7; processing_engine_module mod_core_8; #elif CORE == 4 processing_engine_module mod_core_1; processing_engine_module mod_core_2; processing_engine_module mod_core_3; processing_engine_module mod_core_4; #elif CORE == 2 processing_engine_module mod_core_1; processing_engine_module mod_core_2; #elif CORE == 1 processing_engine_module mod_core_1; #endif top_module(sc_module_name name); SC_HAS_PROCESS(top_module); }; #endif
#ifndef IPS_VGA_TLM_HPP #define IPS_VGA_TLM_HPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "common_func.hpp" #include "important_defines.hpp" #include "vga.hpp" #include "../src/img_target.cpp" // Extended Unification TLM struct vga_tlm : public vga< IPS_BITS, IPS_H_ACTIVE, IPS_H_FP, IPS_H_SYNC_PULSE, IPS_H_BP, IPS_V_ACTIVE, IPS_V_FP, IPS_V_SYNC_PULSE, IPS_V_BP >, public img_target { protected: unsigned char* tmp_img; public: vga_tlm(sc_module_name name) : vga< IPS_BITS, IPS_H_ACTIVE, IPS_H_FP, IPS_H_SYNC_PULSE, IPS_H_BP, IPS_V_ACTIVE, IPS_V_FP, IPS_V_SYNC_PULSE, IPS_V_BP>((std::string(name) + "_HW_block").c_str()), img_target((std::string(name) + "_target").c_str()) { #ifdef DISABLE_VGA_DEBUG this->use_prints = false; #endif // DISABLE_VGA_DEBUG checkprintenableimgtar(use_prints); } // Override do_when_transaction functions virtual void do_when_read_transaction(unsigned char *&data, unsigned int data_length, sc_dt::uint64 address); virtual void do_when_write_transaction(unsigned char *&data, unsigned int data_length, sc_dt::uint64 address); }; #endif // IPS_VGA_TLM_HPP
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #pragma once #define SC_INCLUDE_FX #include <systemc.h> #include "DMA_data_types.h" #include "score_lib.h" #include <list> #include <algorithm> #include <math.h> class monitor_logger { static std::vector<sc_time> &getInEList() { static std::vector<sc_time> _ingressEvent; return _ingressEvent; } static std::vector<sc_time> &getEgEList() { static std::vector<sc_time> _egressEvent; return _egressEvent; } public: static void ingressEvent() { getInEList().push_back(sc_time_stamp()); } static void egressEvent() { getEgEList().push_back(sc_time_stamp()); } static void measure_log() { std::vector<sc_time> delta; std::vector<sc_time> delta_in; std::vector<sc_time> delta_eg; sc_time min = SC_ZERO_TIME; sc_time max = SC_ZERO_TIME; sc_time min_in = SC_ZERO_TIME; sc_time max_in = SC_ZERO_TIME; sc_time min_eg = SC_ZERO_TIME; sc_time max_eg = SC_ZERO_TIME; for(int i=0;i < getEgEList().size();i++) { sc_time tmp; if(i!=0) { tmp = getInEList()[i]-getInEList()[i-1]; delta_in.push_back(tmp); if(min_in == SC_ZERO_TIME || tmp < min_in) min_in = tmp; if(max_in == SC_ZERO_TIME || tmp > max_in) max_in = tmp; tmp = getEgEList()[i]-getEgEList()[i-1]; delta_eg.push_back(tmp); if(min_eg == SC_ZERO_TIME || tmp < min_eg) min_eg = tmp; if(max_eg == SC_ZERO_TIME || tmp > max_eg) max_eg = tmp; } tmp = getEgEList()[i]-getInEList()[i]; delta.push_back(tmp); if(min == SC_ZERO_TIME || tmp < min) min = tmp; if(max == SC_ZERO_TIME || tmp > max) max = tmp; } sc_time avg = SC_ZERO_TIME; sc_time avg_in = SC_ZERO_TIME; sc_time avg_eg = SC_ZERO_TIME; for(int i = 0; i < delta_in.size();i++) { avg_in += delta_in[i]; avg_eg += delta_eg[i]; } avg_in = avg_in / delta_in.size(); avg_eg = avg_eg / delta_eg.size(); for(int i = 0; i < delta.size();i++) { avg += delta[i]; } avg = avg / delta.size(); std::cout << "measure log:" << std::endl; std::cout << "latency: [min , avg , max]: [" << (min) << " , " << (avg) << " , " << (max) <<"]" << std::endl; std::cout << "interval ingress: [min , avg , max]: [" << (min_in) << " , " << (avg_in) << " , " << (max_in) <<"]" << std::endl; std::cout << "interval egress: [min , avg , max]: [" << (min_eg) << " , " << (avg_eg) << " , " << (max_eg) <<"]" << std::endl; } }; SC_MODULE(waveform) { sc_in<bool> clk; sc_out<bool> reset; sc_fifo_out<DATA1024_t > source; SC_CTOR(waveform) { SC_CTHREAD(waveform_thread,clk.pos()); } void waveform_thread() { DATA1024_t tmp; tmp.data = 0; tmp.tlast = 0; reset.write(true); float numberGen = 0; while(true) { wait(); reset.write(false); for(int i=0;i<10;i++) { wait(); if(i==10-1) { tmp.tlast = 1; cout << "sending TLAST signal" << endl; } else { tmp.tlast = 0; } if(i==0) monitor_logger::ingressEvent(); source.write(tmp); //while(source.num_free() != 0) {wait();} for(int i=0;i<64;i++) { sc_fixed<16,8> fx = sin(numberGen)*120.1f; //sc_signed us_tmp(fx.wl()); //us_tmp = (fx << (fx.wl()-fx.iwl())); //tmp.data((16-1) + (16*i),16*i) = (sc_bv<16>)us_tmp; tmp.data((16-1) + (16*i),16*i) = fixed2bv<16,8>(fx); sc_bv<16> tmpCheckRaw = (sc_bv<16>)tmp.data((16-1) + (16*i),16*i); sc_fixed<16,8> tmpCheck = bv2fixed<16,8>(tmpCheckRaw); if(fx != tmpCheck) { sc_stop(); std::cout << "(casting error) got: " << fx << " != " << tmpCheck << std::endl ;//<< " (RAW: " << us_tmp << ")" << std::endl; } else { //std::cout << "(casting OK) got: " << fx << " != " << tmpCheck << std::endl; } numberGen += 0.1; } } } } }; SC_MODULE(monitor) { sc_in<bool> clk; sc_in<bool> reset; sc_fifo_in<DATA32_t > sink; std::ofstream ofs; SC_CTOR(monitor) :ofs("test.txt", std::ofstream::out) { SC_CTHREAD(monitor_thread,clk.pos()); reset_signal_is(reset,true); } ~monitor() { ofs.close(); } void monitor_thread() { DATA32_t tmp; unsigned countdown = 30; while(true) { sink.read(tmp); monitor_logger::egressEvent(); //std::string tmp_string = "PKGnr is: " + std::to_string((unsigned)count.read().to_uint()) + "TDATA: " + std::to_string((unsigned long)tmp.data.to_uint());// + " @ " + sc_time_stamp(); //ofs << "@" << sc_time_stamp() << "last: " << tmp.tlast; //SC_REPORT_WARNING(::SC_ID_ASSERTION_FAILED_, tmp_string.c_str()); //sc_report(true); sc_signed ss_tmp(32); ss_tmp = tmp.data; sc_fixed<32,16> tmpCheck = ((sc_fixed<32*2,16*2>)ss_tmp)>>16; cout << "TDATA: " << tmpCheck << " @ " << sc_time_stamp() << endl; if(tmp.tlast==1) { //clog << "test2" << sc_time_stamp() << endl; //cerr << "test" << sc_time_stamp() << endl; cout << "got TLAST signal @ " << sc_time_stamp() << endl; } countdown--; if(countdown==0) { cout << "sc_stop signal" << endl; sc_stop(); monitor_logger::measure_log(); } } } };
// Copyright (c) 2011-2024 Columbia University, System Level Design Group // SPDX-License-Identifier: MIT #ifndef __ESP_HANDSHAKE_HPP__ #define __ESP_HANDSHAKE_HPP__ #if defined(USE_CYNW_P2P) // Using cynw_p2p library #include "cynw_p2p.h" // Forward declaration class handshake_t; // Handshake request class handshake_req_t { public: // Friend zone friend class handshake_t; // Constructor handshake_req_t(sc_module_name name) : __req(name) { } // Clock and reset binding template<typename CLK, typename RST> void clk_rst(CLK& clk, RST& rst) { __req.clk_rst(clk,rst); } // Reset method void reset_req() { __req.reset(); } // Req method void req() { __req.get(); } private: // Request channel cynw_p2p<bool>::in __req; }; // Handshake acknowledge class handshake_ack_t { public: // Friend zone friend class handshake_t; // Constructor handshake_ack_t(sc_module_name name) : __ack(name) { } // Clock and reset binding template<typename CLK, typename RST> void clk_rst(CLK& clk, RST& rst) { __ack.clk_rst(clk,rst); } // Reset method void reset_ack() { __ack.reset(); } // Ack method void ack() { __ack.put(true); } private: // Ack channel cynw_p2p<bool>::out __ack; }; // Handshake interface class handshake_t { public: // Constructor handshake_t(sc_module_name name) : req(std::string(name).append("_req").c_str()), ack(std::string(name).append("_ack").c_str()), __channel(name) { req.__req.bind(__channel); ack.__ack.bind(__channel); } template < size_t _DMA_WIDTH_ > inline void bind_with(esp_accelerator<_DMA_WIDTH_> &accelerator) { req.clk_rst(accelerator.clk, accelerator.rst); ack.clk_rst(accelerator.clk, accelerator.rst); } // Req and ack handshake_req_t req; handshake_ack_t ack; private: // Channel cynw_p2p<bool> __channel; }; #else // Using initiators (default) #include "esp_systemc.hpp" // Forward declaration class handshake_t; // Handshake request class handshake_req_t { public: // Friend zone friend class handshake_t; // Constructor handshake_req_t(sc_module_name name) : __req(name) { } // Clock and reset binding template<typename CLK, typename RST> void clk_rst(CLK& clk, RST& rst) { __req.clk_rst(clk,rst); } // Reset method void reset_req() { __req.reset_get(); } // Req method void req() { __req.get(); } private: // Request channel b_get_initiator<bool> __req; }; // Handshake acknowledge class handshake_ack_t { public: // Friend zone friend class handshake_t; // Constructor handshake_ack_t(sc_module_name name) : __ack(name) { } // Clock and reset binding template<typename CLK, typename RST> void clk_rst(CLK& clk, RST& rst) { __ack.clk_rst(clk,rst); } // Reset method void reset_ack() { __ack.reset_put(); } // Ack method void ack() { __ack.put(true); } private: // Ack channel b_put_initiator<bool> __ack; }; // Interface class handshake_t { public: // Constructor handshake_t(sc_module_name name) : req(std::string(name).append("_req").c_str()), ack(std::string(name).append("_ack").c_str()), __channel(name) { req.__req.bind(__channel); ack.__ack.bind(__channel); } template < size_t _DMA_WIDTH_ > inline void bind_with(esp_accelerator<_DMA_WIDTH_> &accelerator) { req.clk_rst(accelerator.clk, accelerator.rst); ack.clk_rst(accelerator.clk, accelerator.rst); } // Req and ack handshake_req_t req; handshake_ack_t ack; private: // Channel put_get_channel<bool> __channel; }; #endif #endif // __ESP_HANDSHAKE_HPP__
/***************************************************************************\ * * * ___ ___ ___ ___ * / /\ / /\ / /\ / /\ * / /:/ / /::\ / /::\ / /::\ * / /:/ / /:/\:\ / /:/\:\ / /:/\:\ * / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/ * / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/ * /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/ * \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/ * \ \:\ \ \:\ \ \:\ \ \:\ * \ \ \ \ \:\ \ \:\ \ \:\ * \__\/ \__\/ \__\/ \__\/ * * * * * This file is part of TRAP. * * TRAP is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * or see <http://www.gnu.org/licenses/>. * * * * (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com * \***************************************************************************/ #ifndef MEMORYLT_HPP #define MEMORYLT_HPP #include <systemc.h> #include <tlm.h> #include <tlm_utils/simple_target_socket.h> #include <boost/lexical_cast.hpp> #include <string> #include <map> #include <trap_utils.hpp> namespace trap{ template<unsigned int N_INITIATORS, unsigned int sockSize> class SparseMemoryLT: public sc_module{ public: tlm_utils::simple_target_socket<SparseMemoryLT, sockSize> * socket[N_INITIATORS]; SparseMemoryLT(sc_module_name name, unsigned int size, sc_time latency = SC_ZERO_TIME) : sc_module(name), latency(latency){ for(int i = 0; i < N_INITIATORS; i++){ this->socket[i] = new tlm_utils::simple_target_socket<SparseMemoryLT, sockSize>(("mem_socket_" + boost::lexical_cast<std::string>(i)).c_str()); this->socket[i]->register_b_transport(this, &SparseMemoryLT::b_transport); this->socket[i]->register_get_direct_mem_ptr(this, &SparseMemoryLT::get_direct_mem_ptr); this->socket[i]->register_transport_dbg(this, &SparseMemoryLT::transport_dbg); } end_module(); } ~SparseMemoryLT(){ for(int i = 0; i < N_INITIATORS; i++){ delete this->socket[i]; } } void b_transport(tlm::tlm_generic_payload& trans, sc_time& delay){ tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); unsigned char* ptr = trans.get_data_ptr(); unsigned int len = trans.get_data_length(); unsigned char* byt = trans.get_byte_enable_ptr(); unsigned int wid = trans.get_streaming_width(); if(byt != 0){ trans.set_response_status(tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE); return; } if(cmd == tlm::TLM_READ_COMMAND){ for(int i = 0; i < len; i++, ptr++) *ptr = this->mem[adr + i]; } else if(cmd == tlm::TLM_WRITE_COMMAND){ for(int i = 0; i < len; i++, ptr++) this->mem[adr + i] = *ptr; } // Use temporal decoupling: add memory latency to delay argument delay += this->latency; trans.set_dmi_allowed(false); trans.set_response_status(tlm::TLM_OK_RESPONSE); } // TLM-2 DMI method bool get_direct_mem_ptr(tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data){ // Deny read and write access dmi_data.allow_read_write(); dmi_data.set_start_address(0); dmi_data.set_end_address((sc_dt::uint64)-1); return false; } // TLM-2 debug transaction method unsigned int transport_dbg(tlm::tlm_generic_payload& trans){ tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); unsigned char* ptr = trans.get_data_ptr(); unsigned int len = trans.get_data_length(); if(cmd == tlm::TLM_READ_COMMAND){ for(int i = 0; i < len; i++, ptr++) *ptr = this->mem[adr + i]; } else if(cmd == tlm::TLM_WRITE_COMMAND){ for(int i = 0; i < len; i++, ptr++) this->mem[adr + i] = *ptr; } return len; } //Method used to directly write a word into memory; it is mainly used to load the //application program into memory inline void write_byte_dbg(const unsigned int & address, const unsigned char & datum) throw(){ this->mem[address] = datum; } private: const sc_time latency; std::map<unsigned int, unsigned char> mem; }; }; #endif
/* * readwrite_if.hpp * * Created on: Jun 14, 2014 * Author: Pimenta */ #ifndef READWRITE_IF_HPP_ #define READWRITE_IF_HPP_ // lib #include <systemc.h> struct readwrite_if : public sc_module, public sc_interface { protected: uint32_t start_addr; public: readwrite_if(uint32_t start_addr); uint32_t start_address(); virtual uint32_t size() = 0; virtual void read(uint32_t src, uint32_t bytes, void* dst) = 0; virtual void write(uint32_t dst, uint32_t bytes, void* src) = 0; }; #endif /* READWRITE_IF_HPP_ */
/* * Copyright (C) 2024 Commissariat à l'énergie atomique et aux énergies alternatives (CEA) * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CACHEBASE_HPP #define CACHEBASE_HPP #include <map> #include <unordered_map> #include <unordered_set> #include <list> #include <deque> #include <bitset> #include <iostream> #include "systemc.h" #include "CacheLine.hpp" #include "CacheSet.hpp" #include "CoherenceExtension.hpp" using namespace std; //! //! Recursive template function Log2 provides the Log2 value of its template parameter N at compilation time //! @tparam N the integer whose Log2 value is being evaluated //! @tparam P the temporary count of number of division by 2 propagated throughout recursive calls //! template<int N,uint64_t P=0> struct _Log2 { enum { value = _Log2<N/2,P+1>::value }; }; //! //! Log2<0, p> is a partial template specialization of log2<N,P> used as terminal of the recursion //! It is the case where N reaches 0 (no longer divisable by 2), hence the number of division by 2 (P) is the Log2 value we return //! template <uint64_t P> struct _Log2<0, P> { enum { value = P }; }; //! //! Log2<1, p> is a partial template specialization of log2<N,P> used as terminal of the recursion //! It is the case where N reaches 1 (no longer divisable by 2), hence the number of division by 2 (P) is the Log2 value we return //! template <uint64_t P> struct _Log2<1, P> { enum { value = P }; }; constexpr uint64_t log2(uint64_t n){ return n < 2 ? 0 : 1 + log2(n / 2); } namespace vpsim{ //! //! All write policies for caches //! enum CacheWritePolicy { WThrough, //!< Write-through policy (always forward write to next level cache) WBack //!< Write-back policy (forward write to next level cache only when line get removed from cache) }; //! //! All allocation policies for caches //! enum CacheAllocPolicy { WAllocate, //!< Write-allocate (do allocate data in cache for write that do miss) WAround //!< Write-around (do not allocate data in cache for write that do miss) }; //! //! All inclusion policies for caches //! enum CacheInclusionPolicy { NINE, Inclusive, //!< Contains a copy of cache lines of the higher-level cache, not valid for L1 Exclusive //!< Victim cache for the higher-level cache, not valid for L1 }; //enum CacheAccessMode { Read, Write, Evict, Invalidate }; enum CacheLevel { LOne, // L1, emits requests only to lower-lvel caches Ln, // Intermediate cache level, emits requests to lower- and higher-level caches LLC // Least-level cache, emits requests only to higher-level caches }; //! //! Generic cache structure that supports the following template parameters //! @tparam AddressType the type of the addresses that the cache shall use (e.g uint64_t) //! @tparam CacheSize the total size in Bytes of the cache in terms of storage. CacheSize impacts the number of lines in the cache //! @tparam CacheLineSize the size (in Bytes) of each line of data in the cache //! @tparam Associativity the associativity degree of the cache. An Associativity shall be >0, Associativity of 1 stands for direct mapped cache //! Increasing the Associativity does not increase the size of the cache. //! @tparam ReplPolicy the replacement policy of the cache (defaults to LRU, other values are not implemented yet) //! @tparam WritePolicy the write policy of the cache (defaults to write-back) //! @tparam AllocPolicy the allocation policy of the cache (defaults to write Allocate) //! //class template template <typename AddressType, typename WordType, bool WCETMode=false> class CacheBase : public sc_module { protected : // address bits // the address to a Bytes is of size [AddressBits] that can be decomposed in several fields [TagBits|IndexBits|OffsetBits] uint64_t AddressBits; //!< number of bits composing a data address in the cache uint64_t OffsetBits; //!< number of bits necessary to address a specific byte within a given CacheLine uint64_t IndexBits; //!< number of bits necessary to address a specific cache set uint64_t TagBits; //!< number of bits to be stored as tags to uniquely identify a CacheLine from within a set //address masks uint64_t OffsetMask; //!< mask for the leastx-significant OffsetBits bits in a full AddressType uint64_t IndexMask; //!< mask for the least-significant IndexBits bits in a full AddressType uint64_t TagMask; //!< mask for the least-significant TagBits bits in a full AddressType //address Shifts uint64_t IndexShift; //!< offset of the Index bits in the AddressType uint64_t TagShift; //!< offset of the tag bits in the AddressType uint64_t CacheLineSize; uint64_t CacheSize; bool IsCoherent; bool NotifyEvictions; void (*NotifyEviction) (void* hdl); private : typedef CacheLine<AddressType> CacheLineType; //!< specialization of CacheLine to the cache data types for easier line manipulation typedef CacheSet<CacheLineType, AddressType> CacheSetState; //!< structure representing the state of a CacheSet typedef vector<CacheSetState> CacheState; //!< structure representing the state of a CacheBase, i.e. the state of all its CacheSet(s) CacheState CacheLines; //!< the current state of the CacheBase uint64_t NbLines; //!< number of cache lines in the cache uint64_t NbSets; //!< the number of sets in the cache // indeed associativity = NbLinesPerSet // For WCET // AbstractCacheState<AddressType,Associativity> acs[NbSets]; // ACSImage acs; // unordered_set<AddressType> touched_sets; bool DataSupport; uint32_t Level; bool IsHome = false; uint64_t Associativity; CacheReplacementPolicy ReplPolicy; CacheWritePolicy WritePolicy; CacheAllocPolicy AllocPolicy; //uint64_t MaxLineSharers; //typedef uint64_t SharerIds [MaxLineSharers]; typedef set<idx_t> SharerIds; struct DirectoryEntry { CoherenceState State; idx_t Owner; SharerIds Sharers; }; map<AddressType, DirectoryEntry> Directory; // Directory[3] = {Invalid, NULL_IDX, {0, 0, 0, 0} }; map<AddressType, SharerIds> Sharers; public : uint64_t MissCount, HitCount, NReads, NWrites, NInvals, NTotalInvals, NBackInvals, NEvicts, WriteBacks, EvictBacks, HitReads, HitWrites, MissReads, MissWrites, NPutS, NPutM, NPutI, NGetS, NGetM, NFwdGetS, NFwdGetM, ReadBacks; CacheInclusionPolicy InclusionOfHigher, InclusionOfLower; idx_t IdTest; //! //! constructor of CacheBase //! @param name a unique sc_module_name identifying the CacheBase module //! CacheBase(sc_module_name name, uint64_t cacheSize, uint64_t cacheLineSize, uint64_t associativity, CacheReplacementPolicy replPolicy = LRU, CacheWritePolicy writePolicy = WBack, CacheAllocPolicy allocPolicy = WAllocate, bool dataSupport = false, uint32_t level = 1, CacheInclusionPolicy inclusionOfHigher = NINE, CacheInclusionPolicy inclusionOfLower = NINE, bool isHome = false, bool isCoherent = false, idx_t id = NULL_IDX) : sc_module (name) , CacheLineSize (cacheLineSize) , CacheSize (cacheSize) , IsCoherent (isCoherent) , NotifyEvictions(false) , DataSupport (dataSupport) , Level (level) , IsHome (isHome) , Associativity (associativity) , ReplPolicy (replPolicy) , WritePolicy (writePolicy) , AllocPolicy (allocPolicy) , MissCount (0) , HitCount (0) , InclusionOfHigher (inclusionOfHigher) , InclusionOfLower (inclusionOfLower) , IdTest (id) //, MaxLineSharers (maxLineSharers) { NbLines = CacheSize / CacheLineSize; //!< number of cache lines in the cache NbSets = NbLines / Associativity; //!< the number of sets in the cache // indeed associativity = NbLinesPerSet assert (Associativity <= NbLines); // associativity cannot be greater than the number of lines //address bits // the address to a Bytes is of size [AddressBits] that can be decomposed in several fields [TagBits|IndexBits|OffsetBits] AddressBits = sizeof(AddressType) * 8; //!< number of bits composing a data address in the cache OffsetBits = (log2 (CacheLineSize)); //!< number of bits necessary to address a specific byte within a given CacheLine IndexBits = (log2 (NbSets)); //!< number of bits necessary to address a specific cache set TagBits = AddressBits - IndexBits - OffsetBits; //!< number of bits that are to be stored as tags to uniquely identify a CacheLine from within a set //address masks OffsetMask = (1ULL<<OffsetBits)-1; //!< mask for the least-significant OffsetBits bits in a full AddressType IndexMask = (1ULL<<IndexBits)-1; //!< mask for the least-significant IndexBits bits in a full AddressType TagMask = (1ULL<<TagBits)-1; //!< mask for the least-significant TagBits bits in a full AddressType //address Shifts IndexShift = OffsetBits; //!< offset of the Index bits in the AddressType TagShift = IndexBits+OffsetBits; //!< offset of the tag bits in the AddressType assert (ReplPolicy == LRU || !WCETMode); CacheLines.resize(NbSets); for (auto& set: CacheLines) set = CacheSet <CacheLineType, AddressType> (CacheLineSize, Associativity, ReplPolicy/*, higherCachesNb*/); cout << "Cache parameters: " << endl; cout << "Address bits: " << AddressBits << endl; cout << "Offset bits : " << OffsetBits << endl; cout << "IndexBits : " << IndexBits << endl; //cout << "TagBits : " << TagBits << endl; cout << "Nb sets : " << NbSets << endl; cout << "Cache size : " << CacheSize << endl; //cout << "NbLines : " << NbLines << endl; cout << "Line size : " << CacheLineSize << endl; cout << "Is a home : " << IsHome << endl; NReads = NWrites = NInvals = NTotalInvals = NBackInvals = NEvicts = WriteBacks = EvictBacks = 0; NPutS = NPutM = NPutI = NGetS = NGetM = NFwdGetS = NFwdGetM = ReadBacks = 0; } //! //! Default destructor that displays stats for CacheBase upon destruction //! ~CacheBase() { displayStats(); } void SetEvictionNotifier(void(*ev)(void*)) { NotifyEvictions=true; NotifyEviction=ev; } template<CoherenceCommand accessMode> tlm::tlm_response_status accessNonCoherentCache (unsigned char* src_data_ptr, size_t size, AddressType addr, idx_t id, sc_time& delay, sc_time timestamp, void* handle=nullptr) { uint64_t offset = addr & OffsetMask; uint64_t index = (addr>>IndexShift) & IndexMask; uint64_t tag = (addr>>TagShift) & TagMask; tlm::tlm_response_status stat = tlm::TLM_OK_RESPONSE; CacheSetState& set = CacheLines [index]; CacheLineType* line; bool isHit = set.accessSet (tag, &line); bool alignment; size_t accessSize; assert (!isHit||line->getState()!=Invalid); if (((Level==1)&&((accessMode==Read)||(accessMode==Write))) || ((Level!=1)&&(accessMode==Read))) { if (isHit) HitCount++; else MissCount++; } if (!isHit && line->getState() == Shared) { //if (line->getState()!=Invalid) { if (NotifyEvictions) { this->NotifyEviction(line->handle); } } if (accessMode==Invalidate) { // No replacement NTotalInvals++; if (isHit) { if (line->getState()==Modified) stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Invalid); NInvals++; } } else if (accessMode==ReadBack) { assert (isHit); ReadBacks++; //cacheMemcpy (src_data_ptr, line->getDataPtr()+addr-line->getAddress(), accessSize); } else if (!isHit && InclusionOfHigher==Exclusive && accessMode==Read) { assert(Level!=1); // addr is the line base address NReads++; if (Sharers.find(addr)!=Sharers.end() && Sharers[addr].size()!=0) stat = BackwardRead (src_data_ptr, addr, CacheLineSize, Sharers[addr], delay, timestamp); else stat = ForwardReadData (src_data_ptr, addr, CacheLineSize, delay, timestamp); Sharers[addr].insert(id); return stat; //"return" & multiline accesses: "return" can be used safely here since size=CacheLineSize if Level>1 } else { assert (!isHit||(line->getAddress()<=addr && addr-line->getAddress()<CacheLineSize)); // Write Back if (!isHit && line->getState()==Modified && WritePolicy==WBack) { WriteBacks++; stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Invalid); } // Eviction, assumes exclusive policy with lower cache if (!isHit && line->getState()==Shared && InclusionOfLower==Exclusive) { // assumes WBack policy stat = ForwardEvict (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); EvictBacks++; } // Invalidation, assumes inclusive policy with higher cache if (InclusionOfHigher==Inclusive && !isHit && Sharers[line->getAddress()].size()!=0) { //stat = BackInvalidate (line->getAddress(), delay); stat = BackInvalidate (line->getAddress(), Sharers[line->getAddress()], delay, timestamp); Sharers[line->getAddress()].clear(); NBackInvals++; } // Prepare new line on miss if (!isHit && AllocPolicy==WAllocate) { line->setNewLine(addr-offset, tag); line->handle = handle; } // Check and resolve non-aligned requests alignment = (addr-line->getAddress()+size) > CacheLineSize; // once a new line is set on miss if (alignment) accessSize = CacheLineSize-(addr-line->getAddress()); else accessSize = size; assert (accessSize>=0); assert (accessSize<=CacheLineSize); switch (accessMode) { case Read: assert(InclusionOfHigher!=Exclusive||isHit); Sharers[line->getAddress()].insert(id); if (!isHit) { stat = ForwardReadData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); // get data from memory line->setState(Shared); } else if (InclusionOfHigher==Exclusive){ line->setState(Invalid); } cacheMemcpy (src_data_ptr, line->getDataPtr()+addr-line->getAddress(), accessSize); NReads++; break; case Write: Sharers[line->getAddress()].erase(id); if (InclusionOfHigher==Exclusive && !isHit) { if (Sharers.find(line->getAddress())!=Sharers.end() && Sharers[line->getAddress()].size()!=0) { line->setState(Invalid); } else { stat = ForwardReadData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); cacheMemcpy (line->getDataPtr()+addr-line->getAddress(), src_data_ptr, accessSize); line->setState(Modified); } } else { if (WritePolicy==WThrough) // Forward to next level stat = ForwardWriteData (line->getDataPtr(), addr, accessSize/*sizeof(WordType)*/, delay, timestamp); else { // WritePolicy==WBack if(!isHit) stat = ForwardReadData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); // Get line from memory cacheMemcpy (line->getDataPtr()+addr-line->getAddress(), src_data_ptr, accessSize); line->setState(Modified); } } // Inclusive, forward updated line to maintain inclusion if (InclusionOfLower==Inclusive) stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); /*if (Level != 1 && InclusionOfHigher==Exclusive) { //Sharers[line->getAddress()].erase(id); if (Sharers[line->getAddress()].size()!=0) { stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay); line->setState(Invalid); } }*/ NWrites++; break; case Evict: // From higher cache assert (InclusionOfHigher==Exclusive); cacheMemcpy (line->getDataPtr()+addr-line->getAddress(), src_data_ptr, accessSize); Sharers[line->getAddress()].erase(id); assert(!isHit||line->getState()==Modified); if (Sharers[line->getAddress()].size()!=0) line->setState(Invalid); else line->setState(Shared); NEvicts++; break; default: assert (false); break; //throw runtime_error ("Command prohibited in non-coherent mode\n"); } if (alignment) { if (src_data_ptr) stat = this->accessNonCoherentCache<accessMode> (src_data_ptr+accessSize, size-accessSize, addr+accessSize, id, delay, timestamp, handle); else stat = this->accessNonCoherentCache<accessMode> (NULL, size-accessSize, addr+accessSize, id, delay, timestamp, handle); } } return stat; } template<CoherenceCommand accessMode> tlm::tlm_response_status accessCpuCache (unsigned char* src_data_ptr, size_t size, AddressType addr, idx_t id, sc_time& delay, sc_time timestamp, void* handle=nullptr) { uint64_t offset = addr & OffsetMask; uint64_t index = (addr>>IndexShift) & IndexMask; uint64_t tag = (addr>>TagShift) & TagMask; tlm::tlm_response_status stat = tlm::TLM_OK_RESPONSE; CacheSetState& set = CacheLines [index]; CacheLineType* line; bool isHit = set.accessSet (tag, &line); bool alignment; size_t accessSize; if (accessMode==Read) { if (isHit) HitCount++; else MissCount++; } else if (accessMode==Write) { if (isHit && line->getState()==Modified) HitCount++; else MissCount++; } if (!isHit && line->getState() == Shared) { if (NotifyEvictions) this->NotifyEviction(line->handle); } assert (!isHit||(line->getAddress()<=addr && addr-line->getAddress()<CacheLineSize)); // Proceed Non-allocating requests switch (accessMode) { case ReadBack: assert (false); // replaced by FwdGetS break; case FwdGetS: assert (id != NULL_IDX); assert (isHit); // Shared or Modified line->setState(Shared); NFwdGetS++; return stat; break; case FwdGetM: assert (id != NULL_IDX); assert (isHit); line->setState(Invalid); NFwdGetM++; retu
rn stat; break; case PutI: assert (isHit); assert (line->getState()==Shared); line->setState(Invalid); NPutI++; return stat; break; default: break; } // Writeback dirty line to make room for allocating requests if (!isHit && line->getState()!=Invalid && WritePolicy==WBack) { WriteBacks++; switch (line->getState()) { case Modified: stat = SendPutM (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Invalid); break; case Shared: stat = SendPutS (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Invalid); break; case Invalid: assert (false); break; default: break; } } // Writeback clean line to make room for allocating requests if (!isHit && line->getState()==Shared && InclusionOfLower==Exclusive) { assert (false); // L2-exclusive is only partially supported stat = ForwardEvict (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); NEvicts++; } // Prepare new line for allocating requests if (!isHit && AllocPolicy==WAllocate) { line->setNewLine(addr-offset, tag); line->handle = handle; } assert (addr-offset==line->getAddress()); // Align multiline requests alignment = (addr-line->getAddress()+size) > CacheLineSize; // once a new line is set on miss if (alignment) accessSize = CacheLineSize-(addr-line->getAddress()); else accessSize = size; assert (accessSize>=0); // Proceed allocating requests switch (accessMode) { case Read: if (!isHit) { stat = SendGetS (line->getDataPtr(), addr-offset, CacheLineSize, delay, timestamp); // get data from lower cache line->setState(Shared); } NReads++; break; case Write: // WritePolicy==WBack if (line->getState() != Modified) { stat = SendGetM (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Modified); } NWrites++; break; default: assert(false); break; } if (alignment) { if (src_data_ptr) stat = this->accessCpuCache<accessMode> (src_data_ptr+accessSize, size-accessSize, addr+accessSize, id, delay, timestamp, handle); else stat = this->accessCpuCache<accessMode> (NULL, size-accessSize, addr+accessSize, id, delay, timestamp, handle); } return stat; } template<CoherenceCommand accessMode> tlm::tlm_response_status accessL2Cache (unsigned char* src_data_ptr, size_t size, AddressType addr, idx_t id, sc_time& delay, sc_time timestamp, void* handle=nullptr) { uint64_t offset = addr & OffsetMask; uint64_t index = (addr>>IndexShift) & IndexMask; uint64_t tag = (addr>>TagShift) & TagMask; tlm::tlm_response_status stat = tlm::TLM_OK_RESPONSE; CacheSetState& set = CacheLines [index]; CacheLineType* line; bool isHit = set.accessSet (tag, &line); bool alignment; size_t accessSize; assert (offset==0); assert (size==CacheLineSize); assert (!isHit||(line->getAddress()<=addr && addr-line->getAddress()<CacheLineSize)); assert (!isHit||addr==line->getAddress()); assert(!(isHit && line->getState()==Modified && Directory[addr].State==Modified)); if (accessMode==GetS) { if (isHit) HitCount++; else MissCount++; } else if (accessMode==GetM) { if (isHit && line->getState()==Modified) HitCount++; else MissCount++; } if (!isHit && line->getState() == Shared) { if (NotifyEvictions) this->NotifyEviction(line->handle); } // Proceed Non-allocating requests switch (accessMode) { // should be addr not line->getAddress here case FwdGetS: // In Exclusive L3, Readbacks are FwdGetSs assert (id != NULL_IDX); assert (Directory.find(addr) != Directory.end()); assert (isHit||Directory[addr].State!=Invalid); // Shared or Modified assert (InclusionOfLower==Exclusive || ((isHit&&line->getState()==Modified)||Directory[addr].State==Modified)); if (isHit && line->getState()==Modified) // on miss, line addr!=addr line->setState(Shared); if (!isHit&&Directory[addr].State==Shared) // Readback, exclusive policy stat = SendFwdGetS (src_data_ptr, addr, CacheLineSize, Directory[addr].Sharers, delay, timestamp); if (Directory[addr].State==Modified) { stat = SendFwdGetS (src_data_ptr, addr, CacheLineSize, {Directory[addr].Owner}, delay, timestamp); Directory[addr] = { Shared, NULL_IDX, {Directory[addr].Owner}}; } assert (Directory[addr].State!=Modified); assert (Directory[addr].Owner==NULL_IDX); assert (!isHit || line->getState()==Shared); NFwdGetS++; return stat; case FwdGetM: assert (id != NULL_IDX); assert (Directory.find(addr) != Directory.end()); assert((isHit&&line->getState()==Modified)||Directory[addr].State==Modified); if (isHit) line->setState(Invalid); switch (Directory[addr].State) { // Invalid clean/dirty copy in L1 case Shared: stat = SendFwdGetM (src_data_ptr, addr, CacheLineSize, {Directory[addr].Sharers}, delay, timestamp); Directory[addr] = { Invalid, NULL_IDX, {}}; break; case Modified: stat = SendFwdGetM (src_data_ptr, addr, CacheLineSize, {Directory[addr].Owner}, delay, timestamp); Directory[addr] = { Invalid, NULL_IDX, {}}; break; case Invalid: break; } NFwdGetM++; assert (Directory[addr].State==Invalid); assert (Directory[addr].Owner==NULL_IDX); assert (Directory[addr].Sharers.size()==0); assert (!isHit || line->getState()==Invalid); return stat; case PutS: // Replacement on higher cache, line being in shared state assert (Directory.find(addr) != Directory.end()); assert (Directory[addr].State==Shared); Directory[addr].Sharers.erase(id); if (Directory[addr].Sharers.size()==0) {// Last PutS Directory[addr] = { Invalid, NULL_IDX, {} }; if (!isHit) stat = SendPutS (src_data_ptr, addr, CacheLineSize, delay, timestamp); // Line is no longer in caches, update LLC } assert (Directory[addr].State!=Modified); assert (Directory[addr].Owner==NULL_IDX); //assert (Directory[addr].Sharers.size()==0); // does not hold if L2 is shared NPutS++; return stat; case PutI: assert (Directory.find(addr) != Directory.end()); assert ((isHit&&line->getState()==Shared)||Directory[addr].State==Shared); assert (!isHit||(line->getState()!=Modified&&Directory[addr].State!=Modified)); if (isHit) line->setState(Invalid); if (Directory[addr].State==Shared) { //assert (Directory[addr].Sharers.size()!=0); // redundant stat = SendPutI (src_data_ptr, addr, CacheLineSize, Directory[addr].Sharers, delay, timestamp); Directory[addr] = { Invalid, NULL_IDX, {}}; } NPutI++; assert (Directory[addr].State==Invalid); assert (Directory[addr].Owner==NULL_IDX); assert (Directory[addr].Sharers.size()==0); assert (!isHit||line->getState()==Invalid); return stat; default : break; } // Write-back victim line (clean & dirty) if (!isHit && line->getState()!=Invalid && WritePolicy==WBack) { // line=victim line != req line assert (Directory.find(line->getAddress()) != Directory.end()); //assert (line->getState()!=Modified||Directory[line->getAddress()].State!=Modified); WriteBacks++; switch (Directory[line->getAddress()].State) { case Invalid: if (line->getState()==Shared) stat = SendPutS (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); else // line state = Modified stat = SendPutM (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); break; case Shared: if (line->getState()==Modified) // TODO: Use another request type. GetS will be used for hit counting stat = SendGetS (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); break; case Modified: break; } line->setState(Invalid); } // Prepare new line on miss if (!isHit && AllocPolicy==WAllocate) { line->setNewLine(addr, tag); line->handle = handle; assert (line->getState()==Invalid); } // Proceed allocating requests switch (accessMode) { case PutM: // Replacement on higher cache, line being in modified state assert (Directory.find(line->getAddress()) != Directory.end()); switch (Directory[line->getAddress()].State) { case Invalid: assert(false); break; case Shared: // When this case occurs ? assert(false); Directory[line->getAddress()].Sharers.erase(id); if (Directory[line->getAddress()].Sharers.size()==0) // Last PutM Directory[line->getAddress()] ={ Invalid, NULL_IDX, {} }; break; case Modified: assert (id == Directory[line->getAddress()].Owner); line->setState(Modified); Directory[line->getAddress()] = { Invalid, NULL_IDX, {} }; break; } NPutM++; break; case GetS: if (Directory.find(line->getAddress()) == Directory.end()) { assert (!isHit); stat = SendGetS (line->getDataPtr(), addr, CacheLineSize, delay, timestamp); line->setState(Shared); Directory[line->getAddress()] = { Shared, NULL_IDX, {id} }; } else { switch (Directory[line->getAddress()].State) { case Invalid: if (!isHit) { stat = SendGetS (line->getDataPtr(), addr, CacheLineSize, delay, timestamp); line->setState(Shared); } Directory[line->getAddress()] = { Shared, NULL_IDX, {id} }; break; case Shared: assert (find (Directory[line->getAddress()].Sharers.begin(),Directory[line->getAddress()].Sharers.end(),id)==Directory[line->getAddress()].Sharers.end()); if (!isHit) { stat = SendFwdGetS (line->getDataPtr(), line->getAddress(), CacheLineSize, Directory[line->getAddress()].Sharers, delay, timestamp); line->setState(Shared); } Directory[line->getAddress()].Sharers.insert(id); break; case Modified: assert (id != Directory[line->getAddress()].Owner); stat = SendFwdGetS (line->getDataPtr(), line->getAddress(), CacheLineSize, {Directory[line->getAddress()].Owner}, delay, timestamp); // get updated data Directory[line->getAddress()] = {Shared, NULL_IDX, {id, Directory[line->getAddress()].Owner}}; line->setState(Modified); break; } } assert (Directory[line->getAddress()].State==Shared); assert (Directory[line->getAddress()].Owner==NULL_IDX); assert (Directory[line->getAddress()].Sharers.size()!=0); NGetS++; break; case GetM: if (Directory.find(line->getAddress()) == Directory.end()) { assert (!isHit); stat = SendGetM (line->getDataPtr(), addr, CacheLineSize, delay, timestamp); Directory[line->getAddress()] = { Modified, id, {} }; } else { switch (Directory[line->getAddress()].State) { case Invalid: if (line->getState()!=Modified) { stat = SendGetM (line->getDataPtr(), addr, CacheLineSize, delay, timestamp); } Directory[line->getAddress()] = { Modified, id, {} }; break; case Shared: if (line->getState()!=Modified) stat = SendGetM (line->getDataPtr(), addr, CacheLineSize, delay, timestamp); Directory[line->getAddress()].Sharers.erase(id); if (Directory[line->getAddress()].Sharers.size()!=0) stat = SendPutI (line->getDataPtr(), addr, CacheLineSize, Directory[line->getAddress()].Sharers, delay, timestamp); Directory[line->getAddress()] = { Modified, id, {} }; break; case Modified: // What should be the line state assert (id != Directory[line->getAddress()].Owner); stat = SendFwdGetM (line->getDataPtr(), line->getAddress(), CacheLineSize, {Directory[line->getAddress()].Owner}, delay, timestamp); // give updated data to requester Directory[line->getAddress()].Owner = id; break; } } line->setState(Shared); assert (Directory[line->getAddress()].State==Modified); assert (Directory[line->getAddress()].Owner==id); assert (Directory[line->getAddress()].Sharers.size()==0); NGetM++; break; case PutI: assert (Directory.find(line->getAddress()) != Directory.end()); assert (line->getState()==Shared||Directory[line->getAddress()].State==Shared); if (Directory[line->getAddress()].State==Shared) { assert (Directory[line->getAddress()].Sharers.size()!=0); stat = SendPutI (line->getDataPtr(), addr, CacheLineSize, Directory[line->getAddress()].Sharers, delay, timestamp); Directory[line->getAddress()] = { Invalid, NULL_IDX, {} }; } assert (Directory[line->getAddress()].State==Invalid); assert (Directory[line->getAddress()].Owner==NULL_IDX); assert (Directory[line->getAddress()].Sharers.size()==0); if (line->getState()!=Invalid) line->setState(Invalid); NPutI++; break; default: assert(false); break; //throw runtime_error ("Command prohibited for local coherent caches\n"); break; } assert (Directory.find(line->getAddress())==Directory.end() || (Directory[addr].State==Invalid && Directory[addr].Owner==NULL_IDX && Directory[addr].Sharers.size()==0) || (Directory[addr].State==Shared && Directory[addr].Owner==NULL_IDX && Directory[addr].Sharers.size()!= 0) || (Directory[addr].State==Modified && Directory[addr].Owner!=NULL_IDX && Directory[addr].Sharers.size()==0)); return stat; } template<CoherenceCommand accessMode> tlm::tlm_response_status accessCoherentHome (unsigned char* src_data_ptr, size_t size, AddressType addr, idx_t id, sc_time& delay, sc_time timestamp, void* handle=nullptr) { uint64_t offset = addr & OffsetMask; uint64_t index = (addr>>IndexShift) & IndexMask; uint64_t tag = (addr>>TagShift) & TagMask; tlm::tlm_response_status stat = tlm::TLM_OK_RESPONSE; CacheSetState& set = CacheLines [index]; CacheLineType* line; bool isHit = set.accessSet (tag, &line); bool alignment; //size_t accessSize; assert (id!=NULL_IDX); assert (offset==0); assert (size==CacheLineSize); assert (!isHit||(line->getAddress()<=addr && addr-line->getAddress()<CacheLineSize)); assert (!isHit||addr==line->getAddress()); assert(!(isHit && line->getState()==Modified && Directory[addr].State==Modified)); if (accessMode==GetS) { if (isHit) HitCount++; else MissCount++; } else if (accessMode==GetM) { if (isHit && line->getState()==Modified) HitCount++; else MissCount++; } if (!isHit && line->getState() == Shared) { if (NotifyEvictions) this->NotifyEviction(line->handle); } // If exclusive cache, proceed non-allocating requests on miss if ((InclusionOfHigher==Exclusive) && !isHit) { // TODO: factorize code GetS/GetM // Use addr rather than line (line is possibly not allocated) switch (accessMode) { case GetS: if (Directory.find(addr)==Directory.end()) { // Line has never been requested stat = ForwardReadData (src_data_ptr, addr, CacheLineSize, delay, timestamp); Directory[addr] = { Shared, NULL_IDX, {id} }; } else { switch (Directory[addr].State) { case Invalid: // Line is not in upper cache stat = ForwardReadData (src_data_ptr, addr, CacheLineSize, delay, timestamp); Directory[addr] = { Shared, NULL_IDX, {id} }; break; case Shared:// Line is in upper cache stat = SendFwdGetS (src_data_ptr, addr, CacheLineSize, Directory[addr].Sharers, delay, timestamp); Directory[addr].Sharers.insert(id); break; case Modified: // if Owner==id, LLC should have latest version if (Directory[addr].Owner!=id) stat = SendFwdGetS (src_data_ptr, addr, CacheLineSize, {Directory[addr].Owner}, delay, timestamp); Directory[addr] = { Shared, NULL_IDX, {id, Directory[addr].Owner}}; break; } } assert (Directory[addr].State==Shared); assert (Directory[addr].Owner==NULL_IDX); assert (Directory[addr].Sharers.size()!=0); NGetS++; return stat; //break; case GetM: if (Directory.find(addr)==Directory.end()) { // Line has never been requested stat = ForwardReadData (src_data_ptr, addr, CacheLineSize, delay, timestamp); Directory[addr] = { Modified, id, {} }; } else { switch (Directory[addr].State) { case Invalid: // Line is not in upper cache stat = ForwardReadData (src_data_ptr, addr, CacheLineSize, delay, timestamp); Directory[addr] = { Modified, id, {} }; break; case Shared: // Line is in upper cache //if (!(Directory[line->getAddress()].Sharers.size()==1&&Directory[line->getAddress()].Sharers.find(id))) assert (Directory[addr].Sharers.size()!=0); Directory[addr].Sharers.erase(id); if (Directory[addr].Sharers.size()!=0) stat = SendPutI (src_data_ptr, addr, CacheLineSize, Directory[addr].Sharers, delay, timestamp); Directory[addr] = {Modified, id, {}}; break; case Modified: assert (Directory[addr].Owner!=NULL_IDX); assert (Directory[addr].Owner != id); stat = SendFwdGetM (src_data_ptr, addr, CacheLineSize, {Directory[addr].Owner}, delay, timestamp); Directory[addr].Owner = id; break; } } assert (Directory[addr].State==Modified); assert (Directory[addr].Owner==id); assert (Directory[addr].Sharers.size()==0); NGetM++; return stat; //break; default: break; } } // Write-back dirty victim line if (!isHit && line->getState()==Modified && WritePolicy==WBack) {//TODO: WritePolicy==WBack in coherent mode WriteBacks++; stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); } // Prepare new line for allocating requests if (!isHit && AllocPolicy==WAllocate) { line->setNewLine(addr, tag); line->handle = handle; } assert (addr==line->getAddress()); // Proceed allocating requests switch (accessMode) { case PutS: //PutS is only allocating in exclusive cache assert (Directory.find(line->getAddress()) != Directory.end()); assert (Directory[line->getAddress()].State==Shared); switch (Directory[line->getAddress()].State) { case Invalid: case Modified: assert (false); // do these cases happen ? assert (Directory[line->getAddress()].Sharers.size()==0); break; case Shared: assert (Directory[line->getAddress()].Sharers.size()>0); assert (Directory[line->getAddress()].Owner==NULL_IDX); assert(InclusionOfHigher!=Exclusive||!isHit); Directory[line->getAddress()
].Sharers.erase(id); if (Directory[line->getAddress()].Sharers.size()==0) {// Last PutS Directory[line->getAddress()] = { Invalid, NULL_IDX, {} }; if (InclusionOfHigher==Exclusive) line->setState(Shared); } break; } assert (Directory[line->getAddress()].State!=Modified); assert (Directory[line->getAddress()].Owner==NULL_IDX); NPutS++; break; case PutM: // cache behaviour line->setState(Modified); // directory behaviour assert (Directory.find(line->getAddress()) != Directory.end()); switch (Directory[line->getAddress()].State) { case Invalid: case Shared: assert(false); break; // Maybe for shared, remove req from sharers case Modified: assert (Directory[line->getAddress()].Owner!=NULL_IDX); assert (Directory[line->getAddress()].Sharers.size()==0); assert (id == Directory[line->getAddress()].Owner); Directory[line->getAddress()] = { Invalid, NULL_IDX, {} }; break; } NPutM++; break; case GetS: // TODO: on GetS, line should be either in L2 or in L3 if (Directory.find(line->getAddress())==Directory.end()) { // Line has never been requested assert (!isHit); // first request assert (InclusionOfHigher!=Exclusive); stat = ForwardReadData (src_data_ptr, line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Shared); Directory[line->getAddress()] = { Shared, NULL_IDX, {id} }; } else { switch (Directory[line->getAddress()].State) { case Invalid: // Line is not in upper cache assert (Directory[line->getAddress()].Sharers.size()==0); assert (Directory[line->getAddress()].Owner==NULL_IDX); if (!isHit) { assert (InclusionOfHigher!=Exclusive); stat = ForwardReadData (src_data_ptr, line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Shared); } else if (InclusionOfHigher==Exclusive) { if (line->getState()==Modified) stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); // clean line line->setState(Invalid); } Directory[line->getAddress()] = { Shared, NULL_IDX, {id} }; break; case Shared: // Line is clean in upper cache assert (Directory[line->getAddress()].Owner==NULL_IDX); assert (Directory[line->getAddress()].Sharers.size()>0); if (!isHit) { assert (InclusionOfHigher!=Exclusive); stat = SendFwdGetS (line->getDataPtr(), line->getAddress(), CacheLineSize, Directory[line->getAddress()].Sharers, delay, timestamp); line->setState(Shared); } else if (InclusionOfHigher==Exclusive) { if (line->getState()==Modified) stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); // clean line line->setState(Invalid); } Directory[line->getAddress()].Sharers.insert(id); break; case Modified: // Line is dirty in upper cache assert (Directory[line->getAddress()].Sharers.size()==0); assert (Directory[line->getAddress()].Owner!= NULL_IDX); //if (Directory[line->getAddress()].Owner!=id) // should neccesssarily be owner!=id if correctly designed if (Directory[line->getAddress()].Owner!=id) // possible if eq to PutMGetS stat = SendFwdGetS (line->getDataPtr(), line->getAddress(), CacheLineSize, {Directory[line->getAddress()].Owner}, delay, timestamp); // get updated data Directory[line->getAddress()] = {Shared, NULL_IDX, {id, Directory[line->getAddress()].Owner}}; if (InclusionOfHigher==Exclusive) { assert (isHit); // Exclusive is non-allocating stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Invalid); } else line->setState(Modified); break; } } NGetS++; assert (Directory[line->getAddress()].State==Shared); assert (Directory[line->getAddress()].Owner==NULL_IDX); assert (Directory[line->getAddress()].Sharers.size()!=0); break; case GetM: if (Directory.find(line->getAddress())==Directory.end()) { // Line has never been requested assert (!isHit); // first request assert (InclusionOfHigher!=Exclusive); // No line allocation in exclusive caches stat = ForwardReadData (src_data_ptr, line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Shared); // Line is not dirty yet Directory[line->getAddress()] = { Modified, id, {} }; } else { switch (Directory[line->getAddress()].State) { case Invalid: // Line is not in upper cache assert (Directory[line->getAddress()].Sharers.size()==0); assert (Directory[line->getAddress()].Owner==NULL_IDX); if (!isHit) { assert (InclusionOfHigher!=Exclusive); // No line allocation in exclusive caches stat = ForwardReadData (src_data_ptr, line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Shared); // Line is not dirty yet } else if (InclusionOfHigher==Exclusive && line->getState()==Modified) { // clean line before invalidation stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Invalid); } Directory[line->getAddress()] = { Modified, id, {} }; break; case Shared: // Line is clean in upper cache assert (Directory[line->getAddress()].Owner==NULL_IDX); assert (Directory[line->getAddress()].Sharers.size()>0); if (!isHit) { assert (InclusionOfHigher!=Exclusive); // No line allocation in exclusive caches stat = SendFwdGetS (line->getDataPtr(), line->getAddress(), CacheLineSize, Directory[line->getAddress()].Sharers, delay, timestamp); line->setState(Shared); } else if (InclusionOfHigher==Exclusive && line->getState()==Modified) { // clean line before invalidation stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); line->setState(Invalid); } Directory[line->getAddress()].Sharers.erase(id); assert(Directory[line->getAddress()].Sharers.find(id) == Directory[line->getAddress()].Sharers.end()); if (Directory[line->getAddress()].Sharers.size() != 0) // Invalidate all sharers stat = SendPutI (line->getDataPtr(), addr, CacheLineSize, Directory[line->getAddress()].Sharers, delay, timestamp); Directory[line->getAddress()] = { Modified, id, {} }; break; case Modified: // Line is dirty in upper cache assert (Directory[line->getAddress()].Owner!=NULL_IDX); assert (Directory[line->getAddress()].Owner != id); assert (Directory[line->getAddress()].Sharers.size()==0); stat = SendFwdGetM (line->getDataPtr(), line->getAddress(), CacheLineSize, {Directory[line->getAddress()].Owner}, delay, timestamp); Directory[line->getAddress()].Owner = id; // Line is home and up-to-date, give dirty line to requester, no need for writeback //stat = ForwardWriteData (line->getDataPtr(), line->getAddress(), CacheLineSize, delay, timestamp); if (InclusionOfHigher==Exclusive) line->setState(Invalid); // else line->setState(Modified); break; } } NGetM++; assert (Directory[line->getAddress()].State==Modified); assert (Directory[line->getAddress()].Owner==id); assert (Directory[line->getAddress()].Sharers.size()==0); break; default: assert(false); break; //throw runtime_error ("Command non allowed for home\n"); } assert (Directory.find(line->getAddress())==Directory.end() || (Directory[addr].State==Invalid && Directory[addr].Owner==NULL_IDX && Directory[addr].Sharers.size()==0) || (Directory[addr].State==Shared && Directory[addr].Owner==NULL_IDX && Directory[addr].Sharers.size()!= 0) || ( Directory[addr].State==Modified && Directory[addr].Owner!=NULL_IDX && Directory[addr].Sharers.size()==0)); return stat; } //! //! function used to access the cache and update its state //! @tparam WriteMode, true if the access is actually a write //! @param [in] Addr the address that needs to be read or written //! @param [in] NbBytes the number of successive bytes starting from Addr that this access covers //! @param [in,out] SrcDestBuffer an allocated buffer of NbBytes size from/to which data is read/written depending on WriteMode //! /*template<CacheAccessMode accessMode>*/ /* template<CoherenceCommand accessMode> tlm::tlm_response_status accessCache (unsigned char* src_data_ptr, size_t size, AddressType addr, int id, sc_time& delay, sc_time timestamp=sc_time(0,SC_NS), void* handle=nullptr) { // id contains the initiator Id for downstream transactions and the target id for upstream transactions // TODO add verif on ids if (!IsCoherent) return this-> accessNonCoherentCache<accessMode>(src_data_ptr, size, addr, id, delay, timestamp, handle); else { if (!IsHome) return this-> accessCoherentLocalCache<accessMode>(src_data_ptr, size, addr, id, delay, timestamp, handle); else return this-> accessCoherentHome<accessMode>(src_data_ptr, size, addr, id, delay, timestamp, handle); } }*/ template<CoherenceCommand accessMode> tlm::tlm_response_status accessCache (unsigned char* src_data_ptr, size_t size, AddressType addr, idx_t id, sc_time& delay, sc_time timestamp=sc_time(0,SC_NS), void* handle=nullptr) { // id contains the initiator Id for downstream transactions and the target id for upstream transactions tlm::tlm_response_status stat = tlm::TLM_OK_RESPONSE; if (!IsCoherent) stat = this-> accessNonCoherentCache<accessMode>(src_data_ptr, size, addr, id, delay, timestamp, handle); else { if (IsHome) stat = this-> accessCoherentHome<accessMode>(src_data_ptr, size, addr, id, delay, timestamp, handle); else switch (Level) { case 1: stat = this-> accessCpuCache<accessMode>(src_data_ptr, size, addr, id, delay, timestamp, handle); break; case 2: stat = this-> accessL2Cache<accessMode>(src_data_ptr, size, addr, id, delay, timestamp, handle); break; default: assert (false); break; } } return stat; } inline bool isDataSupported (){ return DataSupport; } inline void cacheMemcpy (unsigned char* dest_ptr, unsigned char* src_ptr, size_t size){ if (DataSupport) memcpy (dest_ptr, src_ptr, size); else return; } //! //! Displays the access counts and miss rate of the CacheBase since the beginning of the simulation //! void displayStats () { uint64_t AccessCount = MissCount + HitCount + NInvals + NEvicts; double MissRate = (AccessCount>0) ? ((double)MissCount)/AccessCount : 0; cout << this->name() << ": MissCount " << MissCount << " , HitCount " << HitCount << endl; cout << this->name() << ": total accesses " << AccessCount << " , MissRate " << MissRate; cout << " writes: " << NWrites << " reads: " << NReads << " WriteBacks: " << WriteBacks; if (InclusionOfLower==Inclusive) cout << " total invalidations: " << NTotalInvals << " real invalidations: " << NInvals; if (InclusionOfLower==Exclusive) cout << " evictions: " << NEvicts; cout << endl; } //! //! Function called by the cache itself whenever it must forward a read access to a next-level cache //! This function may be overriden to implement relevant TLM interfaces for instance //! @param [in] Addr the address that needs to be written //! @param [in] NbBytes the number of successive bytes starting from Addr that this access covers //! @param [in,out] TargetBuffer an allocated buffer of NbBytes size from which access data can be written //! virtual tlm::tlm_response_status ForwardRead (AddressType addr, size_t size, sc_time& delay) { return tlm::TLM_OK_RESPONSE; }; virtual tlm::tlm_response_status ForwardRead (AddressType addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; }; virtual tlm::tlm_response_status ForwardReadData (unsigned char* cacheLineData, AddressType Addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status BackwardRead (unsigned char* lineDataPtr, AddressType addr, size_t size, set<idx_t> sharerIds, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } //! //! Function called by the cache itself whenever it must forward a write access to a next-level cache //! This function may be overriden to implement relevant TLM interfaces for instance //! @param [in] Addr the address that needs to be written //! @param [in] NbBytes the number of successive bytes starting from Addr that this access covers //! @param [in] SrcBuffer an allocated buffer of NbBytes size from which access data can be read //! virtual tlm::tlm_response_status ForwardWrite (AddressType addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status ForwardWriteData (unsigned char* cacheLineData, AddressType addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status ForwardEvict (unsigned char* cacheLineData, AddressType addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } //virtual tlm::tlm_response_status BackInvalidate (AddressType addr, sc_time& delay) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status BackInvalidate (AddressType addr, set<idx_t> sharerIds, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendGetS (unsigned char* lineDataPtr, AddressType addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendGetM (unsigned char* lineDataPtr, AddressType addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendPutS (unsigned char* lineDataPtr, AddressType addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendPutM (unsigned char* lineDataPtr, AddressType addr, size_t size, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendFwdGetS (unsigned char* lineDataPtr, AddressType addr, size_t size, set<idx_t> sharerIds, /*const int id,*/ sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendFwdGetM (unsigned char* lineDataPtr, AddressType addr, size_t size, set<idx_t> ids, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendPutI (unsigned char* lineDataPtr, AddressType addr, size_t size, set<idx_t> sharerIds, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendInvS (unsigned char* lineDataPtr, AddressType addr, size_t size, set<idx_t> sharerIds, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } virtual tlm::tlm_response_status SendInvM (unsigned char* lineDataPtr, AddressType addr, size_t size, idx_t id, sc_time& delay, sc_time timestamp) { return tlm::TLM_OK_RESPONSE; } //! //! Performs a read access to the cache and returns the valid value read in the cache in TargetBuffer //! @param [in] Addr the address that needs to be written //! @param [in] NbBytes the number of successive bytes starting from Addr that this access covers //! @param [out] TargetBuffer an allocated buffer of NbBytes size from which access data can be read //! /*virtual tlm::tlm_response_status Read (AddressType addr, sc_time& delay){ return AccessCache<false>(addr, delay); }*/ virtual inline tlm::tlm_response_status ReadData (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp, void* handle=nullptr){ if (DataSupport) return accessCache<Read>(data_ptr, size, addr, initiatorId, delay, timestamp, handle); else return accessCache<Read>(NULL, size, addr, initiatorId, delay, timestamp, handle); } //! //! Performs a write access to the cache //! @param [in] Addr the address that needs to be written //! @param [in] NbBytes the number of successive bytes starting from Addr that this access covers //! @param [out] TargetBuffer an allocated buffer of NbBytes size from which access data can be read //! /* virtual tlm::tlm_response_status Write (AddressType addr, sc_time& delay){ return AccessCache<true>(addr, delay); } */ virtual inline tlm::tlm_response_status WriteData (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp, void* handle=nullptr){ if (DataSupport) return accessCache<Write>(data_ptr, size, addr, initiatorId, delay, timestamp, handle); else return accessCache<Write>(NULL, size, addr, initiatorId, delay, timestamp, handle); } virtual inline tlm::tlm_response_status InvalidateLine (AddressType addr, sc_time& delay, sc_time timestamp){ return accessCache<Invalidate>(NULL, CacheLineSize, addr, NULL_IDX, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status EvictLine (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<Evict>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<Evict>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessGetM (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<GetM>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<GetM>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessGetS (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<GetS>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<GetS>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessFwdGetM (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<FwdGetM>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<FwdGetM>(NULL, size, addr, initiatorId, delay, timesta
mp, nullptr); } virtual inline tlm::tlm_response_status AccessFwdGetS (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<FwdGetS>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<FwdGetS>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessPutS (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<PutS>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<PutS>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessPutM (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<PutM>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<PutM>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessPutI (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<PutI>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<PutI>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessInvS (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<InvS>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<InvS>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessInvM (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<InvM>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<InvM>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } virtual inline tlm::tlm_response_status AccessReadBack (unsigned char* data_ptr, AddressType addr, size_t size, idx_t initiatorId, sc_time& delay, sc_time timestamp){ if (DataSupport) return accessCache<ReadBack>(data_ptr, size, addr, initiatorId, delay, timestamp, nullptr); else return accessCache<ReadBack>(NULL, size, addr, initiatorId, delay, timestamp, nullptr); } /* TODO: Fix functions below */ //! //! Performs a flushing of all cache lines between address @param Begin and address @param End //! depending on the cache policies, flushing may forward read or write access to next cache level //! FIXME on the other hand the flush is not forwarded to any next-level of cache //! void Flush(AddressType Begin, AddressType End) { assert(End > Begin); for(uint64_t i = 0; i < NbSets; i++){ for(unsigned j = 0; j < Associativity; j++){ AddressType BeginLineAddress = CacheLines[i].Lines[j].line.Address; AddressType EndLineAddress = BeginLineAddress + (this -> CacheLinesize) - 1; if ((BeginLineAddress >= Begin && BeginLineAddress <= End) || (EndLineAddress >= Begin && EndLineAddress <= End) || (BeginLineAddress <= Begin && Begin <= EndLineAddress)) { if (CacheLines[i].Lines[j].line.Valid && CacheLines[i].Lines[j].line.Modified && WritePolicy == WBack) ForwardWrite (BeginLineAddress, CacheLineSize, sc_time (0, SC_NS)); CacheLines[i].Lines[j].line.Valid=false; } } } } }; }//end vpsim namespace #endif //CACHEBASE_HPP
/******************************************************************************* * sc_main.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * The sc_main is the first function always called by the SystemC environment. * This one takes as arguments a test name and an option: * * testname.x [testnumber] [+waveform] * * testnumber - test to run, 0 for t0, 1 for t1, etc. Default = 0. * +waveform - generate VCD file for top level signals. * ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "SmallScreentest.h" SmallScreentest i_SmallScreentest("i_SmallScreentest"); int sc_main(int argc, char *argv[]) { int tn; bool wv = false; if (argc > 3) { SC_REPORT_ERROR("MAIN", "Too many arguments used in call"); return 1; } /* If no arguments are given, argc=1, there is no waveform and we run * test 0. */ else if (argc == 1) { tn = 0; wv = false; } /* If we have at least one argument, we check if it is the waveform command. * If it is, we set a tag. If we have two arguments, we assume the second * one is the test number. */ else if (strcmp(argv[1], "+waveform")==0) { wv = true; /* If two arguments were given (argc=3) we assume the second one is the * test name. If the testnumber was not given, we run test 0. */ if (argc == 3) tn = atoi(argv[2]); else tn = 0; } /* For the remaining cases, we check. If there are two arguments, the first * one must be the test number and the second one might be the waveform * option. If we see 2 arguments, we do that. If we do not, then we just * have a testcase number. */ else { if (argc == 3 && strcmp(argv[2], "+waveform")==0) wv = true; else wv = false; tn = atoi(argv[1]); } /* We start the wave tracing. */ sc_trace_file *tf = NULL; if (wv) { tf = sc_create_vcd_trace_file("waves"); i_SmallScreentest.trace(tf); } /* We need to connect the Arduino pin library to the gpios. */ i_SmallScreentest.i_esp.pininit(); /* Set the test number */ i_SmallScreentest.tn = tn; /* And run the simulation. */ sc_start(); if (wv) sc_close_vcd_trace_file(tf); exit(0); }
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _Seuil_calc1_ #define _Seuil_calc1_ #include "systemc.h" #include <cstdint> #include "constantes.hpp" using namespace std; // #define _DEBUG_SYNCHRO_ SC_MODULE(Seuil_calc1) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_uint<8> > e; sc_fifo_out <bool> detect; // sc_fifo_out <bool> detect1; SC_CTOR(Seuil_calc1) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: void do_gen( ) { sc_uint<8> buffer[32]; sc_uint<22> seuil= 26; #pragma HLS ARRAY_PARTITION variable=buffer complete dim=0 while( true ) { #pragma HLS PIPELINE for (uint8_t j = 0; j < 32-1; j += 1) { // #pragma HLS PIPELINE buffer[j] = buffer[j+1]; } buffer[32-1] = e.read(); const sc_uint<11> ps = (sc_uint<11>) buffer[ 0] + (sc_uint<11>) buffer[ 1] + (sc_uint<11>) buffer[ 4] + (sc_uint<11>) buffer[ 5] + // 2 bits à 1 en PPM (sc_uint<11>) buffer[14] + (sc_uint<11>) buffer[15] + (sc_uint<11>) buffer[18] + (sc_uint<11>) buffer[19]; // 2 bits à 0 en PPM sc_uint<22> sum = 0; for (uint8_t i = 0; i < 32; i += 1) { // #pragma HLS PIPELINE const sc_uint<8> temp = buffer[i]; const sc_uint<16> sqrv = (temp * temp); sum += sqrv; } sum = 8 * sum; const sc_uint<22> res_0 = (ps* ps); const sc_uint<22> res_1 = sum >> 5; const sc_uint<22> res_2 = (res_1 == 0)? (sc_uint<22>)31 :res_1; const sc_uint<22> res_3 = res_0 /res_2; const bool condition = (res_3> seuil); detect.write(condition); // sc_uint<22> res_0 = (ps* ps); // sc_uint<22> res_1 = (res_0 << 5); // sc_uint<22> res_2 = res_1 / sum; // sc_uint<5> res_3 = res_2 & 0x1F; // detect.write(res_3> seuil); } } }; #endif
#include <systemc.h> // #include "hwcore/hf/helperlib.h" #include <random> #define sc_fifo hwcore::hf::sc_fifo_with_trace // #include "hwcore/cnn/cnn.h" #include "hwcore/pipes/data_types.h" #include <cmath> SC_MODULE(tb_cnn_2d) { #if __RTL_SIMULATION__ // DMA_performance_tester_rtl_wrapper u1; #else // DMA_performance_tester u1; #endif typedef sc_fixed<P_data_W, P_data_P> sc_data; sc_data func(int a, int b, int c, int d) { int tmp = ((d & 0xFF) << 24) | ((c & 0xFF) << 16) | ((b & 0xFF) << 8) | ((a & 0xFF) << 0); return (sc_data)tmp; } void func_inv(sc_data in, int &a, int &b, int &c, int &d) { a = (in.to_int() >> 0) & 0xFF; b = (in.to_int() >> 8) & 0xFF; c = (in.to_int() >> 16) & 0xFF; d = (in.to_int() >> 24) & 0xFF; } struct dma_pkg : public hwcore::pipes::sc_fifo_base_dummy<dma_pkg> { typedef sc_bv<P_input_width> sc_data_raw; sc_data_raw *data_array; uint64 size; }; sc_clock clk; sc_in<bool> iclk; sc_signal<bool> reset; sc_fifo<hwcore::pipes::sc_data_stream_t<P_input_width> > dma_source; sc_fifo<hwcore::pipes::sc_data_stream_t<P_input_width> > dma_buf_source; sc_fifo<hwcore::pipes::sc_data_stream_t<P_input_width> > dma_w_source; sc_fifo<hwcore::pipes::sc_data_stream_t<64> > dma_ctrl_source; sc_fifo<hwcore::pipes::sc_data_stream_t<P_output_width> > dma_sink; enum { weight_ctrl = 0, ctrl_row_N = 1, ctrl_row_size_pkg = 2, ctrl_window_size = 3, ctrl_depth = 4, ctrl_stride = 5, ctrl_replay = 6, ctrl_image_size = 7, ctrl_acf = 8, ctrl_zeropad = 9, ctrl_output_channel = 10, ctrl_stitch_depth = 11, ctrl_stitch_buf_depth = 12, ctrl_db_output = 13, ctrl_image_data = 14, ctrl_pool_depth = 15, ctrl_pool_type = 16, ctrl_pool_N = 17, ctrl_pool_size = 18 }; sc_signal<int> status_add, status_val; // sc_fifo<hwcore::pipes::sc_data_stream_t<16> > wave_2_u1; ::cnn cnn_u1; // hwcore::cnn::top_cnn<16,8,1,1,16,16> cnn_u1; sc_trace_file *tracePtr; ofstream of; void log_time(std::string msg) { of << msg << ":" << sc_time_stamp().to_string() << std::endl; } void log(std::string msg) { of << msg << std::endl; } void fifo_debug() { sc_time time_interval(1000, SC_NS); while (true) { wait(time_interval); auto list = hwcore::hf::sc_trace_fifo::getList(); for (auto fifo_wrap : list) { int total = fifo_wrap->num_available() + fifo_wrap->num_free(); int used = fifo_wrap->num_available(); sc_port_base *writer = fifo_wrap->getWriter(); const char *w_name = (writer ? writer->name() : fifo_wrap->name()); sc_port_base *reader = fifo_wrap->getReader(); const char *r_name = (reader ? reader->name() : fifo_wrap->name()); std::cout << "[fifo debug][ " << sc_time_stamp() << " ][Used/Total] name [writer --> reader]: [" << used << " / " << total << "] " << fifo_wrap->name() << " [" << w_name << " --> " << r_name << "]" << std::endl; } } } void status_reg_dump() { sc_time time_interval(1000, SC_NS); while (true) { status_add.write(-1); for (int i = 0; i < 10; i++) wait(); int N_reg = status_val.read(); for (int reg_n = 0; reg_n < N_reg; reg_n++) { status_add.write(reg_n); for (int i = 0; i < 10; i++) wait(); int reg_value = status_val.read(); std::cout << "[status reg dump][ " << sc_time_stamp() << " ]reg[" << reg_n << "] = " << reg_value << std::endl; } wait(time_interval); } } SC_CTOR_DEFAULT(tb_cnn_2d) : SC_INST(cnn_u1), clk("clk", sc_time(5.625, SC_NS)) { of.open("result.txt"); srand(0xbeef); SC_MODULE_LINK(cnn_u1); iclk(clk); cnn_u1.status_add(status_add); cnn_u1.status_val(status_val); cnn_u1.data_sink(dma_source); cnn_u1.data_buf_sink(dma_buf_source); cnn_u1.w_sink(dma_w_source); cnn_u1.data_source(dma_sink); cnn_u1.ctrl_sink(dma_ctrl_source); SC_CTHREAD(cpu_thread_vgg19_test, iclk.pos()); SC_CTHREAD(dma_sink_thread, iclk.pos()); SC_CTHREAD(dma_source_thread, iclk.pos()); SC_CTHREAD(dma_source_buf_thread, iclk.pos()); SC_CTHREAD(dma_source_w_thread, iclk.pos()); SC_CTHREAD(dma_source_ctrl_thread, iclk.pos()); SC_CTHREAD(fifo_debug, iclk.pos()); SC_CTHREAD(status_reg_dump, iclk.pos()); HLS_DEBUG_EXEC(set_stack_size(128 * 10 * 1024 * 1024)); tracePtr = sc_create_vcd_trace_file("tb_CNN"); trace(tracePtr); } inline void trace(sc_trace_file * trace) { SC_TRACE_ADD(clk); SC_TRACE_ADD(reset); // SC_TRACE_ADD_MODULE(wave_2_u1); // SC_TRACE_ADD_MODULE(data_ctrl); SC_TRACE_ADD_MODULE(weight_ctrl); SC_TRACE_ADD_MODULE(ctrl_row_N); SC_TRACE_ADD_MODULE(ctrl_channel); SC_TRACE_ADD_MODULE(cnn_u1); // SC_TRACE_ADD_MODULE(u1_2_mon); } void do_cmd(sc_uint<8> regnr, sc_uint<56> value) { sc_uint<64> pkg = (regnr, value); dma_source_ctrl_ctrl.write(pkg); } const int dma_bw = P_input_BW_N; const int pe_bw = P_pe_bw_n; const int pe_n = P_pe_n; const int db_out_n = P_data_out_n; // typedef sc_fixed<P_data_W, P_data_P> sc_data; void cpu_thread_vgg19_test() { std::cout << "dma_bw:" << dma_bw << ", pe_bw: " << pe_bw << ", pe_n: " << pe_n << ", db_out_n: " << P_data_out_n << std::endl; reset.write(1); for (int i = 0; i < 10; i++) wait(); reset.write(0); wait(); pooling_test_512(); conv_test(16, 1, 64, 64); const int image_size = 32; const int N_images = 1; const int depth = 3; int N_W = 64; #if 0 sc_data *X = new sc_data[image_size * image_size * depth * N_images]; { fstream input; input.open("/home/jonathan/vgg19/dog.txt", ios::in); char test[512]; char *end; const int total_size = image_size * image_size * depth * N_images; std::cout << total_size << std::endl; int idx = 0; for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size; x++) { for (int y = 0; y < image_size; y++) { for (int z = 0; z < depth; z++) { input.getline(test, 512); double tmp = std::strtod(test, &end); std::cout << "W[" << i << "," << x << "," << y << "," << z << "] = " << tmp << std::endl; X[idx] = tmp; idx++; } } } } } #endif sc_ufixed<8, 0> *X = new sc_ufixed<8, 0>[image_size * image_size * depth * N_images]; { fstream input; input.open("/home/jonathan/vgg19/dog.txt", ios::in); char test[512]; char *end; const int total_size = image_size * image_size * depth * N_images; std::cout << total_size << std::endl; int idx = 0; for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size; x++) { for (int y = 0; y < image_size; y++) { for (int z = 0; z < depth; z++) { double tmp; if (z < 3) { input.getline(test, 512); tmp = std::strtod(test, &end); } else { tmp = 0; } X[idx] = tmp; std::cout << "W[" << i << "," << x << "," << y << "," << z << "] = " << X[idx].to_double() << "(" << tmp << ")" << std::endl; idx++; } } } } } double *Y = new double[image_size * image_size * N_W * N_images]; { int zN = 64; fstream input; input.open("/home/jonathan/vgg19/dog_out.txt", ios::in); char test[512]; char *end; input.getline(test, 512); int idx = 0; for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size; x++) { for (int y = 0; y < image_size; y++) { for (int z = 0; z < zN; z++) { input.getline(test, 512); double tmp = std::strtod(test, &end); std::cout << "Y[" << i << "," << x << "," << y << "," << z << "] = " << tmp << std::endl; if (z < N_W) { Y[idx] = tmp; idx++; } } } } } } // std::string line = ; sc_data *W; { fstream conv1; conv1.open("/home/jonathan/vgg19/weights.txt", ios::in); char test[512]; conv1.getline(test, 512); std::string line(test); char *end; int x = 3; int y = 3; int z = 3; int w = 64; W = new sc_data[(x * y * z * N_W) + N_W]; int idx = 0; double tmp; for (int wi = 0; wi < N_W; wi++) { conv1.getline(test, 512); tmp = std::strtod(test, &end); W[idx] = tmp; std::cout << "B[" << wi << "] = " << tmp << std::endl; idx++; for (int xi = 0; xi < x; xi++) { for (int yi = 0; yi < y; yi++) { for (int zi = 0; zi < depth; zi++) { if (zi < z) { conv1.getline(test, 512); tmp = std::strtod(test, &end); } else { tmp = 0; } W[idx] = tmp; idx++; std::cout << "W[" << wi << "," << xi << "," << yi << "," << zi << "] = " << tmp << std::endl; } } } } } dma_pkg dmaX; dma_pkg dmaW; dma_pkg dmaY1; int W_size = 3; int new_W_size; int new_depth; // pre_data(X, dmaX, image_size, N_images, depth, new_depth); pre_data_image(X, dmaX, image_size, N_images, new_depth); pre_weight(W, dmaW, W_size, N_W, depth, new_depth, new_W_size); { ofstream of_w_dump; of_w_dump.open("W_dma_dump_vgg19.txt"); for (int i = 0; i < dmaW.size; i++) { auto tmp = dmaW.data_array[i]; of_w_dump << "dma[" << i << "] = [MSB "; for (int a = dma_bw - 1; a >= 0; a--) { auto sub = tmp((P_data_W * (a + 1)) - 1, P_data_W * a); ; of_w_dump << " (" << (P_data_W * (a + 1)) - 1 << "," << P_data_W * a << ")" << sub.to_string(sc_dt::sc_numrep::SC_HEX) << (a == 0 ? "" : ","); } of_w_dump << " LSB]" << std::endl; } } pre_output(dmaY1, image_size, W_size, depth, N_images, N_W, 1); log_time("conv_start"); do_conv(dmaX, dmaW, dmaY1, new_W_size, new_depth, image_size, 1, N_images, N_W, 1, true); double mse = 0.0f; for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size; x++) { for (int y = 0; y < image_size; y++) { for (int z = 0; z < N_W; z++) { int Yindx = (i * image_size * image_size * N_W) + (x * image_size * N_W) + (y * N_W) + z; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY1.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); debug_cout << "[i,a,b,c]:[" << i << "," << x << "," << y << "," << z << "]:[expected,got] = [" << Y[Yindx] << "," << got_fix.to_double() << "] Yindx = " << Yindx << "==>" << Yindx_add << "." << Yindx_cut << std::endl; mse += (Y[Yindx] - got_fix.to_double()) * (Y[Yindx] - got_fix.to_double()); // sc_assert(got == expected); //#warning fix W before uncomment } } } } mse = mse / (double)(N_images * image_size * image_size * N_W); std::cout << "mse: " << mse << std::endl; log(std::string("mse: ") + std::to_string(mse)); double mse_tol = 1e-1; // sc_assert(mse <= mse_tol); log_time("conv_end"); log_time("pool_start"); dma_pkg dmaY2; pre_output(dmaY2, image_size, 2, N_W, N_images, N_W, 0, 2); do_pool(dmaY1, dmaY2, N_W, image_size, 2, N_images, 2, 0); log_time("pool_end"); for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size / 2; x++) { for (int y = 0; y < image_size / 2; y++) { for (int z = 0; z < N_W; z++) { sc_fixed<P_data_W, P_data_P> exp_fix; for (int px = 0; px < 2; px++) { for (int py = 0; py < 2; py++) { int Yindx = (i * (image_size) * (image_size)*N_W) + (((x * 2) + px) * image_size * N_W) + (((y * 2) + py) * N_W) + z; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> exp_fix_tmp = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY1.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); if ((px == 0 && py == 0) || exp_fix < exp_fix_tmp) { exp_fix = exp_fix_tmp; } std::cout << "exp pool [" << px << "," << py << "] [exp_fix, exp_tmp]=[" << exp_fix.to_float() << ", " << exp_fix_tmp.to_float() << "]" << std::endl; } } int Yindx = (i * (image_size / 2) * (image_size / 2) * N_W) + (x * (image_size / 2) * N_W) + (y * N_W) + z; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); debug_cout << "[i,a,b,c]:[" << i << "," << x << "," << y << "," << z << "]:[expected,got] = [" << exp_fix.to_double() << "," << got_fix.to_double() << "] Yindx = " << Yindx << "==>" << Yindx_add << "." << Yindx_cut << std::endl; sc_assert(got_fix == exp_fix); //#warning fix W before uncomment } } } } fc_test(dmaY2, image_size / 2, N_W, N_images, 128); { /* dma_pkg dmaWfc; dma_pkg dmaY3; int outputs = 2; int inputs = (image_size / 2) * (image_size / 2) * N_W; pre_fc_output(dmaY3, outputs * N_images); int w_row_N; sc_data *Wfc = new sc_data[outputs * (1 + inputs)]; for (int i = 0; i < outputs; i++) { Wfc[i * (1 + inputs)] = sc_data(0.001f * (float)((rand() % 100) - 50)); for (int x = 0; x < inputs; x++) { Wfc[(i * (1 + inputs)) + x + 1] = sc_data(0.001f * (float)((rand() % 100) - 50)); } } int outputs_raw; pre_fc_weight(Wfc, dmaWfc, inputs, outputs, outputs_raw, w_row_N); log_time("fc_start"); do_fc(dmaY2, dmaWfc, dmaY3, inputs, outputs_raw, N_images, w_row_N); mse = 0.0; for (int i = 0; i < N_images; i++) { for (int x = 0; x < outputs; x++) { double exp = Wfc[x * (1 + inputs)].to_double(); for (int in = 0; in < inputs; in++) { int Yindx = (i * inputs) + in; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P, SC_TRN, SC_SAT> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); exp += Wfc[(x * (1 + inputs)) + in + 1].to_double() * input_data.to_double(); } int Yindx = (i * outputs) + x; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY3.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); std::cout << "[" << i << "," << x << "] : [exp <==> got] = [" << exp << " <==> " << input_data.to_double() << "]" << std::endl; mse += (exp - input_data.to_double()) * (exp - input_data.to_double()); // sc_assert(exp == input_data); } } mse /= (double)(N_images * outputs); std::cout << "mse: " << mse << std::endl; log(std::string("mse: ") + std::to_string(mse)); // double mse_tol = 1e-1; // sc_assert(mse <= mse_tol); log_time("fc_end"); */ } sc_stop(); while (true) { std::cout << "done" << std::endl; wait(); } } void conv_test(int image_size, int N_images, int depth, int N_W) { dma_pkg dmaX; dma_pkg dmaW; dma_pkg dmaY1; int W_size = 3; int new_W_size; int new_depth; pre_data(nullptr, dmaX, image_size, N_images, depth, new_depth); // pre_data_image(X, dmaX, image_size, N_images, new_depth); pre_weight(nullptr, dmaW, W_size, N_W, depth, new_depth, new_W_size); pre_output(dmaY1, image_size, W_size, depth, N_images, N_W, 1); log_time("conv_start-" + std::to_string(image_size) + "-" + std::to_string(depth) + "-" + std::to_string(N_W)); do_conv(dmaX, dmaW, dmaY1, new_W_size, new_depth, image_size, 1, N_images, N_W, 1, false); log(std::string("mse: ") + std::to_string(0.0f)); // sc_assert(mse <= mse_tol); log_time("conv_end-" + std::to_string(image_size) + "-" + std::to_string(depth) + "-" + std::to_string(N_W)); } void fc_test(dma_pkg & dmaY2, int image_size, int depth, int N_images, int n_neurons) { log_time("fc_start"); double mse = 0.0; for (int i = 0; i < n_neurons / pe_n; i++) { dma_pkg dmaWfc; dma_pkg dmaY3; int outputs = pe_n; int inputs = image_size * image_size * depth; pre_fc_output(dmaY3, outputs * N_images); int w_row_N; sc_data *Wfc = new sc_data[outputs * (1 + inputs)]; for (int i = 0; i < outputs; i++) { Wfc[i * (1 + inputs)] = sc_data(0.001f * (float)((rand() % 100) - 50)); for (int x = 0; x < inputs; x++) { Wfc[(i * (1 + inputs)) + x + 1] = sc_data(0.001f * (float)((rand() % 100) - 50)); } } int outputs_raw; pre_fc_weight(Wfc, dmaWfc, inputs, outputs, outputs_raw, w_row_N); do_fc(dmaY2, dmaWfc, dmaY3, inputs, outputs_raw, N_images, w_row_N); for (int i = 0; i < N_images; i++) { for (int x = 0; x < outputs; x++) { double exp = Wfc[x * (1 + inputs)].to_double(); for (int in = 0; in < inputs; in++) { int Yindx = (i * inputs) + in; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P, SC_TRN, SC_SAT> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); exp += Wfc[(x * (1 + inputs)) + in + 1].to_double() * input_data.to_double(); } int Yindx = (i * outputs) + x; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY3.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); std::cout << "[" << i << "," << x << "] : [exp <==> got] = [" << exp << " <==> " << input_data.to_double() << "]" << std::endl; mse += (sc_data(exp).to_double() - input_data.to_double()) * (sc_data(exp).to_double() - input_data.to_double()); // sc_assert(exp == input_data); } } } mse /= (double)(N_images * n_neurons); std::cout << "mse: " << mse << std::endl; log(std::string("mse: ") + std::to_string(mse)); // double mse_tol = 1e-1; // sc_assert(mse <= mse_tol); log_time("fc_end"); } void pooling_test_512() { const int image_size = 28; const int N_images = 1; const int depth = 512; sc_data *X = new sc_data[image_size * image_size * depth * N_images]; { const int total_size = image_size * image_size * depth * N_images; std::cout << total_size << std::endl; int idx = 0; for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size; x++) { for (int y = 0; y < image_size; y++) { for (int z = 0; z < depth; z++) { // input.getline(test, 512); double tmp = 0.001 * ((rand() % 2000) - 1000); std::cout << "W[" << i << "," << x << "," << y << "," << z << "] = " << tmp << std::endl; X[idx] = tmp; idx++; } } } } } dma_pkg dmaX; int new_W_size; int new_depth; pre_data(X, dmaX, image_size, N_images, depth, new_depth); log_time("pool512_start"); dma_pkg dmaY2; pre_output(dmaY2, image_size, 2, depth, N_images, depth, 0, 2); do_pool(dmaX, dmaY2, depth, image_size, 2, N_images, 2, 0); log_time("pool512_end"); for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size / 2; x++) { for (int y = 0; y < image_size / 2; y++) { for (int z = 0; z < depth; z++) { sc_fixed<P_data_W, P_data_P> exp_fix; for (int px = 0; px < 2; px++) { for (int py = 0; py < 2; py++) { int Yindx = (i * (image_size) * (image_size)*depth) + (((x * 2) + px) * image_size * depth) + (((y * 2) + py) * depth) + z; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> exp_fix_tmp = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaX.data_array[Yindx_add](P_da
ta_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); if ((px == 0 && py == 0) || exp_fix < exp_fix_tmp) { exp_fix = exp_fix_tmp; } std::cout << "exp pool [" << px << "," << py << "] [exp_fix, exp_tmp]=[" << exp_fix.to_float() << ", " << exp_fix_tmp.to_float() << "]" << std::endl; } } int Yindx = (i * (image_size / 2) * (image_size / 2) * depth) + (x * (image_size / 2) * depth) + (y * depth) + z; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); debug_cout << "[i,a,b,c]:[" << i << "," << x << "," << y << "," << z << "]:[expected,got] = [" << exp_fix.to_double() << "," << got_fix.to_double() << "] Yindx = " << Yindx << "==>" << Yindx_add << "." << Yindx_cut << std::endl; sc_assert(got_fix == exp_fix); //#warning fix W before uncomment } } } } } void cpu_thread_fc_only() { int N_images = 1; int image_size = 16; int depth = 8; int N_W = 8; sc_data *X = new sc_data[image_size * image_size * depth * N_images]; { const int total_size = image_size * image_size * depth * N_images; std::cout << total_size << std::endl; int idx = 0; for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size * image_size * depth; x++) { std::cout << "W[" << i << "," << x << "] = " << x << std::endl; X[idx] = x; idx++; } } } int new_depth; dma_pkg dmaX; pre_data(X, dmaX, image_size, N_images, depth, new_depth); sc_assert(depth == new_depth); dma_pkg dmaWfc; dma_pkg dmaY3; int outputs = pe_n; int inputs = (image_size) * (image_size)*depth; // int inputs_raw = (image_size) * (image_size)*new_depth; int w_row_N; sc_data *Wfc = new sc_data[outputs * (1 + inputs)]; for (int i = 0; i < outputs; i++) { Wfc[i * (1 + inputs)] = 0; // sc_data(0.001f * (float)((rand() % 100) - 50)); for (int x = 0; x < inputs; x++) { Wfc[(i * (1 + inputs)) + x + 1] = x; // sc_data(0.001f * (float)((rand() % 100) - 50)); } } int outputs_raw; pre_fc_weight(Wfc, dmaWfc, inputs, outputs, outputs_raw, w_row_N); pre_fc_output(dmaY3, outputs_raw * N_images); log_time("fc_start"); do_fc(dmaX, dmaWfc, dmaY3, inputs, outputs_raw, N_images, w_row_N); /* mse = 0.0; for (int i = 0; i < N_images; i++) { for (int x = 0; x < outputs; x++) { sc_fixed<P_data_W * 2, P_data_P * 2, SC_TRN, SC_SAT> exp = Wfc[x * (1 + inputs)]; for (int in = 0; in < inputs; in++) { int Yindx = (i * inputs) + in; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P, SC_TRN, SC_SAT> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); exp += (sc_fixed<P_data_W * 2, P_data_P * 2, SC_TRN, SC_SAT>)Wfc[(x * (1 + inputs)) + in + 1] * (sc_fixed<P_data_W * 2, P_data_P * 2, SC_TRN, SC_SAT>)input_data; } sc_fixed<P_data_W, P_data_P, SC_TRN, SC_SAT> exp_small = exp; int Yindx = (i * outputs) + x; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY3.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); std::cout << "[" << i << "," << x << "] : [exp <==> got] = [" << exp_small.to_double() << " <==> " << input_data.to_double() << "]" << std::endl; mse += (exp_small.to_double() - input_data.to_double()) * (exp_small.to_double() - input_data.to_double()); // sc_assert(exp == input_data); } } mse /= (double)(N_images * outputs); std::cout << "mse: " << mse << std::endl; log(std::string("mse: ") + std::to_string(mse)); // double mse_tol = 1e-1; // sc_assert(mse <= mse_tol); */ log_time("fc_end"); sc_stop(); while (true) { std::cout << "done" << std::endl; wait(); } } void cpu_thread() { std::cout << "dma_bw:" << dma_bw << ", pe_bw: " << pe_bw << ", pe_n: " << pe_n << ", db_out_n: " << P_data_out_n << std::endl; reset.write(1); for (int i = 0; i < 10; i++) wait(); reset.write(0); const int image_size = 8; const int N_images = 1; const int depth = fix_size(8, pe_bw); const int W_size = 3; const int N_W = 8; sc_data *X = new sc_data[image_size * image_size * depth * N_images]; const int total_size = image_size * image_size * depth * N_images; std::cout << total_size << std::endl; int idx = 0; for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size; x++) { for (int y = 0; y < image_size; y++) { for (int z = 0; z < depth; z++) { sc_data tmp = func(x, y, z, i); std::cout << "image data: " << tmp.to_string() << std::endl; X[idx] = tmp; idx++; } } } } sc_data *W = new sc_data[(W_size * W_size * depth * N_W) + N_W]; idx = 0; const int w_indx = (int)floor(W_size / 2.0f); for (int i = 0; i < N_W; i++) { W[idx] = i; idx++; for (int x = 0; x < W_size; x++) { for (int y = 0; y < W_size; y++) { for (int z = 0; z < depth; z++) { if (z == i % depth && y == (i / depth) % W_size && x == (i / (depth * W_size)) % W_size) { W[idx] = 1; } else { W[idx] = 0; } std::cout << "w data: " << W[idx].to_string() << std::endl; idx++; } } } } dma_pkg dmaX; dma_pkg dmaW; dma_pkg dmaY1; dma_pkg dmaY2; dma_pkg dmaWfc; dma_pkg dmaY3; int new_W_size; int new_depth; int output_fc = 2; pre_output(dmaY2, image_size, 2, N_W, N_images, N_W, 0, 2); pre_fc_output(dmaY3, output_fc * N_images); int w_row_N; int output_raw_fc; pre_fc_weight(nullptr, dmaWfc, (dmaY2.size * dma_bw) / N_images, 64, output_raw_fc, w_row_N); pre_data(X, dmaX, image_size, N_images, depth, new_depth); pre_weight(W, dmaW, W_size, N_W, depth, new_depth, new_W_size); pre_output(dmaY1, image_size, W_size, depth, N_images, N_W, 1); log_time("conv_start"); do_conv(dmaX, dmaW, dmaY1, new_W_size, new_depth, image_size, 1, N_images, N_W, 1); int zp = 1; for (int i = 0; i < N_images; i++) { for (int x = 0; x < image_size; x++) { for (int y = 0; y < image_size; y++) { for (int z = 0; z < N_W; z++) { int off_x = ((z / (new_depth * new_W_size)) % new_W_size) - zp; int off_y = ((z / new_depth) % new_W_size) - zp; int off_z = z % new_depth; int expected = 0; if (0 <= x + off_x && x + off_x < image_size && 0 <= y + off_y && y + off_y < image_size) { expected = func(x + off_x, y + off_y, off_z, i); } int Yindx = (i * image_size * image_size * N_W) + (x * image_size * N_W) + (y * N_W) + z; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>( dmaY1.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); int got = got_fix.to_int() - z; debug_cout << "[i,a,b,c]:[" << i << "," << x << "," << y << "," << z << "]- func(" << x + off_x << "," << y + off_y << "," << off_z << "," << i << ")=[expected,got]:[" << expected << "," << got << "] Yindx = " << Yindx << "==>" << Yindx_add << "." << Yindx_cut << std::endl; int _x; int _y; int _z; int _i; func_inv(got_fix - sc_fixed<P_data_W, P_data_P>(z), _x, _y, _z, _i); debug_cout << "invfunc got [x,y,z,i]:[" << _x << "," << _y << "," << _z << "," << _i << "]" << std::endl; sc_assert(got == expected); //#warning fix W before uncomment } } } } log_time("conv_end"); log_time("pool_start"); do_pool(dmaY1, dmaY2, N_W, image_size, 2, N_images, 2, 0); log_time("pool_end"); // pre_process(X, W, dmaX, dmaW, dmaY, image_size, W_size, depth, new_W_size, new_depth, N_images, N_W, 1); log_time("fc_start"); do_fc(dmaY2, dmaWfc, dmaY3, dmaY2.size * dma_bw, dmaY3.size * dma_bw, N_images, w_row_N); log_time("fc_end"); sc_stop(); while (true) { std::cout << "done" << std::endl; wait(); } // do_conv(dmaX, dmaW, dmaY, new_W_size, new_depth, image_size, 1, N_images, N_W, 1); } void pre_fc_weight(sc_data * W, dma_pkg & dmaW, int N_input, int N_output, int &N_output_raw, int &w_row_N) { N_output_raw = pe_n; // fix_size(N_output, pe_n); sc_assert(N_output <= N_output_raw); int w_bw = pe_bw * db_out_n; w_row_N = fix_size(N_input, w_bw) + w_bw; // w_row_N = //fix_size(w_row_N + 1, pe_bw * db_out_n); sc_assert((w_row_N * N_output_raw) % dma_bw == 0); int size_raw = w_row_N * N_output_raw; dmaW.data_array = new dma_pkg::sc_data_raw[size_raw / dma_bw]; dmaW.size = size_raw / dma_bw; for (int out = 0; out < N_output_raw; out++) { int bias_ptr_from = out * (1 + N_input); int bias_ptr_to = out * w_bw; if (out < N_output) insert_data_2_buf(dmaW, W[bias_ptr_from], bias_ptr_to, dma_bw); else insert_data_2_buf(dmaW, 0, bias_ptr_to, dma_bw); for (int in = 0; in < N_input; in++) { int ptr_from = (out * (1 + N_input)) + in + 1; int in_ptr_sub = in % w_bw; int in_ptr_big = in / w_bw; int ptr_to = ((1 + in_ptr_big) * N_output_raw * w_bw) + out * w_bw + in_ptr_sub; //= (out * w_row_N) + in + w_bw; if (out < N_output) insert_data_2_buf(dmaW, W[ptr_from], ptr_to, dma_bw); else insert_data_2_buf(dmaW, 0, ptr_to, dma_bw); } } } void pre_fc_output(dma_pkg & dmaY, int N_output) { N_output = fix_size(N_output, dma_bw); sc_assert((N_output) % dma_bw == 0); dmaY.data_array = new dma_pkg::sc_data_raw[(N_output) / dma_bw]; dmaY.size = (N_output) / dma_bw; } int fix_size(int old, int align) { int tmp = (old % align); if (tmp == 0) { return old; } else { return old + (align - tmp); } } void realign_dma_buffer(sc_data * data, dma_pkg & dma_data, int depth, int new_depth, int dma_bw) { int ori_i = 0; for (int i = 0; i < dma_data.size * dma_bw; i++) { int Yindx_add = i / dma_bw; int Yindx_cut = i % dma_bw; sc_bv<P_data_W> tmp; if (i % new_depth < depth) { // tmp <<= P_data_W; std::cout << ori_i << ":" << (data ? data[ori_i].to_string() : "null") << std::endl; tmp = hwcore::hf::fixed2bv((data ? data[ori_i] : sc_data(0))); ori_i++; } else { tmp = 0; } dma_data.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut) = tmp; if (Yindx_cut == dma_bw - 1) { std::cout << "DMA data(" << Yindx_add << ", " << dma_data.size << "): " << dma_data.data_array[Yindx_add].to_string() << std::endl; } } } void insert_data_2_buf(dma_pkg & dma_data, sc_data tmp, int idx, int _dma_bw, int data_w = P_data_W) { int Yindx_add = idx / _dma_bw; int Yindx_cut = idx % _dma_bw; sc_assert(Yindx_add < dma_data.size); sc_assert(Yindx_cut < _dma_bw); dma_data.data_array[Yindx_add](data_w * (Yindx_cut + 1) - 1, data_w * (Yindx_cut)) = hwcore::hf::fixed2bv(tmp); } void realign_dma_buffer_W(sc_data * data, dma_pkg & dma_data, int depth, int new_depth, int _dma_bw, int N, int w_size, int bw) { for (int i = 0; i < N; i++) { int bias_ptr_from = i * (1 + (w_size * w_size * depth)); int pe_index_sub = i % pe_n; int pe_index_ptr = i / pe_n; // int bias_ptr_to = i * (bw + (w_size * w_size * new_depth)); int bias_ptr_to = (pe_index_sub * bw) + (pe_index_ptr * pe_n * (bw + (w_size * w_size * new_depth))); insert_data_2_buf(dma_data, (data ? data[bias_ptr_from] : sc_data(0)), bias_ptr_to, _dma_bw); for (int x = 0; x < w_size; x++) { for (int y = 0; y < w_size; y++) { for (int z = 0; z < depth; z++) { int ptr_from = (i * (1 + (w_size * w_size * depth))) + (x * w_size * depth) + (y * depth) + z + 1; int z_sub = z % pe_bw; int z_ptr = z / pe_bw; // int ptr_to = (i * (bw + (w_size * w_size * new_depth))) + (y * w_size * new_depth) + // (z_ptr * w_size * pe_bw) + ((w_size - x - 1) * pe_bw) + z_sub + bw; int ptr_to_sub = ((y * w_size * new_depth) + (z_ptr * w_size * pe_bw) + ((w_size - x - 1) * pe_bw) + z_sub + bw); int ptr_to_pe_sub = ptr_to_sub % (bw); int ptr_to_pe_ptr = ptr_to_sub / (bw); int ptr_to = bias_ptr_to + ptr_to_pe_ptr * (pe_n * bw) + ptr_to_pe_sub; // int ptr_to = (i * (bw + (w_size * w_size * new_depth))) + (y * w_size * new_depth) + // (z_ptr * w_size * pe_bw) + ((w_size - x - 1) * pe_bw) + z_sub + bw; // ptr_to = std::cout << "[x][y][z][w]=[" << x << "][" << y << "][" << z << "][" << i << "]=[from <=> to][" << ptr_from << "<=>" << ptr_to << "] rel [" << ptr_from - 1 << "<=>" << ptr_to - bw << "] : " << (data ? data[ptr_from].to_float() : 0.0f) << std::endl; insert_data_2_buf(dma_data, (data ? data[ptr_from] : sc_data(0)), ptr_to, _dma_bw); } } } } } void pre_data(sc_data * X, dma_pkg & dmaX, int image_size, int Nimages, int depth, int &new_depth) { new_depth = fix_size(depth, pe_bw); sc_assert((image_size * image_size * new_depth) % pe_bw == 0); dmaX.data_array = new dma_pkg::sc_data_raw[(image_size * image_size * new_depth * Nimages) / dma_bw]; dmaX.size = (image_size * image_size * new_depth * Nimages) / dma_bw; realign_dma_buffer(X, dmaX, depth, new_depth, dma_bw); } void pre_data_image(sc_ufixed<8, 0> * X, dma_pkg & dmaX, int image_size, int Nimages, int &new_depth) { new_depth = fix_size(3, pe_bw); dmaX.size = (image_size * image_size * 3 * 8) / (dma_bw * P_data_W); sc_assert(((image_size * image_size * 3 * 8) % (dma_bw * P_data_W)) == 0); dmaX.data_array = new dma_pkg::sc_data_raw[dmaX.size]; for (int x = 0; x < image_size; x++) { for (int y = 0; y < image_size; y++) { for (int z = 0; z < 3; z++) { int ptr_from = (x * image_size * 3) + (y * 3) + z; int ptr_to = (x * image_size * 3) + (y * 3) + z; int dma8bit_bw = (dma_bw * P_data_W) / 8; int Yindx_add = ptr_to / dma8bit_bw; int Yindx_cut = ptr_to % dma8bit_bw; sc_assert(Yindx_add < dmaX.size); sc_assert(Yindx_cut < dma8bit_bw); sc_assert(dma8bit_bw * 8 == dma_bw * P_data_W); sc_ufixed<8, 0> tmp = X[ptr_from]; dmaX.data_array[Yindx_add](8 * (Yindx_cut + 1) - 1, 8 * (Yindx_cut)) = hwcore::hf::ufixed2bv(tmp); // insert_data_2_buf(dmaX, X[ptr_from], ptr_to, dma_bw, 8); } } } } void pre_weight(sc_data * W, dma_pkg & dmaW, int W_size, int Nwindows, int depth, int &new_depth, int &new_W_size) { new_depth = fix_size(depth, pe_bw); int tmp = fix_size(W_size * W_size, db_out_n); //(pe_bw * db_out_n) / new_depth); new_W_size = sqrt(tmp); sc_assert(((new_W_size * new_W_size * new_depth) + (pe_bw * db_out_n)) % pe_bw * db_out_n == 0); int bias_size = (pe_bw * db_out_n); dmaW.data_array = new dma_pkg::sc_data_raw[(((new_W_size * new_W_size * new_depth) + bias_size) * Nwindows) / dma_bw]; dmaW.size = (((new_W_size * new_W_size * new_depth) + bias_size) * Nwindows) / dma_bw; sc_assert(new_W_size == W_size); realign_dma_buffer_W(W, dmaW, depth, new_depth, dma_bw, Nwindows, W_size, pe_bw * db_out_n); } void pre_output(dma_pkg & dmaY, int image_size, int W_size, int depth, int Nimages, int Nwindows, int zp, int stride = 1) { // sc_assert(stride == 1); // todo add this. // new_depth = fix_size(depth, pe_bw); int Y_size = (int)ceil( ((float)image_size - ((floor(((float)W_size / 2.0f)) - (float)zp) * 2.0f / (float)stride)) / (float)stride); int Y_depth = fix_size(Nwindows, pe_n); // * 2; dmaY.data_array = new dma_pkg::sc_data_raw[(Y_size * Y_size * Y_depth * Nimages) / dma_bw]; dmaY.size = (Y_size * Y_size * Y_depth * Nimages) / dma_bw; } void pre_process(sc_data * X, sc_data * W, dma_pkg & dmaX, dma_pkg & dmaW, dma_pkg & dmaY, int image_size, int W_size, int depth, int &new_W_size, int &new_depth, int Nimages, int Nwindows, int zp, int stride = 1) { sc_assert(stride == 1); // todo add this. new_depth = fix_size(depth, pe_bw); // new_depth_W = new_depth_X * db_out_n; { // sc_assert((pe_bw * db_out_n) % new_depth == 0); int tmp = fix_size(W_size * W_size, db_out_n); //(pe_bw * db_out_n) / new_depth); new_W_size = sqrt(tmp); } sc_assert((image_size * image_size * new_depth) % pe_bw == 0); sc_assert(((new_W_size * new_W_size * new_depth) + (pe_bw * db_out_n)) % pe_bw * db_out_n == 0); int bias_size = (pe_bw * db_out_n); dmaX.data_array = new dma_pkg::sc_data_raw[(image_size * image_size * new_depth * Nimages) / dma_bw]; dmaX.size = (image_size * image_size * new_depth * Nimages) / dma_bw; dmaW.data_array = new dma_pkg::sc_data_raw[(((new_W_size * new_W_size * new_depth) + bias_size) * Nwindows) / dma_bw]; dmaW.size = (((new_W_size * new_W_size * new_depth) + bias_size) * Nwindows) / dma_bw; int Y_size = image_size - (((int)floor(((float)W_size / 2.0f)) - zp) * 2); int Y_depth = fix_size(Nwindows, pe_n); // * 2; dmaY.data_array = new dma_pkg::sc_data_raw[(Y_size * Y_size * Y_depth * Nimages) / dma_bw]; dmaY.size = (Y_size * Y_size * Y_depth * Nimages) / dma_bw; realign_dma_buffer(X, dmaX, depth, new_depth, dma_bw); sc_assert(new_W_size == W_size); realign_dma_buffer_W(W, dmaW, depth, new_depth, dma_bw, Nwindows, W_size, pe_bw * db_out_n); } struct P_data_Pkg { sc_fixed<P_data_W, P_data_P> *data; int depth; int size; int row_size; }; int do_conv(dma_pkg & X, dma_pkg & W, dma_pkg & Y, int window, int depth, int row_size, int stride, int X_N, int W_N, int zp, bool raw_image_data = false, sc_ufixed<15, 1> scale = 1.0) { sc_time start = sc_time_stamp(); sc_assert(depth % pe_bw == 0); int depth_raw = depth / pe_bw; sc_assert((window * window * depth) % (pe_bw * db_out_n) == 0); int wb_ctrl_row_N = ((window * window * depth) / (pe_bw * db_out_n)) + 1; int db_replay = ceil(W_N / pe_n) - 1; int row_size_Y = (row_size - (((int)floor((float)window / 2.0f) - zp) * 2)) / stride; int image_size = depth_raw * row_size * row_size; // used for align multiple images. // start CNNA do_cmd(weight_ctrl, 0 | (wb_ctrl_row_N << 20)); // setup do_cmd(ctrl_image_data, (raw_image_data ? 1 : 0)); do_cmd(ctrl_depth, depth_raw); do_cmd(ctrl_stride, 0); // stride do_cmd(ctrl_window_size, window); do_cmd(ctrl_row_size_pkg, row_size); do_cmd(ctrl_acf, 1 | (hwcore::hf::ufixed2bv<15, 1>(scale).to_uint() << 1)); // set to use ReLU do_cmd(ctrl_output_channel, 0); do_cmd(ctrl_db_output, 0); // setup wb // do_cmd(ctrl_row_N, 1); // wb_ctrl_row_N do_cmd(weight_ctrl, (X_N * row_size_Y * row_size_Y)); // * ); // do_cmd(weight_ctrls_replay, row_size_Y); // setup db do_cmd(ctrl_zeropad, zp); do_cmd(ctrl_replay, db_replay); do_cmd(ctrl_image_size, image_size); do_cmd(ctrl_stitch_depth, 0); do_cmd(ctrl_stitch_buf_depth, 0); sc_time setup = sc_time_stamp() - start; // of << "paramsetup:" << (sc_time_stamp() - start).to_string() << std::endl; // dma magic dma_sink_ctrl.write(Y); dma_source_w_ctrl.write(W); dma_source_ctrl.write(X); dma_source_w_done.read(); dma_source_done.read(); std::cout << "CNNA tb write done------------------------------------------------------------------>>>" << std::endl; dma_sink_done.read(); std::cout << "CNNA tb done------------------------------------
------------------------------<<<" << std::endl; } int do_pool(dma_pkg & X, dma_pkg & Y, int depth, int row_size, int stride, int X_N, int window, int zp) { // ofstream of; // of.open("result.txt"); sc_time start = sc_time_stamp(); sc_assert(depth % pe_bw == 0); int depth_raw = depth / pe_bw; int db_replay = 1; int row_size_Y = (row_size - (((int)floor((float)window / 2.0f) - zp) * 2)) / stride; int image_size = depth_raw * row_size * row_size; // used for align multiple images. // start CNNA // setup do_cmd(ctrl_image_data, 0); do_cmd(ctrl_depth, depth_raw); do_cmd(ctrl_stride, stride - 1); // stride do_cmd(ctrl_window_size, window); do_cmd(ctrl_row_size_pkg, row_size); // do_cmd(ctrl_acf, 1); // set to use ReLU do_cmd(ctrl_output_channel, 1); do_cmd(ctrl_db_output, 1); // setup wb // do_cmd(ctrl_row_N, wb_ctrl_row_N); // do_cmd(weight_ctrl, 0); // do_cmd(weight_ctrl, X_N * row_size_Y * row_size_Y); // * ); // do_cmd(weight_ctrls_replay, row_size_Y); // do_cmd(ctrl_channel, 0); // setup db do_cmd(ctrl_zeropad, zp); do_cmd(ctrl_replay, db_replay); do_cmd(ctrl_image_size, image_size); // pool do_cmd(ctrl_pool_size, window); do_cmd(ctrl_pool_type, 0); do_cmd(ctrl_pool_depth, depth); do_cmd(ctrl_stitch_depth, 0); do_cmd(ctrl_stitch_buf_depth, 0); // do_cmd(ctrl_pool_N,0); sc_time setup = sc_time_stamp() - start; // of << "paramsetup:" << (sc_time_stamp() - start).to_string() << std::endl; // dma magic // Y.data_array // Y.size *= 2; dma_sink_ctrl.write(Y); // dma_source_ctrl.write(W); // of << "Wdone:" << (sc_time_stamp() - start).to_string() << std::endl; dma_source_ctrl.write(X); dma_source_done.read(); // of << "Xdone:" << (sc_time_stamp() - start).to_string() << std::endl; std::cout << "CNNA tb write done------------------------------------------------------------------>>>" << std::endl; dma_sink_done.read(); // of << "done:" << (sc_time_stamp() - start).to_string() << std::endl; // of.close(); std::cout << "CNNA tb done------------------------------------------------------------------<<<" << std::endl; for (int i = 0; i < Y.size; i++) { // int expected = func(a + offset, b + offset, 0, i); int Yindx = i; int Yindx_add = Yindx / dma_bw; int Yindx_cut = Yindx % dma_bw; sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>( Y.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); int got = got_fix.to_int(); debug_cout << "[" << i << "]: " << got_fix.to_float() << std::endl; /* debug_cout << "[i,a,b,c]:[" << i << "," << a << "," << b << "," << c << "]- func(" << a + offset << "," << b + offset << "," << 0 << "," << i << ")=[expected,got]:[" << expected << "," << got << "] Yindx = " << Yindx << "==>" << Yindx_add << "." << Yindx_cut << std::endl; */ } } void do_fc(dma_pkg & X, dma_pkg & W, dma_pkg & Y, int N_in, int N_out, int X_N, int w_row_N, sc_ufixed<15, 1> scale = 1.0) { // ofstream of; // of.open("result.txt"); sc_time start = sc_time_stamp(); sc_assert(X.size * dma_bw == N_in); // sc_assert(Y.size * dma_bw == N_out); // sc_assert(W.size * dma_bw <= w_row_N * N_out); // sc_assert(depth % pe_bw == 0); int depth_raw = 1; sc_assert((w_row_N) % (pe_bw * db_out_n) == 0); int wb_ctrl_row_N = ((w_row_N) / (pe_bw * db_out_n)); int db_replay = ((N_out) / pe_n) - 1; sc_assert(db_replay == 0); int row_size_Y = N_out; int image_size = (N_in / pe_bw); // used for align multiple images. // setup do_cmd(ctrl_image_data, 0); do_cmd(ctrl_depth, 0); do_cmd(ctrl_stride, 0); // stride do_cmd(ctrl_window_size, 0); do_cmd(ctrl_row_size_pkg, (N_in / pe_bw)); do_cmd(ctrl_acf, 0 | (hwcore::hf::ufixed2bv<15, 1>(scale).to_uint() << 1)); // set to use ReLU do_cmd(ctrl_output_channel, 0); do_cmd(ctrl_db_output, 0); // setup wb // do_cmd(ctrl_row_N, 1); do_cmd(weight_ctrl, 1 << 30); // do_cmd(weight_ctrl, X_N); // * ); // do_cmd(weight_ctrls_replay, row_size_Y); // setup db do_cmd(ctrl_zeropad, 0); do_cmd(ctrl_replay, db_replay); do_cmd(ctrl_image_size, image_size); do_cmd(ctrl_stitch_depth, 0); do_cmd(ctrl_stitch_buf_depth, 0); sc_time setup = sc_time_stamp() - start; // of << "paramsetup:" << (sc_time_stamp() - start).to_string() << std::endl; // dma magic dma_sink_ctrl.write(Y); dma_source_w_ctrl.write(W); dma_source_ctrl.write(X); dma_source_w_done.read(); dma_source_done.read(); std::cout << "CNNA tb write done------------------------------------------------------------------>>>" << std::endl; dma_sink_done.read(); std::cout << "CNNA tb done------------------------------------------------------------------<<<" << std::endl; } sc_fifo<dma_pkg> dma_source_ctrl; sc_fifo<uint64> dma_source_done; void dma_source_thread() { while (true) { dma_pkg tmp = dma_source_ctrl.read(); for (int i = 0; i < tmp.size; i++) { hwcore::pipes::sc_data_stream_t<P_input_width> tmp_out; tmp_out.data = tmp.data_array[i]; tmp_out.tlast = (i == tmp.size - 1); tmp_out.setKeep(); dma_source.write(tmp_out); HLS_DEBUG(1, 1, 0, "dma_x_source sending new data[%d,%d]: %s.", i + 1, tmp.size, tmp_out.data.to_string().c_str()); } HLS_DEBUG(1, 1, 0, "done"); dma_source_done.write(tmp.size); } } sc_fifo<dma_pkg> dma_source_buf_ctrl; sc_fifo<uint64> dma_source_buf_done; void dma_source_buf_thread() { while (true) { dma_pkg tmp = dma_source_buf_ctrl.read(); for (int i = 0; i < tmp.size; i++) { hwcore::pipes::sc_data_stream_t<P_input_width> tmp_out; tmp_out.data = tmp.data_array[i]; tmp_out.tlast = (i == tmp.size - 1); tmp_out.setKeep(); dma_buf_source.write(tmp_out); HLS_DEBUG(1, 1, 0, "dma_buf_source sending new data[%d,%d]: %s.", i + 1, tmp.size, tmp_out.data.to_string().c_str()); } HLS_DEBUG(1, 1, 0, "done"); dma_source_buf_done.write(tmp.size); } } sc_fifo<dma_pkg> dma_source_w_ctrl; sc_fifo<uint64> dma_source_w_done; void dma_source_w_thread() { while (true) { dma_pkg tmp = dma_source_w_ctrl.read(); for (int i = 0; i < tmp.size; i++) { hwcore::pipes::sc_data_stream_t<P_input_width> tmp_out; tmp_out.data = tmp.data_array[i]; tmp_out.tlast = (i == tmp.size - 1); tmp_out.setKeep(); dma_w_source.write(tmp_out); HLS_DEBUG(1, 1, 0, "dma_w_source sending new data[%d,%d]: %s.", i + 1, tmp.size, tmp_out.data.to_string().c_str()); } HLS_DEBUG(1, 1, 0, "done"); dma_source_w_done.write(tmp.size); } } sc_fifo<sc_uint<64> > dma_source_ctrl_ctrl; void dma_source_ctrl_thread() { while (true) { sc_uint<64> tmp = dma_source_ctrl_ctrl.read(); hwcore::pipes::sc_data_stream_t<64> tmp_out; tmp_out.setKeep(); tmp_out.data = tmp; tmp_out.tlast = 1; dma_ctrl_source.write(tmp_out); HLS_DEBUG(1, 1, 0, "dma_ctrl_source sending new data: %s.", tmp_out.data.to_string().c_str()); } } sc_fifo<dma_pkg> dma_sink_ctrl; sc_fifo<uint64> dma_sink_done; #if 0 void live_debug() { for(int x= 0; x < 14; x++) { for(int y=0; y < 14 ; y++) { for(int ) } } } #endif void dma_sink_thread() { while (true) { uint64 size = 0; dma_pkg tmp = dma_sink_ctrl.read(); for (int i = 0; i < tmp.size; i++) { size++; hwcore::pipes::sc_data_stream_t<P_input_width> tmp_in; dma_sink.read(tmp_in); tmp.data_array[i] = tmp_in.data; HLS_DEBUG(1, 1, 0, "dma_sink got new data[%d,%d]: %s.", i + 1, tmp.size, tmp_in.data.to_string().c_str()); // sc_assert((tmp_in.tlast == 0 && i != tmp.size - 1) || (tmp_in.tlast == 1 && i == tmp.size - 1)); if (tmp_in.tlast == 1) { // sc_assert(i == tmp.size - 1); break; } } HLS_DEBUG(1, 1, 0, "done"); dma_sink_done.write(size); } } virtual ~tb_cnn_2d() { sc_close_vcd_trace_file(tracePtr); } };
#ifndef SYSTEMC_EXAMPLES_COUNTER_HPP #define SYSTEMC_EXAMPLES_COUNTER_HPP #include <systemc.h> using namespace sc_core; /** * @brief Construct a new Counter module object. * * Count is only during positive edges of the clock. * Reset is only during 1'b0. After reset asserts, it goes out of reset. * Enable must be asserted to start the count, otherwise the output will hold * latest value. * * @tparam N - number of counter bits. */ template <int N> SC_MODULE(Counter) { //------------------------------Module Inputs------------------------------ // Input clock sc_in_clk clk; // Reset bar (reset when 1'b0) sc_in<bool> rstb; // Starts the counter sc_in<bool> enable; // N-bit output of the counter sc_out<sc_uint<N > > count_out; //-----------------------------Local Variables----------------------------- sc_uint<4> count_int; public: /** * @brief Default constructor for Counter. */ SC_CTOR(Counter) { SC_METHOD(count); // Sensitive to the clk posedge to carry out the count sensitive << clk.pos(); // Sensitive to any state change to go in or out of reset sensitive << rstb; } //---------------------------------Methods--------------------------------- /** * @brief Methods that counts in every posedge of the clock, unless rstb is * equal to 0, then the output will be always 0. Enable needs to be * asserted, otherwise it will show latest value of the counter. */ void count(); }; template <int N> void Counter<N>::count() { // When in reset state, set counter to 0. if (this->rstb.read() == 0) { this->count_int = 0; this->count_out.write(count_int); } // Count when module is enable else if (this->enable.read() == 1) { this->count_int += 1; this->count_out.write(count_int); } } #endif // SYSTEMC_EXAMPLES_COUNTER_HPP
#ifndef SOBEL_EDGE_DETECTOR_HPP #define SOBEL_EDGE_DETECTOR_HPP #define USING_TLM_TB_EN #include <systemc.h> SC_MODULE(Edge_Detector) { #ifndef USING_TLM_TB_EN sc_inout<sc_uint<64>> data; sc_in<sc_uint<24>> address; #else sc_uint<64> data; sc_uint<24> address; #endif // USING_TLM_TB_EN const double delay_full_adder_1_bit = 0.361; const double delay_full_adder = delay_full_adder_1_bit * 16; const double delay_multiplier = 9.82; const sc_int<16> sobelGradientX[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}; const sc_int<16> sobelGradientY[3][3] = {{-1, -2, -1}, { 0, 0, 0}, { 1, 2, 1}}; sc_int<16> localWindow[3][3]; sc_int<16> resultSobelGradientX; sc_int<16> resultSobelGradientY; sc_int<16> localMultX[3][3]; sc_int<16> localMultY[3][3]; sc_event gotLocalWindow; sc_event rd_t, wr_t; sc_event mult_x, mult_y, sum_x, sum_y; SC_CTOR(Edge_Detector) { SC_THREAD(wr); SC_THREAD(rd); SC_THREAD(compute_sobel_gradient_x); SC_THREAD(compute_sobel_gradient_y); SC_THREAD(perform_mult_gradient_x); SC_THREAD(perform_mult_gradient_y); SC_THREAD(perform_sum_gradient_x); SC_THREAD(perform_sum_gradient_y); } virtual void write(); virtual void read(); void wr(); void rd(); void compute_sobel_gradient_x(); void compute_sobel_gradient_y(); void perform_mult_gradient_x(); void perform_mult_gradient_y(); void perform_sum_gradient_x(); void perform_sum_gradient_y(); }; #endif // SOBEL_EDGE_DETECTOR_HPP
#ifndef IPS_SEQ_ITEM_VGA_HPP #define IPS_SEQ_ITEM_VGA_HPP #define int64 systemc_int64 #define uint64 systemc_uint64 #include <systemc.h> #include <systemc-ams.h> #undef int64 #undef uint64 #define int64 opencv_int64 #define uint64 opencv_uint64 #include <opencv2/opencv.hpp> #undef int64 #undef uint64 #include "vunit.hpp" // Image path #define IPS_IMG_PATH_TB "../../tools/datagen/src/imgs/car_rgb_noisy_image.jpg" /** * @brief This class is used to generate the data for the AMS test * * @tparam BITS - the number of output bits of the digital pixel * @tparam H_ACTIVE - output horizontal active video pixels * @tparam H_FP - wait after the display period before the sync * horizontal pulse * @tparam H_SYNC_PULSE - assert HSYNC * @tparam H_BP - wait after the sync horizontal pulse before starting * the next display period * @tparam V_ACTIVE - output vertical active video pixels * @tparam V_FP - wait after the display period before the sync * vertical pulse * @tparam V_SYNC_PULSE - assert VSYNC * @tparam V_BP - wait after the sync vertical pulse before starting * the next display period */ template < unsigned int BITS = 8, unsigned int H_ACTIVE = 640, unsigned int H_FP = 16, unsigned int H_SYNC_PULSE = 96, unsigned int H_BP = 48, unsigned int V_ACTIVE = 480, unsigned int V_FP = 10, unsigned int V_SYNC_PULSE = 2, unsigned int V_BP = 33, int VMIN = 0, int VMAX = 5, VUnit VU = VUnit::v> SCA_TDF_MODULE(seq_item_vga) { protected: cv::Mat tx_img; // Min voltage value based on the voltage units const double V_MIN = static_cast<double>(VMIN) / static_cast<double>(VU); // Max voltage value based on the voltage units const double V_MAX = static_cast<double>(VMAX) / static_cast<double>(VU); // Max digital output code const double MAX_DIG = static_cast<double>((1 << BITS) - 1); public: // Counters sca_tdf::sca_de::sca_in<unsigned int> hcount; sca_tdf::sca_de::sca_in<unsigned int> vcount; // Output pixel sca_tdf::sca_out<double> o_red; sca_tdf::sca_out<double> o_green; sca_tdf::sca_out<double> o_blue; SC_CTOR(seq_item_vga) { // Read image const std::string img_path = IPS_IMG_PATH_TB; cv::Mat read_img = cv::imread(img_path, cv::IMREAD_COLOR); // CV_8UC3 Type: 8-bit unsigned, 3 channels (e.g., for a color image) read_img.convertTo(this->tx_img, CV_8UC3); // Check if the image is loaded successfully if (this->tx_img.empty()) { std::cerr << "Error: Could not open or find the image!" << std::endl; exit(EXIT_FAILURE); } } void set_attributes() { // Propagation time from input to output set_timestep(sca_core::sca_time(1, sc_core::SC_NS)); this->o_red.set_delay(17); this->o_green.set_delay(17); this->o_blue.set_delay(17); } void processing() { const int IMG_ROW = static_cast<int>(this->vcount.read()) - (V_SYNC_PULSE + V_BP); const int IMG_COL = static_cast<int>(this->hcount.read()) - (H_SYNC_PULSE + H_BP); if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= static_cast<int>(V_ACTIVE)) || (IMG_COL >= static_cast<int>(H_ACTIVE))) { this->o_red.write(0.0); this->o_green.write(0.0); this->o_blue.write(0.0); } else { if ((IMG_ROW >= this->tx_img.rows) || (IMG_COL >= this->tx_img.cols)) { this->o_red.write(0.0); this->o_green.write(0.0); this->o_blue.write(0.0); } else { cv::Vec3b pixel = tx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL, 0); this->o_red.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[0]))); this->o_green.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[1]))); this->o_blue.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[2]))); } } } /** * @brief Convert the digital signal into analog signal * The N-bit digital code is converted into an analog signal in a voltage * range from Vmin to Vmax */ double sc_uint2double(sc_uint<BITS> in) { double dig_in = static_cast<double>(in); return V_MIN + (dig_in / MAX_DIG) * (V_MAX - V_MIN); } }; #endif // IPS_SEQ_ITEM_VGA_HPP
#ifndef IPS_SEQ_ITEM_VGA_HPP #define IPS_SEQ_ITEM_VGA_HPP #define int64 systemc_int64 #define uint64 systemc_uint64 #include <systemc.h> #include <systemc-ams.h> #undef int64 #undef uint64 #define int64 opencv_int64 #define uint64 opencv_uint64 #include <opencv2/opencv.hpp> #undef int64 #undef uint64 #include "vunit.hpp" // Image path #define IPS_IMG_PATH_TB "../../tools/datagen/src/imgs/car_rgb_noisy_image.jpg" /** * @brief This class is used to generate the data for the AMS test * * @tparam BITS - the number of output bits of the digital pixel * @tparam H_ACTIVE - output horizontal active video pixels * @tparam H_FP - wait after the display period before the sync * horizontal pulse * @tparam H_SYNC_PULSE - assert HSYNC * @tparam H_BP - wait after the sync horizontal pulse before starting * the next display period * @tparam V_ACTIVE - output vertical active video pixels * @tparam V_FP - wait after the display period before the sync * vertical pulse * @tparam V_SYNC_PULSE - assert VSYNC * @tparam V_BP - wait after the sync vertical pulse before starting * the next display period */ template < unsigned int BITS = 8, unsigned int H_ACTIVE = 640, unsigned int H_FP = 16, unsigned int H_SYNC_PULSE = 96, unsigned int H_BP = 48, unsigned int V_ACTIVE = 480, unsigned int V_FP = 10, unsigned int V_SYNC_PULSE = 2, unsigned int V_BP = 33, int VMIN = 0, int VMAX = 5, VUnit VU = VUnit::v> SCA_TDF_MODULE(seq_item_vga) { protected: cv::Mat tx_img; // Min voltage value based on the voltage units const double V_MIN = static_cast<double>(VMIN) / static_cast<double>(VU); // Max voltage value based on the voltage units const double V_MAX = static_cast<double>(VMAX) / static_cast<double>(VU); // Max digital output code const double MAX_DIG = static_cast<double>((1 << BITS) - 1); public: // Counters sca_tdf::sca_de::sca_in<unsigned int> hcount; sca_tdf::sca_de::sca_in<unsigned int> vcount; // Output pixel sca_tdf::sca_out<double> o_red; sca_tdf::sca_out<double> o_green; sca_tdf::sca_out<double> o_blue; SC_CTOR(seq_item_vga) { // Read image const std::string img_path = IPS_IMG_PATH_TB; cv::Mat read_img = cv::imread(img_path, cv::IMREAD_COLOR); // CV_8UC3 Type: 8-bit unsigned, 3 channels (e.g., for a color image) read_img.convertTo(this->tx_img, CV_8UC3); // Check if the image is loaded successfully if (this->tx_img.empty()) { std::cerr << "Error: Could not open or find the image!" << std::endl; exit(EXIT_FAILURE); } } void set_attributes() { // Propagation time from input to output set_timestep(sca_core::sca_time(1, sc_core::SC_NS)); this->o_red.set_delay(17); this->o_green.set_delay(17); this->o_blue.set_delay(17); } void processing() { const int IMG_ROW = static_cast<int>(this->vcount.read()) - (V_SYNC_PULSE + V_BP); const int IMG_COL = static_cast<int>(this->hcount.read()) - (H_SYNC_PULSE + H_BP); if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= static_cast<int>(V_ACTIVE)) || (IMG_COL >= static_cast<int>(H_ACTIVE))) { this->o_red.write(0.0); this->o_green.write(0.0); this->o_blue.write(0.0); } else { if ((IMG_ROW >= this->tx_img.rows) || (IMG_COL >= this->tx_img.cols)) { this->o_red.write(0.0); this->o_green.write(0.0); this->o_blue.write(0.0); } else { cv::Vec3b pixel = tx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL, 0); this->o_red.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[0]))); this->o_green.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[1]))); this->o_blue.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[2]))); } } } /** * @brief Convert the digital signal into analog signal * The N-bit digital code is converted into an analog signal in a voltage * range from Vmin to Vmax */ double sc_uint2double(sc_uint<BITS> in) { double dig_in = static_cast<double>(in); return V_MIN + (dig_in / MAX_DIG) * (V_MAX - V_MIN); } }; #endif // IPS_SEQ_ITEM_VGA_HPP
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #pragma once #define SC_INCLUDE_FX #include <systemc.h> #include "hwcore/pipes/streamsplit.h" #include "hwcore/pipes/streammerge.h" #include "hwcore/pipes/streamresize.h" #include "hwcore/pipes/data_types.h" #if __RTL_SIMULATION__ //#include "DMA_performance_tester_rtl_wrapper.h" //#else //#include "DMA_generic_performance_tester.hpp" #endif #define split_N 64 const long test_size = 20*split_N; SC_MODULE(mon_split_and_merge) { sc_fifo_in<hwcore::pipes::sc_data_stream_t<16> > data_in; SC_CTOR(mon_split_and_merge) { SC_THREAD(mon_thread); } void mon_thread() { for(int a=0;a<2;a++) { uint16_t data_gen = 0; hwcore::pipes::sc_data_stream_t<16> tmp_in; do { tmp_in = data_in.read(); std::cout << "(mon) got signal." << std::endl; //for(int i=0;i<split_N;i++) //{ if(tmp_in.template getKeep<16>(0)==1) { int tmp = tmp_in.template getData<sc_uint, 16>(0).to_uint(); std::cout << "(mon) got new data: " <<tmp << std::endl; sc_assert(tmp == data_gen); data_gen++; } //} }while(data_gen < test_size); } std::cout << "Test finish no errors" << std::endl; sc_stop(); } }; SC_MODULE(wave_split_and_merge) { sc_fifo_out<hwcore::pipes::sc_data_stream_t<16> > data_out; SC_CTOR(wave_split_and_merge) { SC_THREAD(wave_thread); } void wave_thread() { hwcore::pipes::sc_data_stream_t<16> tmp; for (int i = 0; i < test_size; i++) { tmp.data = i; std::cout << "(wave) write new data: " << i << std::endl; tmp.setKeep(); tmp.tlast = 1; data_out.write(tmp); } tmp.setEOP(); data_out.write(tmp); for (int i = 0; i < test_size; i++) { tmp.data = i; std::cout << "(wave) write new data: " << i << std::endl; tmp.setKeep(); tmp.tlast = 1; data_out.write(tmp); } tmp.setEOP(); data_out.write(tmp); } }; SC_MODULE(tb_split_and_merge) { #if __RTL_SIMULATION__ //DMA_performance_tester_rtl_wrapper u1; #else //DMA_performance_tester u1; #endif sc_clock clk; sc_signal<bool> reset; wave_split_and_merge wave; sc_fifo<hwcore::pipes::sc_data_stream_t<16> > wave_2_u1; hwcore::pipes::sc_stream_splitter<16,split_N,false> u1_ss; hwcore::hf::sc_static_list<sc_fifo<hwcore::pipes::sc_data_stream_t<16> >, split_N> u1_2_u2; //sc_fifo<hwcore::pipes::DATA_STREAM_t<16> > u1_2_u2[32]; hwcore::pipes::sc_stream_merge_raw<16,split_N> u2_sm; sc_fifo<hwcore::pipes::sc_data_stream_t<16*split_N> > u2_2_u3; hwcore::pipes::sc_stream_resize<16*split_N, 16> u3_sr; sc_fifo<hwcore::pipes::sc_data_stream_t<16> > u3_2_mon; mon_split_and_merge mon; SC_CTOR(tb_split_and_merge) : u1_ss("u1_ss"),u2_sm("u2_sm"), u3_sr("u3_sr"), wave("wave"), mon("mon"), clk("clock", sc_time(10, SC_NS)),wave_2_u1(64),u2_2_u3(64), u3_2_mon(64),u1_2_u2("fifo",1) { wave.data_out(wave_2_u1); u1_ss.din(wave_2_u1); u1_ss.clk(clk); u1_ss.reset(reset); for(int i=0;i<split_N;i++) { u1_ss.dout[i](u1_2_u2.get(i)); u2_sm.din[i](u1_2_u2.get(i)); } u2_sm.clk(clk); u2_sm.reset(reset); u2_sm.dout(u2_2_u3); u3_sr.din(u2_2_u3); u3_sr.clk(clk); u3_sr.reset(reset); u3_sr.dout(u3_2_mon); mon.data_in(u3_2_mon); } };
#include<systemc.h> #include<vector> #include "interfaces.hpp" #include<nana/gui/widgets/listbox.hpp> using std::vector; class instruction_queue_rob: public sc_module { public: sc_port<read_if> in; sc_port<write_if_f> out; sc_port<read_if> in_rob; SC_HAS_PROCESS(instruction_queue_rob); instruction_queue_rob(sc_module_name name, vector<string> inst_q,int rb_sz, nana::listbox &instr); void main(); void leitura_rob(); bool queue_is_empty(); unsigned int get_instruction_counter(); private: unsigned int pc; struct instr_q { string instruction; unsigned int pc; }; vector<instr_q> instruct_queue; vector<string> original_instruct; vector<vector<instr_q>> last_instr; vector<unsigned int> last_pc; nana::listbox &instructions; void replace_instructions(unsigned int pos,unsigned int index); void add_instructions(unsigned int pos, vector<instr_q> instructions); };
/* * MIPS.hpp * * Created on: Jun 14, 2014 * Author: Pimenta */ #ifndef MIPS_HPP_ #define MIPS_HPP_ // lib #include <systemc.h> // local #include "Context.hpp" #include "Thread.hpp" #include "readwrite_if.hpp" struct Bitmap { uint16_t unused0; uint16_t magic_number; uint32_t file_size; uint32_t reserved; uint32_t header_size; uint32_t data_distance; uint32_t width; uint32_t height; uint16_t planes; uint16_t bpp; uint32_t compression; uint32_t data_size; uint32_t horizontal_resolution; uint32_t vertical_resolution; uint32_t palette_size; uint32_t important_colors; void* buf; }; SC_MODULE(MIPS) { sc_in<bool> clk; sc_port<readwrite_if> ioController; uint32_t breg[32]; Bitmap bg; SC_CTOR(MIPS) { SC_METHOD(exec); sensitive << clk.pos(); const char fn[] = "mandrill2.bmp"; const char mode[] = "rb"; breg[4] = (uint32_t)fn; breg[5] = (uint32_t)mode; fileOpen(); breg[4] = breg[2]; breg[5] = (uint32_t)&bg.magic_number; breg[6] = 54; fileRead(); bg.buf = malloc(bg.width*bg.height*bg.bpp/8); breg[5] = (uint32_t)bg.buf; breg[6] = bg.width*bg.height*bg.bpp/8; fileRead(); fileClose(); } ~MIPS() { free(bg.buf); } void exec() { uint32_t ioWord; static bool inited = false; if (!inited) { inited = true; ioController->read(0xFF400104, 4, &ioWord); int w = ioWord >> 16, h = ioWord & 0xFFFF; for (int y = 0; y < h && y < int(bg.height); y++) { for (int x = 0; x < w && x < int(bg.width); x++) { uint32_t rgbpixel; if (bg.bpp == 8) { uint8_t rawpixel = ((uint8_t*)bg.buf)[(bg.height - 1 - y)*bg.width + x]; rgbpixel = rawpixel | (rawpixel << 8) | (rawpixel << 16); } else rgbpixel = ((uint32_t*)bg.buf)[(bg.height - 1 - y)*bg.width + x]; ioController->write(0xFF000000 + ((y*w + x) << 2), 4, &rgbpixel); } } } ioController->read(0xFF400000 + 'w', 4, &ioWord); if (ioWord == 1) { printf("Insert a string: "); fflush(stdout); std::string tmp; ioController->read(0xFF400114, 4, &ioWord); while (ioWord != '\r') { tmp += char(ioWord); printf("%c", char(ioWord)); fflush(stdout); ioController->read(0xFF400114, 4, &ioWord); } printf("\nString inserted: %s\n", tmp.c_str()); fflush(stdout); } ioController->read(0xFF400102, 4, &ioWord); if (ioWord) exit(); breg[4] = 33; sleep(); } // =========================================================================== // syscalls (code in v0) // =========================================================================== // v0: 2 // a0: 4 // a1: 5 // a2: 6 void exit() { // v0 = 10 sc_stop(); } void fileOpen() { // v0 = 13 breg[2] = (uint32_t)fopen((const char*)breg[4], (const char*)breg[5]); } void fileRead() { // v0 = 14 breg[2] = (uint32_t)fread((void*)breg[5], breg[6], 1, (FILE*)breg[4]); } void fileWrite() { // v0 = 15 breg[2] = (uint32_t)fwrite((const void*)breg[5], breg[6], 1, (FILE*)breg[4]); } void fileClose() { // v0 = 16 fclose((FILE*)breg[4]); } void sleep() { // v0 = 32 Thread::sleep(breg[4]); } }; #endif /* MIPS_HPP_ */
/***************************************************************************\ * * * ___ ___ ___ ___ * / /\ / /\ / /\ / /\ * / /:/ / /::\ / /::\ / /::\ * / /:/ / /:/\:\ / /:/\:\ / /:/\:\ * / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/ * / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/ * /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/ * \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/ * \ \:\ \ \:\ \ \:\ \ \:\ * \ \ \ \ \:\ \ \:\ \ \:\ * \__\/ \__\/ \__\/ \__\/ * * * * * This file is part of TRAP. * * TRAP is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * or see <http://www.gnu.org/licenses/>. * * * * (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com * \***************************************************************************/ #ifndef IRQGENERATOR_HPP #define IRQGENERATOR_HPP #include <iostream> #include <systemc.h> #include <trap_utils.hpp> #include <boost/lexical_cast.hpp> #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> //Now some stuff for generating random numbers #include <ctime> #include <boost/random/linear_congruential.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/uniform_real.hpp> #include <boost/random/variate_generator.hpp> #ifdef BOOST_NO_STDC_NAMESPACE namespace std { using ::time; } #endif class IrqGenerator : public sc_module{ private: sc_time latency; int lastIrq; // Random number generator to be used during algorithm execution boost::minstd_rand generator; public: //The initiator socket is used for sending out, raising interrupts; //the target socket for receiving the acknowledgement tlm_utils::simple_initiator_socket< IrqGenerator, 32 > initSocket; tlm_utils::simple_target_socket< IrqGenerator, 32 > targSocket; SC_HAS_PROCESS( IrqGenerator ); IrqGenerator( sc_module_name generatorName, sc_time latency ) : sc_module(generatorName), targSocket(("irq_target_" + boost::lexical_cast<std::string>(generatorName)).c_str()), latency(latency), generator(static_cast<unsigned int>(std::time(NULL))){ this->targSocket.register_b_transport(this, &IrqGenerator::b_transport); this->lastIrq = -1; SC_THREAD(generateIrq); end_module(); } //Method used for receiving acknowledgements of interrupts; the ack consists of //uninteresting data and the address corresponds to the interrupt signal to //be lowered //As a response, I lower the interrupt by sending a NULL pointer on the initSocket void b_transport(tlm::tlm_generic_payload& trans, sc_time& delay){ if(this->lastIrq < 0){ THROW_EXCEPTION("Error, lowering an interrupt which hasn't been raised yet!!"); } tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); unsigned char* ptr = trans.get_data_ptr(); if(trans.get_command() == tlm::TLM_READ_COMMAND){ THROW_EXCEPTION("Error, the read request is not currently supported by external PINs"); } else if(cmd == tlm::TLM_WRITE_COMMAND){ if(this->lastIrq != adr){ THROW_EXCEPTION("Error, lowering interrupt " << std::hex << std::showbase << (unsigned int)adr << " while " << std::hex << std::showbase << this->lastIrq << " was raised"); } else{ //finally I can really lower the interrupt: I send 0 on //the initSocked unsigned char data = 0; trans.set_data_ptr(&data); trans.set_dmi_allowed(false); trans.set_response_status( tlm::TLM_INCOMPLETE_RESPONSE ); sc_time delay; this->initSocket->b_transport(trans, delay); if(trans.is_response_error()){ std::string errorStr("Error in b_transport of PIN, response status = " + trans.get_response_string()); SC_REPORT_ERROR("TLM-2", errorStr.c_str()); } this->lastIrq = -1; } } trans.set_response_status(tlm::TLM_OK_RESPONSE); } //Simple systemc thread which keeps on generating interrupts; //the number of the interrupt is printed to the screen before sending it to //the processor void generateIrq(){ while(true){ //An interrupt transaction is composed of a data pointer (containing //0 if the interrupt has to be lowered, different if raised) and an //address, corrisponding to the ID of the interrupt if(this->lastIrq == -1){ unsigned char data = 1; tlm::tlm_generic_payload trans; boost::uniform_int<> degen_dist(0x1, 0xe); boost::variate_generator<boost::minstd_rand&, boost::uniform_int<> > deg(this->generator, degen_dist); this->lastIrq = deg(); std::cerr << "Sending out IRQ id=" << std::hex << std::showbase << this->lastIrq << std::endl; trans.set_address(this->lastIrq); trans.set_data_ptr(&data); trans.set_data_length(0); trans.set_byte_enable_ptr(0); trans.set_dmi_allowed(false); trans.set_response_status( tlm::TLM_INCOMPLETE_RESPONSE ); sc_time delay; this->initSocket->b_transport(trans, delay); if(trans.is_response_error()){ std::string errorStr("Error in generateIrq, response status = " + trans.get_response_string()); SC_REPORT_ERROR("TLM-2", errorStr.c_str()); } } wait(this->latency); } } }; #endif
#include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU32 : public rand_obj { randv< sc_bv<2> > op ; randv< sc_uint<32> > a, b ; ALU32() : op(this), a(this), b(this) { constraint ( (op() != 0x0) || ( 4294967295u >= a() + b() ) ); constraint ( (op() != 0x1) || ((4294967295u >= a() - b()) && (b() <= a()) ) ); constraint ( (op() != 0x2) || ( 4294967295u >= a() * b() ) ); constraint ( (op() != 0x3) || ( b() != 0 ) ); } friend std::ostream & operator<< (std::ostream & o, ALU32 const & alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b ; return o; } }; int sc_main (int argc, char** argv) { boost::timer timer; ALU32 c; c.next(); std::cout << "first: " << timer.elapsed() << "\n"; for (int i=0; i<1000; ++i) { c.next(); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
#pragma once /** @class Splitter_module @brief Splits an incoming data stream into two or three parts. Simplified block diagram ------------------------ ``` fifo_port<T> _____ ____ fifo_export<T> \ / Splitter_module --- sig1_export<T> signal_port<T> ___/ \____ sig2_export<T> ``` Reads input from either a connected FIFO or Signal. Write to any connected output. ******************************************************************************** */ #include "systemc.hpp" #include "top.hpp" #include "report.hpp" template< typename T> struct Splitter_module : sc_core::sc_module { constexpr static const char* MSGID = "/Doulos/Example/splitter"; constexpr static auto BIND = sc_core::SC_ZERO_OR_MORE_BOUND; sc_core::sc_port<sc_core::sc_signal_in_if<T>,1,BIND> signal_port { "signal_port" }; sc_core::sc_port<sc_core::sc_fifo_in_if<T>,1,BIND> fifo_port { "fifo_port" }; sc_core::sc_export<sc_core::sc_fifo_in_if<T>> fifo_export { "fifo_export" }; sc_core::sc_export<sc_core::sc_signal_in_if<T>> sig1_export { "sig1_export" }; sc_core::sc_export<sc_core::sc_signal_in_if<T>> sig2_export { "sig2_export" }; Splitter_module( sc_core::sc_module_name instance ) : sc_module( instance ) { SC_HAS_PROCESS( Splitter_module ); SC_THREAD( transfer ); fifo_export.bind( fifo ); sig1_export.bind( sig1 ); sig2_export.bind( sig2 ); } void start_of_simulation(); void transfer(); sc_core::sc_fifo<T> fifo{ 1 }; sc_core::sc_signal<T> sig1{ "sig1" }; sc_core::sc_signal<T> sig2{ "sig2" }; // Following are here only for tracing purposes T xfer_value{}; private: bool is_connected( sc_core::sc_object* self , sc_core::sc_object* channel , sc_core::sc_interface* chan_if ); bool fifo_connected{ false }; bool sig1_connected{ false }; bool sig2_connected{ false }; void end_of_elaboration(); }; template< typename T> bool Splitter_module<T>::is_connected( sc_core::sc_object* self , sc_core::sc_object* channel , sc_core::sc_interface* chan_if ) { sc_assert( self->get_parent_object() != nullptr ); DEBUG( "Looking for connections to " << channel->name() ); auto parent = self->get_parent_object(); using port_ptr = sc_core::sc_port_base*; using export_ptr = sc_core::sc_export_base*; // Examine parent's children for modules for( const auto sibling : parent->get_child_objects() ) { if( sibling != self and "sc_module"s == sibling->kind() ) { // Example siblings ports DEBUG( "Considering " << sibling->name() ); for( const auto obj : sibling->get_child_objects() ) { // Too many kinds of ports to consider, so just check the base class if( auto port = dynamic_cast<port_ptr>(obj); port != nullptr ) { DEBUG( "Considering " << port->name() ); if( port->get_interface() == chan_if ) { DEBUG( port->name() << " connected to " << channel->name() ); return true; } } } } // Continue up tree if exported if( "sc_export"s == sibling->kind() ) { if( dynamic_cast<export_ptr>(sibling)->get_interface() == chan_if ) { DEBUG( "Moving to grandparent" ); if( is_connected( parent, channel, chan_if ) ) return true; } } } return false; } template< typename T> void Splitter_module<T>::end_of_elaboration() { if( fifo_port.size() == signal_port.size() ) { SC_REPORT_FATAL( MSGID, "Exactly one input must be connected" ); } // Note: In the following, we pass the channel address in twice due // to multiple inheritance. First, to find a pointer to the channel // aspect and second to find a pointer to the interface aspect. They // are distinctly different within the object and upcasting will do // the right thing in this situation. fifo_connected = is_connected( this, &fifo, &fifo ); sig1_connected = is_connected( this, &sig1, &sig1 ); sig2_connected = is_connected( this, &sig2, &sig2 ); if ( not ( fifo_connected || sig1_connected || sig2_connected ) ) { SC_REPORT_WARNING( MSGID, "No outputs are connected" ); } if ( ( fifo_connected != (sig1_connected != sig2_connected) ) and not ( fifo_connected && sig1_connected && sig2_connected ) ) { SC_REPORT_WARNING( MSGID, "Only one output is connected" ); } } template< typename T> void Splitter_module<T>::start_of_simulation() { const auto& trace_file { Top_module::trace_file() }; if( trace_file != nullptr ) { auto prefix = std::string(name()) + "."; sc_trace( trace_file, xfer_value, prefix + "xfer_value" ); } } template< typename T> void Splitter_module<T>::transfer() { if( fifo_port.size() != 0 ) { for(;;) { xfer_value = fifo_port->read(); DEBUG( "Transferring " << xfer_value ); if( sig1_connected ) sig1.write( xfer_value ); if( sig2_connected ) sig2.write( xfer_value ); if( fifo_connected ) fifo.nb_write( xfer_value ); } } if ( signal_port.size() != 0 ) { for(;;) { wait( signal_port->value_changed_event() ); xfer_value = signal_port->read(); DEBUG( "Transferring " << xfer_value ); if( sig1_connected ) sig1.write( xfer_value ); if( sig2_connected ) sig2.write( xfer_value ); if( fifo_connected ) fifo.nb_write( xfer_value ); } } sc_assert( false ); //< Paranoia check }
#ifdef EDGE_DETECTOR_PV_EN #ifndef SOBEL_EDGE_DETECTOR_HPP #define SOBEL_EDGE_DETECTOR_HPP #include <systemc.h> SC_MODULE(Edge_Detector) { int localWindow[3][3]; const int sobelGradientX[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}; const int sobelGradientY[3][3] = {{-1, -2, -1}, { 0, 0, 0}, { 1, 2, 1}}; int resultSobelGradientX; int resultSobelGradientY; SC_CTOR(Edge_Detector) { // SC_METHOD(hello_world); } void set_local_window(int window[3][3]); void compute_sobel_gradient_x(); void compute_sobel_gradient_y(); int obtain_sobel_gradient_x(); int obtain_sobel_gradient_y(); }; #endif // SOBEL_EDGE_DETECTOR_HPP #endif // EDGE_DETECTOR_PV_EN
/* * Adder.h * SystemC_SimpleAdder * * Created by Le Gal on 07/05/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #ifndef _Seuil_calc2_ #define _Seuil_calc2_ #include "systemc.h" #include <cstdint> #include "constantes.hpp" using namespace std; // #define _DEBUG_SYNCHRO_ SC_MODULE(Seuil_calc2) { public: sc_in < bool > clock; sc_in < bool > reset; sc_fifo_in < sc_uint<8> > e; sc_fifo_out <bool> detect; // sc_fifo_out <bool> detect1; SC_CTOR(Seuil_calc2) { SC_CTHREAD(do_gen, clock.pos()); reset_signal_is(reset,true); } private: void do_gen( ) { sc_uint<8> buffer[32]; sc_uint<22> seuil= 26; sc_uint<22> sum = 0; sc_uint<8> x0 = buffer[0]; sc_uint<8> x31 = 0; sc_uint<16> x02 = 0; sc_uint<16> x312 = 0; sc_uint<22> tmp = 0; #pragma HLS ARRAY_PARTITION variable=buffer complete dim=0 while( true ) { #pragma HLS PIPELINE for (uint8_t j = 0; j < 32-1; j += 1) { // #pragma HLS PIPELINE buffer[j] = buffer[j+1]; } buffer[32-1] = e.read(); x31 = buffer[32-1]; const sc_uint<11> ps = (sc_uint<11>) buffer[ 0] + (sc_uint<11>) buffer[ 1] + (sc_uint<11>) buffer[ 4] + (sc_uint<11>) buffer[ 5] + // 2 bits à 1 en PPM (sc_uint<11>) buffer[14] + (sc_uint<11>) buffer[15] + (sc_uint<11>) buffer[18] + (sc_uint<11>) buffer[19]; // 2 bits à 0 en PPM x02 = x0 * x0 ; x312 = x31 * x31; tmp = (x312 -x02); sum += 8*tmp; x0 = buffer[0]; const sc_uint<22> res_0 = (ps* ps); const sc_uint<22> res_1 = sum >> 5; const sc_uint<22> res_2 = (res_1 == 0)? (sc_uint<22>)31 :res_1; const sc_uint<22> res_3 = res_0 /res_2; const bool condition = (res_3> seuil); detect.write(condition); } } }; #endif
/* * SPDX-FileCopyrightText: Copyright (c) 2019-2021 NVIDIA CORPORATION & * AFFILIATES. All rights reserved. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file Interconnect.hpp \brief Primary IPA header file */ #ifndef __INTERCONNECT_H__ #define __INTERCONNECT_H__ #include <systemc.h> #include <nvhls_connections.h> #include <nvhls_message.h> #ifndef __SYNTHESIS__ #include <boost/format.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/functional/hash.hpp> #include <typeinfo> #endif #include <boost/preprocessor/facilities/overload.hpp> // Channel type class. #include "InterconnectChannels.hpp" // Include more global type settings. // Needed before defining CRTP mix-in's #include "InterconnectTypeConfig.hpp" // Annotate and others depend on this #include "InterconnectPre.hpp" // Include our own annotation class #include "InterconnectAnnotate.hpp" // CRTP Mix-in #include "InterconnectHandlerFixed.hpp" #include "InterconnectHandlerFlit.hpp" /*! \def ic_header(s) \brief Required include macro header. \param s Should always be set to "INTERCONNECT_GEN" Only use at the top of the *** file: \code #include ic_header(INTERCONNECT_GEN) \endcode */ #define ic_header(s) __ic_str(s) #define __ic_str(s) #s //////////////////////////////////////////////////////////////////////////////////////////////////////// // Interconnect macros //////////////////////////////////////////////////////////////////////////////////////////////////////// //// Defer resolution, to be used with __COUNTER__ so we get unique names. #define __IC_MACRO_DEFERED2(x) x #define __IC_MACRO_DEFERED(x) __IC_MACRO_DEFERED2(x) //// Configuration-related macros /*! \def IC_BEGIN_INTERCONNECTS \brief Close the interconnect object declarations. */ #define IC_BEGIN_INTERCONNECTS struct interconnects { /*! \def IC_ADD_INTERCONNECT(x) \brief Declare an interconnect with name \a x. \param x identifier for new interconnect */ #define IC_ADD_INTERCONNECT(x) \ struct x { \ enum { ic_id = __IC_MACRO_DEFERED(__COUNTER__) }; \ }; /*! \def IC_END_INTERCONNECTS \brief Close the interconnect object declarations. */ #define IC_END_INTERCONNECTS \ } \ ; // +1 below so that it can never be 0 /*! \def IC_BEGIN_DEST_MAPS \brief Declare custom destination index maps \par For now, custom maps are unsupported, but these macros are still required to create the global map: \code IC_BEGIN_DEST_MAPS IC_END_DEST_MAPS \endcode */ #define IC_BEGIN_DEST_MAPS \ struct maps { \ struct global { \ enum { map_id = 0 }; \ }; #define IC_ADD_DEST_MAP(x) \ struct x { \ enum { map_id = (__IC_MACRO_DEFERED(__COUNTER__) + 1) }; \ }; /*! \def IC_END_DEST_MAPS \brief End declarations custom destination index maps \par For now, custom maps are unsupported, but these macros are still required to create the global map: \code IC_BEGIN_DEST_MAPS IC_END_DEST_MAPS \endcode */ #define IC_END_DEST_MAPS \ } \ ; /*! \def IC_BEGIN_PARTITION_TYPES \brief Begin list of declared partitions for IPA. */ #define IC_BEGIN_PARTITION_TYPES struct parts { /*! \def IC_BEGIN_PARTITION(x) \brief Declare a partition with name \a x. \param x identifier for new partition */ #define IC_BEGIN_PARTITION(x) \ struct x { \ enum { part_id = __COUNTER__ }; \ static constexpr const char *name = #x; \ struct ports { //#define IC_ADD_PORT(x) struct x { enum { port_id = //__IC_MACRO_DEFERED(__COUNTER__) }; }; /*! \def IC_END_PARTITION \brief Close the interconnect partition declarations. */ #define IC_END_PARTITION \ } \ ; \ } \ ; /*! \def IC_END_PARTITION_TYPES \brief End list of declared partitions for IPA. */ #define IC_END_PARTITION_TYPES \ } \ ; /*! \def IC_BEGIN_MESSAGE_TYPES \brief Begin list of declared message types for IPA. */ #define IC_BEGIN_MESSAGE_TYPES struct msgs { #define IC_ADD_MESSAGE_TYPE_3(x, d, z) \ struct x { \ enum { \ msg_id = __IC_MACRO_DEFERED(__COUNTER__), \ map_id = maps::z::map_id \ }; \ typedef d data_t; \ static constexpr const char *name = #x; \ }; #define IC_ADD_MESSAGE_TYPE_2(msg_type, msg_data) \ IC_ADD_MESSAGE_TYPE_3(msg_type, msg_data, global) /*! \def IC_ADD_MESSAGE_TYPE(...) \brief Declare a new message type. \param x User-specified identifier for message type \param d Payload (class or primitive) for message type \param map_id Optional parameter for custom destination map (currently unsupported) */ #define IC_ADD_MESSAGE_TYPE(...) \ BOOST_PP_OVERLOAD(IC_ADD_MESSAGE_TYPE_, __VA_ARGS__)(__VA_ARGS__) #define IC_ADD_MESSAGE_TYPE_FLIT(x, d, z) \ struct x { \ enum { \ msg_id = __IC_MACRO_DEFERED(__COUNTER__), \ map_id = maps::z::map_id \ }; \ typedef d router_t; \ static constexpr const char *name = #x; \ }; /*! \def IC_END_MESSAGE_TYPES \brief End list of declared message types for IPA. */ #define IC_END_MESSAGE_TYPES \ } \ ; // Dest Map // Currently not supported #define IC_DEST_MAP(x) interconnect_config::maps::x::map_id #define IC_PORT_MAP_SET_IDX(x, y, z) \ ic_interface.set_map_port_idx(IC_DEST_MAP(x), y, z) /////////////////////////////////////////////////////////////////////////////// //// Top-level macros /////////////////////////////////////////////////////////////////////////////// /*! \def IC_HAS_INTERCONNECT(x) \brief Used within a top-level sc_module class declaration to indicate it contains interconnect \a x. \param x User-specified identifier for interconnect */ #define IC_HAS_INTERCONNECT(x) \ typedef interconnect::Interconnect< \ interconnect_config::interconnects::x::ic_id> interconnect_t; \ interconnect_t ic /*! \def IC_PART_BIND(inst, part_id) \brief Bind partition instance \a inst and designate it as partition id \a part_id for interconnect object \at ic \par Used within the constructor of the top-level sc_module containing the interconnect as specified with IC_HAS_INTERCONNECT. \param inst partition instance \param part_id user-specified partition ID used as the destination ID by messsage sources to address this instance partition */ #define IC_PART_BIND(inst, part_id) \ interconnect::do_interconnect_to_interface_bind<__IC_MACRO_DEFERED( \ __COUNTER__)>(ic, (inst).ic_interface, inst, part_id) /*! \def IC_AT_PART_BIND(ic, inst, part_id) \brief Bind partition instance \a inst and designate it as partition id \a part_id for interconnect object \at ic \par Under normal circumstances, IC_PART_BIND should be used instead, and called directly within the constructor of the top-level sc_module containing the interconnect. However, this macro can be useful if the interconnect object sits elsewhere in the hierarchy, but may not be as well supported for interconect generation. \param ic interconnect object \param inst partition instance \param part_id user-specified partition ID used as the destination ID by messsage sources to address this instance partition */ #define IC_AT_PART_BIND(ic, inst, part_id) \ interconnect::do_interconnect_to_interface_bind<__IC_MACRO_DEFERED( \ __COUNTER__)>(ic, (inst).ic_interface, inst, part_id) /////////////////////////////////////////////////////////////////////////////// //// Partition-level macros /////////////////////////////////////////////////////////////////////////////// // Interface declaration /*! \def IC_HAS_INTERFACE(x) \brief Used within a unit-level sc_module class declaration to indicate it contains an interface to bind to an interconnect. \param x User-specified identifier for partition */ #define IC_HAS_INTERFACE(x) \ typedef interconnect_config::parts::x part_info; \ typedef interconnect::InterconnectInterface<part_info> ic_interface_t; \ ic_interface_t ic_interface // IC_MESSAGE ports #define IC_PORT_BIND_1(port) \ ic_interface.Bind<__IC_MACRO_DEFERED(__COUNTER__)>(port, 0) #define IC_PORT_BIND_2(port, port_id) \ ic_interface.Bind<__IC_MACRO_DEFERED(__COUNTER__)>(port, port_id) /*! \def IC_PORT_BIND(port,port_id) \brief Bind a port of a lower level module within hierarchy \par For binding a port of the current-level of hierarchy, use IC_PIN_BIND instead. \param port Port instance to bind \param port_id Optional user-specified port_id for sharing multiple message types on the unit; currently unsupported */ #define IC_PORT_BIND(...) \ BOOST_PP_OVERLOAD(IC_PORT_BIND_, __VA_ARGS__)(__VA_ARGS__) #define IC_PIN_BIND_1(port) IC_PORT_BIND(interconnect::new_port_pin2(port)->pin) #define IC_PIN_BIND_2(port, port_id) \ IC_PORT_BIND(interconnect::new_port_pin2(port)->pin, port_id) /*! \def IC_PIN_BIND(port,port_id) \brief Bind a port of current level module within hierarchy \par For binding a port of the lower level of hierarchy, use IC_PORT_BIND instead. \param port Port instance to bind \param port_id Optional user-specified port_id for sharing multiple message types on the unit; currently unsupported */ #define IC_PIN_BIND(...) \ BOOST_PP_OVERLOAD(IC_PIN_BIND_, __VA_ARGS__)(__VA_ARGS__) /// Flit ports #define IC_AT_PORT_BIND_FLIT_3(ic, msg_type, port) \ ic.BindFlit<interconnect_config::msgs::msg_type>(port); #define IC_AT_PORT_BIND_FLIT_4(ic, msg_type, port, custom_id) \ ic.BindFlit<interconnect_config::msgs::msg_type>(port, custom_id); #define IC_AT_PORT_BIND_FLIT(...) \ BOOST_PP_OVERLOAD(IC_AT_PORT_BIND_FLIT_, __VA_ARGS__)(__VA_ARGS__) #define IC_AT_PIN_BIND_FLIT_3(ic, msg_type, port) \ IC_AT_PORT_BIND_FLIT(ic, msg_type, interconnect::new_port_pin2(port)->pin) #define IC_AT_PIN_BIND_FLIT_4(ic, msg_type, port, custom_id) \ IC_AT_PORT_BIND_FLIT(ic, msg_type, interconnect::new_port_pin2(port)->pin, \ custom_id) #define IC_AT_PIN_BIND_FLIT(...) \ BOOST_PP_OVERLOAD(IC_AT_PIN_BIND_FLIT_, __VA_ARGS__)(__VA_ARGS__) #define IC_PORT_BIND_FLIT(...) IC_AT_PORT_BIND_FLIT(ic, __VA_ARGS__) #define IC_PIN_BIND_FLIT(...) IC_AT_PIN_BIND_FLIT(ic, __VA_ARGS__) // To add additional port id's to a destination port // Note: we don't use this in the bind3 version, since bind3 can accomodate in // and out ports, and no way ot differentiate #define IC_AT_PORT_ID_FLIT(ic, msg_type, port, custom_id) \ ic.config_dest_map_idx_flit(interconnect_config::msgs::msg_type::map_id, \ custom_id, port) #define IC_PORT_ID_FLIT(...) IC_AT_PORT_ID_FLIT(ic, __VA_ARGS__) /////////////////////////////////////////////////////////////////////////////// //// Message-level macros /////////////////////////////////////////////////////////////////////////////// // IC_PORT_ID is currently unused #define IC_PORT_ID(y) part_info::ports::y::port_id /*! \def IC_MESSAGE(x) \brief Create new message of message type \a x \param x message type identifier */ #define IC_MESSAGE(x) typename interconnect::Msg<interconnect_config::msgs::x> // If the values can change at runtime e.g. from jtag. #define IC_TO_DYNAMIC_1(part_id) interconnect::Destination(part_id, 0) #define IC_TO_DYNAMIC_2(part_id, port_id) \ interconnect::Destination(part_id, port_id) #define IC_TO_DYNAMIC(...) \ BOOST_PP_OVERLOAD(IC_TO_DYNAMIC_, __VA_ARGS__)(__VA_ARGS__) // If the values are fixed/constant #define IC_TO_CONST_1(part_id) interconnect::Destination(part_id, 0) #define IC_TO_CONST_2(part_id, port_id) \ interconnect::Destination(part_id, port_id) #define IC_TO_CONST(...) \ BOOST_PP_OVERLOAD(IC_TO_CONST_, __VA_ARGS__)(__VA_ARGS__) /*! \def IC_TO(part_id,port_id) \brief Send a message to partition instance with id \a part_id \param part_id destination user-specified partition id \param port_id optional user-specified port_id; currently unsupported */ #define IC_TO(...) IC_TO_CONST(__VA_ARGS__) /////////////////////////////////////////////////////////////////////////////// //// Legacy/testbench macros /////////////////////////////////////////////////////////////////////////////// //// Legacy port bind for when we can't or don't want to use IC_INTERFACE #define IC_AT_LEGACY_PORT_BIND_5(ic, msg_type, port, part_id, port_id) \ ic.Bind(port); \ ic.add_to_dest_directory(port, part_id, port_id) #define IC_AT_LEGACY_PORT_BIND_4(ic, msg_type, port, part_id) \ ic.Bind(port); \ ic.add_to_dest_directory(port, part_id) #define IC_AT_LEGACY_PORT_BIND_3(ic, msg_type, port) ic.Bind(port); #define IC_AT_LEGACY_PORT_BIND(...) \ BOOST_PP_OVERLOAD(IC_AT_LEGACY_PORT_BIND_, __VA_ARGS__)(__VA_ARGS__) #define IC_AT_LEGACY_DISTRIBUTED_PORT_BIND_5(ic, msg_type, port, part_id, \ port_id) \ ic.Bind(port); \ ic.add_to_dest_directory(port, part_id, port_id, true) #define IC_AT_LEGACY_DISTRIBUTED_PORT_BIND_4(ic, msg_type, port, part_id) \ ic.Bind(port); \ ic.add_to_dest_directory(port, part_id, 0, true) #define IC_AT_LEGACY_DISTRIBUTED_PORT_BIND_3(ic, msg_type, port) ic.Bind(port); #define IC_AT_LEGACY_DISTRIBUTED_PORT_BIND(...) \ BOOST_PP_OVERLOAD(IC_AT_LEGACY_DISTRIBUTED_PORT_BIND_, __VA_ARGS__)(__VA_ARGS__) #define IC_LEGACY_PORT_BIND(...) IC_AT_LEGACY_PORT_BIND(ic, __VA_ARGS__) #define IC_LEGACY_DISTRIBUTED_PORT_BIND(...) \ IC_AT_LEGACY_DISTRIBUTED_PORT_BIND(ic, __VA_ARGS__) //////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __SYNTHESIS__ namespace interconnect { /*! \brief Message instance class Do not instantiate directly, instead use the `#IC_MESSAGE(x)` macro \tparam MSG_TYPE identifier for message type */ template <typename MSG_TYPE> class Msg : public nvhls_message { static const MSG_ID_t MSG_ID = MSG_TYPE::msg_id; typedef typename MSG_TYPE::data_t data_t; public: /*! \brief Payload data */ data_t msg; /*! \brief Destination mask for this message */ sc_lv<interconnect::MaxDestCount> dest_bits; public: //// Constructor-Destructor /*! \brief Default constructor */ Msg<MSG_TYPE>() { dest_bits = 0; } /*! \brief Constructor to initialize from payload data */ Msg<MSG_TYPE>(const data_t &m) { dest_bits = 0; set_msg(m); } //// Operators /*! \brief Set payload of message */ Msg<MSG_TYPE> &operator=(const data_t &m) { set_msg(m); return *this; } /*! \brief Set message destination, destination id should be used through #IC_TO(part_id,port_id) macro */ Msg<MSG_TYPE> &operator<<(const Destination &dest) { auto tuple_idx = std::make_tuple(dest.part_id, MSG_TYPE::msg_id, dest.port_id); if (interconnect::get_ICManager().dest_directory.find(tuple_idx) == interconnect::get_ICManager().dest_directory.end()) { cout << dec << "Couldn't find destination part_id=" << dest.part_id << ", msg_id=" << MSG_TYPE::msg_id << ", port_id=" << dest.port_id << endl; NVHLS_ASSERT(0); } add_route( interconnect::get_ICManager().dest_directory[tuple_idx].get_next(), 0); return *this; } //// Setter-Getter /*! \brief Set message payload */ void set_msg(const data_t &m) { msg = m; } /*! \brief Get message payload */ data_t get_msg() { return msg; } /*! \brief Get message payload through cast */ operator data_t() { return get_msg(); } /*! \brief Set destination for message */ template <typename interconnect_t, typename route_t> void set_route(interconnect_t &ic, route_t *route) { dest_bits = 0; for (typename route_t::iterator it = route->begin(); it != route->end(); ++it) { add_route(ic.find_dest_idx(*it)); } } // Conversion to generic type template <unsigned int MaxDataWidth, unsigned int MaxDestCount> operator InterconnectMessageSCLV<MaxDataWidth, MaxDestCount>() { assert(MaxDestCount == interconnect::MaxDestCount); assert(Wrapped<data_t>::width <= MaxDataWidth); InterconnectMessageSCLV<MaxDataWidth, MaxDestCount> new_im; new_im.set_msg(msg); new_im.dest_bits = dest_bits; return new_im; } template <unsigned int MaxDataWidth, unsigned int MaxDestCount> explicit Msg<MSG_TYPE>( const InterconnectMessageSCLV<MaxDataWidth, MaxDestCount> &im) { assert(MaxDestCount == interconnect::MaxDestCount); assert(Wrapped<data_t>::width <= MaxDataWidth); im.get_msg(msg); dest_bits = im.dest_bits; } template <unsigned int MaxDataWidth, unsigned int MaxDestCount> Msg<MSG_TYPE> &operator=( const InterconnectMessageSCLV<MaxDataWidth, MaxDestCount> &im) { assert(MaxDestCount == interconnect::MaxDestCount); assert(Wrapped<data_t>::width <= MaxDataWidth); im.get_msg(msg); dest_bits = im.dest_bits; return *this; } //// Route Operators void add_route(const unsigned int &dest_idx, const unsigned int &dest_map_idx = 0) { unsigned int real_dest_idx; real_dest_idx = interconnect::get_real_dest_idx<void>( *interconnect::get_ICManager().registered_ic[0], dest_idx, dest_map_idx); dest_bits[real_dest_idx] = 1; } void clear_route() { dest_bits = 0; } //// Marshall support enum { width = Wrapped<data_t>::width + interconnect::MaxDestCount }; template <unsigned int Size> void Marshall(Marshaller<Size> &m) { m &msg; m &dest_bits; } }; template <typename IM_t> struct GenericDestHandlerIface { public: typename Connections::InBlocking<IM_t> *im_ptr; }; template <typename IM_t> struct GenericSrcHandlerIface { public: typename Connections::OutBlocking<IM_t> *im_ptr; }; template <typename IM_t, typename MSG_TYPE> class ICMFromSpecialized : public sc_module, public Connections::Blocking_abs, public GenericSrcHandlerIface<IM_t> { SC_HAS_PROCESS(ICMFromSpecialized); static const interconnect::MSG_ID_t MSG_ID = MSG_TYPE::msg_id; public: Connections::OutBlocking<IM_t> im; Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p; sc_signal<sc_lv<Wrapped<interconnect::Msg<MSG_TYPE> >::width> > int_msg; sc_signal<bool> int_rdy; sc_signal<bool> int_val; explicit ICMFromSpecialized( Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p_) : sc_module(sc_module_name(s
c_gen_unique_name("im_from_specific"))) // ,ic(ic_) , im(sc_gen_unique_name("im")), p(p_), int_msg("int_msg"), int_rdy("int_rdy"), int_val("int_val") { // Pass up to handler interface this->im_ptr = &im; p._DATNAME_(int_msg); p._RDYNAME_(int_rdy); p._VLDNAME_(int_val); #ifdef CONNECTIONS_SIM_ONLY declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << p._DATNAME_ << p._VLDNAME_ << im._RDYNAME_; im.disable_spawn(); #endif } void do_bypass() { bool is_val = int_val.read(); // Set val and msg respectively im._VLDNAME_.write(is_val); int_rdy.write(im._RDYNAME_.read()); // Only convert if is_val (to prevent X's) if (is_val) { // Convert msg Marshaller<Wrapped<interconnect::Msg<MSG_TYPE> >::width> marshaller( int_msg.read()); Wrapped<interconnect::Msg<MSG_TYPE> > result; result.Marshall(marshaller); // Create the InterconnectMessage IM_t im_msg; interconnect::Msg<MSG_TYPE> m = result.val; im_msg = m; // Convert back to Marshall'd form Marshaller<Wrapped<IM_t>::width> im_marshaller; Wrapped<IM_t> im_wm(im_msg); im_wm.Marshall(im_marshaller); im._DATNAME_.write(im_marshaller.GetResult()); } } }; // class ICMNewToOld template <typename IM_t, typename MSG_TYPE> class ICMToSpecialized : public sc_module, public Connections::Blocking_abs, public GenericDestHandlerIface<IM_t> { SC_HAS_PROCESS(ICMToSpecialized); static const interconnect::MSG_ID_t MSG_ID = MSG_TYPE::msg_id; public: Connections::InBlocking<IM_t> im; Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p; sc_signal<sc_lv<Wrapped<interconnect::Msg<MSG_TYPE> >::width> > int_msg; sc_signal<bool> int_rdy; sc_signal<bool> int_val; explicit ICMToSpecialized( Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p_) : sc_module(sc_module_name(sc_gen_unique_name("icm_to_specialized"))), // ic(ic_), im(sc_gen_unique_name("im")), p(p_), int_msg("int_msg"), int_rdy("int_rdy"), int_val("int_val") { // Pass up to handler interface this->im_ptr = &im; p._DATNAME_(int_msg); p._RDYNAME_(int_rdy); p._VLDNAME_(int_val); #ifdef CONNECTIONS_SIM_ONLY // SC_METHOD(do_bypass); declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << im._DATNAME_ << im._VLDNAME_ << p._RDYNAME_; im.disable_spawn(); #endif } void do_bypass() { bool is_val = im._VLDNAME_.read(); // Set val and msg respectively int_val.write(is_val); im._RDYNAME_.write(int_rdy.read()); // Only convert if is_val (to prevent X's) if (is_val) { // Convert msg from bits Marshaller<Wrapped<IM_t>::width> im_marshaller(im._DATNAME_.read()); Wrapped<IM_t> im_result; im_result.Marshall(im_marshaller); IM_t im_msg = im_result.val; // Convert msg to bits and write Marshaller<Wrapped<interconnect::Msg<MSG_TYPE> >::width> marshaller; interconnect::Msg<MSG_TYPE> m(im_msg); Wrapped<interconnect::Msg<MSG_TYPE> > wm(m); wm.Marshall(marshaller); int_msg.write(marshaller.GetResult()); } } }; // classFixedDestHandler }; #endif //////////////////////////////////////////////////////////////////////////////////////////////////////// namespace interconnect { #ifdef CONNECTIONS_SIM_ONLY // Pointer based message passing template <typename IM> class InterconnectBase : public sc_module, public InterconnectHandlerFixed<InterconnectBase<IM>, IM>, public InterconnectHandlerFlit<InterconnectBase<IM>, IM> { SC_HAS_PROCESS(InterconnectBase); protected: // Declarations class Route; public: typedef IM IM_t; typedef Route route_t; // These are now pushed down into a separate class, so that Handler classse // can access these without templatization. Is there a better way to do this? typedef typename InterconnectTypeConfig<IM>::IM_src_t IM_src_t; typedef typename InterconnectTypeConfig<IM>::IM_dest_t IM_dest_t; typedef typename InterconnectTypeConfig<IM>::IM_chan_t IM_chan_t; typedef typename InterconnectTypeConfig<IM>::IM_chanlink_t IM_chanlink_t; typedef typename InterconnectTypeConfig<IM>::srcs_t srcs_t; typedef typename InterconnectTypeConfig<IM>::dests_t dests_t; typedef typename InterconnectTypeConfig<IM>::channels_begin_t channels_begin_t; typedef typename InterconnectTypeConfig<IM>::channels_middle_inner_t channels_middle_inner_t; typedef typename InterconnectTypeConfig<IM>::channels_middle_t channels_middle_t; typedef typename InterconnectTypeConfig<IM>::channels_end_t channels_end_t; typedef typename InterconnectTypeConfig<IM>::srcs_typeid_t srcs_typeid_t; typedef typename InterconnectTypeConfig<IM>::dests_typeid_t dests_typeid_t; typedef typename InterconnectTypeConfig<IM>::srcs_user_typeid_t srcs_user_typeid_t; typedef typename InterconnectTypeConfig<IM>::dests_user_typeid_t dests_user_typeid_t; typedef typename InterconnectTypeConfig<IM>::srcs_width_t srcs_width_t; typedef typename InterconnectTypeConfig<IM>::dests_width_t dests_width_t; typedef typename InterconnectTypeConfig<IM>::channels_valid_pairs_reverse_inner_t channels_valid_pairs_reverse_inner_t; typedef typename InterconnectTypeConfig<IM>::channels_valid_pairs_reverse_t channels_valid_pairs_reverse_t; typedef typename InterconnectTypeConfig<IM>::idx_t idx_t; typedef typename InterconnectTypeConfig<IM>::dest_map_idx_t dest_map_idx_t; typedef typename InterconnectTypeConfig<IM>::dest_maps_t dest_maps_t; typedef typename InterconnectTypeConfig<IM>::dest_maps_idx_vec_t dest_maps_idx_vec_t; typedef typename InterconnectTypeConfig<IM>::cycles_count_t cycles_count_t; typedef typename InterconnectTypeConfig<IM>::cycle_count_channel_t cycle_count_channel_t; const unsigned int ic_id; public: std::map<IM_src_t *, Connections::Blocking_abs *> srcs_block_abs; std::map<IM_dest_t *, Connections::Blocking_abs *> dests_block_abs; protected: // Vectors of ports srcs_t srcs; dests_t dests; srcs_t disabled_srcs; dests_t disabled_dests; std::vector<std::tuple<Connections::Blocking_abs *, Connections::Blocking_abs *> > disabled_pairs; std::map<IM_src_t *, std::string> srcs_names; std::map<IM_dest_t *, std::string> dests_names; // Maps of channels channels_begin_t channels_begin; public: channels_middle_t channels_middle; protected: channels_end_t channels_end; channels_valid_pairs_reverse_t channels_valid_pairs_reverse; public: // Tracking to find valid combinations of channels srcs_typeid_t srcs_typeid; dests_typeid_t dests_typeid; srcs_user_typeid_t srcs_user_typeid; dests_user_typeid_t dests_user_typeid; std::map<unsigned int, const char *> msg_names; // key = msg_id std::map<unsigned int, const char *> part_names; // key = part_type_id std::map<unsigned int, unsigned int> part_to_part_type; // key = user_part_Id, value = part_type_id std::map<unsigned int, const char *> part_inst_names; // key = user_part_Id, value is part_name std::map<unsigned int, std::map<unsigned int, std::set<unsigned int> > > part_msgs_srcs; // key = part_type_id, set is msg ids std::map<unsigned int, std::map<unsigned int, std::set<unsigned int> > > part_msgs_dests; // key = part_type_id, set is msg ids srcs_width_t srcs_width; dests_width_t dests_width; protected: // Instrumentation cycles_count_t cycle_count_total; cycle_count_channel_t cycle_count_channel; public: // Ports sc_in_clk clk; sc_in<bool> rst; //////////////////////////////////////////////////////////////////////////////////////////////// // Constructors InterconnectBase(const unsigned int &ic_id_) : sc_module(sc_module_name(sc_gen_unique_name("interconnect"))), clk(sc_gen_unique_name("clk")), rst(sc_gen_unique_name("rst")), ic_id(ic_id_) { SC_CTHREAD(run, clk.pos()); async_reset_signal_is(rst, false); } explicit InterconnectBase(const char *name, const unsigned int &ic_id_) : sc_module(sc_module_name(name)), clk(sc_gen_unique_name("clk")), rst(sc_gen_unique_name("rst")), ic_id(ic_id_) { SC_CTHREAD(run, clk.pos()); async_reset_signal_is(rst, false); } //////////////////////////////////////////////////////////////////////////////////////////////// // Run loop void run() { cycle_count_total = 0; wait(); while (1) { cycle_count_total++; wait(); } } //////////////////////////////////////////////////////////////////////////////////////////////// // Channel binding template <typename T> void Bind(IM_src_t &p) { Bind(p, Wrapped<T>::width, typeid(T).name()); } template <typename T> void Bind(IM_dest_t &p) { Bind(p, Wrapped<T>::width, typeid(T).name()); } void Bind(IM_src_t &p, unsigned int type_width, const char *type_name) { srcs.push_back(&p); std::string port_name = p._VLDNAME_.name(); if (port_name.substr(port_name.length() - 4, 4) == "_" _VLDNAMESTR_) { port_name.erase(port_name.length() - 4, 4); } set_src_name(&p, port_name); boost::hash<const char *> typeid_hash; srcs_typeid[&p] = typeid_hash(type_name); srcs_width[&p] = type_width; } void Bind(IM_dest_t &p, unsigned int type_width, const char *type_name) { dests.push_back(&p); std::string port_name = p._VLDNAME_.name(); if (port_name.substr(port_name.length() - 4, 4) == "_" _VLDNAMESTR_) { port_name.erase(port_name.length() - 4, 4); } set_dest_name(&p, port_name); boost::hash<const char *> typeid_hash; dests_typeid[&p] = typeid_hash(type_name); dests_width[&p] = type_width; } template <typename T> void Bind(IM_dest_t &p, unsigned int userid, const char *msg_name) { Bind<T>(p); dests_user_typeid[&p] = userid; msg_names[userid] = msg_name; } template <typename T> void Bind(IM_src_t &p, unsigned int userid, const char *msg_name) { Bind<T>(p); srcs_user_typeid[&p] = userid; msg_names[userid] = msg_name; } void Bind(IM_dest_t &p, unsigned int userid, unsigned int type_width, const char *type_name, const char *msg_name) { Bind(p, type_width, type_name); dests_user_typeid[&p] = userid; msg_names[userid] = msg_name; } void Bind(IM_src_t &p, unsigned int userid, unsigned int type_width, const char *type_name, const char *msg_name) { Bind(p, type_width, type_name); srcs_user_typeid[&p] = userid; msg_names[userid] = msg_name; } //////////////////////////////////////////////////////////////////////////// // New IC_MESSAGE struct GenericDestHandlerIface { public: typename InterconnectBase<IM>::IM_dest_t *im_ptr; }; struct GenericSrcHandlerIface { public: typename InterconnectBase<IM>::IM_src_t *im_ptr; }; std::map<Connections::Blocking_abs *, GenericDestHandlerIface *> generic_iface_dests; std::map<Connections::Blocking_abs *, GenericSrcHandlerIface *> generic_iface_srcs; template <typename MSG_TYPE> class ICMFromSpecialized : public sc_module, public Connections::Blocking_abs, public GenericSrcHandlerIface { SC_HAS_PROCESS(ICMFromSpecialized); public: typedef InterconnectBase<IM> interconnect_t; interconnect_t &ic; typename interconnect_t::IM_src_t im; Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p; sc_signal<sc_lv<Wrapped<interconnect::Msg<MSG_TYPE> >::width> > int_msg; sc_signal<bool> int_rdy; sc_signal<bool> int_val; explicit ICMFromSpecialized( interconnect_t &ic_, Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p_) : sc_module(sc_module_name(sc_gen_unique_name("im_from_specific"))), ic(ic_), im(sc_gen_unique_name("im")), p(p_), int_msg("int_msg"), int_rdy("int_rdy"), int_val("int_val") { // Pass up to handler interface this->im_ptr = &im; p._DATNAME_(int_msg); p._RDYNAME_(int_rdy); p._VLDNAME_(int_val); #ifdef CONNECTIONS_SIM_ONLY declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << p._DATNAME_ << p._VLDNAME_ << im._RDYNAME_; im.disable_spawn(); #endif } void do_bypass() { bool is_val = int_val.read(); // Set val and msg respectively im._VLDNAME_.write(is_val); int_rdy.write(im._RDYNAME_.read()); // Only convert if is_val (to prevent X's) if (is_val) { // Convert msg Marshaller<Wrapped<interconnect::Msg<MSG_TYPE> >::width> marshaller( int_msg.read()); Wrapped<interconnect::Msg<MSG_TYPE> > result; result.Marshall(marshaller); // Create the InterconnectMessage typename interconnect_t::IM_t im_msg; interconnect::Msg<MSG_TYPE> m = result.val; im_msg = m; // Convert back to Marshall'd form Marshaller<Wrapped<typename interconnect_t::IM_t>::width> im_marshaller; Wrapped<typename interconnect_t::IM_t> im_wm(im_msg); im_wm.Marshall(im_marshaller); im._DATNAME_.write(im_marshaller.GetResult()); } } }; // class ICMFromSpecialized template <typename MSG_TYPE> class ICMToSpecialized : public sc_module, public Connections::Blocking_abs, public GenericDestHandlerIface { SC_HAS_PROCESS(ICMToSpecialized); static const interconnect::MSG_ID_t MSG_ID = MSG_TYPE::msg_id; public: typedef InterconnectBase<IM> interconnect_t; interconnect_t &ic; typename interconnect_t::IM_dest_t im; Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p; sc_signal<sc_lv<Wrapped<interconnect::Msg<MSG_TYPE> >::width> > int_msg; sc_signal<bool> int_rdy; sc_signal<bool> int_val; explicit ICMToSpecialized( interconnect_t &ic_, Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p_) : sc_module(sc_module_name(sc_gen_unique_name("icm_to_specialized"))), ic(ic_), im(sc_gen_unique_name("im")), p(p_), int_msg("int_msg"), int_rdy("int_rdy"), int_val("int_val") { // Pass up to handler interface this->im_ptr = &im; p._DATNAME_(int_msg); p._RDYNAME_(int_rdy); p._VLDNAME_(int_val); #ifdef CONNECTIONS_SIM_ONLY // SC_METHOD(do_bypass); declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << im._DATNAME_ << im._VLDNAME_ << p._RDYNAME_; im.disable_spawn(); #endif } void do_bypass() { bool is_val = im._VLDNAME_.read(); // Set val and msg respectively int_val.write(is_val); im._RDYNAME_.write(int_rdy.read()); // Only convert if is_val (to prevent X's) if (is_val) { // Convert msg from bits Marshaller<Wrapped<typename interconnect_t::IM_t>::width> im_marshaller( im._DATNAME_.read()); Wrapped<typename interconnect_t::IM_t> im_result; im_result.Marshall(im_marshaller); typename interconnect_t::IM_t im_msg = im_result.val; // Convert msg to bits and write Marshaller<Wrapped<interconnect::Msg<MSG_TYPE> >::width> marshaller; interconnect::Msg<MSG_TYPE> m(im_msg); Wrapped<interconnect::Msg<MSG_TYPE> > wm(m); wm.Marshall(marshaller); int_msg.write(marshaller.GetResult()); } } }; // ICMToSpecialized template <typename MSG_TYPE> void Bind(Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p) { ICMFromSpecialized<MSG_TYPE> *is = new ICMFromSpecialized<MSG_TYPE>(*this, p); Bind<typename MSG_TYPE::data_t>(is->im, MSG_TYPE::msg_id, MSG_TYPE::name); std::string port_name = p._VLDNAME_.name(); if (port_name.substr(port_name.length() - 4, 4) == "_" _VLDNAMESTR_) { port_name.erase(port_name.length() - 4, 4); } set_src_name(&is->im, port_name); generic_iface_srcs[&p] = is; msg_names[MSG_TYPE::msg_id] = MSG_TYPE::name; } template <typename MSG_TYPE> void Bind(Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p) { ICMToSpecialized<MSG_TYPE> *ij = new ICMToSpecialized<MSG_TYPE>(*this, p); Bind<typename MSG_TYPE::data_t>(ij->im, MSG_TYPE::msg_id, MSG_TYPE::name); std::string port_name = p._VLDNAME_.name(); if (port_name.substr(port_name.length() - 4, 4) == "_" _VLDNAMESTR_) { port_name.erase(port_name.length() - 4, 4); } set_dest_name(&ij->im, port_name); generic_iface_dests[&p] = ij; msg_names[MSG_TYPE::msg_id] = MSG_TYPE::name; } template <typename T, typename MSG_TYPE> void Bind(Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p, unsigned int userid) { assert(userid == MSG_TYPE::msg_id); Bind(p); } template <typename T, typename MSG_TYPE> void Bind(Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p, unsigned int userid) { assert(userid == MSG_TYPE::msg_id); Bind(p); } template <typename MSG_TYPE> void config_dest_map_idx( dest_map_idx_t dest_map_idx, idx_t dest_idx, Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p) { config_dest_map_idx( dest_map_idx, dest_idx, *(generic_iface_dests[(Connections::Blocking_abs *)&p]->im_ptr)); } //////////////////////////////////////////////////////////////////////////// // Disable a source or dest port. Still binds and resets it, // but otherwise disabled it for sending or receiving. // Useful when there are additional ports that need to be bound // but will be unused (edges of an array, testbench, etc). void disable_port(IM_dest_t &p) { disabled_dests.push_back(&p); } void disable_port(IM_src_t &p) { disabled_srcs.push_back(&p); } void disable_pair_of_ports(Connections::Blocking_abs &p1, Connections::Blocking_abs &p2) { disabled_pairs.push_back(std::make_tuple(&p1, &p2)); } template <typename MSG_TYPE> void disable_port(Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p) { disabled_dests.push_back( generic_iface_dests[(Connections::Blocking_abs *)&p]->im_ptr); } template <typename MSG_TYPE> void disable_port(Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p) { disabled_srcs.push_back( generic_iface_srcs[(Connections::Blocking_abs *)&p]->im_ptr); } //////////////////////////////////////////////////////////////////////////////////////////////// // Modifiers idx_t find_src_idx(IM_src_t *p) { unsigned long i = 0; for (typename srcs_t::iterator it_src = srcs.begin(); it_src != srcs.end(); ++it_src, ++i) { if ((*it_src) == p) { return i; } } return -1; } idx_t find_dest_idx(IM_dest_t *p) { unsigned long i = 0; for (typename dests_t::iterator it_dest = dests.begin(); it_dest != dests.end(); ++it_dest, ++i) { if ((*it_dest) == p) { return i; } } return -1; } IM_src_t *get_src_from_idx(idx_t src_idx) { NVHLS_ASSERT_MSG(src_idx != -1, "Source index is not found"); NVHLS_ASSERT_MSG(src_idx < get_src_size(), "Source index exc
eeds number of sources"); return srcs[src_idx]; } idx_t get_real_dest_idx(idx_t dest_idx, dest_map_idx_t dest_map_idx = 0) { idx_t real_dest_idx; if (dest_map_idx == 0) { real_dest_idx = dest_idx; } else { // Assert that dest_map_idx map exists NVHLS_ASSERT_MSG( std::find(dest_maps_idx_vec.begin(), dest_maps_idx_vec.end(), dest_map_idx) != dest_maps_idx_vec.end(), "Destination map not found!"); // Assert that the dest_idx exists in that map. NVHLS_ASSERT_MSG(dest_maps[dest_map_idx].find(dest_idx) != dest_maps[dest_map_idx].end(), "Interconnect coundn't find dest_idx in dest_map_idx."); // Get the real idx real_dest_idx = dest_maps[dest_map_idx][dest_idx]; } return real_dest_idx; } IM_dest_t *get_dest_from_idx(idx_t dest_idx, dest_map_idx_t dest_map_idx = 0) { idx_t real_dest_idx; real_dest_idx = get_real_dest_idx(dest_idx, dest_map_idx); NVHLS_ASSERT_MSG(real_dest_idx != -1, "Real dest index is -1, indicating not found!"); NVHLS_ASSERT_MSG(real_dest_idx < get_dest_size(), "Real dest index exceeds number of dests in design!"); return dests[real_dest_idx]; } void set_src_name(IM_src_t *p, std::string &s) { srcs_names[p] = s; } void set_dest_name(IM_dest_t *p, std::string &s) { dests_names[p] = s; } std::string get_src_name(IM_src_t *p) { return srcs_names[p]; } std::string get_dest_name(IM_dest_t *p) { return dests_names[p]; } unsigned int get_src_size() { return srcs.size(); } unsigned int get_dest_size() { return dests.size(); } //////////////////////////////////////////////////////////////////////////////////////////////// // Route creation dest_maps_t dest_maps; dest_maps_idx_vec_t dest_maps_idx_vec; dest_map_idx_t create_dest_map() { // Seed starting value dest_map_idx_t dest_map_idx = 1; // Find lowest integer not in dest_maps. sort(dest_maps_idx_vec.begin(), dest_maps_idx_vec.end()); for (typename dest_maps_idx_vec_t::iterator it = dest_maps_idx_vec.begin(); it != dest_maps_idx_vec.end(); ++it) { if ((*it) >= dest_map_idx) { if ((*it) == dest_map_idx) dest_map_idx++; // Found it else break; // current value will work } } create_dest_map(dest_map_idx); return dest_map_idx; } dest_map_idx_t create_dest_map(dest_map_idx_t dest_map_idx, const bool &allow_existing = false) { NVHLS_ASSERT(dest_map_idx != 0); if (allow_existing && std::find(dest_maps_idx_vec.begin(), dest_maps_idx_vec.end(), dest_map_idx) != dest_maps_idx_vec.end()) { return dest_map_idx; } NVHLS_ASSERT(std::find(dest_maps_idx_vec.begin(), dest_maps_idx_vec.end(), dest_map_idx) == dest_maps_idx_vec.end()); dest_maps_idx_vec.push_back(dest_map_idx); return dest_map_idx; } void config_dest_map_idx(dest_map_idx_t dest_map_idx, idx_t dest_idx, idx_t real_dest_idx) { NVHLS_ASSERT_MSG(dest_map_idx != 0, "The default dest_map_idx=0 is fixed, and cannot be " "manually assigned. Use a dest_map_idx > 0."); NVHLS_ASSERT_MSG( std::find(dest_maps_idx_vec.begin(), dest_maps_idx_vec.end(), dest_map_idx) != dest_maps_idx_vec.end(), "Couldn't find dest_map_idx!"); dest_maps[dest_map_idx][dest_idx] = real_dest_idx; } void config_dest_map_idx(dest_map_idx_t dest_map_idx, idx_t dest_idx, IM_dest_t &p) { config_dest_map_idx(dest_map_idx, dest_idx, this->find_dest_idx(&p)); } void add_to_dest_directory(IM_dest_t &p, unsigned int part_id, unsigned int msg_id, unsigned int port_id = 0, bool allow_duplicate = false) { auto tuple_idx = std::make_tuple(part_id, msg_id, port_id); if (!allow_duplicate) { NVHLS_ASSERT_MSG( interconnect::get_ICManager().dest_directory.find(tuple_idx) == interconnect::get_ICManager().dest_directory.end(), "Already have a destination matching that index"); } interconnect::get_ICManager().dest_directory[tuple_idx].add( this->find_dest_idx(&p)); } template <typename MSG_TYPE> void add_to_dest_directory( Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p, unsigned int part_id, unsigned int port_id = 0, bool allow_duplicate = false) { add_to_dest_directory(*generic_iface_dests[&p]->im_ptr, part_id, MSG_TYPE::msg_id, port_id, allow_duplicate); } route_t *create_route() { return new Route(*this); } //////////////////////////////////////////////////////////////////////////////////////////////// // Helpers // Sets w to smallest width that is >= min_w. Returns false if no min width is // found. template <typename T> bool ports_min_width(T &ref, unsigned int &w, unsigned int min_w = 0) { bool found = false; for (typename T::iterator it_ref = ref.begin(); it_ref != ref.end(); ++it_ref) { if (it_ref->second >= min_w && (it_ref->second < w || !found)) { w = it_ref->second; found = true; } } return found; } bool srcs_and_dests_min_width(unsigned int &w, unsigned int min_w = 0) { return ports_min_width(srcs_width, w, min_w) || ports_min_width(dests_width, w, min_w); } void pretty_print() { cout << std::string(100, '#') << endl; unsigned int current_port_width; bool port_width_found = srcs_and_dests_min_width(current_port_width); while (port_width_found) { cout << "# " << dec << current_port_width << "-bit Ports" << endl; cout << "## Sources" << endl; for (typename srcs_t::iterator it_src = srcs.begin(); it_src != srcs.end(); ++it_src) { if (srcs_width[*it_src] == current_port_width) { if (find(disabled_srcs.begin(), disabled_srcs.end(), *it_src) != disabled_srcs.end()) { cout << " - " << get_src_name(*it_src) << " is disabled." << endl; } else if (srcs_user_typeid.find(*it_src) != srcs_user_typeid.end()) { cout << " - " << get_src_name(*it_src) << " (user typeid = " << srcs_user_typeid[*it_src] << ") connects to " << num_compatible_channels_from_src(*it_src) << " destinations." << endl; } else { cout << " - " << get_src_name(*it_src) << " connects to " << num_compatible_channels_from_src(*it_src) << " destinations." << endl; } } } cout << endl; cout << "## Destinations" << endl; for (typename dests_t::iterator it_dest = dests.begin(); it_dest != dests.end(); ++it_dest) { if (dests_width[*it_dest] == current_port_width) { if (find(disabled_dests.begin(), disabled_dests.end(), *it_dest) != disabled_dests.end()) { cout << " - " << get_dest_name(*it_dest) << " is disabled." << endl; } else if (dests_user_typeid.find(*it_dest) != dests_user_typeid.end()) { cout << " - " << get_dest_name(*it_dest) << " (user typeid = " << dests_user_typeid[*it_dest] << ") connects from " << num_compatible_channels_to_dest(*it_dest) << " sources." << endl; } else { cout << " - " << get_dest_name(*it_dest) << " connects from " << num_compatible_channels_to_dest(*it_dest) << " sources." << endl; } } } cout << endl; cout << endl; // update port_width_found = srcs_and_dests_min_width(current_port_width, current_port_width + 1); } cout << "# Summary" << endl; cout << "Source Count = " << get_src_size() << endl; cout << "Destination Count = " << get_dest_size() << endl; cout << std::string(100, '#') << endl; cout << endl; } void print_statistics(bool include_no_traffic = false) { cout << std::string(100, '#') << endl; cout << "# Traffic Summary" << endl; unsigned int current_port_width; bool port_width_found = srcs_and_dests_min_width(current_port_width); while (port_width_found) { bool found_one = false; cout << "# " << dec << current_port_width << "-bit Ports" << endl; cout << endl; for (typename channels_middle_t::iterator it_src = channels_middle.begin(); it_src != channels_middle.end(); ++it_src) { for (typename channels_middle_inner_t::iterator it_dest = it_src->second.begin(); it_dest != it_src->second.end(); ++it_dest) { if (srcs_width[it_src->first] == current_port_width) { NVHLS_ASSERT_MSG( dests_width[it_dest->first] == current_port_width, "Src and dest widths should match, but they don't!"); if (cycle_count_channel[it_src->first][it_dest->first] .to_uint64() == 0) { if (include_no_traffic) { cout << "Src = " << get_src_name(it_src->first) << "Dest = " << get_dest_name(it_dest->first) << ", NO TRAFFIC" << endl; found_one = true; } } else { cout << " - " << get_src_name(it_src->first) << " --> " << get_dest_name(it_dest->first) << ", messages = " << dec << cycle_count_channel[it_src->first][it_dest->first] .to_uint64() << " (" << boost::format("%2.f%%") % (100.0 * cycle_count_channel[it_src->first][it_dest->first] .to_uint64() / cycle_count_total.to_uint64()) << ")" << endl; found_one = true; } } } } if (found_one == false) { cout << " (none with non-zero message counts)" << endl; } cout << endl; // update port_width_found = srcs_and_dests_min_width(current_port_width, current_port_width + 1); } cout << endl << "Total cycles was: " << cycle_count_total.to_uint64() << endl; cout << std::string(100, '#') << endl; cout << endl; } protected: // Unsupported in this code-- implement in future void enable_fixed_bypass(IM_src_t &s, IM_dest_t &d) { // Remove channels_middle NVHLS_ASSERT(0); } void before_end_of_elaboration() { for (typename srcs_t::iterator it_src = srcs.begin(); it_src != srcs.end(); ++it_src) { for (typename dests_t::iterator it_dest = dests.begin(); it_dest != dests.end(); ++it_dest) { if (is_compatible_channels_pre_elab(*it_src, *it_dest)) { // Generate the name std::string new_channel_name = get_src_name(*it_src) + "__to__" + get_dest_name(*it_dest); boost::replace_all(new_channel_name, ".", "_"); // Create the new channel object IM_chanlink_t *new_channel = new IM_chanlink_t(new_channel_name.c_str()); std::string src_name_str = get_src_name(*it_src); char *src_name_new = new char[src_name_str.size() + 1]; strcpy(src_name_new, src_name_str.c_str()); new_channel->in_str = src_name_new; std::string dest_name_str = get_dest_name(*it_dest); char *dest_name_new = new char[dest_name_str.size() + 1]; strcpy(dest_name_new, dest_name_str.c_str()); new_channel->out_str = dest_name_new; // Add it to channels_middle channels_middle[(*it_src)][(*it_dest)] = new_channel; // Add it to reverse channels channels_valid_pairs_reverse[(*it_dest)].push_back(*it_src); } } } // Source read channels for (typename srcs_t::iterator it_src = srcs.begin(); it_src != srcs.end(); ++it_src) { // Create new channel IM_chan_t *new_channel = new IM_chan_t(sc_gen_unique_name("new_channel_src")); channels_begin[(*it_src)] = new_channel; // Bind it and disable annotation (*it_src)->Bind(*new_channel); new_channel->disable_annotate(); // Create a new input arbitration object, depending on size if (num_compatible_channels_from_src(*it_src) == 1) { // Special bypass new InputBypass(*this, (*it_src), channels_middle[*it_src].begin()->first, channels_begin, channels_middle, channels_end); } else { // Otherwise the normal input decode module InputDecoder *i_dec = new InputDecoder(*this, (*it_src), channels_begin, channels_middle, channels_end); i_dec->clk(clk); i_dec->rst(rst); } } // Destination write channels for (typename dests_t::iterator it_dest = dests.begin(); it_dest != dests.end(); ++it_dest) { // Create new channel IM_chan_t *new_channel = new IM_chan_t(sc_gen_unique_name("new_channel_dest")); channels_end[(*it_dest)] = new_channel; // Bind it and disable annotation (*it_dest)->Bind(*new_channel); new_channel->disable_annotate(); // Create a new output arbitration object if (num_compatible_channels_to_dest(*it_dest) == 1) { OutputBypass *o_bypass = new OutputBypass(*this, (*it_dest), *(channels_valid_pairs_reverse[*it_dest].begin()), channels_begin, channels_middle, channels_end, channels_valid_pairs_reverse, cycle_count_channel); o_bypass->clk(clk); o_bypass->rst(rst); } else { OutputArbiter *o_arb = new OutputArbiter( *this, (*it_dest), channels_begin, channels_middle, channels_end, channels_valid_pairs_reverse, cycle_count_channel); o_arb->clk(clk); o_arb->rst(rst); } } const char *BUILD_PREFIX = std::getenv("BUILD"); std::string interconnect_dir = "interconnect"; if (BUILD_PREFIX) { interconnect_dir += std::string("_") + std::string(BUILD_PREFIX); BUILD_PREFIX = ""; } else { BUILD_PREFIX = ""; } // Write out latency here. const char *nvhls_elab_only = std::getenv("NVHLS_ELAB_ONLY"); if (nvhls_elab_only && std::string(nvhls_elab_only) == "1") { interconnect::save_connectivity(*this, *this, BUILD_PREFIX, interconnect_dir); cout << "Info: Elaboration only run. Quiting..." << endl; sc_stop(); } else { interconnect::annotate_design(*this, *this, BUILD_PREFIX, interconnect_dir, interconnect_dir); } } bool is_compatible_channels_pre_elab(IM_src_t *src, IM_dest_t *dest) { bool src_exists = (srcs_typeid.find(src) != srcs_typeid.end()); bool dest_exists = (dests_typeid.find(dest) != dests_typeid.end()); bool src_disabled = find(disabled_srcs.begin(), disabled_srcs.end(), src) != disabled_srcs.end(); bool dest_disabled = find(disabled_dests.begin(), disabled_dests.end(), dest) != disabled_dests.end(); // investigate why ModuleArray fails this assertion. Probably need to // populate. srcs_block_abs/dests_block_abs with other Bind() // Disabling for now. // Connections::Blocking_abs *src_port_block_abs = srcs_block_abs[src]; // Connections::Blocking_abs *dest_port_block_abs = dests_block_abs[dest]; // assert(src_port_block_abs && dest_port_block_abs); // bool pair_disabled = find(disabled_pairs.begin(), disabled_pairs.end(), // std::make_tuple(src_port_block_abs, dest_port_block_abs)) // != disabled_pairs.end(); bool pair_disabled = false; bool src_has_user_typeid = (srcs_user_typeid.find(src) != srcs_user_typeid.end()); bool dest_has_user_typeid = (dests_user_typeid.find(dest) != dests_user_typeid.end()); if (!(src_exists && dest_exists)) { if (!src_exists) CDCOUT("Warning: Interconnect bound source port " << get_src_name(src) << " doesn't have an assigned type." << endl, interconnect::kDebugLevel); if (!dest_exists) CDCOUT("Warning: Interconnect bound destination port " << get_dest_name(dest) << " doesn't have an assigned type." << endl, interconnect::kDebugLevel); return true; } // Fail conditions if (src_disabled || dest_disabled || pair_disabled) { return false; } if (src_has_user_typeid != dest_has_user_typeid) { return false; } if (src_has_user_typeid && dest_has_user_typeid && (srcs_user_typeid[src] != dests_user_typeid[dest])) { return false; } if (!src_has_user_typeid || !dest_has_user_typeid) { // HERE adding in this condition. if (srcs_typeid[src] != dests_typeid[dest]) { return false; } } // Pass condition return true; } bool is_compatible_channels(IM_src_t *src, IM_dest_t *dest) { typename channels_middle_t::iterator it_dest = channels_middle.find(src); return (it_dest != channels_middle.end()) && it_dest->second.find(dest) != it_dest->second.end(); } unsigned int num_compatible_channels_from_src(IM_src_t *p) { return (channels_middle.find(p) == channels_middle.end()) ? 0 : channels_middle[p].size(); } unsigned int num_compatible_channels_to_dest(IM_dest_t *p) { return (channels_valid_pairs_reverse.find(p) == channels_valid_pairs_reverse.end()) ? 0 : channels_valid_pairs_reverse[p].size(); } //////////////////////////////////////////////////////////////////////////////// // Route class Route { public: typedef std::vector<IM_dest_t *> route_vec_t; typedef typename route_vec_t::iterator iterator; protected: InterconnectBase<IM> &ic; route_vec_t route_vec; public: Route(InterconnectBase<IM> &ic_) : ic(ic_) {} void add_dest(idx_t dest_idx, dest_map_idx_t dest_map_idx = 0) { route_vec.push_back(ic.get_dest_from_idx(dest_idx, dest_map_idx)); } iterator begin() { return route_vec.begin(); } iterator end() { return route_vec.end(); } int size() { return route_vec.size(); } }; //////////////////////////////////////////////////////////////////////////////// // InputDecoder class InputDecoder : public sc_module, public Connections::Blocking_abs { SC_HAS_PROCESS(InputDecoder); protected: InterconnectBase<IM> &ic; IM_src_t *p; channels_begin_t &channels_begin; channels_middle_t &channels_middle; channels_end_t &channels_end; public: sc_in_clk clk; sc_in<bool> rst; explicit InputDecoder(InterconnectBase<IM> &ic_, IM_src_t *p_, channels_begin_t &channels_begin_, channels_middle_t &channels_middle_, channels_end_t &channels_end_) : sc_module(sc_module_name(sc_gen_unique_name("input_decoder"))), ic(ic_), p(p_), channels_begin(channels_begin_), channels_middle(channels_middle_), channels_end(channels_end_), clk(sc_gen_unique_name("cl
k")), rst(sc_gen_unique_name("rst")) { SC_CTHREAD(input_dec_run, clk.pos()); async_reset_signal_is(rst, false); } void input_dec_run() { IM data; // Reset input channels_begin[p]->ResetRead(); // Check if we have valid outputs. switch (ic.num_compatible_channels_from_src(p)) { case 0: CDCOUT("Info: Source port " << ic.get_src_name(p) << " doesn't have any valid destinations. Disabling " "thread for " "this source port in the interconnect modeler." << endl, interconnect::kDebugLevel); return; } // Reset outputs. for (typename channels_middle_inner_t::iterator it_dest = channels_middle[p].begin(); it_dest != channels_middle[p].end(); ++it_dest) { it_dest->second->ResetWrite(); } while (1) { wait(); IM data; if (channels_begin[p]->PopNB(data)) { data.set_src_idx(ic, p); typename IM::multicast_t multicast_dests = data.get_multicast(ic); for (typename IM::multicast_t::iterator it = multicast_dests.begin(); it != multicast_dests.end(); ++it) { NVHLS_ASSERT_MSG(ic.is_compatible_channels(p, (*it)), "Interconnect received a source mesage to an " "invalid or incompatible destination."); channels_middle[p][(*it)]->Push(data); } } } } }; // end class InputDecoder //////////////////////////////////////////////////////////////////////////////// // InputBypass class InputBypass : public sc_module, public Connections::Blocking_abs { SC_HAS_PROCESS(InputBypass); protected: InterconnectBase<IM> &ic; IM_src_t *p; IM_dest_t *q; channels_begin_t &channels_begin; channels_middle_t &channels_middle; channels_end_t &channels_end; public: explicit InputBypass(InterconnectBase<IM> &ic_, IM_src_t *p_, IM_dest_t *q_, channels_begin_t &channels_begin_, channels_middle_t &channels_middle_, channels_end_t &channels_end_) : sc_module(sc_module_name(sc_gen_unique_name("input_bypass"))), ic(ic_), p(p_), q(q_), channels_begin(channels_begin_), channels_middle(channels_middle_), channels_end(channels_end_) { CDCOUT("Info: Source port " << ic.get_src_name(p) << " only has one valid destination. Adding a bypass to this " "source port in the interconnect modeler." << endl, interconnect::kDebugLevel); #ifdef CONNECTIONS_SIM_ONLY // SC_METHOD(do_bypass); declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << channels_begin[p]->_DATNAMEOUT_ << channels_begin[p]->_VLDNAMEOUT_ << channels_middle[p][q]->_RDYNAMEIN_; channels_begin[p]->out_bound = true; channels_middle[p][q]->in_bound = true; #endif } void do_bypass() { bool is_val = channels_begin[p]->_VLDNAMEOUT_.read(); // Set val and msg respectively channels_middle[p][q]->_VLDNAMEIN_.write(is_val); channels_begin[p]->_RDYNAMEOUT_.write(channels_middle[p][q]->_RDYNAMEIN_.read()); // Only convert if is_val (to prevent X's) if (is_val) { channels_middle[p][q]->_DATNAMEIN_.write(channels_begin[p]->_DATNAMEOUT_.read()); } } }; // end class InputBypass // OutputArbiter class OutputArbiter : public sc_module, public Connections::Blocking_abs { SC_HAS_PROCESS(OutputArbiter); protected: InterconnectBase<IM> &ic; IM_dest_t *p; channels_begin_t &channels_begin; channels_middle_t &channels_middle; channels_end_t &channels_end; channels_valid_pairs_reverse_t &channels_valid_pairs_reverse; cycle_count_channel_t &cycle_count_channel; public: sc_in_clk clk; sc_in<bool> rst; explicit OutputArbiter( InterconnectBase<IM> &ic_, IM_dest_t *p_, channels_begin_t &channels_begin_, channels_middle_t &channels_middle_, channels_end_t &channels_end_, channels_valid_pairs_reverse_t &channels_valid_pairs_reverse_, cycle_count_channel_t &cycle_count_channel_) : sc_module(sc_module_name(sc_gen_unique_name("output_arbiter"))), ic(ic_), p(p_), channels_begin(channels_begin_), channels_middle(channels_middle_), channels_end(channels_end_), channels_valid_pairs_reverse(channels_valid_pairs_reverse_), cycle_count_channel(cycle_count_channel_), clk(sc_gen_unique_name("clk")), rst(sc_gen_unique_name("rst")) { SC_CTHREAD(output_arb_run, clk.pos()); async_reset_signal_is(rst, false); } void output_arb_run() { IM data; // Reset output channels_end[p]->ResetWrite(); // Check if we have valid inputs. switch (ic.num_compatible_channels_to_dest(p)) { case 0: CDCOUT("Info: Destination port " << ic.get_dest_name(p) << " doesn't have any valid sources. Disabling thread for " "this " "destination port in the interconnect modeler." << endl, interconnect::kDebugLevel); return; case 1: CDCOUT("Warning: FIXME Optimization Destination port " << ic.get_dest_name(p) << " only has one source, could optimize." << endl, interconnect::kDebugLevel); break; } for (typename channels_valid_pairs_reverse_inner_t::iterator it_src = channels_valid_pairs_reverse[p].begin(); it_src != channels_valid_pairs_reverse[p].end(); ++it_src) { channels_middle[*it_src][p]->ResetRead(); cycle_count_channel[*it_src][p] = 0; } // Start round robin at beginning. typename channels_valid_pairs_reverse_inner_t::iterator last_grant_it_src_begin = channels_valid_pairs_reverse[p].begin(); typename channels_valid_pairs_reverse_inner_t::iterator last_grant_it_src_end = channels_valid_pairs_reverse[p].end(); typename channels_valid_pairs_reverse_inner_t::iterator last_grant_it_src = last_grant_it_src_begin; while (1) { wait(); typename channels_valid_pairs_reverse_inner_t::iterator it_src = last_grant_it_src; do { if (channels_middle[*it_src][p]->PopNB(data)) { channels_end[p]->Push(data); // Push cycle_count_channel[*it_src][p]++; // Monitor last_grant_it_src = it_src; // Update } if (++it_src == last_grant_it_src_end) { it_src = last_grant_it_src_begin; } } while (it_src != last_grant_it_src); } // while(1) } }; // end class OutputArbiter // OutputBypass class OutputBypass : public sc_module, public Connections::Blocking_abs { SC_HAS_PROCESS(OutputBypass); protected: InterconnectBase<IM> &ic; IM_dest_t *p; IM_src_t *q; channels_begin_t &channels_begin; channels_middle_t &channels_middle; channels_end_t &channels_end; channels_valid_pairs_reverse_t &channels_valid_pairs_reverse; cycle_count_channel_t &cycle_count_channel; public: sc_in_clk clk; sc_in<bool> rst; explicit OutputBypass( InterconnectBase<IM> &ic_, IM_dest_t *p_, IM_src_t *q_, channels_begin_t &channels_begin_, channels_middle_t &channels_middle_, channels_end_t &channels_end_, channels_valid_pairs_reverse_t &channels_valid_pairs_reverse_, cycle_count_channel_t &cycle_count_channel_) : sc_module(sc_module_name(sc_gen_unique_name("output_arb"))), ic(ic_), p(p_), q(q_), channels_begin(channels_begin_), channels_middle(channels_middle_), channels_end(channels_end_), channels_valid_pairs_reverse(channels_valid_pairs_reverse_), cycle_count_channel(cycle_count_channel_), clk(sc_gen_unique_name("clk")), rst(sc_gen_unique_name("rst")) { CDCOUT("Info: Destination port " << ic.get_dest_name(p) << " only has one valid source. Adding a bypass to this " "destination port in the interconnect modeler." << endl, interconnect::kDebugLevel); #ifdef CONNECTIONS_SIM_ONLY // SC_METHOD(do_bypass); declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << channels_middle[q][p]->_DATNAMEOUT_ << channels_middle[q][p]->_VLDNAMEOUT_ << channels_end[p]->_RDYNAMEIN_; channels_end[p]->in_bound = true; channels_middle[q][p]->out_bound = true; #endif SC_CTHREAD(output_bypass_run, clk.pos()); async_reset_signal_is(rst, false); } void do_bypass() { bool is_val = channels_middle[q][p]->_VLDNAMEOUT_.read(); // Set val and msg respectively channels_end[p]->_VLDNAMEIN_.write(is_val); channels_middle[q][p]->_RDYNAMEOUT_.write(channels_end[p]->_RDYNAMEIN_.read()); // Only convert if is_val (to prevent X's) if (is_val) { channels_end[p]->_DATNAMEIN_.write(channels_middle[q][p]->_DATNAMEOUT_.read()); } } void output_bypass_run() { cycle_count_channel[q][p] = 0; while (1) { wait(); if (channels_end[p]->_VLDNAMEIN_.read() && channels_end[p]->_RDYNAMEIN_.read()) cycle_count_channel[q][p]++; // Monitor } // while(1) } }; // end class OutputBypass }; // end class InterconnectBase template <unsigned int IC_ID> class Interconnect : public InterconnectBase<interconnect::IM_t> { public: Interconnect() : InterconnectBase<interconnect::IM_t>(IC_ID) { // Register with static vector of interconnect objects. // Ensure that only one matches the IC_ID. if (interconnect::get_ICManager().registered_ic.find(IC_ID) != interconnect::get_ICManager().registered_ic.end()) { NVHLS_ASSERT_MSG(0, "An interconnect with this IC_ID is already registered"); } interconnect::get_ICManager().registered_ic[IC_ID] = this; } explicit Interconnect(const char *name) : InterconnectBase<interconnect::IM_t>(name, IC_ID) { // Register with static vector of interconnect objects. // Ensure that only one matches the IC_ID. if (interconnect::get_ICManager().registered_ic.find(IC_ID) != interconnect::get_ICManager().registered_ic.end()) { NVHLS_ASSERT_MSG(0, "An interconnect with this IC_ID is already registered"); } interconnect::get_ICManager().registered_ic[IC_ID] = this; } }; template <unsigned int MaxDataWidth, unsigned int MaxDestCount> class InterconnectMessageSCLV : public nvhls_message { public: typedef InterconnectBase<InterconnectMessageSCLV<MaxDataWidth, MaxDestCount> > interconnect_t; typedef typename interconnect_t::route_t route_t; typedef std::vector<typename interconnect_t::IM_dest_t *> multicast_t; // For marshaller enum { width = Wrapped<sc_lv<MaxDataWidth> >::width + Wrapped<typename interconnect_t::idx_t>::width + Wrapped<sc_lv<MaxDestCount> >::width }; protected: sc_lv<MaxDataWidth> msg_bits; typename interconnect_t::idx_t src_idx; public: sc_lv<MaxDestCount> dest_bits; // Need to provide default constructor to be compatible with use as a Message InterconnectMessageSCLV() : msg_bits(0), src_idx(-1), dest_bits(0) {} template <unsigned int Size> void Marshall(Marshaller<Size> &m) { m &msg_bits; m &src_idx; m &dest_bits; } //////////////////////////////////////////////////////////////////////////////// // Getters and Setters //////////////////// // Message template <typename Message> void set_msg(interconnect_t &ic, Message &msg_) { set_msg(msg_); } template <typename Message> void set_msg(Message &msg_) { // Ensure sized appropriately. NVHLS_ASSERT(Wrapped<Message>::width <= MaxDataWidth); // Convert from Message to general sc_lv type Marshaller<Wrapped<Message>::width> marshaller; Wrapped<Message> wm(msg_); wm.Marshall(marshaller); msg_bits.range(Wrapped<Message>::width - 1, 0) = marshaller.GetResult(); } template <typename Message> void get_msg(interconnect_t &ic, Message &m_) const { get_msg(m_); } template <typename Message> void get_msg(Message &m_) const { // Ensure sized appropriately. NVHLS_ASSERT(Wrapped<Message>::width <= MaxDataWidth); // Convert from general sc_lv type to Message sc_lv<Wrapped<Message>::width> mbits; mbits = msg_bits.range(Wrapped<Message>::width - 1, 0); Marshaller<Wrapped<Message>::width> marshaller(mbits); Wrapped<Message> result; result.Marshall(marshaller); m_ = result.val; } //////////////////// // Source void set_src_idx(interconnect_t &ic, typename interconnect_t::IM_src_t *p) { src_idx = ic.find_src_idx(p); } typename interconnect_t::IM_src_t *get_src_from_idx(interconnect_t &ic) { return ic.get_src_from_idx(src_idx); } //////////////////// // Destination // get_route() to replace this multicast_t get_multicast(interconnect_t &ic) { multicast_t a; // Ensure sized appropriately NVHLS_ASSERT(ic.get_dest_size() <= MaxDestCount); for (unsigned int i = 0; i < ic.get_dest_size(); i++) { if (dest_bits[i] == 1) { a.push_back(ic.get_dest_from_idx(i)); } } return a; } void set_route(interconnect_t &ic, route_t *route) { dest_bits = 0; for (typename route_t::iterator it = route->begin(); it != route->end(); ++it) { dest_bits[ic.find_dest_idx(*it)] = 1; } } bool does_support_multicast() { return true; } }; #endif // ifdef CONNECTIONS_SIM_ONLY template <typename Message> class OutPortPin : public sc_module { SC_HAS_PROCESS(OutPortPin); public: Connections::OutBlocking<Message> &port; Connections::InBlocking<Message> pin; explicit OutPortPin(Connections::OutBlocking<Message> &port_) : sc_module(sc_module_name(sc_gen_unique_name("out_port_to_in_pin"))), port(port_) { // SC_METHOD(do_bypass); declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << pin._DATNAME_ << pin._VLDNAME_ << port._RDYNAME_; #ifdef CONNECTIONS_SIM_ONLY port.disable_spawn(); pin.disable_spawn(); #endif } void do_bypass() { bool is_val = pin._VLDNAME_.read(); // Set val and msg respectively port._VLDNAME_.write(is_val); pin._RDYNAME_.write(port._RDYNAME_.read()); // Only convert if is_val (to prevent X's) if (is_val) { port._DATNAME_.write(pin._DATNAME_.read()); } } }; // class OutPortPin template <typename Message> class InPortPin : public sc_module { SC_HAS_PROCESS(InPortPin); public: Connections::InBlocking<Message> &port; Connections::OutBlocking<Message> pin; explicit InPortPin(Connections::InBlocking<Message> &port_) : sc_module(sc_module_name(sc_gen_unique_name("in_port_to_out_pin"))), port(port_) { // SC_METHOD(do_bypass); declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << port._DATNAME_ << port._VLDNAME_ << pin._RDYNAME_; #ifdef CONNECTIONS_SIM_ONLY port.disable_spawn(); pin.disable_spawn(); #endif } void do_bypass() { bool is_val = port._VLDNAME_.read(); // Set val and msg respectively pin._VLDNAME_.write(is_val); port._RDYNAME_.write(pin._RDYNAME_.read()); // Only convert if is_val (to prevent X's) if (is_val) { pin._DATNAME_.write(port._DATNAME_.read()); } } }; // class InPortPin template <typename Message> class OutPortPin2 : public sc_module { SC_HAS_PROCESS(OutPortPin2); public: Connections::OutBlocking<Message> port; Connections::InBlocking<Message> pin; explicit OutPortPin2() : sc_module(sc_module_name(sc_gen_unique_name("out_port_to_in_pin"))) { // SC_METHOD(do_bypass); declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << pin._DATNAME_ << pin._VLDNAME_ << port._RDYNAME_; #ifdef CONNECTIONS_SIM_ONLY port.disable_spawn(); pin.disable_spawn(); #endif } void do_bypass() { bool is_val = pin._VLDNAME_.read(); // Set val and msg respectively port._VLDNAME_.write(is_val); pin._RDYNAME_.write(port._RDYNAME_.read()); // Only convert if is_val (to prevent X's) #ifndef __SYNTHESIS__ if (is_val) { #endif port._DATNAME_.write(pin._DATNAME_.read()); #ifndef __SYNTHESIS__ } #endif } }; // class OutPortPin2 template <typename Message> class InPortPin2 : public sc_module { SC_HAS_PROCESS(InPortPin2); public: Connections::InBlocking<Message> port; Connections::OutBlocking<Message> pin; explicit InPortPin2() : sc_module(sc_module_name(sc_gen_unique_name("in_port_to_out_pin"))) { // SC_METHOD(do_bypass); declare_method_process(do_bypass_handle, sc_gen_unique_name("do_bypass"), SC_CURRENT_USER_MODULE, do_bypass); this->sensitive << port._DATNAME_ << port._VLDNAME_ << pin._RDYNAME_; #ifdef CONNECTIONS_SIM_ONLY port.disable_spawn(); pin.disable_spawn(); #endif } void do_bypass() { bool is_val = port._VLDNAME_.read(); // Set val and msg respectively pin._VLDNAME_.write(is_val); port._RDYNAME_.write(pin._RDYNAME_.read()); // Only convert if is_val (to prevent X's) #ifndef __SYNTHESIS__ if (is_val) { #endif pin._DATNAME_.write(port._DATNAME_.read()); #ifndef __SYNTHESIS__ } #endif } }; // class InPortPin2 template <typename Message> InPortPin<Message> *new_port_pin(Connections::InBlocking<Message> &port_) { return new InPortPin<Message>(port_); } template <typename Message> OutPortPin<Message> *new_port_pin(Connections::OutBlocking<Message> &port_) { return new OutPortPin<Message>(port_); } template <typename Message> InPortPin2<Message> *new_port_pin2(Connections::InBlocking<Message> &port_) { auto *port_pin = new InPortPin2<Message>(); port_pin->port(port_); return port_pin; } template <typename Message> OutPortPin2<Message> *new_port_pin2(Connections::OutBlocking<Message> &port_) { auto *port_pin = new OutPortPin2<Message>(); port_pin->port(port_); return port_pin; } }; #ifndef __SYNTHESIS__ namespace interconnect { template <typename PART_TYPE, Connections::connections_port_t PortType = AUTO_PORT> class InterconnectInterface { public: sc_in_clk clk; sc_in<bool> rst; // IC_t *parent_ic; InterconnectBase<IM_t> *parent_ic; unsigned int part_id; bool is_bound; std::map<Connections::Blocking_abs *, GenericDestHandlerIface<IM_t> *> generic_iface_dests; std::map<Connections::Blocking_abs *, MSG_ID_t> msg_id_dests; std::map<Connections::Blocking_abs *, unsigned int> port_id_dests; std::map<Connections::Blocking_abs *, std::string> port_name_dests; std::map<Connections::Blocking_a
bs *, width_t> type_width_dests; std::map<Connections::Blocking_abs *, const char *> type_name_dests; std::map<Connections::Blocking_abs *, const char *> msg_name_dests; std::map<Connections::Blocking_abs *, GenericSrcHandlerIface<IM_t> *> generic_iface_srcs; std::map<Connections::Blocking_abs *, MSG_ID_t> msg_id_srcs; std::map<Connections::Blocking_abs *, unsigned int> port_id_srcs; std::map<Connections::Blocking_abs *, std::string> port_name_srcs; std::map<Connections::Blocking_abs *, width_t> type_width_srcs; std::map<Connections::Blocking_abs *, const char *> type_name_srcs; std::map<Connections::Blocking_abs *, const char *> msg_name_srcs; #ifdef CONNECTIONS_SIM_ONLY InterconnectInterface() : clk("clk"), rst("rst"), is_bound(false) {} explicit InterconnectInterface(const char *name) : clk("clk"), rst("rst"), is_bound(false) {} template <unsigned int BIND_ID, typename MSG_TYPE> void Bind(Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p, unsigned int port_id) { ICMToSpecialized<IM_t, MSG_TYPE> *ij = new ICMToSpecialized<IM_t, MSG_TYPE>(p); std::string port_name = p._VLDNAME_.name(); if (port_name.substr(port_name.length() - 4, 4) == "_" _VLDNAMESTR_) { port_name.erase(port_name.length() - 4, 4); } generic_iface_dests[&p] = ij; msg_id_dests[&p] = MSG_TYPE::msg_id; port_id_dests[&p] = port_id; port_name_dests[&p] = port_name; type_width_dests[&p] = Wrapped<typename MSG_TYPE::data_t>::width; type_name_dests[&p] = typeid(typename MSG_TYPE::data_t).name(); msg_name_dests[&p] = MSG_TYPE::name; if (is_bound) { Bind2_Dest(&p, msg_id_dests[&p], port_id_dests[&p], msg_name_dests[&p]); } } template <unsigned int BIND_ID, typename MSG_TYPE> void Bind(Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p, unsigned int port_id) { ICMFromSpecialized<IM_t, MSG_TYPE> *is = new ICMFromSpecialized<IM_t, MSG_TYPE>(p); std::string port_name = p._VLDNAME_.name(); if (port_name.substr(port_name.length() - 4, 4) == "_" _VLDNAMESTR_) { port_name.erase(port_name.length() - 4, 4); } generic_iface_srcs[&p] = is; msg_id_srcs[&p] = MSG_TYPE::msg_id; port_id_srcs[&p] = port_id; port_name_srcs[&p] = port_name; type_width_srcs[&p] = Wrapped<typename MSG_TYPE::data_t>::width; type_name_srcs[&p] = typeid(typename MSG_TYPE::data_t).name(); msg_name_srcs[&p] = MSG_TYPE::name; if (is_bound) { Bind2_Src(&p, msg_id_srcs[&p], port_id_srcs[&p], msg_name_srcs[&p]); } } template <unsigned int IC_ID> void do_parent_bind(Interconnect<IC_ID> &ic, const sc_object &parent, const unsigned int &part_id_) { assert(!is_bound); parent_ic = &ic; part_id = part_id_; is_bound = true; ic.part_names[PART_TYPE::part_id] = PART_TYPE::name; ic.part_to_part_type[part_id_] = PART_TYPE::part_id; ic.part_inst_names[part_id_] = parent.name(); NVHLS_ASSERT(parent.name()); for (std::map<Connections::Blocking_abs *, MSG_ID_t>::iterator it = msg_id_dests.begin(); it != msg_id_dests.end(); ++it) { // Bind Bind2_Dest(it->first, it->second, port_id_dests[it->first], msg_name_dests[it->first]); ic.part_msgs_dests[PART_TYPE::part_id][it->second].insert( port_id_dests[it->first]); } for (std::map<Connections::Blocking_abs *, MSG_ID_t>::iterator it = msg_id_srcs.begin(); it != msg_id_srcs.end(); ++it) { Bind2_Src(it->first, it->second, port_id_srcs[it->first], msg_name_srcs[it->first]); ic.part_msgs_srcs[PART_TYPE::part_id][it->second].insert( port_id_srcs[it->first]); } } protected: void Bind2_Dest(Connections::Blocking_abs *p, unsigned int msg_id, unsigned int port_id, const char *msg_name) { parent_ic->Bind(*generic_iface_dests[p]->im_ptr, msg_id_dests[p], type_width_dests[p], type_name_dests[p], msg_name); parent_ic->set_dest_name(generic_iface_dests[p]->im_ptr, port_name_dests[p]); parent_ic->add_to_dest_directory(*generic_iface_dests[p]->im_ptr, part_id, msg_id, port_id); parent_ic->dests_block_abs[generic_iface_dests[p]->im_ptr] = p; } void Bind2_Src(Connections::Blocking_abs *p, unsigned int msg_id, unsigned int port_id, const char *msg_name) { parent_ic->Bind(*generic_iface_srcs[p]->im_ptr, msg_id_srcs[p], type_width_srcs[p], type_name_srcs[p], msg_name); parent_ic->set_src_name(generic_iface_srcs[p]->im_ptr, port_name_srcs[p]); parent_ic->srcs_block_abs[generic_iface_srcs[p]->im_ptr] = p; } public: #else InterconnectInterface() { NVHLS_ASSERT_MSG(0, "Need an HLS compatible InterconnectInterface!"); } template <unsigned int PORT_ID, typename MSG_TYPE> void Bind(Connections::InBlocking<interconnect::Msg<MSG_TYPE> > &p_) { NVHLS_ASSERT(0); } template <unsigned int PORT_ID, typename MSG_TYPE> void Bind(Connections::OutBlocking<interconnect::Msg<MSG_TYPE> > &p_) { NVHLS_ASSERT(0); } #endif }; // Enable bottom-up (versus top-down) binding. // template <unsigned int BIND_ID, unsigned int IC_ID, unsigned int PART_TYPE, // Connections::connections_port_t IfacePortType> template <unsigned int BIND_ID, unsigned int IC_ID, typename PART_TYPE, Connections::connections_port_t IfacePortType> void do_interconnect_to_interface_bind( Interconnect<IC_ID> &ic, interconnect::InterconnectInterface<PART_TYPE, IfacePortType> &ic_interface, const sc_object &parent, const unsigned int &part_id) { ic_interface.do_parent_bind(ic, parent, part_id); } template <class Dummy> unsigned int get_real_dest_idx(InterconnectBase<IM_t> &ic, const unsigned int &dest_idx, const unsigned int &dest_map_idx) { return ic.get_real_dest_idx(dest_idx, dest_map_idx); } }; #else namespace interconnect { template <typename PART_TYPE, Connections::connections_port_t PortType = AUTO_PORT> class InterconnectInterface {}; }; #endif #endif // #ifdef __INTERCONNECT_H__
#include <systemc.h> #include <systemc-ams.h> #include <config.hpp> SCA_TDF_MODULE(Power_bus){ //Rate 1ms //Input Port sca_tdf::sca_in <double> core_current; sca_tdf::sca_in <double> core_voltage; sca_tdf::sca_in <double> voltage_sensors[NUM_SENSORS]; sca_tdf::sca_in <double> current_sensors[NUM_SENSORS]; #if NUM_SOURCES>0 sca_tdf::sca_in <double> current_sources[NUM_SOURCES]; #endif #if NUM_BATTERIES>0 sca_tdf::sca_out <double> current_batteries[NUM_BATTERIES]; #endif SCA_CTOR(Power_bus): core_current("Current_of_CPU"), core_voltage("Voltage_of_CPU") {} void set_attributes(); void initialize(); void processing(); private: double total_current = 0; Power_bus(){} };
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #pragma once #define SC_INCLUDE_FX #include "hwcore/pipes/pipes.h" #include <systemc.h> #if __RTL_SIMULATION__ //#include "DMA_performance_tester_rtl_wrapper.h" //#else //#include "DMA_generic_performance_tester.hpp" #endif const long test_size = 250; SC_MODULE(mon_bufferstreamer) { sc_fifo_out<sc_uint<31> > ctrl_out; sc_fifo_in<hwcore::pipes::sc_data_stream_t<16> > data_in; SC_CTOR(mon_bufferstreamer) { SC_THREAD(mon_thread); } void mon_thread() { uint16_t data_gen = 0; std::cout << "(mon) req. newset (start) " << std::endl; ctrl_out.write(hwcore::pipes::sc_stream_buffer<>::ctrls::newset); std::cout << "(mon) req. newset (done) " << std::endl; hwcore::pipes::sc_data_stream_t<16> raw_tmp; for (int a = 0; a < 5; a++) { ctrl_out.write(hwcore::pipes::sc_stream_buffer<>::ctrls::reapeat); for (int i = 0; i < test_size; i++) { raw_tmp = data_in.read(); uint16_t tmp = raw_tmp.data.to_uint(); std::cout << "(mon) got new data: " << tmp << ", last? " << (raw_tmp.tlast ? "true" : "false") << std::endl; sc_assert((i == test_size - 1) == (raw_tmp.tlast == 1)); sc_assert(tmp == i); if (tmp != i) { sc_stop(); } } raw_tmp = data_in.read(); uint16_t tmp = raw_tmp.data.to_uint(); std::cout << "(mon) got new data: " << tmp << ", last? " << (raw_tmp.tlast ? "true" : "false") << std::endl; sc_assert(raw_tmp.EOP()); } std::cout << "(mon) req. newset (start) " << std::endl; ctrl_out.write(hwcore::pipes::sc_stream_buffer<>::ctrls::newset); std::cout << "(mon) req. newset (done) " << std::endl; for (int a = 0; a < 5; a++) { ctrl_out.write(hwcore::pipes::sc_stream_buffer<>::ctrls::reapeat); for (int i = 0; i < test_size; i++) { raw_tmp = data_in.read(); uint16_t tmp = raw_tmp.data.to_uint(); std::cout << "(mon) got new data: " << tmp << ", last? " << (raw_tmp.tlast ? "true" : "false") << std::endl; sc_assert((i == test_size - 1) == (raw_tmp.tlast == 1)); sc_assert(tmp == i + 0xBF); if (tmp != i + 0xBF) { sc_stop(); } } raw_tmp = data_in.read(); uint16_t tmp = raw_tmp.data.to_uint(); std::cout << "(mon) got new data: " << tmp << ", last? " << (raw_tmp.tlast ? "true" : "false") << std::endl; sc_assert(raw_tmp.EOP()); } std::cout << "Test finish no errors" << std::endl; sc_stop(); } }; SC_MODULE(wave_bufferstreamer) { sc_fifo_out<hwcore::pipes::sc_data_stream_t<16> > data_out; SC_CTOR(wave_bufferstreamer) { SC_THREAD(wave_thread); } void wave_thread() { hwcore::pipes::sc_data_stream_t<16> tmp; for (int i = 0; i < test_size; i++) { tmp.data = i; std::cout << "(wave) write new data: " << i << std::endl; tmp.tkeep = 0b11; tmp.tlast = (i == test_size - 1); std::cout << "(wave) tlast " << (tmp.tlast ? "true" : "false") << std::endl; data_out.write(tmp); } tmp.setEOP(); data_out.write(tmp); for (int i = 0; i < test_size; i++) { tmp.data = i + 0xBF; std::cout << "(wave) write new data: " << i << std::endl; tmp.tkeep = 0b11; tmp.tlast = (i == test_size - 1); std::cout << "(wave) tlast " << (tmp.tlast ? "true" : "false") << std::endl; data_out.write(tmp); } tmp.setEOP(); data_out.write(tmp); } }; SC_MODULE(tb_bufferstreamer) { #if __RTL_SIMULATION__ // DMA_performance_tester_rtl_wrapper u1; #else // DMA_performance_tester u1; #endif sc_clock clk; sc_signal<bool> reset; hwcore::pipes::sc_stream_buffer_not_stream_while_write<16> bs_u1; wave_bufferstreamer wave; mon_bufferstreamer mon; sc_fifo<hwcore::pipes::sc_data_stream_t<16> > bs2mon_data; sc_fifo<sc_uint<31> > mon2bs_ctrl; sc_fifo<hwcore::pipes::sc_data_stream_t<16> > wave2bs_data; SC_CTOR(tb_bufferstreamer) : bs_u1("BS"), wave("wave"), mon("mon"), clk("clock", sc_time(10, SC_NS)) { bs_u1.clk(clk); bs_u1.reset(reset); bs_u1.din(wave2bs_data); bs_u1.dout(bs2mon_data); bs_u1.ctrls_in(mon2bs_ctrl); wave.data_out(wave2bs_data); mon.ctrl_out(mon2bs_ctrl); mon.data_in(bs2mon_data); } };
// Copyright (c) 2011-2024 Columbia University, System Level Design Group // SPDX-License-Identifier: Apache-2.0 #ifndef __CACHE_TYPES_HPP__ #define __CACHE_TYPES_HPP__ #include <stdint.h> #include <sstream> #include "math.h" #include "systemc.h" #include "cache_consts.hpp" /* * Cache data types */ typedef sc_uint<CPU_MSG_TYPE_WIDTH> cpu_msg_t; // CPU bus requests typedef sc_uint<COH_MSG_TYPE_WIDTH> coh_msg_t; // Requests without DMA, Forwards, Responses typedef sc_uint<MIX_MSG_TYPE_WIDTH> mix_msg_t; // Requests if including DMA typedef sc_uint<HSIZE_WIDTH> hsize_t; typedef sc_uint<HPROT_WIDTH> hprot_t; typedef sc_uint<INVACK_CNT_WIDTH> invack_cnt_t; typedef sc_uint<INVACK_CNT_CALC_WIDTH> invack_cnt_calc_t; typedef sc_uint<ADDR_BITS> addr_t; typedef sc_uint<LINE_ADDR_BITS> line_addr_t; typedef sc_uint<L2_ADDR_BITS> l2_addr_t; typedef sc_uint<LLC_ADDR_BITS> llc_addr_t; typedef sc_uint<BITS_PER_WORD> word_t; typedef sc_biguint<BITS_PER_LINE> line_t; typedef sc_uint<L2_TAG_BITS> l2_tag_t; typedef sc_uint<LLC_TAG_BITS> llc_tag_t; typedef sc_uint<L2_SET_BITS> l2_set_t; typedef sc_uint<LLC_SET_BITS> llc_set_t; #if (L2_WAY_BITS == 1) typedef sc_uint<2> l2_way_t; #else typedef sc_uint<L2_WAY_BITS> l2_way_t; #endif typedef sc_uint<LLC_WAY_BITS> llc_way_t; typedef sc_uint<OFFSET_BITS> offset_t; typedef sc_uint<WORD_BITS> word_offset_t; typedef sc_uint<DMA_WORD_BITS> dma_word_offset_t; typedef sc_uint<BYTE_BITS> byte_offset_t; typedef sc_uint<STABLE_STATE_BITS> state_t; typedef sc_uint<LLC_STATE_BITS> llc_state_t; typedef sc_uint<UNSTABLE_STATE_BITS> unstable_state_t; typedef sc_uint<CACHE_ID_WIDTH> cache_id_t; typedef sc_uint<LLC_COH_DEV_ID_WIDTH> llc_coh_dev_id_t; typedef sc_uint<MAX_N_L2_BITS> owner_t; typedef sc_uint<MAX_N_L2> sharers_t; typedef sc_uint<DMA_BURST_LENGTH_BITS> dma_length_t; typedef sc_uint<BRESP_WIDTH> bresp_t; typedef sc_uint<AMO_WIDTH> amo_t; /* * L2 cache coherence channels types */ /* L1 to L2 */ // L1 request class l2_cpu_req_t { public: cpu_msg_t cpu_msg; // r, w, r atom., w atom., flush hsize_t hsize; hprot_t hprot; addr_t addr; word_t word; amo_t amo; l2_cpu_req_t() : cpu_msg(0), hsize(0), hprot(0), addr(0), word(0), amo(0) {} inline l2_cpu_req_t& operator = (const l2_cpu_req_t& x) { cpu_msg = x.cpu_msg; hsize = x.hsize; hprot = x.hprot; addr = x.addr; word = x.word; amo = x.amo; return *this; } inline bool operator == (const l2_cpu_req_t& x) const { return (x.cpu_msg == cpu_msg && x.hsize == hsize && x.hprot == hprot && x.addr == addr && x.word == word && x.amo == amo); } inline friend void sc_trace(sc_trace_file *tf, const l2_cpu_req_t& x, const std::string & name) { sc_trace(tf, x.cpu_msg , name + ".cpu_msg "); sc_trace(tf, x.hsize, name + ".hsize"); sc_trace(tf, x.hprot, name + ".hprot"); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.word, name + ".word"); sc_trace(tf, x.amo, name + ".amo"); } inline friend ostream & operator<<(ostream& os, const l2_cpu_req_t& x) { os << hex << "(" << "cpu_msg: " << x.cpu_msg << ", hsize: " << x.hsize << ", hprot: " << x.hprot << ", addr: " << x.addr << ", word: " << x.word << ", amo: " << x.amo << ")"; return os; } }; /* L2 to L1 */ // read data response class l2_rd_rsp_t { public: line_t line; l2_rd_rsp_t() : line(0) {} inline l2_rd_rsp_t& operator = (const l2_rd_rsp_t& x) { line = x.line; return *this; } inline bool operator == (const l2_rd_rsp_t& x) const { return (x.line == line); } inline friend void sc_trace(sc_trace_file *tf, const l2_rd_rsp_t& x, const std::string & name) { sc_trace(tf, x.line , name + ".line "); } inline friend ostream & operator<<(ostream& os, const l2_rd_rsp_t& x) { os << hex << "(" << "line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ")"; return os; } }; // invalidate address typedef line_addr_t l2_inval_addr_t; class l2_inval_t { public: l2_inval_addr_t addr; hprot_t hprot; l2_inval_t() : addr(0), hprot(0) {} inline l2_inval_t& operator = (const l2_inval_t& x) { addr = x.addr; hprot = x.hprot; return *this; } inline bool operator == (const l2_inval_t& x) const { return (x.addr == addr); return (x.hprot == hprot); } inline friend void sc_trace(sc_trace_file *tf, const l2_inval_t& x, const std::string & name) { sc_trace(tf, x.addr , name + ".addr "); sc_trace(tf, x.hprot , name + ".hprot "); } inline friend ostream & operator<<(ostream& os, const l2_inval_t& x) { os << hex << "(" << "addr: " << x.addr << ", hprot: " << x.hprot << ")"; return os; } }; /* L2/LLC to L2 */ // forwards class l2_fwd_in_t { public: mix_msg_t coh_msg; // fwd-gets, fwd-getm, fwd-invalidate line_addr_t addr; cache_id_t req_id; l2_fwd_in_t() : coh_msg(0), addr(0), req_id(0) { } inline l2_fwd_in_t& operator = (const l2_fwd_in_t& x) { coh_msg = x.coh_msg; addr = x.addr; req_id = x.req_id; return *this; } inline bool operator == (const l2_fwd_in_t& x) const { return (x.coh_msg == coh_msg && x.addr == addr && x.req_id == req_id); } inline friend void sc_trace(sc_trace_file *tf, const l2_fwd_in_t& x, const std::string & name) { sc_trace(tf, x.coh_msg , name + ".coh_msg "); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.req_id, name + ".req_id"); } inline friend ostream & operator<<(ostream& os, const l2_fwd_in_t& x) { os << hex << "(" << "coh_msg: " << x.coh_msg << ", addr: " << x.addr << ", req_id: " << x.req_id << ")"; return os; } }; // responses class l2_rsp_in_t { public: coh_msg_t coh_msg; // data, e-data, inv-ack, put-ack line_addr_t addr; line_t line; invack_cnt_t invack_cnt; l2_rsp_in_t() : coh_msg(0), addr(0), line(0), invack_cnt(0) {} inline l2_rsp_in_t& operator = (const l2_rsp_in_t& x) { coh_msg = x.coh_msg; addr = x.addr; line = x.line; invack_cnt = x.invack_cnt; return *this; } inline bool operator == (const l2_rsp_in_t& x) const { return (x.coh_msg == coh_msg && x.addr == addr && x.line == line && x.invack_cnt == invack_cnt); } inline friend void sc_trace(sc_trace_file *tf, const l2_rsp_in_t& x, const std::string & name) { sc_trace(tf, x.coh_msg , name + ".cpu_msg "); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); sc_trace(tf, x.invack_cnt, name + ".invack_cnt"); } inline friend ostream & operator<<(ostream& os, const l2_rsp_in_t& x) { os << hex << "(" << "coh_msg: " << x.coh_msg << ", addr: " << x.addr << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ", invack_cnt: " << x.invack_cnt << ")"; return os; } }; template <unsigned REQ_ID_WIDTH> class llc_rsp_out_t { public: coh_msg_t coh_msg; // data, e-data, inv-ack, rsp-data-dma line_addr_t addr; line_t line; invack_cnt_t invack_cnt; // used to mark last line of RSP_DATA_DMA sc_uint<REQ_ID_WIDTH> req_id; cache_id_t dest_id; word_offset_t word_offset; llc_rsp_out_t() : coh_msg(0), addr(0), line(0), invack_cnt(0), req_id(0), dest_id(0), word_offset(0) {} inline llc_rsp_out_t& operator = (const llc_rsp_out_t& x) { coh_msg = x.coh_msg; addr = x.addr; line = x.line; invack_cnt = x.invack_cnt; req_id = x.req_id; dest_id = x.dest_id; word_offset = x.word_offset; return *this; } inline bool operator == (const llc_rsp_out_t& x) const { return (x.coh_msg == coh_msg && x.addr == addr && x.line == line && x.invack_cnt == invack_cnt && x.req_id == req_id && x.dest_id == dest_id && x.word_offset == word_offset); } inline friend void sc_trace(sc_trace_file *tf, const llc_rsp_out_t& x, const std::string & name) { sc_trace(tf, x.coh_msg , name + ".cpu_msg "); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); sc_trace(tf, x.invack_cnt, name + ".invack_cnt"); sc_trace(tf, x.req_id, name + ".req_id"); sc_trace(tf, x.dest_id, name + ".dest_id"); sc_trace(tf, x.word_offset, name + ".word_offset"); } inline friend ostream & operator<<(ostream& os, const llc_rsp_out_t& x) { os << hex << "(coh_msg: "; switch (x.coh_msg) { case RSP_DATA : os << "DATA"; break; case RSP_EDATA : os << "EDATA"; break; case RSP_INVACK : os << "INVACK"; break; case RSP_DATA_DMA : os << "DATA_DMA"; break; default: os << "UNKNOWN"; break; } os << ", addr: " << x.addr << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ", invack_cnt: " << x.invack_cnt << ", req_id: " << x.req_id << ", dest_id: " << x.dest_id << ", word_offset: " << x.word_offset << ")"; return os; } }; template <unsigned REQ_ID_WIDTH> class llc_dma_rsp_out_t { public: coh_msg_t coh_msg; // data, e-data, inv-ack, rsp-data-dma line_addr_t addr; line_t line; invack_cnt_t invack_cnt; // used to mark last line of RSP_DATA_DMA sc_uint<REQ_ID_WIDTH> req_id; cache_id_t dest_id; dma_word_offset_t word_offset; llc_dma_rsp_out_t() : coh_msg(0), addr(0), line(0), invack_cnt(0), req_id(0), dest_id(0), word_offset(0) {} inline llc_dma_rsp_out_t& operator = (const llc_dma_rsp_out_t& x) { coh_msg = x.coh_msg; addr = x.addr; line = x.line; invack_cnt = x.invack_cnt; req_id = x.req_id; dest_id = x.dest_id; word_offset = x.word_offset; return *this; } inline bool operator == (const llc_dma_rsp_out_t& x) const { return (x.coh_msg == coh_msg && x.addr == addr && x.line == line && x.invack_cnt == invack_cnt && x.req_id == req_id && x.dest_id == dest_id && x.word_offset == word_offset); } inline friend void sc_trace(sc_trace_file *tf, const llc_dma_rsp_out_t& x, const std::string & name) { sc_trace(tf, x.coh_msg , name + ".cpu_msg "); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); sc_trace(tf, x.invack_cnt, name + ".invack_cnt"); sc_trace(tf, x.req_id, name + ".req_id"); sc_trace(tf, x.dest_id, name + ".dest_id"); sc_trace(tf, x.word_offset, name + ".word_offset"); } inline friend ostream & operator<<(ostream& os, const llc_dma_rsp_out_t& x) { os << hex << "(coh_msg: "; switch (x.coh_msg) { case RSP_DATA : os << "DATA"; break; case RSP_EDATA : os << "EDATA"; break; case RSP_INVACK : os << "INVACK"; break; case RSP_DATA_DMA : os << "DATA_DMA"; break; default: os << "UNKNOWN"; break; } os << ", addr: " << x.addr << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ", invack_cnt: " << x.invack_cnt << ", req_id: " << x.req_id << ", dest_id: " << x.dest_id << ", word_offset: " << x.word_offset << ")"; return os; } }; class llc_fwd_out_t { public: mix_msg_t coh_msg; // fwd_gets, fwd_getm, fwd_inv line_addr_t addr; cache_id_t req_id; cache_id_t dest_id; llc_fwd_out_t() : coh_msg(0), addr(0), req_id(0), dest_id(0) {} inline llc_fwd_out_t& operator = (const llc_fwd_out_t& x) { coh_msg = x.coh_msg; addr = x.addr; req_id = x.req_id; dest_id = x.dest_id; return *this; } inline bool operator == (const llc_fwd_out_t& x) const { return (x.coh_msg == coh_msg && x.addr == addr && x.req_id == req_id && x.dest_id == dest_id); } inline friend void sc_trace(sc_trace_file *tf, const llc_fwd_out_t& x, const std::string & name) { sc_trace(tf, x.coh_msg , name + ".cpu_msg "); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.req_id, name + ".req_id"); sc_trace(tf, x.dest_id, name + ".dest_id"); } inline friend ostream & operator<<(ostream& os, const llc_fwd_out_t& x) { os << hex << "(coh_msg: "; switch (x.coh_msg) { case FWD_GETS : os << "GETS"; break; case FWD_GETM : os << "GETM"; break; case FWD_INV : os << "INV"; break; case FWD_PUTACK : os << "PUTACK"; break; case FWD_GETM_LLC : os << "RECALL_EM"; break; case FWD_INV_LLC : os << "RECALL_S"; break; default: os << "UNKNOWN"; break; } os << ", addr: " << x.addr << ", req_id: " << x.req_id << ", dest_id: " << x.dest_id << ")"; return os; } }; /* L2 to L2/LLC */ // requests class l2_req_out_t { public: coh_msg_t coh_msg; // gets, getm, puts, putm hprot_t hprot; line_addr_t addr; line_t line; l2_req_out_t() : coh_msg(coh_msg_t(0)), hprot(0), addr(0), line(0) {} inline l2_req_out_t& operator = (const l2_req_out_t& x) { coh_msg = x.coh_msg; hprot = x.hprot; addr = x.addr; line = x.line; return *this; } inline bool operator == (const l2_req_out_t& x) const { return (x.coh_msg == coh_msg && x.hprot == hprot && x.addr == addr && x.line == line); } inline friend void sc_trace(sc_trace_file *tf, const l2_req_out_t& x, const std::string & name) { sc_trace(tf, x.coh_msg , name + ".coh_msg "); sc_trace(tf, x.hprot, name + ".hprot"); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); } inline friend ostream & operator<<(ostream& os, const l2_req_out_t& x) { os << hex << "(" << "coh_msg: " << x.coh_msg << ", hprot: " << x.hprot << ", addr: " << x.addr << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ")"; return os; } }; template <unsigned REQ_ID_WIDTH> class llc_req_in_t { public: mix_msg_t coh_msg; // gets, getm, puts, putm, dma_read, dma_write hprot_t hprot; // used for dma write burst end (0) and non-aligned addr (1) line_addr_t addr; line_t line; // used for dma burst length too sc_uint<REQ_ID_WIDTH> req_id; word_offset_t word_offset; word_offset_t valid_words; llc_req_in_t() : coh_msg(coh_msg_t(0)), hprot(0), addr(0), line(0), req_id(0), word_offset(0), valid_words(0) {} inline llc_req_in_t& operator = (const llc_req_in_t& x) { coh_msg = x.coh_msg; hprot = x.hprot; addr = x.addr; line = x.line; req_id = x.req_id; word_offset = x.word_offset; valid_words = x.valid_words; return *this; } inline bool operator == (const llc_req_in_t& x) const { return (x.coh_msg == coh_msg && x.hprot == hprot && x.addr == addr && x.line == line && x.req_id == req_id && x.word_offset == word_offset && x.valid_words == valid_words); } inline friend void sc_trace(sc_trace_file *tf, const llc_req_in_t& x, const std::string & name) { sc_trace(tf, x.coh_msg, name + ".coh_msg "); sc_trace(tf, x.hprot, name + ".hprot"); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); sc_trace(tf, x.req_id, name + ".req_id"); sc_trace(tf, x.word_offset, name + ".word_offset"); sc_trace(tf, x.valid_words, name + ".valid_words"); } inline friend ostream & operator<<(ostream& os, const llc_req_in_t& x) { os << hex << "(coh_msg: "; switch (x.coh_msg) { case REQ_GETS : os << "GETS"; break; case REQ_GETM : os << "GETM"; break; case REQ_PUTS : os << "PUTS"; break; case REQ_PUTM : os << "PUTM"; break; case REQ_DMA_READ : os << "DMA_READ"; break; case REQ_DMA_WRITE : os << "DMA_WRITE"; break; case REQ_DMA_READ_BURST : os << "DMA_READ_BURST"; break; case REQ_DMA_WRITE_BURST : os << "DMA_WRITE_BURST"; break; default: os << "UNKNOWN"; break; } os << ", hprot: " << x.hprot << ", addr: " << x.addr << ", req_id: " << x.req_id << ", word_offset: " << x.word_offset << ", valid_words: " << x.valid_words << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ")"; return os; } }; //dma req in template <unsigned REQ_ID_WIDTH> class llc_dma_req_in_t { public: mix_msg_t coh_msg; // gets, getm, puts, putm, dma_read, dma_write hprot_t hprot; // used for dma write burst end (0) and non-aligned addr (1) line_addr_t addr; line_t line; // used for dma burst length too sc_uint<REQ_ID_WIDTH> req_id; dma_word_offset_t word_offset; dma_word_offset_t valid_words; llc_dma_req_in_t() : coh_msg(coh_msg_t(0)), hprot(0), addr(0), line(0), req_id(0), word_offset(0), valid_words(0) {} inline llc_dma_req_in_t& operator = (const llc_dma_req_in_t& x) { coh_msg = x.coh_msg; hprot = x.hprot; addr = x.addr; line = x.line; req_id = x.req_id; word_offset = x.word_offset; valid_words = x.valid_words; return *this; } inline bool operator == (const llc_dma_req_in_t& x) const { return (x.coh_msg == coh_msg && x.hprot == hprot && x.addr == addr && x.line == line && x.req_id == req_id && x.word_offset == word_offset && x.valid_words == valid_words); } inline friend void sc_trace(sc_trace_file *tf, const llc_dma_req_in_t& x, const std::string & name) { sc_trace(tf, x.coh_msg, name + ".coh_msg "); sc_trace(tf, x.hprot, name + ".hprot"); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); sc_trace(tf, x.req_id, name + ".req_id"); sc_trace(tf, x.word_offset, name + ".word_offset"); sc_trace(tf, x.valid_words, name + ".valid_words"); } inline friend ostream & operator<<(ostream& os, const llc_dma_req_in_t& x) { os << hex << "(coh_msg: "; switch (x.coh_msg) { case REQ_GETS : os << "GETS"; break; case REQ_GETM : os << "GETM"; break; case REQ_PUTS : os << "PUTS"; break; case REQ_PUTM : os << "PUTM"; break; case REQ_DMA_READ : os << "DMA_READ"; break; case REQ_DMA_WRITE : os << "DMA_WRITE"; break; case REQ_DMA_READ_BURST : os << "DMA_READ_BURST"; break; case REQ_DMA_WRITE_BURST : os << "DMA_WRITE_BURST"; break; default: os << "UNKNOWN"; break; } os << ", hprot: " << x.hprot << ", addr: " << x.addr << ", req_id: " << x.req_id << ", word_offset: " << x.word_offset << ", valid_words: " << x.valid_words << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ")"; return os; } }; // responses class l2_rsp_out_t { public: coh_msg_t coh_msg; // gets, getm, puts, putm cache_id_t req_id; sc_uint<2> to_req; line_addr_t addr; line_t line; l2_rsp_out_t() : coh_msg(coh_msg_t(0)), req
_id(0), to_req(0), addr(0), line(0) {} inline l2_rsp_out_t& operator = (const l2_rsp_out_t& x) { coh_msg = x.coh_msg; req_id = x.req_id; to_req = x.to_req; addr = x.addr; line = x.line; return *this; } inline bool operator == (const l2_rsp_out_t& x) const { return (x.coh_msg == coh_msg && x.req_id == req_id && x.to_req == to_req && x.addr == addr && x.line == line); } inline friend void sc_trace(sc_trace_file *tf, const l2_rsp_out_t& x, const std::string & name) { sc_trace(tf, x.coh_msg , name + ".coh_msg "); sc_trace(tf, x.req_id, name + ".req_id"); sc_trace(tf, x.to_req, name + ".to_req"); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); } inline friend ostream & operator<<(ostream& os, const l2_rsp_out_t& x) { os << hex << "(" << "coh_msg: " << x.coh_msg << ", req_id: " << x.req_id << ", to_req: " << x.to_req << ", addr: " << x.addr << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ")"; return os; } }; class llc_rsp_in_t { public: coh_msg_t coh_msg; line_addr_t addr; line_t line; cache_id_t req_id; llc_rsp_in_t() : coh_msg(0), addr(0), line(0), req_id(0) {} inline llc_rsp_in_t& operator = (const llc_rsp_in_t& x) { coh_msg = x.coh_msg; addr = x.addr; line = x.line; req_id = x.req_id; return *this; } inline bool operator == (const llc_rsp_in_t& x) const { return (x.coh_msg == coh_msg && x.addr == addr && x.line == line && x.req_id == req_id); } inline friend void sc_trace(sc_trace_file *tf, const llc_rsp_in_t& x, const std::string & name) { sc_trace(tf, x.coh_msg, name + ".coh_msg"); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); sc_trace(tf, x.req_id, name + ".req_id"); } inline friend ostream & operator<<(ostream& os, const llc_rsp_in_t& x) { os << hex << "(" << "coh_msg: " << x.coh_msg << ", addr: " << x.addr << ", req_id: " << x.req_id << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ")"; return os; } }; /* LLC to Memory */ // requests class llc_mem_req_t { public: bool hwrite; // r, w, r atom., w atom., flush hsize_t hsize; hprot_t hprot; line_addr_t addr; line_t line; llc_mem_req_t() : hwrite(0), hsize(0), hprot(0), addr(0), line(0) {} inline llc_mem_req_t& operator = (const llc_mem_req_t& x) { hwrite = x.hwrite; hsize = x.hsize; hprot = x.hprot; addr = x.addr; line = x.line; return *this; } inline bool operator == (const llc_mem_req_t& x) const { return (x.hwrite == hwrite && x.hsize == hsize && x.hprot == hprot && x.addr == addr && x.line == line); } inline friend void sc_trace(sc_trace_file *tf, const llc_mem_req_t& x, const std::string & name) { sc_trace(tf, x.hwrite , name + ".hwrite "); sc_trace(tf, x.hsize, name + ".hsize"); sc_trace(tf, x.hprot, name + ".hprot"); sc_trace(tf, x.addr, name + ".addr"); sc_trace(tf, x.line, name + ".line"); } inline friend ostream & operator<<(ostream& os, const llc_mem_req_t& x) { os << hex << "(" << "hwrite: " << x.hwrite << ", hsize: " << x.hsize << ", hprot: " << x.hprot << ", addr: " << x.addr << ", line: " << x.line << ")"; return os; } }; // responses typedef l2_rd_rsp_t llc_mem_rsp_t; /* * Ongoing transaction buffer tuypes */ // ongoing request buffer class reqs_buf_t { public: cpu_msg_t cpu_msg; l2_tag_t tag; l2_tag_t tag_estall; l2_set_t set; l2_way_t way; hsize_t hsize; word_offset_t w_off; byte_offset_t b_off; unstable_state_t state; hprot_t hprot; invack_cnt_calc_t invack_cnt; word_t word; line_t line; amo_t amo; reqs_buf_t() : cpu_msg(0), tag(0), tag_estall(0), set(0), way(0), hsize(0), w_off(0), b_off(0), state(0), hprot(0), invack_cnt(0), word(0), line(0), amo(0) {} inline reqs_buf_t& operator = (const reqs_buf_t& x) { cpu_msg = x.cpu_msg; tag = x.tag; tag_estall = x.tag_estall; set = x.set; way = x.way; hsize = x.hsize; w_off = x.w_off; b_off = x.b_off; state = x.state; hprot = x.hprot; invack_cnt = x.invack_cnt; word = x.word; line = x.line; amo = x.amo; return *this; } inline bool operator == (const reqs_buf_t& x) const { return (x.cpu_msg == cpu_msg && x.tag == tag && x.tag_estall == tag_estall && x.set == set && x.way == way && x.hsize == hsize && x.w_off == w_off && x.b_off == b_off && x.state == state && x.hprot == hprot && x.invack_cnt == invack_cnt && x.word == word && x.line == line && x.amo == amo); } inline friend void sc_trace(sc_trace_file *tf, const reqs_buf_t& x, const std::string & name) { sc_trace(tf, x.cpu_msg , name + ".cpu_msg "); sc_trace(tf, x.tag , name + ".tag"); sc_trace(tf, x.tag_estall , name + ".tag_estall"); sc_trace(tf, x.set , name + ".set"); sc_trace(tf, x.way , name + ".way"); sc_trace(tf, x.hsize , name + ".hsize"); sc_trace(tf, x.w_off , name + ".w_off"); sc_trace(tf, x.b_off , name + ".b_off"); sc_trace(tf, x.state , name + ".state"); sc_trace(tf, x.hprot , name + ".hprot"); sc_trace(tf, x.invack_cnt , name + ".invack_cnt"); sc_trace(tf, x.word , name + ".word"); sc_trace(tf, x.line , name + ".line"); sc_trace(tf, x.amo , name + ".amo"); } inline friend ostream & operator<<(ostream& os, const reqs_buf_t& x) { os << hex << "(" << "cpu_msg: " << x.cpu_msg << "tag: " << x.tag << "tag_estall: " << x.tag_estall << ", set: "<< x.set << ", way: " << x.way << ", hsize: " << x.hsize << ", w_off: " << x.w_off << ", b_off: " << x.b_off << ", state: " << x.state << ", hprot: " << x.hprot << ", invack_cnt: " << x.invack_cnt << ", word: " << x.word << ", amo: " << x.amo << ", line: "; for (int i = WORDS_PER_LINE-1; i >= 0; --i) { int base = i*BITS_PER_WORD; os << x.line.range(base + BITS_PER_WORD - 1, base) << " "; } os << ")"; return os; } }; // forward stall backup class fwd_stall_backup_t { public: coh_msg_t coh_msg; line_addr_t addr; fwd_stall_backup_t() : coh_msg(0), addr(0) {} inline fwd_stall_backup_t& operator = (const fwd_stall_backup_t& x) { coh_msg = x.coh_msg; addr = x.addr; return *this; } inline bool operator == (const fwd_stall_backup_t& x) const { return (x.coh_msg == coh_msg && x.addr == addr); } inline friend ostream & operator<<(ostream& os, const fwd_stall_backup_t& x) { os << hex << "(" << "coh_msg: " << x.coh_msg << ", addr: " << x.addr << ")"; return os; } }; // addr breakdown class addr_breakdown_t { public: addr_t line; line_addr_t line_addr; addr_t word; l2_tag_t tag; l2_set_t set; word_offset_t w_off; byte_offset_t b_off; addr_breakdown_t() : line(0), line_addr(0), word(0), tag(0), set(0), w_off(0), b_off(0) {} inline addr_breakdown_t& operator = (const addr_breakdown_t& x) { line = x.line; line_addr = x.line_addr; word = x.word; tag = x.tag; set = x.set; w_off = x.w_off; b_off = x.b_off; return *this; } inline bool operator == (const addr_breakdown_t& x) const { return (x.line == line && x.line_addr == line_addr && x.word == word && x.tag == tag && x.set == set && x.w_off == w_off && x.b_off == b_off); } inline friend ostream & operator<<(ostream& os, const addr_breakdown_t& x) { os << hex << "(" << "line: " << x.line << "line_addr: " << x.line_addr << ", word: " << x.word << ", tag: " << x.tag << ", set: " << x.set << ", w_off: " << x.w_off << ", b_off: " << x.b_off << ")"; return os; } void tag_incr(int a) { line += a * L2_TAG_OFFSET; line_addr += a * L2_SETS; word += a * L2_TAG_OFFSET; tag += a; } void set_incr(int a) { line += a * SET_OFFSET; line_addr += a; word += a * SET_OFFSET; set += a; } void tag_decr(int a) { line -= a * L2_TAG_OFFSET; line_addr -= a * L2_SETS; word -= a * L2_TAG_OFFSET; tag -= a; } void set_decr(int a) { line -= a * SET_OFFSET; line_addr -= a; word -= a * SET_OFFSET; set -= a; } void breakdown(addr_t addr) { line = addr; line_addr = addr.range(TAG_RANGE_HI, SET_RANGE_LO); word = addr; tag = addr.range(TAG_RANGE_HI, L2_TAG_RANGE_LO); set = addr.range(L2_SET_RANGE_HI, SET_RANGE_LO); w_off = addr.range(W_OFF_RANGE_HI, W_OFF_RANGE_LO); b_off = addr.range(B_OFF_RANGE_HI, B_OFF_RANGE_LO); line.range(OFF_RANGE_HI, OFF_RANGE_LO) = 0; word.range(B_OFF_RANGE_HI, B_OFF_RANGE_LO) = 0; } }; // addr breakdown class addr_breakdown_llc_t { public: addr_t line; line_addr_t line_addr; addr_t word; llc_tag_t tag; llc_set_t set; word_offset_t w_off; byte_offset_t b_off; addr_breakdown_llc_t() : line(0), line_addr(0), word(0), tag(0), set(0), w_off(0), b_off(0) {} inline addr_breakdown_llc_t& operator = (const addr_breakdown_llc_t& x) { line = x.line; line_addr = x.line_addr; word = x.word; tag = x.tag; set = x.set; w_off = x.w_off; b_off = x.b_off; return *this; } inline bool operator == (const addr_breakdown_llc_t& x) const { return (x.line == line && x.line_addr == line_addr && x.word == word && x.tag == tag && x.set == set && x.w_off == w_off && x.b_off == b_off); } inline friend ostream & operator<<(ostream& os, const addr_breakdown_llc_t& x) { os << hex << "(" << "line: " << x.line << "line_addr: " << x.line_addr << ", word: " << x.word << ", tag: " << x.tag << ", set: " << x.set << ", w_off: " << x.w_off << ", b_off: " << x.b_off << ")"; return os; } void tag_incr(int a) { line += a * LLC_TAG_OFFSET; line_addr += a * LLC_SETS; word += a * LLC_TAG_OFFSET; tag += a; } void set_incr(int a) { line += a * SET_OFFSET; line_addr += a; word += a * SET_OFFSET; set += a; } void tag_decr(int a) { line -= a * LLC_TAG_OFFSET; line_addr -= a * LLC_SETS; word -= a * LLC_TAG_OFFSET; tag -= a; } void set_decr(int a) { line -= a * SET_OFFSET; line_addr -= a; word -= a * SET_OFFSET; set -= a; } void breakdown(addr_t addr) { line = addr; line_addr = addr.range(TAG_RANGE_HI, SET_RANGE_LO); word = addr; tag = addr.range(TAG_RANGE_HI, LLC_TAG_RANGE_LO); set = addr.range(LLC_SET_RANGE_HI, SET_RANGE_LO); w_off = addr.range(W_OFF_RANGE_HI, W_OFF_RANGE_LO); b_off = addr.range(B_OFF_RANGE_HI, B_OFF_RANGE_LO); line.range(OFF_RANGE_HI, OFF_RANGE_LO) = 0; word.range(B_OFF_RANGE_HI, B_OFF_RANGE_LO) = 0; } }; // line breakdown template <class tag_t, class set_t> class line_breakdown_t { public: tag_t tag; set_t set; line_breakdown_t() : tag(0), set(0) {} inline line_breakdown_t& operator = (const line_breakdown_t& x) { tag = x.tag; set = x.set; return *this; } inline bool operator == (const line_breakdown_t& x) const { return (x.tag == tag && x.set == set); } inline friend ostream & operator<<(ostream& os, const line_breakdown_t& x) { os << hex << "(" << ", tag: " << x.tag << ", set: " << x.set << ")"; return os; } void tag_incr(int a) { tag += a; } void set_incr(int a) { set += a; } void tag_decr(int a) { tag -= a; } void set_decr(int a) { set -= a; } void l2_line_breakdown(line_addr_t addr) { tag = addr.range(ADDR_BITS - OFFSET_BITS - 1, L2_SET_BITS); set = addr.range(L2_SET_BITS - 1, 0); } void llc_line_breakdown(line_addr_t addr) { tag = addr.range(ADDR_BITS - OFFSET_BITS - 1, LLC_SET_BITS); set = addr.range(LLC_SET_BITS - 1, 0); } }; #endif // __CACHE_TYPES_HPP__