text
stringlengths
41
20k
/* * @ASCK */ #include <systemc.h> SC_MODULE (Memory) { sc_in <bool> r_nw; sc_in <sc_uint<13>> addr; sc_in <sc_int<8>> data; sc_out <sc_int<8>> out; /* ** module global variables */ sc_int<8> mem[8192] = {0}; // 2^13 rows bool done = false; SC_CTOR (Memory){ SC_METHOD (process); sensitive << r_nw << addr << data; } void process () { if(done){ return; } if(addr.read() < 8192){ if(r_nw.read()){ out.write(mem[addr.read()]); } else{ mem[addr.read()] = data.read(); out.write(mem[addr.read()]); } } else{ out.write(0); } } };
#include <systemc.h> SC_MODULE (counter) { sc_in_clk clock ; // Clock input of the design sc_in<bool> reset ; // active high, synchronous Reset input sc_in<bool> enable; // Active high enable signal for counter sc_out<sc_uint<4> > counter_out; // 4 bit vector output of the counter //Local Variables sc_uint<4> count; // Counter logic void incr_count () { // At every rising edge of clock we check if reset is active // If active, we load the counter output with 4'b0000 if (reset.read() == 1) { count = 0; counter_out.write(count); // If enable is active, then we increment the counter } else if (enable.read() == 1) { count = count + 1; counter_out.write(count); cout<<"@" << sc_time_stamp() <<" :: Incremented Counter " <<counter_out.read()<<endl; } } // End of function incr_count // Constructor for the counter // Since this counter is a positive edge trigged one, // We trigger the below block with respect to positive // edge of the clock and also when ever reset changes state SC_CTOR(counter) { cout<<"Executing new"<<endl; SC_METHOD(incr_count); sensitive << reset; sensitive << clock.pos(); } // End of Constructor }; // End of Module counter
/* * Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and * University of Bologna * * 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. */ /* * Authors: Germain Haugou, GreenWaves Technologies ([email protected]) */ #include <iostream> #include <sstream> #include <string> #include <stdio.h> #include <vp/vp.hpp> #include <stdio.h> #include "string.h" #include <iostream> #include <sstream> #include <string> #include <dlfcn.h> #include <algorithm> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <poll.h> #include <signal.h> #include <regex> #include <gv/gvsoc_proxy.hpp> #include <gv/gvsoc.h> #include <sys/types.h> #include <unistd.h> #include <sys/prctl.h> #include <vp/time/time_scheduler.hpp> #include <vp/proxy.hpp> #include <vp/queue.hpp> #include <vp/signal.hpp> extern "C" long long int dpi_time_ps(); #ifdef __VP_USE_SYSTEMC #include <systemc.h> #endif #ifdef __VP_USE_SYSTEMV extern "C" void dpi_raise_event(); #endif char vp_error[VP_ERROR_SIZE]; static Gv_proxy *proxy = NULL; void vp::component::get_trace(std::vector<vp::trace *> &traces, std::string path) { if (this->get_path() != "" && path.find(this->get_path()) != 0) { return; } for (vp::component *component: this->get_childs()) { component->get_trace(traces, path); } for (auto x: this->traces.traces) { if (x.second->get_full_path().find(path) == 0) { traces.push_back(x.second); } } for (auto x: this->traces.trace_events) { if (x.second->get_full_path().find(path) == 0) { traces.push_back(x.second); } } } void vp::component::reg_step_pre_start(std::function<void()> callback) { this->pre_start_callbacks.push_back(callback); } void vp::component::register_build_callback(std::function<void()> callback) { this->build_callbacks.push_back(callback); } void vp::component::post_post_build() { traces.post_post_build(); } void vp::component::final_bind() { for (auto port : this->slave_ports) { port.second->final_bind(); } for (auto port : this->master_ports) { port.second->final_bind(); } for (auto &x : this->childs) { x->final_bind(); } } void vp::component::set_vp_config(js::config *config) { this->vp_config = config; } void vp::component::set_gv_conf(struct gv_conf *gv_conf) { if (gv_conf) { memcpy(&this->gv_conf, gv_conf, sizeof(struct gv_conf)); } else { memset(&this->gv_conf, 0, sizeof(struct gv_conf)); gv_init(&this->gv_conf); } } js::config *vp::component::get_vp_config() { if (this->vp_config == NULL) { if (this->parent != NULL) { this->vp_config = this->parent->get_vp_config(); } } vp_assert_always(this->vp_config != NULL, NULL, "No VP config found\n"); return this->vp_config; } void vp::component::load_all() { for (auto &x : this->childs) { x->load_all(); } this->load(); } int vp::component::build_new() { this->bind_comps(); this->post_post_build_all(); this->pre_start_all(); this->start_all(); this->final_bind(); return 0; } void vp::component::post_post_build_all() { for (auto &x : this->childs) { x->post_post_build_all(); } this->post_post_build(); } void vp::component::start_all() { for (auto &x : this->childs) { x->start_all(); } this->start(); } void vp::component::stop_all() { for (auto &x : this->childs) { x->stop_all(); } this->stop(); } void vp::component::flush_all() { for (auto &x : this->childs) { x->flush_all(); } this->flush(); } void vp::component::pre_start_all() { for (auto &x : this->childs) { x->pre_start_all(); } this->pre_start(); for (auto x : pre_start_callbacks) { x(); } } void vp::component_clock::clk_reg(component *_this, component *clock) { _this->clock = (clock_engine *)clock; for (auto &x : _this->childs) { x->clk_reg(x, clock); } } void vp::component::reset_all(bool active, bool from_itf) { // Small hack to not propagate the reset from top level if the reset has // already been done through the interface from another component. // This should be all implemented with interfaces to better control // the reset propagation. this->reset_done_from_itf |= from_itf; if (from_itf || !this->reset_done_from_itf) { this->get_trace()->msg("Reset\n"); this->pre_reset(); for (auto reg : this->regs) { reg->reset(active); } this->block::reset_all(active); if (active) { for (clock_event *event: this->events) { this->event_cancel(event); } } for (auto &x : this->childs) { x->reset_all(active); } } } void vp::component_clock::reset_sync(void *__this, bool active) { component *_this = (component *)__this; _this->reset_done_from_itf = true; _this->reset_all(active, true); } void vp::component_clock::pre_build(component *comp) { clock_port.set_reg_meth((vp::clk_reg_meth_t *)&component_clock::clk_reg); comp->new_slave_port("clock", &clock_port); reset_port.set_sync_meth(&component_clock::reset_sync); comp->new_slave_port("reset", &reset_port); comp->traces.new_trace("comp", comp->get_trace(), vp::DEBUG); comp->traces.new_trace("warning", &comp->warning, vp::WARNING); } int64_t vp::time_engine::get_next_event_time() { if (this->first_client) { return this->first_client->next_event_time; } return this->time; } bool vp::time_engine::dequeue(time_engine_client *client) { if (!client->is_enqueued) return false; client->is_enqueued = false; time_engine_client *current = this->first_client, *prev = NULL; while (current && current != client) { prev = current; current = current->next; } if (prev) prev->next = client->next; else this->first_client = client->next; return true; } bool vp::time_engine::enqueue(time_engine_client *client, int64_t time) { vp_assert(time >= 0, NULL, "Time must be positive\n"); int64_t full_time = this->get_time() + time; #ifdef __VP_USE_SYSTEMC // Notify to the engine that something has been pushed in case it is done // by an external systemC component and the engine needs to be waken up if (started) sync_event.notify(); #endif #ifdef __VP_USE_SYSTEMV dpi_raise_event(); #endif if (client->is_running()) return false; if (client->is_enqueued) { if (client->next_event_time <= full_time) return false; this->dequeue(client); } client->is_enqueued = true; time_engine_client *current = first_client, *prev = NULL; client->next_event_time = full_time; while (current && current->next_event_time < client->next_event_time) { prev = current; current = current->next; } if (prev) prev->next = client; else first_client = client; client->next = current; return true; } bool vp::clock_engine::dequeue_from_engine() { if (this->is_running() || !this->is_enqueued) return false; this->engine->dequeue(this); return true; } void vp::clock_engine::reenqueue_to_engine() { this->engine->enqueue(this, this->next_event_time); } void vp::clock_engine::apply_frequency(int frequency) { if (frequency > 0) { bool reenqueue = this->dequeue_from_engine(); int64_t period = this->period; this->freq = frequency; this->period = 1e12 / this->freq; if (reenqueue && period > 0) { int64_t cycles = (this->next_event_time - this->get_time()) / period; this->next_event_time = cycles * this->period; this->reenqueue_to_engine(); } else if (period == 0) { // Case where the clock engine was clock-gated // We need to reenqueue the engine in case it has pending events if (this->has_events()) { // Compute the time of the next event based on the new frequency this->next_event_time = (this->get_next_event()->get_cycle() - this->get_cycles()) * this->period; this->reenqueue_to_engine(); } } } else if (frequency == 0) { this->dequeue_from_engine(); this->period = 0; } } void vp::clock_engine::update() { if (this->period == 0) return; int64_t diff = this->get_time() - this->stop_time; #ifdef __VP_USE_SYSTEMC if ((int64_t)sc_time_stamp().to_double() > this->get_time()) diff = (int64_t)sc_time_stamp().to_double() - this->stop_time; engine->update((int64_t)sc_time_stamp().to_double()); #endif if (diff > 0) { int64_t cycles = (diff + this->period - 1) / this->period; this->stop_time += cycles * this->period; this->cycles += cycles; } } vp::clock_event *vp::clock_engine::enqueue_other(vp::clock_event *event, int64_t cycle) { // Slow case where the engine is not running or we must enqueue out of the // circular buffer. // First check if we have to enqueue it to the global time engine in case we // were not running. // Check if we can enqueue to the fast circular queue in case were not // running. bool can_enqueue_to_cycle = false; if (!this->is_running()) { //this->current_cycle = (this->get_cycles() + 1) & CLOCK_EVENT_QUEUE_MASK; //can_enqueue_to_cycle = this->current_cycle + cycle - 1 < CLOCK_EVENT_QUEUE_SIZE; } if (can_enqueue_to_cycle) { //this->current_cycle = (this->get_cycles() + cycle) & CLOCK_EVENT_QUEUE_MASK; this->enqueue_to_cycle(event, cycle - 1); if (this->period != 0) enqueue_to_engine(period); } else { this->must_flush_delayed_queue = true; if (this->period != 0) { enqueue_to_engine(cycle * period); } vp::clock_event *current = delayed_queue, *prev = NULL; int64_t full_cycle = cycle + get_cycles(); while (current && current->cycle < full_cycle) { prev = current; current = current->next; } if (prev) prev->next = event; else delayed_queue = event; event->next = current; event->cycle = full_cycle; } return event; } vp::clock_event *vp::clock_engine::get_next_event() { // There is no quick way of getting the next event. // We have to first check if there is an event in the circular buffer // and if not in the delayed queue if (this->nb_enqueued_to_cycle) { for (int i = 0; i < CLOCK_EVENT_QUEUE_SIZE; i++) { int cycle = (current_cycle + i) & CLOCK_EVENT_QUEUE_MASK; vp::clock_event *event = event_queue[cycle]; if (event) { return event; } } vp_assert(false, 0, "Didn't find any event in circular buffer while it is not empty\n"); } return this->delayed_queue; } void vp::clock_engine::cancel(vp::clock_event *event) { if (!event->is_enqueued()) return; // There is no way to know if the event is enqueued into the circular buffer // or in the delayed queue so first go through the delayed queue and if it is // not found, look in the circular buffer // First the delayed queue vp::clock_event *current = delayed_queue, *prev = NULL; while (current) { if (current == event) { if (prev) prev->next = event->next; else delayed_queue = event->next; goto end; } prev = current; current = current->next; } // Then in the circular buffer for (int i = 0; i < CLOCK_EVENT_QUEUE_SIZE; i++) { vp::clock_event *current = event_queue[i], *prev = NULL; while (current) { if (current == event) { if (prev) prev->next = event->next; else event_queue[i] = event->next; this->nb_enqueued_to_cycle--; goto end; } prev = current; current = current->next; } } vp_assert(0, NULL, "Didn't find event in any queue while canceling event\n"); end: event->enqueued = false; if (!this->has_events()) this->dequeue_from_engine(); } void vp::clock_engine::flush_delayed_queue() { clock_event *event = delayed_queue; this->must_flush_delayed_queue = false; while (event) { if (nb_enqueued_to_cycle == 0) cycles = event->cycle; uint64_t cycle_diff = event->cycle - get_cycles(); if (cycle_diff >= CLOCK_EVENT_QUEUE_SIZE) break; clock_event *next = event->next; enqueue_to_cycle(event, cycle_diff); event = next; delayed_queue = event; } } int64_t vp::clock_engine::exec() { vp_assert(this->has_events(), NULL, "Executing clock engine while it has no event\n"); vp_assert(this->get_next_event(), NULL, "Executing clock engine while it has no next event\n"); this->cycles_trace.event_real(this->cycles); // The clock engine has a circular buffer of events to be executed. // Events longer than the buffer as put temporarly in a queue. // Everytime we start again at the beginning of the buffer, we need // to check if events must be enqueued from the queue to the buffer // in case they fit the window. if (unlikely(this->must_flush_delayed_queue)) { this->flush_delayed_queue(); } vp_assert(this->get_next_event(), NULL, "Executing clock engine while it has no next event\n"); // Now take all events available at the current cycle and execute them all without returning // to the main engine to execute them faster. clock_event *current = event_queue[current_cycle]; while (likely(current != NULL)) { event_queue[current_cycle] = current->next; current->enqueued = false; nb_enqueued_to_cycle--; current->meth(current->_this, current); current = event_queue[current_cycle]; } // Now we need to tell the time engine when is the next event. // The most likely is that there is an event in the circular buffer, // in which case we just return the clock period, as we will go through // each element of the circular buffer, even if the next event is further in // the buffer. if (likely(nb_enqueued_to_cycle)) { cycles++; current_cycle = (current_cycle + 1) & CLOCK_EVENT_QUEUE_MASK; if (unlikely(current_cycle == 0)) this->must_flush_delayed_queue = true; return period; } else { // Otherwise if there is an event in the delayed queue, return the time // to this event. // In both cases, force the delayed queue flush so that the next event to be // executed is moved to the circular buffer. this->must_flush_delayed_queue = true; // Also remember the current time in order to resynchronize the clock engine // in case we enqueue and event from another engine. this->stop_time = this->get_time(); if (delayed_queue) { return (delayed_queue->cycle - get_cycles()) * period; } else { // In case there is no more event to execute, returns -1 to tell the time // engine we are done. return -1; } } } vp::clock_event::clock_event(component_clock *comp, clock_event_meth_t *meth) : comp(comp), _this((void *)static_cast<vp::component *>((vp::component_clock *)(comp))), meth(meth), enqueued(false) { comp->add_clock_event(this); } void vp::component_clock::add_clock_event(clock_event *event) { this->events.push_back(event); } vp::time_engine *vp::component::get_time_engine() { if (this->time_engine_ptr == NULL) { this->time_engine_ptr = (vp::time_engine*)this->get_service("time"); } return this->time_engine_ptr; } vp::master_port::master_port(vp::component *owner) : vp::port(owner) { } void vp::component::new_master_port(std::string name, vp::master_port *port) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New master port (name: %s, port: %p)\n", name.c_str(), port); port->set_owner(this); port->set_context(this); port->set_name(name); this->add_master_port(name, port); } void vp::component::new_master_port(void *comp, std::string name, vp::master_port *port) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New master port (name: %s, port: %p)\n", name.c_str(), port); port->set_owner(this); port->set_context(comp); port->set_name(name); this->add_master_port(name, port); } void vp::component::add_slave_port(std::string name, vp::slave_port *port) { vp_assert_always(port != NULL, this->get_trace(), "Adding NULL port\n"); //vp_assert_always(this->slave_ports[name] == NULL, this->get_trace(), "Adding already existing port\n"); this->slave_ports[name] = port; } void vp::component::add_master_port(std::string name, vp::master_port *port) { vp_assert_always(port != NULL, this->get_trace(), "Adding NULL port\n"); //vp_assert_always(this->master_ports[name] == NULL, this->get_trace(), "Adding already existing port\n"); this->master_ports[name] = port; } void vp::component::new_slave_port(std::string name, vp::slave_port *port) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New slave port (name: %s, port: %p)\n", name.c_str(), port); port->set_owner(this); port->set_context(this); port->set_name(name); this->add_slave_port(name, port); } void vp::component::new_slave_port(void *comp, std::string name, vp::slave_port *port) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New slave port (name: %s, port: %p)\n", name.c_str(), port); port->set_owner(this); port->set_context(comp); port->set_name(name); this->add_slave_port(name, port); } void vp::component::add_service(std::string name, void *service) { if (this->parent) this->parent->add_service(name, service); else if (all_services[name] == NULL) all_services[name] = service; } void vp::component::new_service(std::string name, void *service) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New service (name: %s, service: %p)\n", name.c_str(), service); if (this->parent) this->parent->add_service(name, service); all_services[name] = service; } void *vp::component::get_service(string name) { if (all_services[name]) return all_services[name]; if (this->parent) return this->parent->get_service(name); return NULL; } std::vector<std::string> split_name(const std:
:string &s, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } vp::config *vp::config::create_config(jsmntok_t *tokens, int *_size) { jsmntok_t *current = tokens; config *config = NULL; switch (current->type) { case JSMN_PRIMITIVE: if (strcmp(current->str, "True") == 0 || strcmp(current->str, "False") == 0 || strcmp(current->str, "true") == 0 || strcmp(current->str, "false") == 0) { config = new config_bool(current); } else { config = new config_number(current); } current++; break; case JSMN_OBJECT: { int size; config = new config_object(current, &size); current += size; break; } case JSMN_ARRAY: { int size; config = new config_array(current, &size); current += size; break; } case JSMN_STRING: config = new config_string(current); current++; break; case JSMN_UNDEFINED: break; } if (_size) { *_size = current - tokens; } return config; } vp::config *vp::config_string::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; return NULL; } vp::config *vp::config_number::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; return NULL; } vp::config *vp::config_bool::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; return NULL; } vp::config *vp::config_array::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; return NULL; } vp::config *vp::config_object::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; vp::config *result = NULL; std::string name; int name_pos = 0; for (auto &x : name_list) { if (x != "*" && x != "**") { name = x; break; } name_pos++; } for (auto &x : childs) { if (name == x.first) { result = x.second->get_from_list(std::vector<std::string>(name_list.begin() + name_pos + 1, name_list.begin() + name_list.size())); if (name_pos == 0 || result != NULL) return result; } else if (name_list[0] == "*") { result = x.second->get_from_list(std::vector<std::string>(name_list.begin() + 1, name_list.begin() + name_list.size())); if (result != NULL) return result; } else if (name_list[0] == "**") { result = x.second->get_from_list(name_list); if (result != NULL) return result; } } return result; } vp::config *vp::config_object::get(std::string name) { return get_from_list(split_name(name, '/')); } vp::config_string::config_string(jsmntok_t *tokens) { value = tokens->str; } vp::config_number::config_number(jsmntok_t *tokens) { value = atof(tokens->str); } vp::config_bool::config_bool(jsmntok_t *tokens) { value = strcmp(tokens->str, "True") == 0 || strcmp(tokens->str, "true") == 0; } vp::config_array::config_array(jsmntok_t *tokens, int *_size) { jsmntok_t *current = tokens; jsmntok_t *top = current++; for (int i = 0; i < top->size; i++) { int child_size; elems.push_back(create_config(current, &child_size)); current += child_size; } if (_size) { *_size = current - tokens; } } vp::config_object::config_object(jsmntok_t *tokens, int *_size) { jsmntok_t *current = tokens; jsmntok_t *t = current++; for (int i = 0; i < t->size; i++) { jsmntok_t *child_name = current++; int child_size; config *child_config = create_config(current, &child_size); current += child_size; if (child_config != NULL) { childs[child_name->str] = child_config; } } if (_size) { *_size = current - tokens; } } vp::config *vp::component::import_config(const char *config_string) { if (config_string == NULL) return NULL; jsmn_parser parser; jsmn_init(&parser); int nb_tokens = jsmn_parse(&parser, config_string, strlen(config_string), NULL, 0); jsmntok_t tokens[nb_tokens]; jsmn_init(&parser); nb_tokens = jsmn_parse(&parser, config_string, strlen(config_string), tokens, nb_tokens); char *str = strdup(config_string); for (int i = 0; i < nb_tokens; i++) { jsmntok_t *tok = &tokens[i]; tok->str = &str[tok->start]; str[tok->end] = 0; } return new vp::config_object(tokens); } void vp::component::conf(string name, string path, vp::component *parent) { this->name = name; this->parent = parent; this->path = path; if (parent != NULL) { parent->add_child(name, this); } } void vp::component::add_child(std::string name, vp::component *child) { this->childs.push_back(child); this->childs_dict[name] = child; } vp::component *vp::component::get_component(std::vector<std::string> path_list) { if (path_list.size() == 0) { return this; } std::string name = ""; unsigned int name_pos= 0; for (auto x: path_list) { if (x != "*" && x != "**") { name = x; break; } name_pos += 1; } for (auto x:this->childs) { vp::component *comp; if (name == x->get_name()) { comp = x->get_component({ path_list.begin() + name_pos + 1, path_list.end() }); } else if (path_list[0] == "**") { comp = x->get_component(path_list); } else if (path_list[0] == "*") { comp = x->get_component({ path_list.begin() + 1, path_list.end() }); } if (comp) { return comp; } } return NULL; } void vp::component::elab() { for (auto &x : this->childs) { x->elab(); } } void vp::component::new_reg_any(std::string name, vp::reg *reg, int bits, uint8_t *reset_val) { reg->init(this, name, bits, NULL, reset_val); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_1 *reg, uint8_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 1, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_8 *reg, uint8_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 8, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_16 *reg, uint16_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 16, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_32 *reg, uint32_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 32, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_64 *reg, uint64_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 64, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } bool vp::reg::access_callback(uint64_t reg_offset, int size, uint8_t *value, bool is_write) { if (this->callback != NULL) this->callback(reg_offset, size, value, is_write); return this->callback != NULL; } void vp::reg::init(vp::component *top, std::string name, int bits, uint8_t *value, uint8_t *reset_value) { this->top = top; this->nb_bytes = (bits + 7) / 8; this->bits = bits; if (reset_value) this->reset_value_bytes = new uint8_t[this->nb_bytes]; else this->reset_value_bytes = NULL; if (value) this->value_bytes = value; else this->value_bytes = new uint8_t[this->nb_bytes]; this->name = name; if (reset_value) memcpy((void *)this->reset_value_bytes, (void *)reset_value, this->nb_bytes); top->traces.new_trace(name + "/trace", &this->trace, vp::TRACE); top->traces.new_trace_event(name, &this->reg_event, bits); } void vp::reg::reset(bool active) { if (active) { this->trace.msg("Resetting register\n"); if (this->reset_value_bytes) { memcpy((void *)this->value_bytes, (void *)this->reset_value_bytes, this->nb_bytes); } else { memset((void *)this->value_bytes, 0, this->nb_bytes); } if (this->reg_event.get_event_active()) { this->reg_event.event((uint8_t *)this->value_bytes); } } } void vp::reg_1::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 1, (uint8_t *)&this->value, reset_val); } void vp::reg_8::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 8, (uint8_t *)&this->value, reset_val); } void vp::reg_16::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 16, (uint8_t *)&this->value, reset_val); } void vp::reg_32::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 32, (uint8_t *)&this->value, reset_val); } void vp::reg_64::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 64, (uint8_t *)&this->value, reset_val); } void vp::reg_1::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::reg_8::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::reg_16::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::reg_32::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::reg_32::write(int reg_offset, int size, uint8_t *value) { uint8_t *dest = this->value_bytes+reg_offset; uint8_t *src = value; uint8_t *mask = ((uint8_t *)&this->write_mask) + reg_offset; for (int i=0; i<size; i++) { dest[i] = (dest[i] & ~mask[i]) | (src[i] & mask[i]); } this->dump_after_write(); if (this->reg_event.get_event_active()) { this->reg_event.event((uint8_t *)this->value_bytes); } } void vp::reg_64::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::master_port::final_bind() { if (this->is_bound) { this->finalize(); } } void vp::slave_port::final_bind() { if (this->is_bound) this->finalize(); } extern "C" char *vp_get_error() { return vp_error; } extern "C" void vp_port_bind_to(void *_master, void *_slave, const char *config_str) { vp::master_port *master = (vp::master_port *)_master; vp::slave_port *slave = (vp::slave_port *)_slave; vp::config *config = NULL; if (config_str != NULL) { config = master->get_comp()->import_config(config_str); } master->bind_to(slave, config); slave->bind_to(master, config); } void vp::component::throw_error(std::string error) { throw std::invalid_argument("[\033[31m" + this->get_path() + "\033[0m] " + error); } void vp::component::build_instance(std::string name, vp::component *parent) { std::string comp_path = parent->get_path() != "" ? parent->get_path() + "/" + name : name == "" ? "" : "/" + name; this->conf(name, comp_path, parent); this->pre_pre_build(); this->pre_build(); this->build(); this->power.build(); for (auto x : build_callbacks) { x(); } } vp::component *vp::component::new_component(std::string name, js::config *config, std::string module_name) { if (module_name == "") { module_name = config->get_child_str("vp_component"); if (module_name == "") { module_name = "utils.composite_impl"; } } if (this->get_vp_config()->get_child_bool("sv-mode")) { module_name = "sv." + module_name; } else if (this->get_vp_config()->get_child_bool("debug-mode")) { module_name = "debug." + module_name; } this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New component (name: %s, module: %s)\n", name.c_str(), module_name.c_str()); std::replace(module_name.begin(), module_name.end(), '.', '/'); std::string path = std::string(getenv("GVSOC_PATH")) + "/" + module_name + ".so"; void *module = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL | RTLD_DEEPBIND); if (module == NULL) { this->throw_error("ERROR, Failed to open periph model (module: " + module_name + ", error: " + std::string(dlerror()) + ")"); } vp::component *(*constructor)(js::config *) = (vp::component * (*)(js::config *)) dlsym(module, "vp_constructor"); if (constructor == NULL) { this->throw_error("ERROR, couldn't find vp_constructor in loaded module (module: " + module_name + ")"); } vp::component *instance = constructor(config); instance->build_instance(name, this); return instance; } vp::component::component(js::config *config) : block(NULL), traces(*this), power(*this), reset_done_from_itf(false) { this->comp_js_config = config; //this->conf(path, parent); } void vp::component::create_ports() { js::config *config = this->get_js_config(); js::config *ports = config->get("vp_ports"); if (ports == NULL) { ports = config->get("ports"); } if (ports != NULL) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating ports\n"); for (auto x : ports->get_elems()) { std::string port_name = x->get_str(); this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating port (name: %s)\n", port_name.c_str()); if (this->get_master_port(port_name) == NULL && this->get_slave_port(port_name) == NULL) this->add_master_port(port_name, new vp::virtual_port(this)); } } } void vp::component::create_bindings() { js::config *config = this->get_js_config(); js::config *bindings = config->get("vp_bindings"); if (bindings == NULL) { bindings = config->get("bindings"); } if (bindings != NULL) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating bindings\n"); for (auto x : bindings->get_elems()) { std::string master_binding = x->get_elem(0)->get_str(); std::string slave_binding = x->get_elem(1)->get_str(); int pos = master_binding.find_first_of("->"); std::string master_comp_name = master_binding.substr(0, pos); std::string master_port_name = master_binding.substr(pos + 2); pos = slave_binding.find_first_of("->"); std::string slave_comp_name = slave_binding.substr(0, pos); std::string slave_port_name = slave_binding.substr(pos + 2); this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating binding (%s:%s -> %s:%s)\n", master_comp_name.c_str(), master_port_name.c_str(), slave_comp_name.c_str(), slave_port_name.c_str() ); vp::component *master_comp = master_comp_name == "self" ? this : this->get_childs_dict()[master_comp_name]; vp::component *slave_comp = slave_comp_name == "self" ? this : this->get_childs_dict()[slave_comp_name]; vp_assert_always(master_comp != NULL, this->get_trace(), "Binding from invalid master\n"); vp_assert_always(slave_comp != NULL, this->get_trace(), "Binding from invalid slave\n"); vp::port *master_port = master_comp->get_master_port(master_port_name); vp::port *slave_port = slave_comp->get_slave_port(slave_port_name); vp_assert_always(master_port != NULL, this->get_trace(), "Binding from invalid master port\n"); vp_assert_always(slave_port != NULL, this->get_trace(), "Binding from invalid slave port\n"); master_port->bind_to_virtual(slave_port); } } } std::vector<vp::slave_port *> vp::slave_port::get_final_ports() { return { this }; } std::vector<vp::slave_port *> vp::master_port::get_final_ports() { std::vector<vp::slave_port *> result; for (auto x : this->slave_ports) { std::vector<vp::slave_port *> slave_ports = x->get_final_ports(); result.insert(result.end(), slave_ports.begin(), slave_ports.end()); } return result; } void vp::master_port::bind_to_slaves() { for (auto x : this->slave_ports) { for (auto y : x->get_final_ports()) { this->get_owner()->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating final binding (%s:%s -> %s:%s)\n", this->get_owner()->get_path().c_str(), this->get_name().c_str(), y->get_owner()->get_path().c_str(), y->get_name().c_str() ); this->bind_to(y, NULL); y->bind_to(this, NULL); } } } void vp::component::bind_comps() { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating final bindings\n"); for (auto x : this->get_childs()) { x->bind_comps(); } for (auto x : this->master_ports) { if (!x.second->is_virtual()) { x.second->bind_to_slaves(); } } } void *vp::component::external_bind(std::string comp_name, std::string itf_name, void *handle) { for (auto &x : this->childs) { void *result = x->external_bind(comp_name, itf_name, handle); if (result != NULL) return result; } return NULL; } void vp::master_port::bind_to_virtual(vp::port *port) { vp_assert_always(port != NULL, this->get_comp()->get_trace(), "Trying to bind master port to NULL\n"); this->slave_ports.push_back(port); } void vp::component::create_comps() { js::config *config = this->get_js_config(); js::config *comps = config->get("vp_comps"); if (comps == NULL) { comps = config->get("components"); } if (comps != NULL) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating components\n"); for (auto x : comps->get_elems()) { std::string comp_name = x->get_str(); js::config *comp_config = config->get(comp_name); std::string vp_component = comp_config->get_child_str("vp_component"); if (vp_component == "") vp_component = "utils.composite_impl"; this->new_component(comp_name, comp_config, vp_component); } } } void vp::component::dump_traces_recursive(FILE *file) { this->dump_traces(file); for
(auto& x: this->get_childs()) { x->dump_traces_recursive(file); } } vp::component *vp::__gv_create(std::string config_path, struct gv_conf *gv_conf) { setenv("PULP_CONFIG_FILE", config_path.c_str(), 1); js::config *js_config = js::import_config_from_file(config_path); if (js_config == NULL) { fprintf(stderr, "Invalid configuration."); return NULL; } js::config *gv_config = js_config->get("**/gvsoc"); std::string module_name = "vp.trace_domain_impl"; if (gv_config->get_child_bool("sv-mode")) { module_name = "sv." + module_name; } else if (gv_config->get_child_bool("debug-mode")) { module_name = "debug." + module_name; } std::replace(module_name.begin(), module_name.end(), '.', '/'); std::string path = std::string(getenv("GVSOC_PATH")) + "/" + module_name + ".so"; void *module = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL | RTLD_DEEPBIND); if (module == NULL) { throw std::invalid_argument("ERROR, Failed to open periph model (module: " + module_name + ", error: " + std::string(dlerror()) + ")"); } vp::component *(*constructor)(js::config *) = (vp::component * (*)(js::config *)) dlsym(module, "vp_constructor"); if (constructor == NULL) { throw std::invalid_argument("ERROR, couldn't find vp_constructor in loaded module (module: " + module_name + ")"); } vp::component *instance = constructor(js_config); vp::top *top = new vp::top(); top->top_instance = instance; top->power_engine = new vp::power::engine(instance); instance->set_vp_config(gv_config); instance->set_gv_conf(gv_conf); return (vp::component *)top; } extern "C" void *gv_create(const char *config_path, struct gv_conf *gv_conf) { return (void *)vp::__gv_create(config_path, gv_conf); } extern "C" void gv_destroy(void *arg) { } extern "C" void gv_start(void *arg) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; instance->pre_pre_build(); instance->pre_build(); instance->build(); instance->build_new(); if (instance->gv_conf.open_proxy || instance->get_vp_config()->get_child_bool("proxy/enabled")) { int in_port = instance->gv_conf.open_proxy ? 0 : instance->get_vp_config()->get_child_int("proxy/port"); int out_port; proxy = new Gv_proxy(instance, instance->gv_conf.req_pipe, instance->gv_conf.reply_pipe); if (proxy->open(in_port, &out_port)) { instance->throw_error("Failed to start proxy"); } if (instance->gv_conf.proxy_socket) { *instance->gv_conf.proxy_socket = out_port; } } } extern "C" void gv_reset(void *arg, bool active) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; instance->reset_all(active); } extern "C" void gv_step(void *arg, int64_t timestamp) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; instance->step(timestamp); } extern "C" int64_t gv_time(void *arg) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; return instance->get_time_engine()->get_next_event_time(); } extern "C" void *gv_open(const char *config_path, bool open_proxy, int *proxy_socket, int req_pipe, int reply_pipe) { struct gv_conf gv_conf; gv_conf.open_proxy = open_proxy; gv_conf.proxy_socket = proxy_socket; gv_conf.req_pipe = req_pipe; gv_conf.reply_pipe = reply_pipe; void *instance = gv_create(config_path, &gv_conf); if (instance == NULL) return NULL; gv_start(instance); return instance; } Gvsoc_proxy::Gvsoc_proxy(std::string config_path) : config_path(config_path) { } void Gvsoc_proxy::proxy_loop() { FILE *sock = fdopen(this->reply_pipe[0], "r"); while(1) { char line[1024]; if (!fgets(line, 1024, sock)) return ; std::string s = std::string(line); std::regex regex{R"([\s]+)"}; std::sregex_token_iterator it{s.begin(), s.end(), regex, -1}; std::vector<std::string> words{it, {}}; if (words.size() > 0) { if (words[0] == "stopped") { int64_t timestamp = std::atoll(words[1].c_str()); printf("GOT STOP AT %ld\n", timestamp); this->mutex.lock(); this->stopped_timestamp = timestamp; this->running = false; this->cond.notify_all(); this->mutex.unlock(); } else if (words[0] == "running") { int64_t timestamp = std::atoll(words[1].c_str()); printf("GOT RUN AT %ld\n", timestamp); this->mutex.lock(); this->running = true; this->cond.notify_all(); this->mutex.unlock(); } else if (words[0] == "req=") { } else { printf("Ignoring invalid command: %s\n", words[0].c_str()); } } } } int Gvsoc_proxy::open() { pid_t ppid_before_fork = getpid(); if (pipe(this->req_pipe) == -1) return -1; if (pipe(this->reply_pipe) == -1) return -1; pid_t child_id = fork(); if(child_id == -1) { return -1; } else if (child_id == 0) { int r = prctl(PR_SET_PDEATHSIG, SIGTERM); if (r == -1) { perror(0); exit(1); } // test in case the original parent exited just // before the prctl() call if (getppid() != ppid_before_fork) exit(1); void *instance = gv_open(this->config_path.c_str(), true, NULL, this->req_pipe[0], this->reply_pipe[1]); int retval = gv_run(instance); gv_stop(instance, retval); return retval; } else { this->running = false; this->loop_thread = new std::thread(&Gvsoc_proxy::proxy_loop, this); } return 0; } void Gvsoc_proxy::run() { dprintf(this->req_pipe[1], "cmd=run\n"); } int64_t Gvsoc_proxy::pause() { int64_t result; dprintf(this->req_pipe[1], "cmd=stop\n"); std::unique_lock<std::mutex> lock(this->mutex); while (this->running) { this->cond.wait(lock); } result = this->stopped_timestamp; lock.unlock(); return result; } void Gvsoc_proxy::close() { dprintf(this->req_pipe[1], "cmd=quit\n"); } void Gvsoc_proxy::add_event_regex(std::string regex) { dprintf(this->req_pipe[1], "cmd=event add %s\n", regex.c_str()); } void Gvsoc_proxy::remove_event_regex(std::string regex) { dprintf(this->req_pipe[1], "cmd=event remove %s\n", regex.c_str()); } void Gvsoc_proxy::add_trace_regex(std::string regex) { dprintf(this->req_pipe[1], "cmd=trace add %s\n", regex.c_str()); } void Gvsoc_proxy::remove_trace_regex(std::string regex) { dprintf(this->req_pipe[1], "cmd=trace remove %s\n", regex.c_str()); } vp::time_scheduler::time_scheduler(js::config *config) : time_engine_client(config), first_event(NULL) { } int64_t vp::time_scheduler::exec() { vp::time_event *current = this->first_event; while (current && current->time == this->get_time()) { this->first_event = current->next; current->meth(current->_this, current); current = this->first_event; } if (this->first_event == NULL) { return -1; } else { return this->first_event->time - this->get_time(); } } vp::time_event::time_event(time_scheduler *comp, time_event_meth_t *meth) : comp(comp), _this((void *)static_cast<vp::component *>((vp::time_scheduler *)(comp))), meth(meth), enqueued(false) { } vp::time_event *vp::time_scheduler::enqueue(time_event *event, int64_t time) { vp::time_event *current = this->first_event, *prev = NULL; int64_t full_time = time + this->get_time(); while (current && current->time < full_time) { prev = current; current = current->next; } if (prev) prev->next = event; else this->first_event = event; event->next = current; event->time = full_time; this->enqueue_to_engine(time); return event; } extern "C" int gv_run(void *arg) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; if (!proxy) { instance->run(); } return instance->join(); } extern "C" void gv_init(struct gv_conf *gv_conf) { gv_conf->open_proxy = 0; if (gv_conf->proxy_socket) { *gv_conf->proxy_socket = -1; } gv_conf->req_pipe = 0; gv_conf->reply_pipe = 0; } extern "C" void gv_stop(void *arg, int retval) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; if (proxy) { proxy->stop(retval); } instance->stop_all(); delete top->power_engine; } #ifdef __VP_USE_SYSTEMC static void *(*sc_entry)(void *); static void *sc_entry_arg; void set_sc_main_entry(void *(*entry)(void *), void *arg) { sc_entry = entry; sc_entry_arg = arg; } int sc_main(int argc, char *argv[]) { sc_entry(sc_entry_arg); return 0; } #endif void vp::fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (vfprintf(stderr, fmt, ap) < 0) {} va_end(ap); abort(); } extern "C" void *gv_chip_pad_bind(void *handle, char *name, int ext_handle) { vp::top *top = (vp::top *)handle; vp::component *instance = (vp::component *)top->top_instance; return instance->external_bind(name, "", (void *)(long)ext_handle); }
/* * @ASCK */ #include <systemc.h> SC_MODULE (IF) { sc_in_clk clk; sc_in <sc_uint<20>> prev_data; sc_out <sc_uint<20>> next_data; /* ** module global variables */ SC_CTOR (IF){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ cout<<"\t\t\t\t*******************" << endl; wait(micro_acc_ev); } next_data.write(prev_data.read()); } } };
/* * @ASCK */ #include <systemc.h> SC_MODULE (Memory) { sc_in <bool> r_nw; sc_in <sc_uint<13>> addr; sc_in <sc_int<8>> data; sc_out <sc_int<8>> out; /* ** module global variables */ sc_int<8> mem[8192] = {0}; // 2^13 rows bool done = false; SC_CTOR (Memory){ SC_METHOD (process); sensitive << r_nw << addr << data; } void process () { if(done){ return; } if(addr.read() < 8192){ if(r_nw.read()){ out.write(mem[addr.read()]); } else{ mem[addr.read()] = data.read(); out.write(mem[addr.read()]); } } else{ out.write(0); } } };
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you 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. *****************************************************************************/ /***************************************************************************** numgen.cpp -- The implementation for the numgen module. Original Author: Amit Rao, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "numgen.h" // definition of the `generate' method void numgen::generate() { static double a = 134.56; static double b = 98.24; a -= 1.5; b -= 2.8; out1.write(a); out2.write(b); } // end of `generate' method
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // 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 PACKET_H #define PACKET_H #include <vector> using std::vector; #include <systemc.h> #include <tlm.h> using namespace sc_core; class packet { public: short cmd; int addr; vector<char> data; }; //------------------------------------------------------------------------------ // Begin UVMC-specific code #include "uvmc.h" using namespace uvmc; UVMC_UTILS_3 (packet,cmd,addr,data) #endif // PACKET_H
#ifndef PACKET_GENERATOR_TLM_CPP #define PACKET_GENERATOR_TLM_CPP #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 "packetGenerator_tlm.hpp" #include "common_func.hpp" #include "address_map.hpp" void packetGenerator_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ dbgimgtarmodprint(use_prints, "Calling do_when_read_transaction"); if ((address >= IMG_OUTPUT_STATUS_ADDRESS_LO) && (address < IMG_OUTPUT_STATUS_ADDRESS_HI)) { if (packetGenerator::tmp_data_out_valid == true) { *data = 1; } else { *data = 0; } } } void packetGenerator_tlm::do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { dbgimgtarmodprint(use_prints, "Calling do_when_write_transaction"); if ((address >= IMG_OUTPUT_ADDRESS_LO) && (address < IMG_OUTPUT_SIZE_ADDRESS_LO)) { memcpy(tmp_data + address - IMG_OUTPUT_ADDRESS_LO, data, data_length); } else if ((address >= IMG_OUTPUT_SIZE_ADDRESS_LO) && (address < IMG_OUTPUT_DONE_ADDRESS_LO)) { unsigned char *data_length_ptr = (unsigned char *)&tmp_data_length; memcpy(data_length_ptr + address - IMG_OUTPUT_SIZE_ADDRESS_LO, data, data_length); dbgimgtarmodprint(use_prints, "Current data_length %0d", tmp_data_length); } else if ((address >= IMG_OUTPUT_DONE_ADDRESS_LO) && (address < IMG_OUTPUT_STATUS_ADDRESS_LO) && (*data == 1)) { if (tmp_data_length == 0) { *(tmp_data) = 0; tmp_data_length = 1; } dbgimgtarmodprint(use_prints, "Preparing to send %0d bytes", tmp_data_length); fill_data(tmp_data, (int)tmp_data_length); tmp_data_length = 0; } } #endif // PACKET_GENERATOR_TLM_CPP
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program 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. * * * * 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 General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <math.h> #define cD_03_ANN_INPUTS 2 // Number of inputs #define cD_03_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // Physical constants //----------------------------------------------------------------------------- static double cD_03_I_0 = 77.3 ; // [A] Nominal current static double cD_03_T_0 = 298.15 ; // [K] Ambient temperature static double cD_03_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State) static double cD_03_V_0 = 47.2 ; // [V] Nominal voltage static double cD_03_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State static double cD_03_ThermalConstant = 0.75 ; static double cD_03_Tau = 0.02 ; // [s] Sampling period //----------------------------------------------------------------------------- // Status descriptors //----------------------------------------------------------------------------- typedef struct cD_03_DEVICE // Descriptor of the state of the device { double t ; // Operating temperature double r ; // Operating Drain-Source resistance in the On State double i ; // Operating current double v ; // Operating voltage double time_Ex ; int fault ; } cD_03_DEVICE ; static cD_03_DEVICE cD_03_device; //----------------------------------------------------------------------------- // Mnemonics to access the array that contains the sampled data //----------------------------------------------------------------------------- #define cD_03_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements #define cD_03_I_INDEX 0 // Current #define cD_03_V_INDEX 1 // Voltage #define cD_03_TIME_INDEX 2 // Time ///----------------------------------------------------------------------------- // Forward references //----------------------------------------------------------------------------- static int cD_03_initDescriptors(cD_03_DEVICE device) ; //static void getSample(int index, double sample[SAMPLE_LEN]) ; static void cD_03_cleanData(int index, double sample[cD_03_SAMPLE_LEN]) ; static double cD_03_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ; static void cD_03_normalize(int index, double x[cD_03_ANN_INPUTS]) ; static double cD_03_degradationModel(double tNow) ; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int cD_03_initDescriptors(cD_03_DEVICE device) {HEPSY_S(cleanData_03_id) // for (int i = 0; i < NUM_DEV; i++) // { HEPSY_S(cleanData_03_id) device.t = cD_03_T_0 ; // Operating temperature = Ambient temperature HEPSY_S(cleanData_03_id) device.r = cD_03_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // printf("Init %d \n",i); // } HEPSY_S(cleanData_03_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_03_cleanData(int index, double sample[cD_03_SAMPLE_LEN]) {HEPSY_S(cleanData_03_id) // the parameter "index" could be useful to retrieve the characteristics of the device HEPSY_S(cleanData_03_id) if ( sample[cD_03_I_INDEX] < 0 ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = 0 ; HEPSY_S(cleanData_03_id)} else if ( sample[cD_03_I_INDEX] > (2.0 * cD_03_I_0) ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = (2.0 * cD_03_I_0) ; // Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0) HEPSY_S(cleanData_03_id)} HEPSY_S(cleanData_03_id) if ( sample[cD_03_V_INDEX] < 0 ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = 0 ; HEPSY_S(cleanData_03_id)} else if ( sample[cD_03_V_INDEX] > (2.0 * cD_03_V_0 ) ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = (2.0 * cD_03_V_0) ; // Postcondition: (0 <= sample[V_INDEX] <= 2.0*V_0) HEPSY_S(cleanData_03_id)} } //----------------------------------------------------------------------------- // Input: // - tPrev = temperature at previous step // - iPrev = current at previous step // - iNow = current at this step // - rPrev = resistance at the previous step // Return: // - The new temperature // Very simple model: // - one constant for dissipation and heat capacity // - temperature considered constant during the step //----------------------------------------------------------------------------- double cD_03_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double t ; // Temperature HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double i = 0.5*(iPrev + iNow); // Average current // printf("cD_03_extractFeatures tPrev=%f\n",tPrev); HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) t = tPrev + // Previous temperature rPrev * (i * i) * cD_03_Tau - // Heat generated: P = I·R^2 cD_03_ThermalConstant * (tPrev - cD_03_T_0) * cD_03_Tau ; // Dissipation and heat capacity HEPSY_S(cleanData_03_id) return( t ); } //----------------------------------------------------------------------------- // Input: // - tNow: temperature at this step // Return: // - the resistance // The model isn't realistic because the even the simpler law is exponential //----------------------------------------------------------------------------- double cD_03_degradationModel(double tNow) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double r ; //r = R_0 + Alpha * tNow ; HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) r = cD_03_R_0 * ( 2 - exp(-cD_03_Alpha*tNow) ); HEPSY_S(cleanData_03_id) return( r ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_03_normalize(int index, double sample[cD_03_ANN_INPUTS]) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double i ; double v ; // Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) i = sample[cD_03_I_INDEX] <= cD_03_I_0 ? 0.0 : 1.0; HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) v = sample[cD_03_V_INDEX] <= cD_03_V_0 ? 0.0 : 1.0; HEPSY_S(cleanData_03_id) // Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0}) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = i ; HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = v ; } void mainsystem::cleanData_03_main() { // datatype for channels sampleTimCord_cleanData_xx_payload sampleTimCord_cleanData_xx_payload_var; cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; //device var uint8_t dev; //step var uint16_t step; // ex_time (for extractFeatures...) double ex_time; //samples i and v double sample_i; double sample_v; //var for samples, to re-use cleanData() double cD_03_sample[cD_03_SAMPLE_LEN] ; double x[cD_03_ANN_INPUTS + cD_03_ANN_OUTPUTS] ; // NOTE: commented, should be changed param by ref... //cD_03_initDescriptors(cD_03_device); HEPSY_S(cleanData_03_id) cD_03_device.t = cD_03_T_0 ; // Operating temperature = Ambient temperature HEPSY_S(cleanData_03_id) cD_03_device.r = cD_03_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // ### added for time related dynamics //static double cD_03_Tau = 0.02 ; // [s] Sampling period HEPSY_S(cleanData_03_id) double cD_03_last_sample_time = 0; //implementation HEPSY_S(cleanData_03_id) while(1) {HEPSY_S(cleanData_03_id) // content HEPSY_S(cleanData_03_id) sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_03_channel->read(); HEPSY_S(cleanData_03_id) dev = sampleTimCord_cleanData_xx_payload_var.dev; HEPSY_S(cleanData_03_id) step = sampleTimCord_cleanData_xx_payload_var.step; HEPSY_S(cleanData_03_id) ex_time = sampleTimCord_cleanData_xx_payload_var.ex_time; HEPSY_S(cleanData_03_id) sample_i = sampleTimCord_cleanData_xx_payload_var.sample_i; HEPSY_S(cleanData_03_id) sample_v = sampleTimCord_cleanData_xx_payload_var.sample_v; // cout << "cleanData_03 rcv \t dev: " << dev // <<"\t step: " << step // <<"\t time_ex:" << ex_time // <<"\t i:" << sample_i // <<"\t v:" << sample_v // << endl; // reconstruct sample HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_I_INDEX] = sample_i; HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_V_INDEX] = sample_v; HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_TIME_INDEX] = ex_time; // ### C L E A N D A T A (0 <= I <= 2.0*I_0) and (0 <= V <= 2.0*V_0) HEPSY_S(cleanData_03_id) cD_03_cleanData(dev, cD_03_sample) ; HEPSY_S(cleanData_03_id) cD_03_device.time_Ex = cD_03_sample[cD_03_TIME_INDEX] ; HEPSY_S(cleanData_03_id) cD_03_device.i = cD_03_sample[cD_03_I_INDEX] ; HEPSY_S(cleanData_03_id) cD_03_device.v = cD_03_sample[cD_03_V_INDEX] ; // ### added for time related dynamics //static double cD_03_Tau = 0.02 ; // [s] Sampling period HEPSY_S(cleanData_03_id) cD_03_Tau = ex_time - cD_03_last_sample_time; HEPSY_S(cleanData_03_id) cD_03_last_sample_time = ex_time; // ### F E A T U R E S E X T R A C T I O N (compute the temperature) HEPSY_S(cleanData_03_id) cD_03_device.t = cD_03_extractFeatures( cD_03_device.t, // Previous temperature cD_03_device.i, // Previous current cD_03_sample[cD_03_I_INDEX], // Current at this step cD_03_device.r) ; // Previous resistance // ### D E G R A D A T I O N M O D E L (compute R_DS_On) HEPSY_S(cleanData_03_id) cD_03_device.r = cD_03_degradationModel(cD_03_device.t) ; // ### N O R M A L I Z E: (x[0] in {0.0, 1.0}) and (x[1] in {0.0, 1.0}) HEPSY_S(cleanData_03_id) x[0] = cD_03_device.i ; HEPSY_S(cleanData_03_id) x[1] = cD_03_device.v ; HEPSY_S(cleanData_03_id) cD_03_normalize(dev, x) ; // // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ //prepare out data payload HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.dev = dev; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.step = step; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.ex_time = ex_time; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_i = cD_03_device.i; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_v = cD_03_device.v; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_t = cD_03_device.t; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_r = cD_03_device.r; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_0 = x[0]; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_1 = x[1]; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_2 = x[2]; HEPSY_S(cleanData_03_id) cleanData_03_ann_03_channel->write(cleanData_xx_ann_xx_payload_var); HEPSY_P(cleanData_03_id) } } //END
/****************************************************************************** * This file is part of 3D-ICE, version 3.1.0 . * * * * 3D-ICE 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 any later * * version. * * * * 3D-ICE 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 3D-ICE. If not, see <http://www.gnu.org/licenses/>. * * * * Copyright (C) 2021 * * Embedded Systems Laboratory - Ecole Polytechnique Federale de Lausanne * * All Rights Reserved. * * * * Authors: Arvind Sridhar Alessandro Vincenzi * * Giseong Bak Martino Ruggiero * * Thomas Brunschwiler Eder Zulian * * Federico Terraneo Darong Huang * * Luis Costero Marina Zapater * * David Atienza * * * * For any comment, suggestion or request about 3D-ICE, please register and * * write to the mailing list (see http://listes.epfl.ch/doc.cgi?liste=3d-ice) * * Any usage of 3D-ICE for research, commercial or other purposes must be * * properly acknowledged in the resulting products or publications. * * * * EPFL-STI-IEL-ESL Mail : [email protected] * * Batiment ELG, ELG 130 (SUBSCRIPTION IS NECESSARY) * * Station 11 * * 1015 Lausanne, Switzerland Url : http://esl.epfl.ch/3d-ice * ******************************************************************************/ #include <iostream> #include <systemc.h> #include <string> #include <fstream> #include <stdlib.h> #include "network_socket.h" #include "network_message.h" #include "IceWrapper.h" #define NARGC 3 #define EXE_NAME argv[0] #define SERVER_IP argv[1] #define SERVER_PORT argv[2] static std::string ServerIp; static unsigned int ServerPort; SC_MODULE(YourSimulator) { IceWrapper *thermalSimulation; SC_CTOR(YourSimulator) { thermalSimulation = new IceWrapper(ServerIp, ServerPort); SC_THREAD(process); } void process() { std::vector<float> powerValues = {0, // 1: CPUs 0, // 2: GPU 1, // 3: BASEBAND1 0, // 4: BASEBAND2 0, // 5: LLCACHE 0, // 6: DRAMCTRL1 0, // 7: DRAMCTRL2 0, // 8: TSVs 0, // 9: ACELLERATORS 1, //10: C0 0, //11: C1 0, //12: C2 0, //13: C3 0, //14: TSVs 0, //10: C0 0, //11: C1 0, //12: C2 0, //13: C3 0, //14: TSVs 0, //10: C0 0, //11: C1 0, //12: C2 0, //13: C3 0, //14: TSVs 0, //10: C0 0, //11: C1 0, //12: C2 0, //13: C3 0 //14: TSVs }; while(true) { wait(sc_time(50,SC_MS)); if(sc_time_stamp() >= sc_time(1,SC_SEC)) { powerValues.at(1) = 5; } if(sc_time_stamp() >= sc_time(2,SC_SEC)) { sc_stop(); } std::vector<float> temperatureValues; thermalSimulation->sendPowerValues(&powerValues); thermalSimulation->simulate(); thermalSimulation->getTemperature(temperatureValues, TDICE_OUTPUT_INSTANT_SLOT, TDICE_OUTPUT_TYPE_TCELL, TDICE_OUTPUT_QUANTITY_NONE); // Visualize this file within octave: // imagesc(flipud(load("temperature_map.txt"))) thermalSimulation->getTemperatureMap("temperature_map.txt"); thermalSimulation->getPowerMap("power_map.txt"); std::cout << "@" << sc_time_stamp() << "\tTemperature=" << temperatureValues.at(0) << endl; } } }; int sc_main(int argc, char *argv[]) { std::cout << "\n\t2015 University of Kaiserslautern" << std::endl; if (argc != NARGC) { std::cerr << "\n\tUsage: " << EXE_NAME << " <server IP> <server port>" << std::endl; exit(EXIT_FAILURE); } ServerIp = SERVER_IP; ServerPort = atoi(SERVER_PORT); YourSimulator("YourSimulator"); sc_start(); return 0; }
//--------Function definitions for classes os and os_task--------- //-----You must modify this file as indicated by TODO comments---- #include "systemc.h" #include "os.h" using namespace std; // implementation of os_task methods //placeholder constructor since we have a pool os_task::os_task() { } os_task::~os_task() { } void os_task::instantiate(sc_core::sc_process_handle handle, const char *name, unsigned int priority) { static unsigned int count = 0; task_name = name; // All tasks are initially ready when created task_state = READY; task_id = count; task_priority = priority; task_handle = handle; activation_flag = rd_suspended_flag = wr_suspended_flag = false; count++; } const char *os_task::get_name() { return task_name.data(); } enum state os_task::get_state() { return task_state; } unsigned int os_task::get_id() { return task_id; } unsigned int os_task::get_priority() { return task_priority; } sc_core::sc_process_handle os_task::get_handle() { return task_handle; } void os_task::activate() { // TODO: set the activation flag and notify the event activation_flag = true; activation_event.notify(); task_state = RUNNING; return; } void os_task::wait_for_activation() { // TODO: If the activation flag is not set, // TODO: wait for it to be set if (activation_flag == false) { wait(activation_event); } // TODO: reset the activation flag activation_flag = false; // TODO: update the task state //task_state = SUSPENDED; return; } //os class method implementation os::os() { // empty constructor } os::~os() { } // dynamic task creation function // this function is called by the main SC thread in the top module // it may also be called by tasks to dynamically create children os_task *os::task_create(const char* name, unsigned int priority, sc_core::sc_process_handle h) { // get a task object from the pool static int count = 0; os_task *t = &(task_pool[count++]); // TODO: instantiate the user task in the OS model t->instantiate(h, name, priority); // TODO: add the task to the ALL_TASKS list ALL_TASKS.push_back(t); //newly created task is in the ready state // TODO: add it to READY vector list READY_TASKS.push_back(t); // return the task pointer return t; } // task initialization function // this function is called by the SystemC thread // for the task, at the very beginning void os::task_init() { os_task *t = NULL; // TODO: find this task's pointer "t" static int count = 0; t = &(task_pool[count++]); // TODO: wait for the task to be scheduled by the OS t->wait_for_activation(); cout << sc_time_stamp() << ": Task " << t->get_name() << " is initialized" << endl; return; } // task termination function // this function is called by the running task // to terminate itself void os::task_terminate() { // TODO: update the state of the task os_task *t = CURRENT; t->task_state = TERMINATED; // TODO: do a rescheduling on remaining tasks schedule(); // TODO: wait till end of simulation if no tasks remain bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *temp_t = ALL_TASKS[i]; if (temp_t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { wait(); } } // this function displays the states of // all the tasks in the order of their creation // It is called by the OS schedule method // whenever a rescheduling takes place void os::status() { cout << endl << sc_time_stamp() << ": STATUS" << endl; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; cout << t->get_name() << ": "; if (t->get_state() == RUNNING) cout << "RUNNING" << endl; else if (t->get_state() == READY) cout << "READY" << endl; else if (t->get_state() == SUSPENDED) cout << "SUSPENDED" << endl; else if (t->get_state() == TERMINATED) cout << "TERMINATED" << endl; } } void os::time_wait(sc_time t) { // TODO: consume time on the SystemC scheduler wait(t); return; } // end time_wait ERROR os::schedule() { // TODO: If there are no tasks or all tasks have terminated // TODO: Print the status and return code E_NO_TASKS if (READY_TASKS.empty()) { status(); return E_NO_TASKS; } bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { status(); return E_NO_TASKS; } // TODO: If all tasks are suspended, just display // TODO: the states and return code E_OK bool not_all_suspended = false; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != SUSPENDED) { not_all_suspended = true; break; } } // otherwise, we have some scheduling to do! // TODO: find the highest priority ready task if (not_all_suspended) { // TODO: remove the highest priority task from the ready list // TODO: and activate it! unsigned int task_index = 0; unsigned int priority = READY_TASKS[0]->get_priority(); for (int i = 1; i < READY_TASKS.size(); i++) { os_task *t = READY_TASKS[i]; if (t->get_priority() > priority) { task_index = i; priority = t->get_priority(); } } CURRENT = READY_TASKS[task_index]; READY_TASKS.erase(READY_TASKS.begin() + task_index); CURRENT->activate(); } // print out the status of all the tasks status(); return E_OK; } // end schedule void os::run() { // all the initial tasks have been created // kickstart the scheduler cout << "Initializing Scheduler... " << endl; schedule(); }
/******************************************************************************* * panic.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file replaces the run time error functions from the ESP32 with * equivalents that will kill the model and print a message on the screen. ******************************************************************************* * 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. * * This file was based off the work covered by the license below: * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 "info.h" #include <stdlib.h> #include <esp_system.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> /* Note: The linker script will put everything in this file in IRAM/DRAM, so it also works with flash cache disabled. */ void __attribute__((weak)) vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ) { printf("***ERROR*** A stack overflow in task "); printf((char *)pcTaskName); printf(" has been detected.\r\n"); espm_abort(); } /* These two weak stubs for esp_reset_reason_{get,set}_hint are used when * the application does not call esp_reset_reason() function, and * reset_reason.c is not linked into the output file. */ void __attribute__((weak)) esp_reset_reason_set_hint(esp_reset_reason_t hint) { } esp_reset_reason_t __attribute__((weak)) esp_reset_reason_get_hint(void) { return ESP_RST_UNKNOWN; } static inline void invoke_abort() { SC_REPORT_FATAL("PANIC", "Abort Called"); } /* Renamed to espm_abort to not conflict with the system abort(). */ void espm_abort() { printf("abort() was called\n"); /* Calling code might have set other reset reason hint (such as Task WDT), * don't overwrite that. */ if (esp_reset_reason_get_hint() == ESP_RST_UNKNOWN) { esp_reset_reason_set_hint(ESP_RST_PANIC); } invoke_abort(); } /* This disables all the watchdogs for when we call the gdbstub. */ static void esp_panic_dig_reset() { SC_REPORT_FATAL("PANIC", "Panic Dig Reset"); } void esp_set_breakpoint_if_jtag(void *fn) { PRINTF_INFO("PANIC", "Set breakpoint %p", fn); } esp_err_t esp_set_watchpoint(int no, void *adr, int size, int flags) { if (no < 0 || no > 1) { return ESP_ERR_INVALID_ARG; } if (flags & (~0xC0000000)) { return ESP_ERR_INVALID_ARG; } PRINTF_INFO("PANIC", "Setting watchpoint %d addr=%p size=%d flags=%x", no, adr, size, flags); return ESP_OK; } void esp_clear_watchpoint(int no) { PRINTF_INFO("PANIC", "Clearing watchpoint %d", no); } static void esp_error_check_failed_print(const char *msg, esp_err_t rc, const char *file, int line, const char *function, const char *expression) { printf("%s failed: esp_err_t 0x%x", msg, rc); } void _esp_error_check_failed_without_abort(esp_err_t rc, const char *file, int line, const char *function, const char *expression) { esp_error_check_failed_print("ESP_ERROR_CHECK_WITHOUT_ABORT", rc, file, line, function, expression); } void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const char *function, const char *expression) { esp_error_check_failed_print("ESP_ERROR_CHECK", rc, file, line, function, expression); invoke_abort(); }
/******************************************************************************* * uart.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Model for a UART. ******************************************************************************* * 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 "uart.h" #include "info.h" void uart::intake() { int cnt; unsigned char msg; unsigned char pos; bool incomming; /* First we wait for the signal to rise. */ while (rx.read() != true) wait(); /* Sometimes we have a glitch at powerup. If a dead time is defined, we * use it. */ if (deadtime != sc_time(0, SC_NS)) wait(deadtime); /* Now we can listen for a packet. */ while(true) { /* We wait for the RX to go low. */ wait(); if (rx.read() != false) continue; /* If we are in autodetect mode, we will keep looking for a rise. */ if (autodetect) { sc_time start = sc_time_stamp(); wait(sc_time(2, SC_MS), rx.value_changed_event()); sc_time delta = start - sc_time_stamp(); if (delta >= sc_time(2, SC_MS)) { PRINTF_WARN("UART", "%s: autodetect timed out", name()); set_baud(300); } else if (delta >= sc_time(3, SC_MS)) set_baud(300); else if (delta >= sc_time(1, SC_MS)) set_baud(600); else if (delta >= sc_time(800, SC_US)) set_baud(1200); else if (delta >= sc_time(400, SC_US)) set_baud(2400); else if (delta >= sc_time(200, SC_US)) set_baud(4800); else if (delta >= sc_time(100, SC_US)) set_baud(9600); else if (delta >= sc_time(50, SC_US)) set_baud(19200); else if (delta >= sc_time(20, SC_US)) set_baud(38400); else if (delta >= sc_time(15, SC_US)) set_baud(57600); else if (delta >= sc_time(12, SC_US)) set_baud(74880); else if (delta >= sc_time(7, SC_US)) set_baud(115200); else if (delta >= sc_time(4, SC_US)) set_baud(230400); else if (delta >= sc_time(3, SC_US)) set_baud(256000); else if (delta >= sc_time(2, SC_US)) set_baud(460800); else if (delta >= sc_time(900, SC_NS)) set_baud(921600); else if (delta >= sc_time(400, SC_NS)) set_baud(1843200); else if (delta >= sc_time(200, SC_NS)) set_baud(3686400); else { PRINTF_WARN("UART", "rate too fast on UART %s", name()); set_baud(3686400); } /* We wait now for the packet to end, assuming 2 stop bits and some * extra time. */ wait(baudperiod * 10); /* And we clear the flag. */ autodetect = false; continue; } /* We jump halfway into the start pulse. */ wait(baudperiod/2); /* And we advance to the next bit. */ wait(baudperiod); /* And we take one bit at a time and merge them together. */ msg = 0; for(cnt = 0, pos = 1; cnt < 8; cnt = cnt + 1, pos = pos << 1) { incomming = rx.read(); if (debug) { PRINTF_INFO("UART", "[%s/%d]: received lvl %c", name(), cnt, (incomming)?'h':'l'); } if (incomming == true) msg = msg | pos; wait(baudperiod); } /* And we send the char. If the buffer is filled, we discard it and * warn the user. If it is free, then we take it. This is needed as * the sender has no way to know if the buffer has space or not. */ if (from.num_free() == 0) { PRINTF_WARN("UART", "Buffer overflow on UART %s", name()); } else { from.write(msg); if (debug && isprint(msg)) { PRINTF_INFO("UART", "[%s] received-'%c'/%02x\n", name(), msg, msg); } else if (debug) { PRINTF_INFO("UART", "[%s] received-%02x\n", name(), msg); } } } } void uart::outtake() { int cnt; unsigned char msg; unsigned char pos; tx.write(true); while(true) { /* We block until we receive something to send. */ msg = to.read(); if (debug && isprint(msg)) { PRINTF_INFO("UART","[%s] sending-'%c'/%02x", name(), msg, msg); } else if (debug) { PRINTF_INFO("UART","[%s] sending-%02x", name(), msg); } /* Then we send the packet asynchronously. */ tx.write(false); wait(baudperiod); for(cnt = 0, pos = 1; cnt < 8; cnt = cnt + 1, pos = pos << 1) { if(debug) { PRINTF_INFO("UART", "[%s/%d]: sent '%c'", name(), cnt, ((pos & msg)>0)?'h':'l'); } if ((pos & msg)>0) tx.write(true); else tx.write(false); wait(baudperiod); } /* And we send the stop bit. */ tx.write(true); if (stopbits < 2) wait(baudperiod); else if (stopbits == 2) wait(baudperiod + baudperiod / 2); else wait(baudperiod * 2); } } void uart::set_baud(unsigned int rate) { baudrate = rate; baudperiod = sc_time(8680, SC_NS) * (115200 / rate); } int uart::getautorate() { /* If autodetect is still true, it is not done, we return 0. */ if (autodetect) { return 0; } /* if it is false, we return the rate. */ else { return get_baud(); } }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you 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. *****************************************************************************/ /***************************************************************************** in_class_initialization.cpp : Showcase for in-class initialization macros Original Author: Roman I. Popov, Intel *****************************************************************************/ #include <systemc.h> #ifdef USE_PIMPL_ADDER #include "adder_int_5_pimpl.h" #else #include "adder.h" #endif const int TEST_SIZE = 10; template <typename T, int N_INPUTS> struct adder_tester : sc_module { sc_in<bool> SC_NAMED(clock); sc_in<bool> SC_NAMED(reset); sc_in<T> SC_NAMED(res); sc_vector<sc_out<T>> SC_NAMED(din, N_INPUTS); SC_CTOR(adder_tester){} private: // In-class initialization of SC_CTHREAD, second parameter is clock edge, // third parameter is arbitrary initialization code SC_CTHREAD_IMP(adder_tester_cthread, clock.pos(), { async_reset_signal_is(reset, true); } ) { wait(); for (int ii = 0; ii < TEST_SIZE; ++ii) { T ref_res = 0; for (int jj = 0; jj < N_INPUTS; ++jj) { T input = ii + jj; ref_res += input; din[jj] = input; } wait(); cout << "RES: " << res << " REFERENCE: " << ref_res << "\n"; sc_assert(res == ref_res); } sc_stop(); } }; template <typename T, int N_INPUTS> struct testbench : sc_module { sc_clock SC_NAMED(clock, 10, SC_NS); sc_signal<bool> SC_NAMED(reset); sc_signal<T> SC_NAMED(res); sc_vector<sc_signal<T>> SC_NAMED(din, N_INPUTS); SC_CTOR(testbench) {} private: // SC_NAMED_WITH_INIT allows to specify arbitrary initialization code after member declaration // for example you can bind module ports here adder_tester<T, N_INPUTS> SC_NAMED_WITH_INIT(tester_inst) { tester_inst.clock(clock); tester_inst.reset(reset); tester_inst.res(res); tester_inst.din(din); } #ifdef USE_PIMPL_ADDER adder_int_5_pimpl SC_NAMED_WITH_INIT(adder_inst) #else adder<T, N_INPUTS> SC_NAMED_WITH_INIT(adder_inst) #endif { adder_inst.res(res); adder_inst.din(din); } SC_THREAD_IMP(reset_thread, sensitive << clock.posedge_event();) { reset = 1; wait(); reset = 0; } }; int sc_main(int argc, char **argv) { testbench<int, 5> SC_NAMED(tb_inst); sc_start(); return 0; }
#include "systemc.h" #include "mwr.h" #include "vcml.h" #include "spikevp/system.h" int sc_main(int argc, char *argv[]) { spikevp::system system("system"); return system.run(); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_multiplication_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // 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 "tlm.h" using namespace sc_core; using namespace tlm; //----------------------------------------------------------------------------- // Title: UVMC Connection Example - Hierarchical Connection, SC side // // This example illustrates how to make hierarchical UVMC connections, i.e. how // to promote a ~port~, ~export~, ~imp~, or ~socket~ from a child component to // a parent that resides in the other language. In effect, we are using a // component written in SV as the implementation for a component in SC. // See <UVMC Connection Example - Hierarchical Connection, SV side> to see // the SC portion of the example. // // (see UVMC_Connections_SCwrapsSV.png) // // By hiding the SV implementation, we create what appears to be a pure SC-based // testbench, just like the <UVMC Connection Example - Native SC to SC>. // However, the SC producer is implemented in SV and uses UVMC to make a // behind-the-scenes connection. // // This example illustates good programming principles by exposing only standard // TLM interfaces to the user. The implementation of those interfaces is hidden // and therefore can change (or be implemented in another language) without // affecting end user code. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Class: producer // // Our ~producer~ module is merely a wrapper around an SV-side implementation, // but users of this producer will not be aware of that. The producer does not // actually instantiate a SV component. It simply promotes the socket in the // SV producer to a corresponding socket in the SC producer. From the outside, // the SC producer appears as an ordinary SC component with a TLM2 socket as // its public interface. //----------------------------------------------------------------------------- //(begin inline source) #include "uvmc.h" using namespace uvmc; class producer: public sc_module { public: tlm_initiator_socket<32> out; SC_CTOR(producer) : out("out") { uvmc_connect_hier(out,"sv_out"); } }; //(end inline source) //----------------------------------------------------------------------------- // Group: sc_main // // The ~sv_main~ top-level module below creates and starts the SV portion of this // example. It instantiates our "pure" SC producer and consumer, binds their // sockets to complete the local connection, then starts SC simulation. // // Notice that the code is identical to that used in the // <UVMC Connection Example - Native SC to SC> example. From the SC user's // perspective, there is no difference between the two testbenches. We've // hidden the UVMC implementation details from the user. //----------------------------------------------------------------------------- //(begin inline source) #include "consumer.h" int sc_main(int argc, char* argv[]) { producer prod("prod"); consumer cons("cons"); prod.out.bind(cons.in); sc_start(-1); return 0; }; //(end inline source)
#include <systemc.h> SC_MODULE (hello_world) { SC_CTOR (hello_world) { } void say_hello() { cout << "Hello World SystemC-2.3.1.\n"; } }; int sc_main(int argc, char* argv[]) { hello_world hello("HELLO"); hello.say_hello(); return(0); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/* Problem 1 Design */ #include<systemc.h> SC_MODULE(sequenceDetector) { sc_in<bool> clock , reset , clear; sc_in<bool> input; sc_out<bool> output; sc_out<bool> state; void detectorAlgo(); void updateValues(); enum states {S1,S2,S3,S4,S5}; sc_signal<states> currentState , nextState; SC_CTOR(sequenceDetector) { currentState.write(S1); nextState.write(S1); SC_METHOD(detectorAlgo); sensitive<<clock.pos(); SC_METHOD(updateValues); sensitive<<reset.neg()<<clear.pos()<<nextState; } }; void sequenceDetector::updateValues() { cout<<"@ "<<sc_time_stamp()<<"------Start UpdateValues--------"<<endl; currentState.write(reset.read() == true ? nextState.read() : S1); output.write(nextState.read() == S5 && clear.read() == false ? true : false); state.write((reset.read() == false || nextState.read() == S1 || nextState.read() == S3) ? false : true); cout<<"@ "<<sc_time_stamp()<<"------End updateValues--------"<<endl; } void sequenceDetector::detectorAlgo() { cout<<"@ "<<sc_time_stamp()<<"------Start detectorAlgos--------"<<endl; bool inputVal = input.read(); if(reset.read() == false) { nextState.write(S1); return; } switch(currentState.read()) { case S1 : if(inputVal == true) { nextState.write(S2); } break; case S2 : if(inputVal == false) { nextState.write(S3); } break; case S3 : if(inputVal == true) { nextState.write(S4); } else { nextState.write(S1); } break; case S4 : if(inputVal == true) { nextState.write(S5); } else { nextState.write(S3); } break; case S5 : if(inputVal == false) { nextState.write(S3); } else { nextState.write(S2); } break; default: break; } cout<<"@ "<<sc_time_stamp()<<"------End detectorAlgos--------"<<endl; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_divider_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { tensor_divider tensor_divider("TENSOR_ADDER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; tensor_divider.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { tensor_divider.data_a_in[i][j][k](data_a_in[i][j][k]); tensor_divider.data_b_in[i][j][k](data_b_in[i][j][k]); tensor_divider.data_out[i][j][k](data_out[i][j][k]); } } } for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { data_a_in[i][j][k] = i + j + k; data_b_in[i][j][k] = i - j + k; } } } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl; } } } return 0; }
//----------------------------------------------------- #include "systemc.h" SC_MODULE (ram) { sc_inout<sc_uint<32> > data; sc_in<sc_uint<32> > address; //-----------Internal variables------------------- sc_uint <32> mem[1024]; sc_event rd_t, wr_t; // Constructor for memory //SC_CTOR(ram) { SC_HAS_PROCESS(ram); ram(sc_module_name ram) { SC_THREAD(wr); SC_THREAD(rd); } // End of Constructor //------------Code Starts Here------------------------- void write() { wr_t.notify(2, SC_NS); } void read() { rd_t.notify(2, SC_NS); } void wr() { while(true) { wait(wr_t); mem [address.read()] = data.read(); } } void rd() { while(true) { wait(rd_t); data = mem [address.read()]; } } }; // End of Module memory
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
#include <systemc.h> #include "Memory.h" using namespace std; void Memory::execute() { // Initialize memory to some predefined contents. for (int i=0; i<MEM_SIZE; i++) _data[i] = i + 0xff000; port_Stall = true; for (;;) { wait(); int addr = port_Addr % MEM_SIZE; if (port_Read) { // Read word from memory. int data = _data[addr]; port_RData = data; port_Stall = false; // Always ready. #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Done read request. Addr = " << showbase << hex << addr << ", Data = " << showbase << hex << data << endl; #endif // Hold data until read cleared. do { wait(); } while (port_Read); port_RData = 0; } else if (port_Write) { // Write a word to memory. int data = port_WData; //int be = port_BE; port_Stall = true; #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Started write request. Addr = " << showbase << hex << addr << ", Data = " << showbase << hex << data << endl; #endif wait(10); port_Stall = false; _data[addr] = data; // TODO: byte enable #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Finished write request. Addr = " << showbase << hex << addr << endl; #endif // Wait until write cleared. do { wait(); } while (port_Write); } } }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_d_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_usage_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/************************************************************************** * * * Catapult(R) MatchLib Toolkit Example Design Library * * * * Software Version: 2.2 * * * * Release Date : Thu Aug 22 21:10:31 PDT 2024 * * Release Type : Production Release * * Release Build : 2.2.0 * * * * Copyright 2020 Siemens * * * ************************************************************************** * 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. * ************************************************************************** * * * The most recent version of this package is available at github. * * * *************************************************************************/ #include <systemc.h> #include "dut.h" #include <mc_scverify.h> using namespace::std; class Top : public sc_module { public: CCS_DESIGN(dut) CCS_INIT_S1(dut1); sc_clock clk; SC_SIG(bool, rst_bar); Connections::Combinational<dut::T> CCS_INIT_S1(out1); Connections::Combinational<dut::T> CCS_INIT_S1(in1); int matlab_input; bool matlab_input_valid; int matlab_output; bool matlab_output_valid; SC_CTOR(Top) : clk("clk", 1, SC_NS, 0.5,0,SC_NS,true) { sc_object_tracer<sc_clock> trace_clk(clk); dut1.clk(clk); dut1.rst_bar(rst_bar); dut1.out1(out1); dut1.in1(in1); SC_CTHREAD(reset, clk); SC_THREAD(stim); sensitive << clk.posedge_event(); async_reset_signal_is(rst_bar, false); SC_THREAD(resp); sensitive << clk.posedge_event(); async_reset_signal_is(rst_bar, false); } void stim() { CCS_LOG("Stimulus started"); in1.ResetWrite(); wait(); int i1 = 0; while (1) { #ifdef EXTERNAL_TESTBENCH if (matlab_input_valid) { in1.Push(matlab_input); matlab_input_valid = 0; } else { wait(); } #else in1.Push(i1++); if (i1 > 10) sc_stop(); #endif } } void resp() { out1.ResetRead(); wait(); while (1) { #ifdef EXTERNAL_TESTBENCH matlab_output = out1.Pop(); matlab_output_valid = 1; std::cout << "calling sc_pause()\n"; sc_pause(); #else CCS_LOG("See: " << out1.Pop()); #endif } } void reset() { rst_bar.write(0); wait(5); rst_bar.write(1); wait(); } }; Top *top_ptr{0}; // sc_main instantiates the SC hierarchy but does not run the simulation - that is handled elsewhere int sc_main(int argc, char **argv) { sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", SC_DO_NOTHING); sc_report_handler::set_actions(SC_ERROR, SC_DISPLAY); // This function instantiates the design hiearchy including the testbench. sc_trace_file *trace_file_ptr = sc_trace_static::setup_trace_file("trace"); top_ptr = new Top("top"); trace_hierarchy(top_ptr, trace_file_ptr); #ifndef EXTERNAL_TESTBENCH sc_start(); #endif return 0; } #ifdef EXTERNAL_TESTBENCH // This class represents the SC simulator to Python or Matlab Mex class sc_simulator { public: sc_simulator() { sc_elab_and_sim(0, 0); } // This function represents the python or Matlab Mex function that would be called repeatedly // to process one (or more) data inputs and return one (or more) data outputs int process_one_sample(int in1) { top_ptr->matlab_input = in1; top_ptr->matlab_input_valid = true; std::cout << "calling sc_start()\n"; sc_start(); // This returns when sc_pause is called above return top_ptr->matlab_output; } }; // Python does not have a native C++ interface, so we export regular C functions to Python extern "C" { sc_simulator* sc_simulator_new() { return new sc_simulator(); } int process_one_sample(sc_simulator* sim, int in1) { return sim->process_one_sample(in1); } } #endif
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you 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 main.cpp * @brief This implementation assigns preset values to a list of cci-parameters * (without any knowledge of them being present in the model) and then * instantiates the 'parameter_owner' and 'parameter_configurator' modules * @author P V S Phaneendra, CircuitSutra Technologies <[email protected]> * @date 21st July, 2011 (Thursday) */ #include <cci_configuration> #include <systemc.h> #include <string> #include <cci_configuration> #include "ex18_cci_configFile_Tool.h" #include "ex18_parameter_owner.h" #include "ex18_parameter_configurator.h" /** * @fn int sc_main(int sc_argc, char* sc_argv[]) * @brief Here, a reference of the global broker is taken with the help of * the originator information and then preset values are assigned to * a list of cci-parameters. * @param sc_argc The number of input arguments * @param sc_argv The list of input arguments * @return An integer denoting the return status of execution. */ int sc_main(int sc_argc, char* sc_argv[]) { cci::cci_register_broker(new cci_utils::broker("My Global Broker")); cci::ex18_cci_configFile_Tool configTool("ConfigTool"); configTool.config("Configuration_File.txt"); #if 0 // In case, if user doesn't want to use the reading from configuration file // approach, here is an alternative that assigns preset values to the // cci-parameters // Get reference/handle of the default global broker cci::cci_broker_handle myMainBrokerIF = cci::cci_get_broker(); SC_REPORT_INFO("sc_main", "[MAIN] : Set preset value to 'integer type" " parameter'"); myMainBrokerIF.set_preset_cci_value("param_owner.int_param", cci::cci_value(10)); SC_REPORT_INFO("sc_main", "[MAIN] : Set preset value to 'float type" " parameter'"); myMainBrokerIF.set_preset_cci_value("param_owner.float_param", cci::cci_value(11.11)); SC_REPORT_INFO("sc_main", "[MAIN] : Set preset value to 'string type" " parameter'"); myMainBrokerIF.set_preset_cci_value("param_owner.string_param", cci::cci_value::from_json("Used_parameter")); SC_REPORT_INFO("sc_main", "[MAIN] : Set preset value to 'double type" " parameter'"); myMainBrokerIF.set_preset_cci_value("param_owner.double_param", cci::cci_value(100.123456789)); #endif // Instatiation of 'parameter_owner' and 'parameter_configurator' modules ex18_parameter_owner param_owner("param_owner"); ex18_parameter_configurator param_cfgr("param_cfgr"); // BEOE, EOE and simulation phases advance from here SC_REPORT_INFO("sc_main", "Begin Simulation."); sc_core::sc_start(10.0, sc_core::SC_NS); SC_REPORT_INFO("sc_main", "End Simulation."); return EXIT_SUCCESS; } // sc_main
#include <systemc.h> // // Basic d flip flop // // :attention: using this unit is pointless because HWToolkit can automatically // generate such a register for any interface and datatype // // .. hwt-autodoc:: // SC_MODULE(DReg) { // ports sc_in_clk clk; sc_in<sc_uint<1>> din; sc_out<sc_uint<1>> dout; sc_in<sc_uint<1>> rst; // component instances // internal signals sc_uint<1> internReg = sc_uint<1>("0b0"); sc_signal<sc_uint<1>> internReg_next; void assig_process_dout() { dout.write(internReg); } void assig_process_internReg() { if (rst.read() == sc_uint<1>("0b1")) internReg = sc_uint<1>("0b0"); else internReg = internReg_next.read(); } void assig_process_internReg_next() { internReg_next.write(din.read()); } SC_CTOR(DReg) { SC_METHOD(assig_process_dout); sensitive << internReg; SC_METHOD(assig_process_internReg); sensitive << clk.pos(); SC_METHOD(assig_process_internReg_next); sensitive << din; // connect ports } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_scalar_deviation_function_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/******************************************************************************* * task.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file reimplements the freertos tasks to get them to compile under the * ESPMOD SystemC model. The tasks were rewrittent to spawn SC dynamic * threads. ******************************************************************************* * 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. * * This file was based off the work covered by the license below: * FreeRTOS V8.2.0 - Copyright (C) 2015 Real Time Engineers Ltd. * All rights reserved * * FreeRTOS is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License (version 2) as published by the * Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. * * FreeRTOS 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. Full license text is available on the following * link: http://www.freertos.org/a00114.html */ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> #include "FreeRTOS.h" #include "task.h" void vTaskDelay( const TickType_t xTicksToDelay ) { /* We set the portTICK_RATE_MS to 1, so the value should be the * number in lilliseconds. Perhaps we should change this later. */ wait(xTicksToDelay, SC_MS); } BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pvCreatedTask, const BaseType_t xCoreID) { sc_spawn(sc_bind(pvTaskCode, pvParameters)); return pdTRUE; } void vTaskDelete( TaskHandle_t xTaskToDelete ) { }
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019 Cadence Design Systems, Inc. All rights reserved worldwide. // // The code contained herein is the proprietary and confidential information // of Cadence or its licensors, and is supplied subject to a previously // executed license and maintenance agreement between Cadence and customer. // This code is intended for use with Cadence high-level synthesis tools and // may not be used with other high-level synthesis tools. Permission is only // granted to distribute the code as indicated. Cadence grants permission for // customer to distribute a copy of this code to any partner to aid in designing // or verifying the customer's intellectual property, as long as such // distribution includes a restriction of no additional distributions from the // partner, unless the partner receives permission directly from Cadence. // // ALL CODE FURNISHED BY CADENCE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, AND CADENCE SPECIFICALLY DISCLAIMS ANY WARRANTY OF NONINFRINGEMENT, // FITNESS FOR A PARTICULAR PURPOSE OR MERCHANTABILITY. CADENCE SHALL NOT BE // LIABLE FOR ANY COSTS OF PROCUREMENT OF SUBSTITUTES, LOSS OF PROFITS, // INTERRUPTION OF BUSINESS, OR FOR ANY OTHER SPECIAL, CONSEQUENTIAL OR // INCIDENTAL DAMAGES, HOWEVER CAUSED, WHETHER FOR BREACH OF WARRANTY, // CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE. // //////////////////////////////////////////////////////////////////////////////// #include <systemc.h> // SystemC definitions #include "system.h" // Top-level System module header file static System * m_system = NULL; // The pointer that holds the top-level System module instance. void esc_elaborate() // This function is required by Stratus to support { // SystemC-Verilog co-simulation. This is where an instance of the m_system = new System( "system" ); // top-level module should be created. } void esc_cleanup() // This function is called at the end of simulation by the { // Stratus co-simulation hub. It should delete the top-level delete m_system; // module instance. } int sc_main( int argc, char ** argv ) // This function is called by the SystemC kernel for pure SystemC simulations { esc_initialize( argc, argv ); // esc_initialize() passes in the cmd-line args. This initializes the Stratus simulation // environment (such as opening report files for later logging and analysis). esc_elaborate(); // esc_elaborate() (defined above) creates the top-level module instance. In a SystemC-Verilog // co-simulation, this is called during cosim initialization rather than from sc_main. sc_start(); // Starts the simulation. Returns when a module calls esc_stop(), which finishes the simulation. // esc_cleanup() (defined above) is automatically called before sc_start() returns. return 0; // Returns the status of the simulation. Required by most C compilers. }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" SC_MODULE(scalar_subtractor) { sc_in_clk clock; sc_in<int> data_a_in; sc_in<int> data_b_in; sc_out<int> data_out; SC_CTOR(scalar_subtractor) { SC_METHOD(subtractor); sensitive << clock.pos(); sensitive << data_a_in; sensitive << data_b_in; } void subtractor() { data_out.write(data_a_in.read() - data_b_in.read()); } };
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #ifdef HW_COSIM //#define __GMP_WITHIN_CONFIGURE #endif #define DEBUG_SYSTEMC #define SC_INCLUDE_FX #include "hwcore/tb/cnn/tb_pe.hpp" #include <systemc.h> unsigned errors = 0; const char simulation_name[] = "tb_pe"; int sc_main(int argc, char *argv[]) { cout << "INFO: Elaborating " << simulation_name << endl; sc_core::sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", sc_core::SC_DO_NOTHING); sc_report_handler::set_actions(SC_ID_LOGIC_X_TO_BOOL_, SC_LOG); sc_report_handler::set_actions(SC_ID_VECTOR_CONTAINS_LOGIC_VALUE_, SC_LOG); // sc_report_handler::set_actions( SC_ID_OBJECT_EXISTS_, SC_LOG); // sc_set_time_resolution(1,SC_PS); // sc_set_default_time_unit(1,SC_NS); // ModuleSingle modulesingle("modulesingle_i"); return 0; tb_pe<sizeof(int) * 8, sizeof(int) * 4, 1> tb_01("tb_pe"); cout << "INFO: Simulating " << simulation_name << endl; sc_time time_out(1000, SC_US); sc_start(time_out); return errors ? 1 : 0; cout << "INFO: end time is: " << sc_time_stamp().to_string() << ", and max time is: " << time_out.to_string() << std::endl << std::flush; sc_assert(sc_time_stamp() != time_out); cout << "INFO: Post-processing " << simulation_name << endl; cout << "INFO: Simulation " << simulation_name << " " << (errors ? "FAILED" : "PASSED") << " with " << errors << " errors" << std::endl << std::flush; #ifdef __RTL_SIMULATION__ cout << "HW cosim done" << endl; #endif return errors ? 1 : 0; } // test2
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 #define SIZE_K_IN 4 SC_MODULE(tensor_matrix_convolution) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(tensor_matrix_convolution) { SC_METHOD(convolution); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { sensitive << data_a_in[i][j][k]; } sensitive << data_b_in[i][j]; } } } void convolution() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { int temporal = 0; for (int m = 0; m < i; m++) { for (int n = 0; n < j; n++) { for (int p = 0; p < k; p++) { temporal += data_a_in[m][n][p].read() * data_b_in[i - m][j - n].read(); } } } data_out[i][j] = temporal; } } } } };
// Copyright 2020 Glenn Ramalho - RFIDo Design // // 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. // // This code was based off the work from Espressif Systems covered by the // License: // // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // 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 "esp32-hal.h" #include "clockpacer.h" //Undocumented!!! Get chip temperature in Farenheit //Source: https://github.com/pcbreflux/espressif/blob/master/esp32/arduino/sketchbook/ESP32_int_temp_sensor/ESP32_int_temp_sensor.ino uint8_t temprature_sens_read(); float temperatureRead() { return (temprature_sens_read() - 32) / 1.8; } /* We need to use the C prototype style so that the weak alias will work. */ extern "C" { void __yield(); } void __yield() { /* We do a wait, as that hands the control back to the SystemC Scheduler, * which is also handling our FreeRTOS scheduler. */ wait(clockpacer.get_cpu_period()); } void yield() __attribute__ ((weak, alias("__yield"))); /* This is something often used inside the model and drivers for the model. */ void del1cycle() { if (clockpacer.is_thread()) clockpacer.wait_next_cpu_clk(); } #if CONFIG_AUTOSTART_ARDUINO /* extern TaskHandle_t loopTaskHandle; extern bool loopTaskWDTEnabled; void enableLoopWDT(){ if(loopTaskHandle != NULL){ if(esp_task_wdt_add(loopTaskHandle) != ESP_OK){ log_e("Failed to add loop task to WDT"); } else { loopTaskWDTEnabled = true; } } } void disableLoopWDT(){ if(loopTaskHandle != NULL && loopTaskWDTEnabled){ loopTaskWDTEnabled = false; if(esp_task_wdt_delete(loopTaskHandle) != ESP_OK){ log_e("Failed to remove loop task from WDT"); } } } void feedLoopWDT(){ esp_err_t err = esp_task_wdt_reset(); if(err != ESP_OK){ log_e("Failed to feed WDT! Error: %d", err); } } */ #endif /* void enableCore0WDT(){ TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 == NULL || esp_task_wdt_add(idle_0) != ESP_OK){ log_e("Failed to add Core 0 IDLE task to WDT"); } } void disableCore0WDT(){ TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 == NULL || esp_task_wdt_delete(idle_0) != ESP_OK){ log_e("Failed to remove Core 0 IDLE task from WDT"); } } #ifndef CONFIG_FREERTOS_UNICORE void enableCore1WDT(){ TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 == NULL || esp_task_wdt_add(idle_1) != ESP_OK){ log_e("Failed to add Core 1 IDLE task to WDT"); } } void disableCore1WDT(){ TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 == NULL || esp_task_wdt_delete(idle_1) != ESP_OK){ log_e("Failed to remove Core 1 IDLE task from WDT"); } } #endif */ /* BaseType_t xTaskCreateUniversal( TaskFunction_t pxTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask, const BaseType_t xCoreID ){ #ifndef CONFIG_FREERTOS_UNICORE if(xCoreID >= 0 && xCoreID < 2) { return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID); } else { #endif return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); #ifndef CONFIG_FREERTOS_UNICORE } #endif } */ /* micros and millis get the current time from the SystemC simulation time * instead of the CPU. */ unsigned long int micros() { return (unsigned long int)floor(sc_time_stamp().to_seconds() * 1000000); } unsigned long int millis() { return (unsigned long int)floor(sc_time_stamp().to_seconds() * 1000); } /* Delay does a SystemC wait. */ void delay(uint32_t del) { wait(del, SC_MS); } /* For the delayMicroseconds we do the same thing. We definitely do not want * the busy-wait loop that the original code uses. It bogs down too much the * simulation. */ void delayMicroseconds(uint32_t del) { wait(del, SC_US); } /* Not sure why these are here, but they do nothing, so they can remain here. */ void initVariant() __attribute__((weak)); void initVariant() {} void init() __attribute__((weak)); void init() {} bool verifyOta() __attribute__((weak)); bool verifyOta() { return true; } #ifdef CONFIG_BT_ENABLED //overwritten in esp32-hal-bt.c bool btInUse() __attribute__((weak)); bool btInUse(){ return false; } #endif /* void initArduino() { #ifdef CONFIG_APP_ROLLBACK_ENABLE const esp_partition_t *running = esp_ota_get_running_partition(); esp_ota_img_states_t ota_state; if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) { if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) { if (verifyOta()) { esp_ota_mark_app_valid_cancel_rollback(); } else { log_e("OTA verification failed! Start rollback to the previous version ..."); esp_ota_mark_app_invalid_rollback_and_reboot(); } } } #endif //init proper ref tick value for PLL (uncomment if REF_TICK is different than 1MHz) //ESP_REG(APB_CTRL_PLL_TICK_CONF_REG) = APB_CLK_FREQ / REF_CLK_FREQ - 1; #ifdef F_CPU setCpuFrequencyMhz(F_CPU/1000000); #endif #if CONFIG_SPIRAM_SUPPORT psramInit(); #endif esp_log_level_set("*", CONFIG_LOG_DEFAULT_LEVEL); esp_err_t err = nvs_flash_init(); if(err == ESP_ERR_NVS_NO_FREE_PAGES){ const esp_partition_t* partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, NULL); if (partition != NULL) { err = esp_partition_erase_range(partition, 0, partition->size); if(!err){ err = nvs_flash_init(); } else { log_e("Failed to format the broken NVS partition!"); } } } if(err) { log_e("Failed to initialize NVS! Error: %u", err); } #ifdef CONFIG_BT_ENABLED if(!btInUse()){ esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); } #endif init(); initVariant(); } */ //used by hal log const char *pathToFileName(const char * path) { size_t i = 0; size_t pos = 0; char * p = (char *)path; while(*p){ i++; if(*p == '/' || *p == '\\'){ pos = i; } p++; } return path+pos; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you 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. *****************************************************************************/ /***************************************************************************** simple_bus_main.cpp : sc_main Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "simple_bus_test.h" int sc_main(int, char **) { simple_bus_test top("top"); sc_start(10000, SC_NS); return 0; }
/* * @ASCK */ #include <systemc.h> SC_MODULE (ID) { sc_in_clk clk; sc_in <sc_int<8>> prev_A; sc_in <sc_int<8>> prev_B; sc_in <sc_int<13>> prev_Imm; sc_in <sc_uint<3>> prev_Sa; sc_in <sc_uint<5>> prev_AluOp; sc_in <bool> prev_r; sc_in <bool> prev_w; sc_in <bool> prev_AluMux; sc_in <bool> prev_WbMux; sc_in <bool> prev_call; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_A; sc_out <sc_int<8>> next_B; sc_out <sc_int<13>> next_Imm; sc_out <sc_uint<3>> next_Sa; sc_out <sc_uint<5>> next_AluOp; sc_out <bool> next_r; sc_out <bool> next_w; sc_out <bool> next_AluMux; sc_out <bool> next_WbMux; sc_out <bool> next_call; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (ID){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_A.write(prev_A.read()); next_B.write(prev_B.read()); next_Imm.write(prev_Imm.read()); next_Sa.write(prev_Sa.read()); next_AluOp.write(prev_AluOp.read()); next_AluMux.write(prev_AluMux.read()); next_r.write(prev_r.read()); next_w.write(prev_w.read()); next_WbMux.write(prev_WbMux.read()); next_call.write(prev_call.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
#include <Gemmini.h> #include <systemc.h> #include <ac_int.h> #include <ac_std_float.h> #include <cfenv> template<class To, class From> To _bit_cast(const From& src) noexcept { To dst; std:: memcpy(&dst, &src, sizeof(To)); return dst; } sc_biguint<8> Gemmini::ScaleInputType(sc_biguint<8> input,sc_biguint<32> scale){ // Bit-cast scale to float ac_ieee_float32 scale_ac_float = _bit_cast<float, uint32_t>(scale.to_uint()); // Convert input to float ac_ieee_float32 input_ac_float(_bit_cast<int8_t,uint8_t>(input.to_uint())); // Perform multiply auto result_ac_float = input_ac_float * scale_ac_float; // Cast to int with rounding to the nearest even number // TODO: Make clamping programmatic with generated gemmini bitwidths // TODO: Use custom types corresponding to the gemmini configuration auto result_float = result_ac_float.to_float(); auto result_int = static_cast<int64_t>(std::nearbyint(result_float)); int8_t result_clamped = result_int > INT8_MAX ? INT8_MAX : (result_int < INT8_MIN ? INT8_MIN : result_int); // Bit-cast back to sc_biguint8 uint8_t result_uint = _bit_cast<uint8_t, int8_t>(result_clamped); sc_biguint<8> to_return(result_uint); return to_return; } sc_biguint<8> Gemmini::ScaleAccType(sc_biguint<32> input,sc_biguint<32> scale){ // bitcast scale to float ac_ieee_float32 scale_ac_float = _bit_cast<float, uint32_t>(scale.to_uint()); // Cast scale and input to 64 bit floats ac_ieee_float64 scale_ac_float64(scale_ac_float); ac_ieee_float64 input_float64(_bit_cast<int32_t,uint32_t>(input.to_uint())); // Perform multiply ac_ieee_float64 result_float64 = scale_ac_float64 * input_float64; // Cast to int with rounding to the nearest integer auto result_double = result_float64.to_double(); auto result_rounded = std::nearbyint(result_double); auto result_clamped = result_rounded > INT8_MAX ? INT8_MAX : (result_rounded < INT8_MIN ? INT8_MIN : result_rounded); auto result_int = static_cast<int8_t>(result_clamped); // Cast back to sc_biguint sc_biguint<8> out(result_int); return out; }
/******************************************************************************* * cd4097_channel.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a simple model for a single channel of a CD4079 dual analog Mux. ******************************************************************************* * 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 "info.h" #include "cd4097_channel.h" int cd4097_channel::get_selector() { return (((c.read())?1:0) << 2) | (((b.read())?1:0) << 1) | ((a.read())?1:0); } void cd4097_channel::process_th() { int line; bool channel_is_driver = false; x.write(GN_LOGIC_Z); for(line = 0; line < channel.size(); line = line + 1) channel[line]->write(GN_LOGIC_Z); sel = get_selector(); bool recheck = false; while(true) { /* If the recheck is high, this means the selector changed and we need * to refigure out who is driving. */ if (recheck) { /* We wait a time stamp and redo the driving. */ wait(1, SC_NS); recheck = false; /* In these cases, we just keep everyone at Z. */ if (inh.read() || sel >= channel.size()) continue; /* We check who is the driver and drive the other. If they are both * being driven, we drive X everywhere. */ if (x.read() == GN_LOGIC_Z) { channel_is_driver = true; x.write(channel[sel]->read()); } else if (channel[sel]->read()==GN_LOGIC_Z) { channel_is_driver = false; channel[sel]->write(x.read()); } else { PRINTF_WARN("TEST", "Two drivers on MUX"); channel[sel]->write(GN_LOGIC_X); x.write(GN_LOGIC_X); } continue; } /* We wait for one either a change in the selector or a change in * either side of the mux. If the selector is pointing to an illegal * value, we then just wait for a change in the selector. */ if (sel >= channel.size()) wait(a->default_event() | b->default_event() | c->default_event() | inh->default_event()); else wait(channel[sel]->default_event() | a->default_event() | b->default_event() | c->default_event() | inh->default_event() | x->default_event()); bool sel_triggered = a->value_changed_event().triggered() || b->value_changed_event().triggered() || c->value_changed_event().triggered(); if (debug) { /* If the sel is illegal, we only can process the selector. */ if (sel >= channel.size()) printf("%s: sel = %d, triggers: sel %c, inh %c, x %c\n", name(), sel, (sel_triggered)?'t':'f', (inh->value_changed_event().triggered())?'t':'f', (x->value_changed_event().triggered())?'t':'f'); else printf( "%s: sel = %d, triggers: channel %c, sel %c, inh %c, x %c\n", name(), sel, (channel[sel]->value_changed_event().triggered())?'t':'f', (sel_triggered)?'t':'f', (inh->value_changed_event().triggered())?'t':'f', (x->value_changed_event().triggered())?'t':'f'); } /* If inh went high we shut it all off, it does not matter who triggered * what. */ if (inh.read() == GN_LOGIC_1) { x.write(GN_LOGIC_Z); if (sel < channel.size()) channel[sel]->write(GN_LOGIC_Z); channel_is_driver = false; } /* If inh came back, we then need to resolve. */ else if (inh.value_changed_event().triggered()) { /* No need to drive Z if it is already. */ recheck = true; channel_is_driver = false; } /* Now we check the selector. If it changed, we need to drive Z and * recheck. This is because it is difficult to check every single * driver in a signal to find out what is going on. */ else if (sel_triggered) { int newsel = get_selector(); /* We now drive Z everywhere. */ if (sel < channel.size()) channel[sel]->write(GN_LOGIC_Z); x.write(GN_LOGIC_Z); channel_is_driver = false; /* And we update the selector variable. */ sel = newsel; /* And if the new selector is valid, we do a recheck. */ if (sel < channel.size()) recheck = true; } /* If the selector is not valid, we just ignore any activity on either * side as there can't be any change. We simply drive Z everywhere. * Note: this path is a safety one, it is probably never called. */ else if (sel >= channel.size()) { channel_is_driver = false; x.write(GN_LOGIC_Z); } /* When we update a output pin, there is always a reflection. If both * sides have the same value, this probably was a reflection, so we * can dump it. */ else if (x.read() == channel[sel]->read()) continue; /* We have an analog mux. In a real mux system, we would do a fight * between the sides and eventually settle to something. This is a * digital simulator though, so we need a simplification. If I get a * driver on one side, we drive that value on the other. */ else if (channel[sel]->value_changed_event().triggered() && (channel_is_driver || x.read() == GN_LOGIC_Z)) { channel_is_driver = true; x.write(channel[sel]->read()); } else if (x.default_event().triggered() && (!channel_is_driver || channel[sel]->read() == GN_LOGIC_Z)) { channel_is_driver = false; channel[sel]->write(x.read()); } /* If there are drivers on both sides, we need to put X on both sides. * Note: the current model will not leave this state unless there is * an inh or sel change. */ else { PRINTF_WARN("TEST", "Two drivers on MUX"); channel[sel]->write(GN_LOGIC_X); x.write(GN_LOGIC_X); } } } void cd4097_channel::trace(sc_trace_file *tf) { sc_trace(tf, x, x.name()); sc_trace(tf, a, a.name()); sc_trace(tf, b, b.name()); sc_trace(tf, c, c.name()); sc_trace(tf, inh, inh.name()); }
#include "memory.h" #include "system.h" #include "systemc.h" /** Read formatted binary file with data and text sections. */ uint32_t read_input_file(mem_cursor_t *cursors, uint32_t max_n_cursor, uint32_t *out, uint32_t max_mem_size) { // open ASM file FILE *fp = fopen(get_asm_file_name(), "rb"); if (!fp) return 0; uint32_t out_cursor = 0; int i; for (i = 0; i < max_n_cursor; i++) { // read eight bytes for address and size if (!fread((void*)(cursors + i), sizeof(uint32_t), 2, fp)) break; uint32_t size = cursors[i].size; // determine if contiguous with previous block if (i > 0 && (cursors[i-1].addr + (cursors[i-1].size << 2) == cursors[i].addr)) { // add to previous block i--; cursors[i].size += size; } else { // set cursor in newly allocated entry cursors[i].mem_cursor = out_cursor; } if (!fread((void*)(out + out_cursor), sizeof(uint32_t), size, fp)) break; out_cursor += size; } fclose(fp); return i; } memory::memory(sc_module_name name, uint32_t max_cursors, uint32_t max_mem_words): sc_module(name) { if (max_cursors > 0 && max_mem_words > 0) { _max_cursors = max_cursors; _cursors = new mem_cursor_t[max_cursors]; _max_mem_words = max_mem_words; _mem = new uint32_t[max_mem_words]; _n_cursors = read_input_file(_cursors, max_cursors, _mem, max_mem_words); _mem_words = 0; for (int i = 0; i < _n_cursors; ++i) { _mem_words += _cursors[i].size; } LOGF("[%s]: %d cursors and %d words", this->name(), _n_cursors, _mem_words); } else { _n_cursors = 0; _max_cursors = 0; _cursors = nullptr; _mem_words = 0; _max_mem_words = 0; _mem = nullptr; } } memory::~memory() { if (_max_cursors) delete _cursors; if (_max_mem_words) delete _mem; } bool memory::read(uint32_t addr, uint32_t& data) { // find memory entry containing the address // use data as the counter to save memory for (data = 0; data < _n_cursors; ++data) { if (_cursors[data].addr <= addr && _cursors[data].addr + (_cursors[data].size << 2) > addr) { break; } } if (data == _n_cursors) { // iterated through list without finding the address data = 0; } else { // calculate the address in the memory array addr = _cursors[data].mem_cursor + ((addr - _cursors[data].addr) >> 2); data = _mem[addr]; } return true; } bool memory::write(uint32_t addr, uint32_t data, uint8_t size) { // find memory entry containing the address int i; for (i = 0; i < _n_cursors; ++i) { if (_cursors[i].addr <= addr && _cursors[i].addr + (_cursors[i].size << 2) > addr) { break; } } if (i == _n_cursors) { // iterated through list without finding the address if (_n_cursors < _max_cursors) { // find spot for new cursor in order for (i = 0; i < _n_cursors; ++i) { if (_cursors[i].addr > addr) { break; } } // shift list elements for (int j = _n_cursors; j > i; --j) { _cursors[j] = _cursors[j-1]; } // insert into cursor list _cursors[i].addr = addr; _cursors[i].size = 1; _cursors[i].mem_cursor = _mem_words; // insert into memory write_int(_mem_words, data, addr & 0b11, size); _mem_words++; return true; } else { return false; } } // calculate the address in the memory array write_int(_cursors[i].mem_cursor + ((addr - _cursors[i].addr) >> 2), data, addr & 0b11, size); return true; } void memory::write_int(uint32_t addr_int, uint32_t data, uint32_t offset, uint32_t size) { switch (size) { case 4: _mem[addr_int] = data; break; case 2: *((uint16_t*)(_mem + addr_int) + (offset >> 1)) = (uint16_t)data; break; case 1: *((uint8_t*)(_mem + addr_int) + offset) = (uint8_t)data; break; }; } void memory::print() { int i, j; uint32_t addr_print, addr_int; mem_cursor_t *c = _cursors; for (i = 0; i < _n_cursors; ++i, ++c) { printf("\n=====\n0x%08x -> 0x%08x\n=====", c->addr, c->addr + (c->size << 2)); addr_print = c->addr; addr_int = c->mem_cursor; for (j = 0; j < c->size; ++j, addr_print += 4, ++addr_int) { if ((j & 0b11) == 0) { printf("\n0x%08x: ", addr_print); } printf("%08x ", _mem[addr_int]); } printf("\n"); } }
/******************************************************************************* * clkgen.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Emulates the clocks on the ESP32. ******************************************************************************* * 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 "Arduino.h" #include "clkgen.h" void clkgen::gen() { bool lvl = false; while(true) { apb_clk.write(lvl); lvl = !lvl; del1cycle(); } }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_adder_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_adder vector_adder("VECTOR_ADDER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN]; vector_adder.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_adder.data_a_in[i](data_a_in[i]); vector_adder.data_b_in[i](data_b_in[i]); vector_adder.data_out[i](data_out[i]); } for (int i = 0; i < SIZE_I_IN; i++) { data_a_in[i] = i; data_b_in[i] = i + 1; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl; } return 0; }
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program 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. * * * * 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 General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include "display.h" #include <systemc.h> void display::main() { int i = 1; system_display_payload system_display_payload_var; /* //implementation while(1) { system_display_payload_var = system_display_port_in->read(); cout << "Display-" << i << "\t at time \t" << sc_time_stamp().to_seconds() << endl; i++; } */ //implementation while(i <= 100) { system_display_payload_var = system_display_port_in->read(); cout << "Display-" << i <<": \t" << "\t at time \t" << sc_time_stamp().to_seconds() << endl; i++; } sc_stop(); }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // 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" using namespace sc_core; class sub_object { public: unsigned int extra_int; }; #include "uvmc.h" using namespace uvmc; UVMC_UTILS_1(sub_object,extra_int)
// ================================================================ // NVDLA Open Source Project // // Copyright(c) 2016 - 2017 NVIDIA Corporation. Licensed under the // NVDLA Open Hardware License; Check "LICENSE" which comes with // this distribution for more information. // ================================================================ // File Name: cdp_hls_wrapper.cpp #include "log.h" #include "ac_int.h" #include "ac_channel.h" #include "log.h" #include <systemc.h> #include "arnvdla.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "vlibs.h" #include "cdp_hls_wrapper.h" #pragma CTC SKIP int half2single(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) source; // Type pun input as an unsigned 16-bit int unsigned int *xp = (unsigned int *) target; // Type pun output as an unsigned 32-bit int unsigned short h, hs, he, hm; unsigned int xs, xe, xm; int xes; int e; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) // Nothing to convert (e.g., imag part of pure real) return 0; while( numel-- ) { h = *hp++; if( (h & 0x7FFFu) == 0 ) { // Signed zero *xp++ = ((unsigned int) h) << 16; // Return the signed zero } else { // Not zero hs = h & 0x8000u; // Pick off sign bit he = h & 0x7C00u; // Pick off exponent bits hm = h & 0x03FFu; // Pick off mantissa bits if( he == 0 ) { // Denormal will convert to normalized e = -1; // The following loop figures out how much extra to adjust the exponent do { e++; hm <<= 1; } while( (hm & 0x0400u) == 0 ); // Shift until leading bit overflows into exponent bit xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127 - e; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) (hm & 0x03FFu)) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } else if( he == 0x7C00u ) { // Inf or NaN (all the exponent bits are set) if( hm == 0 ) { // If mantissa is zero ... *xp++ = (((unsigned int) hs) << 16) | ((unsigned int) 0x7F800000u); // Signed Inf } else { *xp++ = (unsigned int) 0xFFC00000u; // NaN, only 1st mantissa bit set } } else { // Normalized number xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) hm) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } } } return 0; } int single2half(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) target; // Type pun output as an unsigned 16-bit int unsigned int *xp = (unsigned int *) source; // Type pun input as an unsigned 32-bit int unsigned short hs, he, hm; unsigned int x, xs, xe, xm; int hes; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) { // Nothing to convert (e.g., imag part of pure real) return 0; } while( numel-- ) { x = *xp++; if( (x & 0x7FFFFFFFu) == 0 ) { // Signed zero *hp++ = (unsigned short) (x >> 16); // Return the signed zero } else { // Not zero xs = x & 0x80000000u; // Pick off sign bit xe = x & 0x7F800000u; // Pick off exponent bits xm = x & 0x007FFFFFu; // Pick off mantissa bits if( xe == 0 ) { // Denormal will underflow, return a signed zero *hp++ = (unsigned short) (xs >> 16); } else if( xe == 0x7F800000u ) { // Inf or NaN (all the exponent bits are set) if( xm == 0 ) { // If mantissa is zero ... *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else { *hp++ = (unsigned short) 0xFE00u; // NaN, only 1st mantissa bit set } } else { // Normalized number hs = (unsigned short) (xs >> 16); // Sign bit hes = ((int)(xe >> 23)) - 127 + 15; // Exponent unbias the single, then bias the halfp if( hes >= 0x1F ) { // Overflow *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else if( hes <= 0 ) { // Underflow if( (14 - hes) > 24 ) { // Mantissa shifted all the way off & no rounding possibility hm = (unsigned short) 0u; // Set mantissa to zero } else { xm |= 0x00800000u; // Add the hidden leading bit hm = (unsigned short) (xm >> (14 - hes)); // Mantissa if( (xm >> (13 - hes)) & 0x00000001u ) // Check for rounding hm += (unsigned short) 1u; // Round, might overflow into exp bit, but this is OK } *hp++ = (hs | hm); // Combine sign bit and mantissa bits, biased exponent is zero } else { he = (unsigned short) (hes << 10); // Exponent hm = (unsigned short) (xm >> 13); // Mantissa if( xm & 0x00001000u ) // Check for rounding *hp++ = (hs | he | hm) + (unsigned short) 1u; // Round, might overflow to inf, this is OK else *hp++ = (hs | he | hm); // No rounding } } } } return 0; } #pragma CTC ENDSKIP // Inputs: 12 HLS_FP17 after icvt // Outputs: 1 HLS_FP17 after Interplolation void HLS_CDP_lookup_lut ( vFp32Type square_sum, uint16_t lut_upper_index, bool le, // True: linear_exp table bool exp_mode, // Only for linear_exp table int16_t* lut, // LUT table uint64_t lut_start, uint64_t lut_end, int16_t slope_uflow_scale, // It's accutally signed value int16_t slope_oflow_scale, int16_t index_offset, int8_t index_select, // Outputs bool & underflow, bool & overflow, bool & lut_hit, ac_channel<vFp17Type> & chn_result_fp17) { #if !ASSERT_WAR_CONSTRAIN // assert(density_end - pow(2, cdp_lut_lo_index_select_ + 8) == density_start); #endif // Variables for sub input_offset vFp32Type lut_start_fp32, lut_end_fp32; vFp32Type lut_sub_result_fp32; ac_channel<vFp32Type> chn_square_sum_fp32; ac_channel<vFp32Type> chn_lut_start_fp32, chn_lut_end_fp32; ac_channel<vFp32Type> chn_lut_sub_result_fp32; ac_channel<vFp17Type> chn_lut_sub_result_fp17; float lut_sub_result_float; float lut_shifted; uint16_t lut_offset; int32_t lut_index; ac_channel<vFp17Type> chn_lut_offset_fp17; // Varibales for underflow/overflow vFp16Type slope_fp16; ac_channel<vFp16Type> chn_slope_fp16; ac_channel<vFp17Type> chn_slope_fp17; ac_channel<vFp17Type> chn_lo_sub_result_fp17; ac_channel<vFp17Type> chn_mul_result_fp17; ac_channel<vFp17Type> chn_result_lut_underflow; ac_channel<vFp17Type> chn_result_lut_overflow; // Variables for Interpolation uint16_t result_0, result_1; vFp16Type result_0_fp16, result_1_fp16; ac_channel<vFp16Type> chn_result_0_fp16, chn_result_1_fp16; vFp32Type result_0_fp32, result_1_fp32; ac_channel<vFp32Type> chn_result_0_fp32, chn_result_1_fp32; ac_channel<vFp17Type> chn_result_0_fp17; ac_channel<vFp17Type> chn_result_1_fp17; // ac_channel<vFp17Type> chn_result_underflow_fp17; // ac_channel<vFp17Type> chn_result_overflow_fp17; ac_channel<vFp32Type> chn_L1_minus_L0_fp32; ac_channel<vFp17Type> chn_L1_minus_L0_fp17; ac_channel<vFp17Type> chn_result_lut_tmp; //-------------------------------------------- underflow = false; overflow = false; //exp_underflow = false; //exp_overflow = false; lut_hit = false; //-------------------------------------------- // 1. sub offset lut_start_fp32 = lut_start; chn_lut_start_fp32.write(lut_start_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_start_fp32, chn_lut_sub_result_fp32); lut_sub_result_fp32 = chn_lut_sub_result_fp32.read(); lut_sub_result_float = *(float *)(&lut_sub_result_fp32); // vFp32Type is actually integer type cslDebug((70, "lut_start=0x%x, lut_sub_result=0x%x\n", (uint32_t)lut_start_fp32, (uint32_t)lut_sub_result_fp32)); if(lut_sub_result_float <= 0 || std::isnan(lut_sub_result_float)) { underflow = true; } if (!underflow) { if (le && exp_mode) { // Log2. If lo_sub_result_float is 0, exp will be 0 uint32_t tmp_uint32 = *(uint32_t*)(&lut_sub_result_float); int32_t exp_raw = (tmp_uint32 >> 23) & 0xff; // 8bits //int32_t exp = (exp_raw == 0)? 0 : exp_raw - 127; int32_t exp = exp_raw - 127; lut_index = exp - index_offset; lut_offset = (tmp_uint32 >> 7) & 0xffff; if(lut_index < 0) { lut_offset >>= -lut_index; lut_index = 0; underflow = true; } else if (lut_index >= lut_upper_index) { overflow = true; } cslDebug((70, "exp=%d, index_offset=%d, lut_index=%d, lut_offset=%d\n", exp, index_offset, lut_index, lut_offset)); } else { // lo or (le && linear_mode) // To int and Shift using float of C++ // In RTL, HLS is not used in below code if(index_select >= 0) lut_shifted = lut_sub_result_float / pow(2, index_select); else lut_shifted = lut_sub_result_float * pow(2, -index_select); overflow = lut_shifted >= lut_upper_index; lut_index = lut_shifted; lut_offset = (lut_shifted - int32_t(lut_shifted)) * 0x10000; // 16 MSB bits of fraction cslDebug((70, "index_select=%d, lut_shifted=%f, lut_index=%d, lut_offset=%d\n", index_select, lut_shifted, lut_index, lut_offset)); } } // Convert Fraction from special INT16 to HLS_FP17 vU16Type lut_offset_u16 = lut_offset; ac_channel<vU16Type> chn_lut_offset_u16; chn_lut_offset_u16.write(lut_offset_u16); HLS_uint16_to_fp17(chn_lut_offset_u16, chn_lut_offset_fp17); //if ((underflow || (le&&exp_underflow))) { if (underflow) { result_0 = lut[0]; result_0_fp16 = result_0; chn_result_0_fp16.write(result_0_fp16); cslDebug((70, "L0=0x%x\n", result_0)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); slope_fp16 = (int16_t)slope_uflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 if(le && exp_mode) { float offset; #pragma CTC SKIP if(index_offset <= -127) { offset = 0; } #pragma CTC ENDSKIP else { offset = pow(2, index_offset); } ac_channel<vFp32Type> chn_offset, chn_offset_adj; chn_offset.write(*(vFp32Type *)(&offset)); chn_lut_start_fp32.write(lut_start_fp32); HLS_fp32_add(chn_lut_start_fp32, chn_offset, chn_offset_adj); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_offset_adj, chn_lut_sub_result_fp32); } else { chn_lut_sub_result_fp32.write(lut_sub_result_fp32); } HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_0_fp17, chn_result_fp17); } //else if ((overflow || (le&&exp_overflow))) { else if (overflow) { result_1 = lut[lut_upper_index]; result_1_fp16 = result_1; chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L1=0x%x\n", result_1)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_1_fp16, chn_result_1_fp17); slope_fp16 = (int16_t)slope_oflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 lut_end_fp32 = lut_end; chn_lut_end_fp32.write(lut_end_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_end_fp32, chn_lut_sub_result_fp32); HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_1_fp17, chn_result_fp17); } else { result_0 = lut[lut_index]; result_1 = lut[lut_index+1]; result_0_fp16 = result_0; result_1_fp16 = result_1; chn_result_0_fp16.write(result_0_fp16); chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L0=0x%x, L1=0x%x\n", result_0, result_1)); // Convert HLS_FP16 to HLS_FP32 HLS_fp16_to_fp32(chn_result_0_fp16, chn_result_0_fp32); HLS_fp16_to_fp32(chn_result_1_fp16, chn_result_1_fp32); // Convert result_lo_0 of HLS FP16 to HLS_FP17 chn_result_0_fp16.write(result_0_fp16); HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); // Interpolation HLS_fp32_sub(chn_result_1_fp32, chn_result_0_fp32, chn_L1_minus_L0_fp32); //vFp32Type L1_minus_L0_fp32 = chn_L1_minus_L0_fp32.read(); //cslDebug((70,"L1_minus_L0_fp32=0x%x\n", L1_minus_L0_fp32)); //chn_L1_minus_L0_fp32.write(L1_minus_L0_fp32); HLS_fp32_to_fp17(chn_L1_minus_L0_fp32, chn_L1_minus_L0_fp17); HLS_fp17_mul(chn_L1_minus_L0_fp17, chn_lut_offset_fp17, chn_result_lut_tmp); HLS_fp17_add(chn_result_lut_tmp, chn_result_0_fp17, chn_result_fp17); lut_hit = true; /* float L0_float, L1_float, L1_minus_L0_float, result_float; half2single(&L0_float,&result_0_fp16, 1); cslDebug((70,"L0: %f(0x%x)\n", L0_float, *(int *)(&L0_float) )); half2single(&L1_float,&result_1_fp16, 1); cslDebug((70,"L1: %f(0x%x)\n", L1_float, *(int *)(&L1_float) )); L1_minus_L0_float = L1_float - L0_float; cslDebug((70,"L1-L1: %f(0x%x)\n", L1_minus_L0_float, *(int *)(&L1_minus_L0_float) )); result_float = L0_float + L1_minus_L0_float * lut_offset; cslDebug((70,"result: %f(0x%x)\n", result_float, *(int *)(&result_float) ));*/ } } void HLS_CDP_lookup_fp16 ( int16_t *data_in, // 12 * fp17 int16_t *le_lut, int16_t *lo_lut, // Configurations uint16_t normalz_len, uint16_t raw_method, bool lut_uflow_priority, bool lut_oflow_priority, bool lut_hybrid_priority, uint64_t le_start, int16_t le_index_offset, int8_t le_index_select, uint64_t le_end, uint64_t lo_start, int8_t lo_index_select, uint64_t lo_end, uint16_t datin_offset, uint16_t datin_scale, uint8_t datin_shifter, uint32_t datout_offset, uint16_t datout_scale, uint8_t datout_shifter, int16_t le_slope_uflow_scale, int16_t le_slope_oflow_scale, int16_t lo_slope_uflow_scale, int16_t lo_slope_oflow_scale, bool sqsum_bypass, bool mul_bypass, int16_t *normalz_out, uint32_t *lut_u_flow, uint32_t *lut_o_flow, uint32_t *lut_le_hit, uint32_t *lut_lo_hit, uint32_t *lut_hybrid_hit) // 16bits { int i; // Outputs bool le_underflow; bool le_overflow; //bool exp_underflow; //bool exp_overflow; bool lo_underflow; bool lo_overflow; bool le_hit; bool lo_hit; // Variables int32_t icvt_data_out[12]; ac_channel<vFp32Type> fp17tofp32_out[12]; ac_channel<vFp32Type> square_array[12]; //ac_channel<vFp32Type> square_sum; vFp32Type square_result[12]; // Outputs of lut tables ac_channel<vFp17Type> chn_result_le_fp17; ac_channel<vFp17Type> chn_result_lo_fp17; // ac_channel<vFp17Type> chn_result_fp17; ac_channel<vFp17Type> chn_result_to_ocvt_fp17; ac_channel<vFp17Type> chn_ocvt_out_fp17; #if 0 // Initialization le_underflow = false; le_overflow = false; exp_underflow = false; exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; #endif vFp32Type icvt_data_out_fp32[12]; float tmp[12], din_offset, din_scale; half2single(&din_offset, &datin_offset, 1); half2single(&din_scale, &datin_scale, 1); cslDebug((70, "Data before input converter(float)\n")); for(i=0; i<12; i++) { half2single(&tmp[i], &data_in[i], 1); cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); cslDebug((70, "Data after square(float)\n")); for(i=0; i<12; i++) { tmp[i] = tmp[i] * tmp[i]; cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); for(i=0; i<12; i++) { //***** Input Convertor (FP16->FP17) ****** cdp_icvt_hls(&data_in[i], datin_offset, datin_scale, datin_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &icvt_data_out[i]);
//***** Convert FP17 to FP32 ****** ac_channel<vFp17Type> chn_a; chn_a.write(icvt_data_out[i]); HLS_fp17_to_fp32(chn_a, fp17tofp32_out[i]); icvt_data_out_fp32[i] = fp17tofp32_out[i].read(); ac_channel<vFp32Type> chn_b, chn_c; chn_b.write(icvt_data_out_fp32[i]); chn_c.write(icvt_data_out_fp32[i]); if(sqsum_bypass) { square_result[i] = icvt_data_out_fp32[i]; } else { HLS_fp32_mul(chn_b, chn_c, square_array[i]); // HLS_FP32 mul square_result[i] = square_array[i].read(); //keep data to re-write the square_array later } } // cslDebug((70, "Data after input convertor(FP17):\n")); // for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out[i]) )); // cslDebug((70, "\n")); cslDebug((70, "Data after input convertor(FP32):\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out_fp32[i]) )); cslDebug((70, "\n")); cslDebug((70, "Data after square:\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&square_result[i]) )); cslDebug((70, "\n")); //***** Per Element ****** for (i=0; i<4; i++) { le_underflow = false; le_overflow = false; //exp_underflow = false; //exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; //re-write square_array in each iteration since it is empty after read for(int j=0; j<12; j++) square_array[j].write(square_result[j]); //***** Sum ****** vFp32Type square_sum_result; if(sqsum_bypass) { square_sum_result = square_array[i+4].read(); } else { ac_channel<vFp32Type> square_sum_1, square_sum_2; HLS_fp32_add(square_array[i+3], square_array[i+5], square_sum_1); //3 + 5 HLS_fp32_add(square_sum_1, square_array[i+4], square_sum_2); //sum3 = (3 + 5) + 4 ac_channel<vFp32Type> square_sum_3, square_sum_4; if(normalz_len > 0) //5+ elements { HLS_fp32_add(square_array[i+2], square_array[i+6], square_sum_3); //2 + 6 HLS_fp32_add(square_sum_2, square_sum_3, square_sum_4); //sum5 = sum3 + (2 + 6) } ac_channel<vFp32Type> square_sum_5, square_sum_6; if(normalz_len > 1) //7+ elements { HLS_fp32_add(square_array[i+1], square_array[i+7], square_sum_5); //1 + 7 HLS_fp32_add(square_sum_4, square_sum_5, square_sum_6); //sum7 = sum5 + (1 + 7) } ac_channel<vFp32Type> square_sum_7, square_sum_8; if(normalz_len > 2) //9 elements { HLS_fp32_add(square_array[i+0], square_array[i+8], square_sum_7); //1 + 7 HLS_fp32_add(square_sum_6, square_sum_7, square_sum_8); //sum9 = sum7 + (0 + 8) } switch(normalz_len) { case 0: square_sum_result = square_sum_2.read(); break; case 1: square_sum_result = square_sum_4.read(); break; case 2: square_sum_result = square_sum_6.read(); break; case 3: square_sum_result = square_sum_8.read(); break; #pragma CTC SKIP default: break; #pragma CTC ENDSKIP } } cslDebug((70, "Square sum: %x\n", *(int *)(&square_sum_result) )); // Look up Raw table if(NVDLA_CDP_S_LUT_CFG_0_LUT_LE_FUNCTION_EXPONENT == raw_method) { //raw lut is exponential cslDebug((70, "Lookup exp table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, true, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } else { // raw lut is linear cslDebug((70, "Lookup lin table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, false, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } cslDebug((70, "Lookup lo table\n")); // Look up LO(Linear Only) table HLS_CDP_lookup_lut(square_sum_result, 256, false, false, lo_lut, lo_start, lo_end, lo_slope_uflow_scale, lo_slope_oflow_scale, 0, lo_index_select, lo_underflow, lo_overflow, lo_hit, chn_result_lo_fp17); vFp17Type result_le = chn_result_le_fp17.read(); vFp17Type result_lo = chn_result_lo_fp17.read(); vFp17Type result_out; // Select result between RAW table and Density Table if(le_underflow && lo_underflow) { result_out = lut_uflow_priority? result_lo : result_le; (*lut_u_flow)++; } else if(le_overflow && lo_overflow) { result_out = lut_oflow_priority? result_lo : result_le; (*lut_o_flow)++; } else { if(le_hit ^ lo_hit) { result_out = le_hit? result_le : result_lo; if(le_hit) { (*lut_le_hit)++; } else { (*lut_lo_hit)++; } } else { if(lut_hybrid_priority) result_out = result_lo; else result_out = result_le; (*lut_hybrid_hit)++; } } cslDebug((70, "le:%x, lo:%x, out:%x\n" , *(int *)(&result_le), *(int *)(&result_lo), *(int *)(&result_out) )); if(mul_bypass) { float icvt_data_out_float = *(float *)&icvt_data_out_fp32[i+4]; if(std::isnan(icvt_data_out_float)) { chn_result_to_ocvt_fp17.write(icvt_data_out[i+4]); } else { chn_result_to_ocvt_fp17.write(result_out); } } else { ac_channel<vFp17Type> chn_result_fp17, chn_icvt_data_out_fp17; chn_result_fp17.write(result_out); vFp17Type icvt_data_out_fp17 = icvt_data_out[i+4]; chn_icvt_data_out_fp17.write(icvt_data_out_fp17); HLS_fp17_mul(chn_icvt_data_out_fp17, chn_result_fp17, chn_result_to_ocvt_fp17); } // Output Converter int64_t ocvt_data_in = chn_result_to_ocvt_fp17.read(); cslDebug((70, "ocvt_data_in:%x\n", (int)ocvt_data_in)); uint8_t flag; cdp_ocvt_hls(&ocvt_data_in, datout_offset, datout_scale, datout_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &normalz_out[i], &flag); } }
// ================================================================ // NVDLA Open Source Project // // Copyright(c) 2016 - 2017 NVIDIA Corporation. Licensed under the // NVDLA Open Hardware License; Check "LICENSE" which comes with // this distribution for more information. // ================================================================ // File Name: cdp_hls_wrapper.cpp #include "log.h" #include "ac_int.h" #include "ac_channel.h" #include "log.h" #include <systemc.h> #include "arnvdla.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "vlibs.h" #include "cdp_hls_wrapper.h" #pragma CTC SKIP int half2single(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) source; // Type pun input as an unsigned 16-bit int unsigned int *xp = (unsigned int *) target; // Type pun output as an unsigned 32-bit int unsigned short h, hs, he, hm; unsigned int xs, xe, xm; int xes; int e; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) // Nothing to convert (e.g., imag part of pure real) return 0; while( numel-- ) { h = *hp++; if( (h & 0x7FFFu) == 0 ) { // Signed zero *xp++ = ((unsigned int) h) << 16; // Return the signed zero } else { // Not zero hs = h & 0x8000u; // Pick off sign bit he = h & 0x7C00u; // Pick off exponent bits hm = h & 0x03FFu; // Pick off mantissa bits if( he == 0 ) { // Denormal will convert to normalized e = -1; // The following loop figures out how much extra to adjust the exponent do { e++; hm <<= 1; } while( (hm & 0x0400u) == 0 ); // Shift until leading bit overflows into exponent bit xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127 - e; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) (hm & 0x03FFu)) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } else if( he == 0x7C00u ) { // Inf or NaN (all the exponent bits are set) if( hm == 0 ) { // If mantissa is zero ... *xp++ = (((unsigned int) hs) << 16) | ((unsigned int) 0x7F800000u); // Signed Inf } else { *xp++ = (unsigned int) 0xFFC00000u; // NaN, only 1st mantissa bit set } } else { // Normalized number xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) hm) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } } } return 0; } int single2half(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) target; // Type pun output as an unsigned 16-bit int unsigned int *xp = (unsigned int *) source; // Type pun input as an unsigned 32-bit int unsigned short hs, he, hm; unsigned int x, xs, xe, xm; int hes; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) { // Nothing to convert (e.g., imag part of pure real) return 0; } while( numel-- ) { x = *xp++; if( (x & 0x7FFFFFFFu) == 0 ) { // Signed zero *hp++ = (unsigned short) (x >> 16); // Return the signed zero } else { // Not zero xs = x & 0x80000000u; // Pick off sign bit xe = x & 0x7F800000u; // Pick off exponent bits xm = x & 0x007FFFFFu; // Pick off mantissa bits if( xe == 0 ) { // Denormal will underflow, return a signed zero *hp++ = (unsigned short) (xs >> 16); } else if( xe == 0x7F800000u ) { // Inf or NaN (all the exponent bits are set) if( xm == 0 ) { // If mantissa is zero ... *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else { *hp++ = (unsigned short) 0xFE00u; // NaN, only 1st mantissa bit set } } else { // Normalized number hs = (unsigned short) (xs >> 16); // Sign bit hes = ((int)(xe >> 23)) - 127 + 15; // Exponent unbias the single, then bias the halfp if( hes >= 0x1F ) { // Overflow *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else if( hes <= 0 ) { // Underflow if( (14 - hes) > 24 ) { // Mantissa shifted all the way off & no rounding possibility hm = (unsigned short) 0u; // Set mantissa to zero } else { xm |= 0x00800000u; // Add the hidden leading bit hm = (unsigned short) (xm >> (14 - hes)); // Mantissa if( (xm >> (13 - hes)) & 0x00000001u ) // Check for rounding hm += (unsigned short) 1u; // Round, might overflow into exp bit, but this is OK } *hp++ = (hs | hm); // Combine sign bit and mantissa bits, biased exponent is zero } else { he = (unsigned short) (hes << 10); // Exponent hm = (unsigned short) (xm >> 13); // Mantissa if( xm & 0x00001000u ) // Check for rounding *hp++ = (hs | he | hm) + (unsigned short) 1u; // Round, might overflow to inf, this is OK else *hp++ = (hs | he | hm); // No rounding } } } } return 0; } #pragma CTC ENDSKIP // Inputs: 12 HLS_FP17 after icvt // Outputs: 1 HLS_FP17 after Interplolation void HLS_CDP_lookup_lut ( vFp32Type square_sum, uint16_t lut_upper_index, bool le, // True: linear_exp table bool exp_mode, // Only for linear_exp table int16_t* lut, // LUT table uint64_t lut_start, uint64_t lut_end, int16_t slope_uflow_scale, // It's accutally signed value int16_t slope_oflow_scale, int16_t index_offset, int8_t index_select, // Outputs bool & underflow, bool & overflow, bool & lut_hit, ac_channel<vFp17Type> & chn_result_fp17) { #if !ASSERT_WAR_CONSTRAIN // assert(density_end - pow(2, cdp_lut_lo_index_select_ + 8) == density_start); #endif // Variables for sub input_offset vFp32Type lut_start_fp32, lut_end_fp32; vFp32Type lut_sub_result_fp32; ac_channel<vFp32Type> chn_square_sum_fp32; ac_channel<vFp32Type> chn_lut_start_fp32, chn_lut_end_fp32; ac_channel<vFp32Type> chn_lut_sub_result_fp32; ac_channel<vFp17Type> chn_lut_sub_result_fp17; float lut_sub_result_float; float lut_shifted; uint16_t lut_offset; int32_t lut_index; ac_channel<vFp17Type> chn_lut_offset_fp17; // Varibales for underflow/overflow vFp16Type slope_fp16; ac_channel<vFp16Type> chn_slope_fp16; ac_channel<vFp17Type> chn_slope_fp17; ac_channel<vFp17Type> chn_lo_sub_result_fp17; ac_channel<vFp17Type> chn_mul_result_fp17; ac_channel<vFp17Type> chn_result_lut_underflow; ac_channel<vFp17Type> chn_result_lut_overflow; // Variables for Interpolation uint16_t result_0, result_1; vFp16Type result_0_fp16, result_1_fp16; ac_channel<vFp16Type> chn_result_0_fp16, chn_result_1_fp16; vFp32Type result_0_fp32, result_1_fp32; ac_channel<vFp32Type> chn_result_0_fp32, chn_result_1_fp32; ac_channel<vFp17Type> chn_result_0_fp17; ac_channel<vFp17Type> chn_result_1_fp17; // ac_channel<vFp17Type> chn_result_underflow_fp17; // ac_channel<vFp17Type> chn_result_overflow_fp17; ac_channel<vFp32Type> chn_L1_minus_L0_fp32; ac_channel<vFp17Type> chn_L1_minus_L0_fp17; ac_channel<vFp17Type> chn_result_lut_tmp; //-------------------------------------------- underflow = false; overflow = false; //exp_underflow = false; //exp_overflow = false; lut_hit = false; //-------------------------------------------- // 1. sub offset lut_start_fp32 = lut_start; chn_lut_start_fp32.write(lut_start_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_start_fp32, chn_lut_sub_result_fp32); lut_sub_result_fp32 = chn_lut_sub_result_fp32.read(); lut_sub_result_float = *(float *)(&lut_sub_result_fp32); // vFp32Type is actually integer type cslDebug((70, "lut_start=0x%x, lut_sub_result=0x%x\n", (uint32_t)lut_start_fp32, (uint32_t)lut_sub_result_fp32)); if(lut_sub_result_float <= 0 || std::isnan(lut_sub_result_float)) { underflow = true; } if (!underflow) { if (le && exp_mode) { // Log2. If lo_sub_result_float is 0, exp will be 0 uint32_t tmp_uint32 = *(uint32_t*)(&lut_sub_result_float); int32_t exp_raw = (tmp_uint32 >> 23) & 0xff; // 8bits //int32_t exp = (exp_raw == 0)? 0 : exp_raw - 127; int32_t exp = exp_raw - 127; lut_index = exp - index_offset; lut_offset = (tmp_uint32 >> 7) & 0xffff; if(lut_index < 0) { lut_offset >>= -lut_index; lut_index = 0; underflow = true; } else if (lut_index >= lut_upper_index) { overflow = true; } cslDebug((70, "exp=%d, index_offset=%d, lut_index=%d, lut_offset=%d\n", exp, index_offset, lut_index, lut_offset)); } else { // lo or (le && linear_mode) // To int and Shift using float of C++ // In RTL, HLS is not used in below code if(index_select >= 0) lut_shifted = lut_sub_result_float / pow(2, index_select); else lut_shifted = lut_sub_result_float * pow(2, -index_select); overflow = lut_shifted >= lut_upper_index; lut_index = lut_shifted; lut_offset = (lut_shifted - int32_t(lut_shifted)) * 0x10000; // 16 MSB bits of fraction cslDebug((70, "index_select=%d, lut_shifted=%f, lut_index=%d, lut_offset=%d\n", index_select, lut_shifted, lut_index, lut_offset)); } } // Convert Fraction from special INT16 to HLS_FP17 vU16Type lut_offset_u16 = lut_offset; ac_channel<vU16Type> chn_lut_offset_u16; chn_lut_offset_u16.write(lut_offset_u16); HLS_uint16_to_fp17(chn_lut_offset_u16, chn_lut_offset_fp17); //if ((underflow || (le&&exp_underflow))) { if (underflow) { result_0 = lut[0]; result_0_fp16 = result_0; chn_result_0_fp16.write(result_0_fp16); cslDebug((70, "L0=0x%x\n", result_0)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); slope_fp16 = (int16_t)slope_uflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 if(le && exp_mode) { float offset; #pragma CTC SKIP if(index_offset <= -127) { offset = 0; } #pragma CTC ENDSKIP else { offset = pow(2, index_offset); } ac_channel<vFp32Type> chn_offset, chn_offset_adj; chn_offset.write(*(vFp32Type *)(&offset)); chn_lut_start_fp32.write(lut_start_fp32); HLS_fp32_add(chn_lut_start_fp32, chn_offset, chn_offset_adj); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_offset_adj, chn_lut_sub_result_fp32); } else { chn_lut_sub_result_fp32.write(lut_sub_result_fp32); } HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_0_fp17, chn_result_fp17); } //else if ((overflow || (le&&exp_overflow))) { else if (overflow) { result_1 = lut[lut_upper_index]; result_1_fp16 = result_1; chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L1=0x%x\n", result_1)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_1_fp16, chn_result_1_fp17); slope_fp16 = (int16_t)slope_oflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 lut_end_fp32 = lut_end; chn_lut_end_fp32.write(lut_end_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_end_fp32, chn_lut_sub_result_fp32); HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_1_fp17, chn_result_fp17); } else { result_0 = lut[lut_index]; result_1 = lut[lut_index+1]; result_0_fp16 = result_0; result_1_fp16 = result_1; chn_result_0_fp16.write(result_0_fp16); chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L0=0x%x, L1=0x%x\n", result_0, result_1)); // Convert HLS_FP16 to HLS_FP32 HLS_fp16_to_fp32(chn_result_0_fp16, chn_result_0_fp32); HLS_fp16_to_fp32(chn_result_1_fp16, chn_result_1_fp32); // Convert result_lo_0 of HLS FP16 to HLS_FP17 chn_result_0_fp16.write(result_0_fp16); HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); // Interpolation HLS_fp32_sub(chn_result_1_fp32, chn_result_0_fp32, chn_L1_minus_L0_fp32); //vFp32Type L1_minus_L0_fp32 = chn_L1_minus_L0_fp32.read(); //cslDebug((70,"L1_minus_L0_fp32=0x%x\n", L1_minus_L0_fp32)); //chn_L1_minus_L0_fp32.write(L1_minus_L0_fp32); HLS_fp32_to_fp17(chn_L1_minus_L0_fp32, chn_L1_minus_L0_fp17); HLS_fp17_mul(chn_L1_minus_L0_fp17, chn_lut_offset_fp17, chn_result_lut_tmp); HLS_fp17_add(chn_result_lut_tmp, chn_result_0_fp17, chn_result_fp17); lut_hit = true; /* float L0_float, L1_float, L1_minus_L0_float, result_float; half2single(&L0_float,&result_0_fp16, 1); cslDebug((70,"L0: %f(0x%x)\n", L0_float, *(int *)(&L0_float) )); half2single(&L1_float,&result_1_fp16, 1); cslDebug((70,"L1: %f(0x%x)\n", L1_float, *(int *)(&L1_float) )); L1_minus_L0_float = L1_float - L0_float; cslDebug((70,"L1-L1: %f(0x%x)\n", L1_minus_L0_float, *(int *)(&L1_minus_L0_float) )); result_float = L0_float + L1_minus_L0_float * lut_offset; cslDebug((70,"result: %f(0x%x)\n", result_float, *(int *)(&result_float) ));*/ } } void HLS_CDP_lookup_fp16 ( int16_t *data_in, // 12 * fp17 int16_t *le_lut, int16_t *lo_lut, // Configurations uint16_t normalz_len, uint16_t raw_method, bool lut_uflow_priority, bool lut_oflow_priority, bool lut_hybrid_priority, uint64_t le_start, int16_t le_index_offset, int8_t le_index_select, uint64_t le_end, uint64_t lo_start, int8_t lo_index_select, uint64_t lo_end, uint16_t datin_offset, uint16_t datin_scale, uint8_t datin_shifter, uint32_t datout_offset, uint16_t datout_scale, uint8_t datout_shifter, int16_t le_slope_uflow_scale, int16_t le_slope_oflow_scale, int16_t lo_slope_uflow_scale, int16_t lo_slope_oflow_scale, bool sqsum_bypass, bool mul_bypass, int16_t *normalz_out, uint32_t *lut_u_flow, uint32_t *lut_o_flow, uint32_t *lut_le_hit, uint32_t *lut_lo_hit, uint32_t *lut_hybrid_hit) // 16bits { int i; // Outputs bool le_underflow; bool le_overflow; //bool exp_underflow; //bool exp_overflow; bool lo_underflow; bool lo_overflow; bool le_hit; bool lo_hit; // Variables int32_t icvt_data_out[12]; ac_channel<vFp32Type> fp17tofp32_out[12]; ac_channel<vFp32Type> square_array[12]; //ac_channel<vFp32Type> square_sum; vFp32Type square_result[12]; // Outputs of lut tables ac_channel<vFp17Type> chn_result_le_fp17; ac_channel<vFp17Type> chn_result_lo_fp17; // ac_channel<vFp17Type> chn_result_fp17; ac_channel<vFp17Type> chn_result_to_ocvt_fp17; ac_channel<vFp17Type> chn_ocvt_out_fp17; #if 0 // Initialization le_underflow = false; le_overflow = false; exp_underflow = false; exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; #endif vFp32Type icvt_data_out_fp32[12]; float tmp[12], din_offset, din_scale; half2single(&din_offset, &datin_offset, 1); half2single(&din_scale, &datin_scale, 1); cslDebug((70, "Data before input converter(float)\n")); for(i=0; i<12; i++) { half2single(&tmp[i], &data_in[i], 1); cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); cslDebug((70, "Data after square(float)\n")); for(i=0; i<12; i++) { tmp[i] = tmp[i] * tmp[i]; cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); for(i=0; i<12; i++) { //***** Input Convertor (FP16->FP17) ****** cdp_icvt_hls(&data_in[i], datin_offset, datin_scale, datin_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &icvt_data_out[i]);
//***** Convert FP17 to FP32 ****** ac_channel<vFp17Type> chn_a; chn_a.write(icvt_data_out[i]); HLS_fp17_to_fp32(chn_a, fp17tofp32_out[i]); icvt_data_out_fp32[i] = fp17tofp32_out[i].read(); ac_channel<vFp32Type> chn_b, chn_c; chn_b.write(icvt_data_out_fp32[i]); chn_c.write(icvt_data_out_fp32[i]); if(sqsum_bypass) { square_result[i] = icvt_data_out_fp32[i]; } else { HLS_fp32_mul(chn_b, chn_c, square_array[i]); // HLS_FP32 mul square_result[i] = square_array[i].read(); //keep data to re-write the square_array later } } // cslDebug((70, "Data after input convertor(FP17):\n")); // for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out[i]) )); // cslDebug((70, "\n")); cslDebug((70, "Data after input convertor(FP32):\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out_fp32[i]) )); cslDebug((70, "\n")); cslDebug((70, "Data after square:\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&square_result[i]) )); cslDebug((70, "\n")); //***** Per Element ****** for (i=0; i<4; i++) { le_underflow = false; le_overflow = false; //exp_underflow = false; //exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; //re-write square_array in each iteration since it is empty after read for(int j=0; j<12; j++) square_array[j].write(square_result[j]); //***** Sum ****** vFp32Type square_sum_result; if(sqsum_bypass) { square_sum_result = square_array[i+4].read(); } else { ac_channel<vFp32Type> square_sum_1, square_sum_2; HLS_fp32_add(square_array[i+3], square_array[i+5], square_sum_1); //3 + 5 HLS_fp32_add(square_sum_1, square_array[i+4], square_sum_2); //sum3 = (3 + 5) + 4 ac_channel<vFp32Type> square_sum_3, square_sum_4; if(normalz_len > 0) //5+ elements { HLS_fp32_add(square_array[i+2], square_array[i+6], square_sum_3); //2 + 6 HLS_fp32_add(square_sum_2, square_sum_3, square_sum_4); //sum5 = sum3 + (2 + 6) } ac_channel<vFp32Type> square_sum_5, square_sum_6; if(normalz_len > 1) //7+ elements { HLS_fp32_add(square_array[i+1], square_array[i+7], square_sum_5); //1 + 7 HLS_fp32_add(square_sum_4, square_sum_5, square_sum_6); //sum7 = sum5 + (1 + 7) } ac_channel<vFp32Type> square_sum_7, square_sum_8; if(normalz_len > 2) //9 elements { HLS_fp32_add(square_array[i+0], square_array[i+8], square_sum_7); //1 + 7 HLS_fp32_add(square_sum_6, square_sum_7, square_sum_8); //sum9 = sum7 + (0 + 8) } switch(normalz_len) { case 0: square_sum_result = square_sum_2.read(); break; case 1: square_sum_result = square_sum_4.read(); break; case 2: square_sum_result = square_sum_6.read(); break; case 3: square_sum_result = square_sum_8.read(); break; #pragma CTC SKIP default: break; #pragma CTC ENDSKIP } } cslDebug((70, "Square sum: %x\n", *(int *)(&square_sum_result) )); // Look up Raw table if(NVDLA_CDP_S_LUT_CFG_0_LUT_LE_FUNCTION_EXPONENT == raw_method) { //raw lut is exponential cslDebug((70, "Lookup exp table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, true, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } else { // raw lut is linear cslDebug((70, "Lookup lin table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, false, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } cslDebug((70, "Lookup lo table\n")); // Look up LO(Linear Only) table HLS_CDP_lookup_lut(square_sum_result, 256, false, false, lo_lut, lo_start, lo_end, lo_slope_uflow_scale, lo_slope_oflow_scale, 0, lo_index_select, lo_underflow, lo_overflow, lo_hit, chn_result_lo_fp17); vFp17Type result_le = chn_result_le_fp17.read(); vFp17Type result_lo = chn_result_lo_fp17.read(); vFp17Type result_out; // Select result between RAW table and Density Table if(le_underflow && lo_underflow) { result_out = lut_uflow_priority? result_lo : result_le; (*lut_u_flow)++; } else if(le_overflow && lo_overflow) { result_out = lut_oflow_priority? result_lo : result_le; (*lut_o_flow)++; } else { if(le_hit ^ lo_hit) { result_out = le_hit? result_le : result_lo; if(le_hit) { (*lut_le_hit)++; } else { (*lut_lo_hit)++; } } else { if(lut_hybrid_priority) result_out = result_lo; else result_out = result_le; (*lut_hybrid_hit)++; } } cslDebug((70, "le:%x, lo:%x, out:%x\n" , *(int *)(&result_le), *(int *)(&result_lo), *(int *)(&result_out) )); if(mul_bypass) { float icvt_data_out_float = *(float *)&icvt_data_out_fp32[i+4]; if(std::isnan(icvt_data_out_float)) { chn_result_to_ocvt_fp17.write(icvt_data_out[i+4]); } else { chn_result_to_ocvt_fp17.write(result_out); } } else { ac_channel<vFp17Type> chn_result_fp17, chn_icvt_data_out_fp17; chn_result_fp17.write(result_out); vFp17Type icvt_data_out_fp17 = icvt_data_out[i+4]; chn_icvt_data_out_fp17.write(icvt_data_out_fp17); HLS_fp17_mul(chn_icvt_data_out_fp17, chn_result_fp17, chn_result_to_ocvt_fp17); } // Output Converter int64_t ocvt_data_in = chn_result_to_ocvt_fp17.read(); cslDebug((70, "ocvt_data_in:%x\n", (int)ocvt_data_in)); uint8_t flag; cdp_ocvt_hls(&ocvt_data_in, datout_offset, datout_scale, datout_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &normalz_out[i], &flag); } }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you 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. *****************************************************************************/ /***************************************************************************** numgen.cpp -- The implementation for the numgen module. Original Author: Amit Rao, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "numgen.h" // definition of the `generate' method void numgen::generate() { static double a = 134.56; static double b = 98.24; a -= 1.5; b -= 2.8; out1.write(a); out2.write(b); } // end of `generate' method
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // 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 PACKET_H #define PACKET_H #include <vector> using std::vector; #include <systemc.h> #include <tlm.h> using namespace sc_core; class packet { public: short cmd; int addr; vector<char> data; }; //------------------------------------------------------------------------------ // Begin UVMC-specific code #include "uvmc.h" using namespace uvmc; UVMC_UTILS_3 (packet,cmd,addr,data) #endif // PACKET_H
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
#include <systemc.h> #include "HammingRegister.h" void HamReg::ham_main_din(){ din.read(); } void HamReg::ham_main_codedin(){ coded_din.read(); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_multiplication_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_multiplication_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_multiplication_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_multiplication_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/* Copyright (c) 2015 Convey Computer Corporation * * This file is part of the OpenHT toolset located at: * * https://github.com/TonyBrewer/OpenHT * * Use and distribution licensed under the BSD 3-clause license. * See the LICENSE file for the complete license text. */ // Synthesize.cpp // ////////////////////////////////////////////////////////////////////// #include "Htv.h" #include "HtvArgs.h" #include "HtvDesign.h" #include "HtvFileBkup.h" void CHtvDesign::GenVerilog() { if (GetErrorCnt() != 0) { ParseMsg(PARSE_ERROR, "unable to generate verilog due to previous errors"); ErrorExit(); } CHtvIdentTblIter topHierIter(GetTopHier()->GetIdentTbl()); for (topHierIter.Begin(); !topHierIter.End(); topHierIter++) { if (!topHierIter->IsModule() || !topHierIter->IsMethodDefined()) continue; CHtvIdent *pModule = topHierIter->GetThis(); CHtvIdentTblIter moduleIter(pModule->GetIdentTbl()); // insert function memory initialization statements into caller for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (!moduleIter->IsFunction() || moduleIter->IsMethod() || moduleIter->GetName() == pModule->GetName()) continue; CHtvIdent *pFunc = moduleIter->GetThis(); if (pFunc->GetCallerListCnt() == 0 || pFunc->GetMemInitStatements() == 0) continue; // sc_memory functions must be called from a single method bool bMultiple; CHtvIdent *pMethod = FindUniqueAccessMethod(&pFunc->GetCallerList(), bMultiple); if (bMultiple) ParseMsg(PARSE_FATAL, pFunc->GetLineInfo(), "function with sc_memory variables called from more than one method"); pMethod->InsertStatementList(pFunc->GetMemInitStatements()); } // find global variables used within functions for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (!moduleIter->IsFunction() || moduleIter->IsMethod() || moduleIter->GetName() == pModule->GetName() || moduleIter->IsGlobalReadRef()) continue; FindGlobalRefSet(moduleIter->GetThis(), (CHtvStatement *)moduleIter->GetStatementList()); moduleIter->SetIsGlobalReadRef(true); } // Generate logic blocks if (g_htvArgs.GetXilinxFdPrims()) { for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (!moduleIter->IsMethod()) continue; FindXilinxFdPrims(moduleIter->GetThis(), 0); } } for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (!moduleIter->IsMethod()) continue; FindWriteRefSets(moduleIter->GetThis()); } GenModuleHeader(topHierIter()); // Generate global functions used in module CHtvIdentTblIter topHierIter2(GetTopHier()->GetIdentTbl()); for (topHierIter2.Begin(); !topHierIter2.End(); topHierIter2++) { if (!topHierIter2->IsFunction()) continue; CHtvIdent *pFunc = topHierIter2->GetThis(); if (!pFunc->IsBodyDefined() || pFunc->IsScPrim()) continue; // check if used in this module if (!isMethodCalledByModule(&(pFunc->GetCallerList()), pModule)) continue; GenFunction(pFunc, 0, 0); } // Generate functions for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (!moduleIter->IsFunction() || moduleIter->IsMethod() || moduleIter->GetName() == pModule->GetName()) continue; GenFunction(moduleIter->GetThis(), 0, 0); } // Generate logic blocks for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (!moduleIter->IsMethod()) continue; m_pInlineHier = moduleIter->GetPrevHier(); GenFuncVarDecl(moduleIter->GetThis()); SynIndividualStatements(moduleIter->GetThis(), 0, 0); m_pInlineHier = 0; } // flush all statements m_vFile.FlushLineBuffer(); // flush primitive instances m_vFile.SetLineBuffer(1); m_vFile.FlushLineBuffer(); m_vFile.SetLineBuffering(false); // Generate memories SynHtDistQueRams(topHierIter()); SynHtBlockQueRams(topHierIter()); SynHtUltraQueRams(topHierIter()); SynHtDistRams(topHierIter()); SynHtBlockRams(topHierIter()); SynHtUltraRams(topHierIter()); SynHtAsymBlockRams(topHierIter()); SynHtAsymUltraRams(topHierIter()); GenModuleTrailer(); // generate template modules SynHtDistRamModule(true); SynHtDistRamModule(false); SynHtBlockRamModule(); SynHtAsymBlockRamModule(); SynHtUltraRamModule(); SynHtAsymUltraRamModule(); if (g_htvArgs.IsLedaEnabled()) m_vFile.Print("\n`include \"leda_trailer.vh\"\n"); } } bool CHtvDesign::isMethodCalledByModule(const vector<CHtfeIdent *> *pCallerList, CHtfeIdent *pModule) { if (pCallerList == 0) return false; for (size_t i = 0; i < pCallerList->size(); i += 1) { Assert((*pCallerList)[i]->IsFunction()); if ((*pCallerList)[i]->GetPrevHier() == pModule) return true; if ((*pCallerList)[i]->GetCallerListCnt() == 0) continue; if (isMethodCalledByModule(&(*pCallerList)[i]->GetCallerList(), pModule)) return true; } return false; } void CHtvDesign::GenerateScModule(CHtvIdent *pClass) { // Generate transactions for an ScModule (v, cpp or both) // first create a signal/port list GenScModuleInsertMissingInstancePorts(pClass); // The complete signal list is now created, write out scModule m_incFile.Print(" {\n"); GenScModuleWritePortAndSignalList(pClass); // Now write out instance declarations m_incFile.Print("\n"); GenScModuleWriteInstanceDecl(pClass); // Write out destructor GenScModuleWriteInstanceDestructors(pClass); m_incFile.Print("\n SC_CTOR(%s) {\n", pClass->GetName().c_str()); m_incFile.Print("\n"); m_vFile.Print("\n"); GenScModuleWriteSignalsAssignedConstant(pClass); m_incFile.Flush(); GenScModuleWriteInstanceAndPortList(pClass); m_incFile.Print(" }\n};\n"); m_vFile.Print("\nendmodule\n"); m_vFile.Print("\n"); ////////////////////////////////////// // Update Fixture.h and Fixture.cpp // if (g_htvArgs.IsGenFixture() && pClass->IsScFixtureTop()) GenFixtureFiles(pClass); } void CHtvDesign::GenScModuleWriteInstanceAndPortList(CHtvIdent *pClass) { char *pFirstStr; // write out instance with port list CHtvArrayTblIter instanceIter(pClass->GetIdentTbl()); for (instanceIter.Begin(); !instanceIter.End(); instanceIter++) { if (instanceIter->GetId() != CHtvIdent::id_variable || !instanceIter->IsReference()) continue; int elemIdx = instanceIter->GetElemIdx(); CHtvIdent *pBaseIdent; if (instanceIter->GetPrevHier()->IsArrayIdent()) pBaseIdent = instanceIter->GetPrevHier(); else pBaseIdent = instanceIter(); const string identName = instanceIter->GetName(); const string typeName = instanceIter->GetType()->GetName(); const string instName = instanceIter->GetInstanceName(); Assert(identName == pBaseIdent->GetDimenElemName(elemIdx)); Assert(typeName == pBaseIdent->GetType()->GetName()); Assert(instName == pBaseIdent->GetInstanceName(elemIdx)); m_incFile.Print(" %s = new %s(\"%s\");\n", identName.c_str(), typeName.c_str(), instName.c_str()); CHtvIdent *pInstance = instanceIter->GetThis(); CHtvIdent *pModule = pInstance->GetType(); bool bIsScFixture = pModule->IsScFixture(); if (!bIsScFixture) { m_vFile.Print("\n"); string verilogInstName = instanceIter->GetFlatIdent()->GetName(); Assert(verilogInstName == pBaseIdent->GetVerilogName(elemIdx)); GenHtAttributes(instanceIter(), verilogInstName); m_vFile.Print(" %s %s(\n", typeName.c_str(), verilogInstName.c_str()); } else { m_vFile.Print("\n initial begin\n"); m_vFile.Print(" clock = 1;\n"); m_vFile.Print(" end\n"); m_vFile.Print("\n always begin\n"); m_vFile.Print(" #5 clock = ~clock;\n"); m_vFile.Print(" end\n"); const char *pModuleStr = typeName.c_str(); m_vFile.Print("\n initial $%s (\n", pModuleStr); } pFirstStr = ""; int clockCnt = 0; string clockName = "clock"; if (pClass->IsScFixtureTop() && pModule->IsScFixture()) { CHtvIdentTblIter instPortIter(instanceIter->GetIdentTbl()); for (instPortIter.Begin(); !instPortIter.End(); instPortIter++) { m_incFile.Print(" %s->%s(%s);\n", identName.c_str(), instPortIter->GetName().c_str(), instPortIter->GetSignalIdent()->GetName().c_str()); } CHtvIdentTblIter moduleIdentIter(pClass->GetIdentTbl()); for (moduleIdentIter.Begin(); !moduleIdentIter.End(); moduleIdentIter++) { if (moduleIdentIter->IsOutPort()) { const string portName = moduleIdentIter->GetName(); m_vFile.Print("%s %s", pFirstStr, portName.c_str()); pFirstStr = ",\n"; } } for (moduleIdentIter.Begin(); !moduleIdentIter.End(); moduleIdentIter++) { if (moduleIdentIter->IsInPort()) { const string portName = moduleIdentIter->GetName(); m_vFile.Print("%s %s", pFirstStr, portName.c_str()); pFirstStr = ",\n"; } } } else { CHtvArrayTblIter modulePortIter(pModule->GetIdentTbl()); for (modulePortIter.Begin(); !modulePortIter.End(); modulePortIter++) { // find ports of module if (!modulePortIter->IsPort()) continue; string signalName; string verilogSignalName; CHtvIdent *pInstancePort = pInstance->FindIdent(modulePortIter->GetName()); if (modulePortIter->GetDimenCnt() == 0) { if (pInstancePort) { signalName = pInstancePort->GetPortSignal()->GetName(); verilogSignalName = pInstancePort->GetPortSignal()->GetFlatIdent()->GetName(); } else { signalName = modulePortIter->GetName(); verilogSignalName = modulePortIter->GetFlatIdent()->GetName(); } m_incFile.Print(" %s->%s(%s);\n", instanceIter->GetName().c_str(), modulePortIter->GetName().c_str(), signalName.c_str()); } else { CHtvIdentTblIter instPortIter(modulePortIter->GetIdentTbl()); for (instPortIter.Begin(); !instPortIter.End(); instPortIter++) { if (pInstancePort) { signalName = pInstancePort->GetPortSignal()->GetName(); verilogSignalName = pInstancePort->GetPortSignal()->GetFlatIdent()->GetName(); } else { signalName = instPortIter->GetName(); verilogSignalName = instPortIter->GetFlatIdent()->GetName(); } m_incFile.Print(" %s->%s(%s);\n", instanceIter->GetName().c_str(), instPortIter->GetName().c_str(), signalName.c_str()); } } if (!bIsScFixture) { m_vFile.Print("%s .%s(%s)", pFirstStr, modulePortIter->GetFlatIdent()->GetName().c_str(), verilogSignalName.c_str()); pFirstStr = ",\n"; } else { // defer print of 2nd occurrence of clock to prevent Verilog sim crash if (modulePortIter->GetSignalIdent()->IsClock() && clockCnt++ > 0) continue; int width = modulePortIter->GetWidth(); if (width <= 32) { m_vFile.Print("%s %s", pFirstStr, signalName.c_str()); pFirstStr = ",\n"; } else { for (int i = 0; i < width; i += 32) { m_vFile.Print("%s %s[%d:%d]", pFirstStr, signalName.c_str(), (width < i+32) ? width-1 : i+31, i); pFirstStr = ",\n"; } } } } } m_incFile.Print("\n"); m_vFile.Print("\n );\n"); } } struct CMissingInfo { CMissingInfo() { m_bHasPrefix = false; m_bIsUsedOnInputPort = false; m_bIsUsedOnOutputPort = false; m_bIsDeclAsInput = false; m_bIsDeclAsOutput = false; m_bIsDeclAsSignal = false; m_pSignal = 0; } bool m_bHasPrefix; bool m_bIsUsedOnInputPort; bool m_bIsUsedOnOutputPort; bool m_bIsDeclAsInput; bool m_bIsDeclAsOutput; bool m_bIsDeclAsSignal; CHtvIdent * m_pSignal; }; void CHtvDesign::GenScModuleInsertMissingInstancePorts(CHtvIdent *pClass) { // First create a table of missing port names. The information is used // to decide if the created signal name is local to the module, or // is itself a port name. typedef map<string, CMissingInfo> MissingInfoTblMap; typedef pair<string, CMissingInfo> MissingInfoTblMap_ValuePair; typedef MissingInfoTblMap::iterator MissingInfoTblMap_Iter; typedef pair<MissingInfoTblMap_Iter, bool> MissingInfoTblMap_InsertPair; MissingInfoTblMap missingInfoTblMap; CHtvArrayTblIter instanceIter(pClass->GetIdentTbl()); for (instanceIter.Begin(); !instanceIter.End(); instanceIter++) { if (instanceIter->GetId() != CHtvIdent::id_variable || !instanceIter->IsReference()) continue; CHtvIdent *pModule = instanceIter->GetType(); // was Array CHtvArrayTblIter modulePortIter(pModule->GetIdentTbl()); for (modulePortIter.Begin(); !modulePortIter.End(); modulePortIter++) { // find ports of module if (!modulePortIter->IsPort()) continue; CHtvIdent *pInstancePort = instanceIter->FindIdent(modulePortIter->GetName()); string signalName; if (pInstancePort) { signalName = pInstancePort->GetSignalIdent()->GetName(); // strip off indexing signalName = signalName.substr(0, signalName.find('[')); } else { signalName = modulePortIter->GetName(); // strip off indexing signalName = signalName.substr(0, signalName.find('[')); } string prefix = signalName.substr(0,2); bool bHasPrefix = false; if (prefix == "i_" || prefix == "o_") { signalName = signalName.substr(2); bHasPrefix = true; } CMissingInfo *pInfo; MissingInfoTblMap_Iter iter = missingInfoTblMap.find(signalName); if (iter == missingInfoTblMap.end()) { MissingInfoTblMap_InsertPair insertPair = missingInfoTblMap.insert(MissingInfoTblMap_ValuePair(signalName, CMissingInfo())); pInfo = &insertPair.first->second; } else pInfo = &iter->second; pInfo->m_bHasPrefix |= bHasPrefix; if (modulePortIter->IsInPort()) pInfo->m_bIsUsedOnInputPort = true; else if (modulePortIter->IsOutPort()) pInfo->m_bIsUsedOnOutputPort = true; else Assert(0); CHtvIdent *pIdent = pClass->FindIdent(signalName); if (pIdent && pIdent->GetId() != CHtvIdent::id_new) { pInfo->m_bIsDeclAsSignal = true; pInfo->m_pSignal = pIdent; } string inPortName = (bHasPrefix ? "i_" : "") + signalName; pIdent = pClass->FindIdent(inPortName); if (pIdent && pIdent->GetId() != CHtvIdent::id_new) { pInfo->m_bIsDeclAsInput = true; pInfo->m_pSignal = pIdent; } string outPortName = (bHasPrefix ? "o_" : "") + signalName; pIdent = pClass->FindIdent(outPortName); if (pIdent && pIdent->GetId() != CHtvIdent::id_new) { pInfo->m_bIsDeclAsOutput = true; pInfo->m_pSignal = pIdent; } } } // determine port/signal for missing info and insert into pClass table MissingInfoTblMap_Iter iter = missingInfoTblMap.begin(); for ( ; iter != missingInfoTblMap.end(); iter++) { string signalName = iter->first; if (pClass->IsScFixtureTop()) { // all signals are local for fixture top if (iter->second.m_pSignal == 0) { iter->second.m_pSignal = pClass->InsertIdent(signalName); //iter->second.m_pSignal->SetElemIdx(0); } if (iter->second.m_pSignal->GetPortDir() == port_zero) { if (iter->second.m_bIsUsedOnInputPort) iter->second.m_pSignal->SetPortDir(port_out); else iter->second.m_pSignal->SetPortDir(port_in); } } else if (iter->second.m_bIsUsedOnInputPort && iter->second.m_bIsUsedOnOutputPort) { // local signal if (iter->second.m_pSignal == 0) { iter->second.m_pSignal = pClass->InsertIdent(signalName); //iter->second.m_pSignal->SetElemIdx(0); } if (iter->second.m_pSignal->GetPortDir() == port_zero) iter->second.m_pSignal->SetPortDir(port_signal); } else if (iter->second.m_bIsUsedOnInputPort) { // input port string inPortName = (iter->second.m_bHasPrefix ? "i_" : "") + signalName; if (iter->second.m_pSignal == 0) { iter->second.m_pSignal = pClass->InsertIdent(inPortName); //iter->second.m_pSignal->SetElemIdx(0); } if (iter->second.m_pSignal->GetPortDir() == port_zero) iter->second.m_pSignal->SetPortDir(port_in); } else { // output port string outPortName = (iter->second.m_bHasPrefix ? "o_" : "") + signalName; if (iter->second.m_pSignal == 0) { iter->second.m_pSignal = pClass->InsertIdent(outPortName); //iter->second.m_pSignal->SetElemIdx(0); } if (iter->second.m_pSignal->GetPortDir() == port_zero) iter->second.m_pSignal->SetPortDir(port_out); } iter->second.m_pSignal->SetId(CHtvIdent::id_variable); } // scan the instantiated modules again for (instanceIter.Begin(); !instanceIter.End(); instanceIter++) { if (instanceIter->GetId() != CHtvIdent::id_variable || !instanceIter->IsReference()) continue; CHtvIdent *pModule = instanceIter->GetType(); // was Array CHtvArrayTblIter modulePortIter(pModule->GetIdentTbl()); for (modulePortIter.Begin(); !modulePortIter.End(); modulePortIter++) { // find ports of module if (!modulePortIter->IsPort()) continue; // Instance ports are not kept as arrays CHtvIde
nt *pInstancePort = instanceIter->FindIdent(modulePortIter->GetName()); CHtvIdent *pSignal = 0; if (pInstancePort) { pSignal = pInstancePort->GetPortSignal(); Assert(pSignal); } else { string signalName = modulePortIter->GetName(); string prefix = signalName.substr(0,2); if (prefix == "i_" || prefix == "o_") signalName = signalName.substr(2); // get name from missing signal info table string baseSignalName = signalName.substr(0, signalName.find('[')); MissingInfoTblMap_Iter iter = missingInfoTblMap.find(baseSignalName); CMissingInfo *pInfo = &iter->second; Assert(pInfo); pSignal = pInfo->m_pSignal; pSignal->SetId(CHtvIdent::id_variable); pSignal->SetType(modulePortIter->GetType()); pSignal->SetLineInfo(modulePortIter->GetLineInfo()); CHtvIdent *pPortArrayIdent = 0; if (modulePortIter->GetPrevHier()->IsArrayIdent()) pPortArrayIdent = modulePortIter->GetPrevHier(); if (pPortArrayIdent) { if (pSignal->GetDimenCnt() == 0) { vector<int> emptyList = pPortArrayIdent->GetDimenList(); for (size_t i = 0; i < emptyList.size(); i += 1) emptyList[i] = 0; pSignal->SetDimenList(emptyList); pSignal->SetIsArrayIdent(); pSignal->SetFlatIdentTbl(pSignal->GetFlatIdent()->GetFlatIdentTbl()); UpdateVarArrayDecl(pSignal, pPortArrayIdent->GetDimenList()); } string dimIdxStr = signalName.substr(signalName.find('[')); CHtvIdent *pSignal2 = pSignal->FindIdent(pSignal->GetName() + dimIdxStr); if (!pSignal2) { ParseMsg(PARSE_ERROR, instanceIter->GetLineInfo(), "signal '%s' does not have index %s\n", pSignal->GetName().c_str(), dimIdxStr.c_str()); ErrorExit(); } pSignal = pSignal2; } else { // non-arrayed port bool bDimenMatch = true; for (size_t i = 0; i < pSignal->GetDimenCnt() && i < modulePortIter->GetDimenCnt(); i += 1) bDimenMatch &= pSignal->GetDimenList()[i] == modulePortIter->GetDimenList()[i]; if (!bDimenMatch || pSignal->GetDimenCnt() != modulePortIter->GetDimenCnt()) { char dimStr[16]; string portName = modulePortIter->GetName(); for (size_t i = 0; i < modulePortIter->GetDimenCnt(); i += 1) { //_itoa(modulePortIter->GetDimenList()[i], dimStr, 10); sprintf(dimStr, "%d", modulePortIter->GetDimenList()[i]); portName.append("[").append(dimStr).append("]"); } string signalName = pSignal->GetName(); for (size_t i = 0; i < pSignal->GetDimenCnt(); i += 1) { //_itoa(pSignal->GetDimenList()[i], dimStr, 10); sprintf(dimStr, "%d", pSignal->GetDimenList()[i]); signalName.append("[").append(dimStr).append("]"); } ParseMsg(PARSE_FATAL, instanceIter->GetLineInfo(), "module port (%s) and signal (%s) dimensions do not match", portName.c_str(), signalName.c_str()); } } if (modulePortIter->IsClock()) pSignal->SetIsClock(); modulePortIter->SetSignalIdent(pSignal); pInstancePort = instanceIter->InsertIdent(modulePortIter->GetName(), false); pInstancePort->SetSignalIdent(pSignal); pInstancePort->SetPortSignal(pSignal); if (modulePortIter->GetDimenCnt()) { CHtvIdentTblIter moduleArrayIter(modulePortIter->GetIdentTbl()); CHtvIdentTblIter instArrayIter(pSignal->GetIdentTbl()); for (moduleArrayIter.Begin(), instArrayIter.Begin(); !moduleArrayIter.End(); moduleArrayIter++, instArrayIter++) { moduleArrayIter->SetSignalIdent(instArrayIter->GetThis()); } } } if (modulePortIter->GetPortDir() == port_in) pSignal->SetReadRef(pSignal->GetElemIdx()); else if (modulePortIter->GetPortDir() == port_out) pSignal->SetWriteRef(pSignal->GetElemIdx()); else if (modulePortIter->GetPortDir() == port_inout) { pSignal->SetReadRef(pSignal->GetElemIdx()); pSignal->SetWriteRef(pSignal->GetElemIdx()); } } } } void CHtvDesign::GenScModuleWritePortAndSignalList(CHtvIdent *pClass) { char *pFirstStr; if (pClass->IsScFixtureTop()) { CHtvIdent *pClk4x = 0; CHtvIdent *pClk2x = 0; CHtvIdent *pClk1x = 0; // find highest frequency clock clk2x, clk, or clkhx CHtvIdentTblIter moduleIdentIter(pClass->GetIdentTbl()); for (moduleIdentIter.Begin(); !moduleIdentIter.End(); moduleIdentIter++) { if (moduleIdentIter->GetName() == "clk4x" || moduleIdentIter->GetName() == "clock4x") { pClk4x = moduleIdentIter(); pClk4x->SetIsClock(); } if (moduleIdentIter->GetName() == "clk2x" || moduleIdentIter->GetName() == "clock2x") { pClk2x = moduleIdentIter(); pClk2x->SetIsClock(); } if (moduleIdentIter->GetName() == "clk1x" || moduleIdentIter->GetName() == "clock1x" || moduleIdentIter->GetName() == "clock") { pClk1x = moduleIdentIter(); pClk1x->SetIsClock(); } } if (pClk4x) pClass->AddClock(pClk4x); if (pClk2x) pClass->AddClock(pClk2x); if (pClk1x) pClass->AddClock(pClk1x); } if (g_htvArgs.IsKeepHierarchyEnabled()) m_vFile.Print("(* keep_hierarchy = \"true\" *)\n"); GenHtAttributes(pClass); m_vFile.Print("module %s (\n", pClass->GetName().c_str()); if (pClass->IsScFixtureTop()) { // Top level topology file is handled special. All top level signals become I/O ports for fixture m_vFile.Print(");\n\n"); CHtvIdentTblIter identIter(pClass->GetIdentTbl()); for (identIter.Begin(); !identIter.End(); identIter++) { if (!identIter->IsPort()) continue; string signalDecl = VA("sc_signal<%s>", identIter->GetType()->GetType()->GetName().c_str()); m_incFile.Print(" %-24s %s;\n", signalDecl.c_str(), identIter->GetName().c_str()); GenHtAttributes(identIter(), identIter->GetName()); string bitRange; if (identIter->GetWidth() > 1) bitRange = VA("[%d:0]", identIter->GetWidth()-1); m_vFile.Print(" %s %-8s %s;\n", identIter->IsClock() ? "reg " : "wire", bitRange.c_str(), identIter->GetName().c_str()); } } else { CHtvIdentTblIter hierIdentIter(pClass->GetIdentTbl()); for (hierIdentIter.Begin(); !hierIdentIter.End(); hierIdentIter++) { if (!hierIdentIter->IsSignal()) continue; for(int elemIdx = 0; elemIdx < hierIdentIter->GetDimenElemCnt(); elemIdx += 1) { bool bIsReadRef = hierIdentIter->IsReadRef(elemIdx); bool bIsWriteRef = hierIdentIter->IsWriteRef(elemIdx); string name = hierIdentIter->GetDimenElemName(elemIdx); if (!bIsReadRef && !bIsWriteRef) ParseMsg(PARSE_ERROR, hierIdentIter->GetLineInfo(), "signal not referenced %s", name.c_str()); else if (hierIdentIter->GetWriterListCnt() > 1) ParseMsg(PARSE_ERROR, hierIdentIter->GetLineInfo(), "signal is written by multiple output ports", hierIdentIter->GetName().c_str()); else if (!bIsReadRef) ParseMsg(PARSE_ERROR, hierIdentIter->GetLineInfo(), "signal not read %s", hierIdentIter->GetName().c_str()); else if (!bIsWriteRef) ParseMsg(PARSE_ERROR, hierIdentIter->GetLineInfo(), "signal not written %s", hierIdentIter->GetName().c_str()); } } // First write out input ports for SC file //CHtvIdentTblIter hierIdentIter(pClass->GetIdentTbl()); pFirstStr = ""; for (hierIdentIter.Begin(); !hierIdentIter.End(); hierIdentIter++) { if (!hierIdentIter->IsInPort()) continue; if (pClass->IsScTopologyTop() && !hierIdentIter->IsWriteRef()) { ParseMsg(PARSE_INFO, "signal %s was not written in top topology file", hierIdentIter->GetName().c_str()); continue; } else if (hierIdentIter->IsWriteRef()) { ParseMsg(PARSE_ERROR, "module input signal %s was written", hierIdentIter->GetName().c_str()); continue; } Assert(hierIdentIter->GetType() && hierIdentIter->GetType()->GetType()); string inDecl = VA("sc_in<%s>", hierIdentIter->GetType()->GetType()->GetSignalName().c_str()); m_incFile.Print(" %-24s %s", inDecl.c_str(), hierIdentIter->GetName().c_str()); for (size_t i = 0; i < hierIdentIter->GetDimenCnt(); i += 1) m_incFile.Print("[%d]", hierIdentIter->GetDimenList()[i]); m_incFile.Print(";\n"); // now input ports for verilog string bitRange; if (hierIdentIter->GetWidth() > 1) bitRange = VA("[%d:0]", hierIdentIter->GetWidth()-1); CHtvIdent *pFlatIdent = hierIdentIter->GetFlatIdent(); CScArrayIdentIter flatIdentIter(pFlatIdent, pFlatIdent->GetFlatIdentTbl()); for (flatIdentIter.Begin(); !flatIdentIter.End(); flatIdentIter++) { m_vFile.Print("%s", pFirstStr); GenHtAttributes(pFlatIdent, flatIdentIter->GetName()); m_vFile.Print(" input %-8s %s", bitRange.c_str(), flatIdentIter->GetName().c_str()); pFirstStr = ",\n"; } } // Next write out output ports for (hierIdentIter.Begin(); !hierIdentIter.End(); hierIdentIter++) { if (!hierIdentIter->IsOutPort()) continue; if (pClass->IsScTopologyTop() && !hierIdentIter->IsReadRef()) { ParseMsg(PARSE_INFO, "signal %s was not read in top topology file", hierIdentIter->GetName().c_str()); continue; } Assert(hierIdentIter->GetType() && hierIdentIter->GetType()->GetType()); string outDecl = VA("sc_out<%s>", hierIdentIter->GetType()->GetType()->GetSignalName().c_str()); m_incFile.Print(" %-24s %s", outDecl.c_str(), hierIdentIter->GetName().c_str()); for (size_t i = 0; i < hierIdentIter->GetDimenCnt(); i += 1) m_incFile.Print("[%d]", hierIdentIter->GetDimenList()[i]); m_incFile.Print(";\n"); // now output ports for verilog string bitRange; if (hierIdentIter->GetWidth() > 1) bitRange = VA("[%d:0]", hierIdentIter->GetWidth()-1); CHtvIdent *pFlatIdent = hierIdentIter->GetFlatIdent(); CScArrayIdentIter flatIdentIter(pFlatIdent, pFlatIdent->GetFlatIdentTbl()); for (flatIdentIter.Begin(); !flatIdentIter.End(); flatIdentIter++) { m_vFile.Print("%s", pFirstStr); GenHtAttributes(pFlatIdent, flatIdentIter->GetName()); m_vFile.Print(" output %-8s %s", bitRange.c_str(), flatIdentIter->GetName().c_str()); pFirstStr = ",\n"; } } m_vFile.Print("\n);\n\n"); // Next write out signals for (hierIdentIter.Begin(); !hierIdentIter.End(); hierIdentIter++) { if (!hierIdentIter->IsSignal() || hierIdentIter->IsHtQueue()) continue; Assert(hierIdentIter->GetType() && hierIdentIter->GetType()->GetType()); string signalDecl = VA("sc_signal<%s>", hierIdentIter->GetType()->GetType()->GetSignalName().c_str()); m_incFile.Print(" %-24s %s", signalDecl.c_str(), hierIdentIter->GetName().c_str()); for (size_t i = 0; i < hierIdentIter->GetDimenCnt(); i += 1) m_incFile.Print("[%d]", hierIdentIter->GetDimenList()[i]); m_incFile.Print(";\n"); // now signals for verilog string bitRange; if (hierIdentIter->GetWidth() > 1) bitRange = VA("[%d:0]", hierIdentIter->GetWidth()-1); CHtvIdent *pFlatIdent = hierIdentIter->GetFlatIdent(); CScArrayIdentIter flatIdentIter(pFlatIdent, pFlatIdent->GetFlatIdentTbl()); for (flatIdentIter.Begin(); !flatIdentIter.End(); flatIdentIter++) { vector<int> refList(flatIdentIter->GetDimenCnt(), 0); do { string identName = GenVerilogIdentName(flatIdentIter->GetName(), refList); GenHtAttributes(pFlatIdent, identName); m_vFile.Print(" %s %-8s %s;\n", hierIdentIter->IsClock() ? "reg " : "wire", bitRange.c_str(), identName.c_str()); } while (!flatIdentIter->DimenIter(refList)); } } } } void CHtvDesign::GenScModuleWriteInstanceDecl(CHtvIdent *pClass) { CHtvIdentTblIter instanceIter(pClass->GetIdentTbl()); for (instanceIter.Begin(); !instanceIter.End(); instanceIter++) { if (instanceIter->GetId() != CHtvIdent::id_variable || !instanceIter->IsReference()) continue; m_incFile.Print(" %s *%s", instanceIter->GetType()->GetName().c_str(), instanceIter->GetName().c_str()); for (size_t i = 0; i < instanceIter->GetDimenCnt(); i += 1) m_incFile.Print("[%d]", instanceIter->GetDimenList()[i]); m_incFile.Print(";\n"); } } void CHtvDesign::GenScModuleWriteInstanceDestructors(CHtvIdent *pClass) { m_incFile.Print("\n"); m_incFile.Print(" ~%s() {\n", pClass->GetName().c_str()); CHtvArrayTblIter instanceIter(pClass->GetIdentTbl()); for (instanceIter.Begin(); !instanceIter.End(); instanceIter++) { if (instanceIter->GetId() != CHtvIdent::id_variable || !instanceIter->IsReference()) continue; m_incFile.Print(" delete %s;\n", instanceIter->GetName().c_str()); } m_incFile.Print(" }\n"); } void CHtvDesign::GenScModuleWriteSignalsAssignedConstant(CHtvIdent *pClass) { // write out signals assigned a const value CHtvArrayTblIter signalIter(pClass->GetIdentTbl()); for (signalIter.Begin(); !signalIter.End(); signalIter++) { if (!(signalIter->IsSignal() || signalIter->IsOutPort()) || !signalIter->IsConst()) continue; m_incFile.Print(" %s = 0x%llx;\n", signalIter->GetName().c_str(), signalIter->GetConstValue().GetUint64()); m_vFile.Print(" assign %s = %d;\n", signalIter->GetFlatIdent()->GetName().c_str(), signalIter->GetConstValue().GetUint64()); } m_incFile.Print("\n"); } void CHtvDesign::GenerateScMain() { // write signals CHtvSignalTblIter signalIter(GetSignalTbl()); for (signalIter.Begin() ; !signalIter.End(); signalIter++) { if (signalIter->IsClock()) continue; if (signalIter->GetRefCnt() > 0) { CHtvIdent *pType = signalIter->GetType(); if (pType == 0) pType = signalIter->GetRefList(0)->GetModulePort()->GetBaseType(); if (pType) { string signalDecl = VA(" sc_signal<%s>", pType->GetName().c_str()); m_cppFile.Print("%-32s%s;\n", signalDecl.c_str(), signalIter->GetName().c_str()); } } } m_cppFile.Print("\n"); // write clocks CHtfeSignalTblIter clockIter(GetSignalTbl()); for (clockIter.Begin() ; !clockIter.End(); clockIter++) { if (!clockIter->IsClock()) continue; m_cppFile.Print(" sc_clock %s", clockIter->GetName().c_str()); for (unsigned int i = 0; i < clockIter->GetClockTokenList().size(); i += 1) { CToken const &tl = clockIter->GetClockTokenList()[i]; m_cppFile.Print("%s", tl.GetString().c_str()); if (tl.GetToken() == tk_comma) m_cppFile.Print(" "); } m_cppFile.Print(";\n"); } m_cppFile.Print("\n"); // Generate module instances CHtfeInstanceTblIter instanceIter(GetInstanceTbl()); for (instanceIter.Begin() ; !instanceIter.End(); instanceIter++) { m_cppFile.Print(" %s %s(\"%s\");\n", instanceIter->GetModule()->GetName().c_str(), instanceIter->GetName().c_str(), instanceIter->GetName().c_str()); // Generate instance port list CHtfeInstancePortTblIter instancePortIter(instanceIter->GetInstancePortTbl()); for (instancePortIter.Begin(); !instancePortIter.End(); instancePortIter++) { m_cppFile.Print(" %s.%s(%s%s);\n", instanceIter->GetName().c_str(), instancePortIter->GetName().c_str(), instancePortIter->GetSignal()->GetName().c_str(), instancePortIter->GetSignal()->IsClock() ? ".signal()" : ""); } m_cppFile.Print("\n"); } // generate sc_start statement CHtfeLex::CTokenList const & stStart = GetScStartList(); if (stStart.size() == 0) ParseMsg(PARSE_ERROR, "Expected a sc_start statement"); else { m_cppFile.Print(" sc_start"); for (unsigned int i = 0; i < stStart.size(); i += 1) { CToken const &tl = stStart[i]; m_cppFile.Print("%s", tl.GetString().c_str()); if (tl.GetToken() == tk_comma) m_cppFile.Print(" "); } m_cppFile.Print(";\n"); } m_cppFile.Print("\n return 0;\n}\n"); } void CHtvDesign::FindGlobalRefSet(CHtvIdent *pFunc, CHtvStatement *pStatement) { // create identifier global list for each statement for ( ; pStatement; pStatement = pStatement->GetNext()) { switch (pStatement->GetStType()) { case st_compound: FindGlobalRefSet(pFunc, pStatement->GetCompound1()); break; case st_assign: case st_return: FindGlobalRefSet(pFunc, pStatement->GetExpr()); break; case st_if: // special case for memory write statements. FindGlobalRefSet(pFunc, pStatement->GetExpr()); FindGlobalRefSet(pFunc, pStatement->GetCompound1()); FindGlobalRefSet(pFunc, pStatement->GetCompound2()); break; case st_switch: case st_case: FindGlobalRefSet(pFunc, pStatement->GetExpr()); FindGlobalRefSet(pFunc, pStatement->GetCompound1()); break; case st_default: FindGlobalRefSet(pFunc, pStatement->GetCompound1()); break; case st_null: case st_break: break; default: Assert(0); } } } void CHtvDesign::FindGlobalRefSet(CHtvIdent *pFunc, CHtvOperand *pExpr) { // recursively desend expression tree Assert(pExpr != 0); if (pExpr->IsLeaf()) { CHtvIdent *pIdent = pExpr->G
etMember(); if (pIdent == 0 || pIdent->IsScState() || (pIdent->IsLocal() && !pIdent->IsFunction())) return; if (pIdent->GetId() == CHtvIdent::id_function) { for (unsigned int i = 0; i < pExpr->GetParamCnt(); i += 1) { //bool bIsReadOnly = pIdent->GetParamIsConst(i); //if (bIsReadOnly) FindGlobalRefSet(pFunc, pExpr->GetParam(i)); } // find global variable references in called function if (!pIdent->IsGlobalReadRef()) { FindGlobalRefSet(pIdent, (CHtvStatement *)pIdent->GetStatementList()); pIdent->SetIsGlobalReadRef(true); } // merge called references pFunc->MergeGlobalRefSet(pIdent->GetGlobalRefSet()); } else if (pIdent->IsVariable()) { vector<bool> fieldConstList(pExpr->GetIndexCnt(), false); vector<int> refList(pExpr->GetIndexCnt(), 0); for (size_t j = 0; j < pExpr->GetIndexCnt(); j += 1) { fieldConstList[j] = pExpr->GetIndex(j)->IsConstValue(); if (pExpr->GetIndex(j)->IsConstValue()) { refList[j] = pExpr->GetIndex(j)->GetConstValue().GetSint32(); continue; } } do { int elemIdx = CalcElemIdx(pIdent, refList); CHtIdentElem identElem(pIdent, elemIdx); pFunc->AddGlobalRef(identElem); } while (!pIdent->DimenIter(refList, fieldConstList)); } } else { CHtvOperand *pOp1 = pExpr->GetOperand1(); CHtvOperand *pOp2 = pExpr->GetOperand2(); CHtvOperand *pOp3 = pExpr->GetOperand3(); if (pOp1) FindGlobalRefSet(pFunc, pOp1); if (pOp2) FindGlobalRefSet(pFunc, pOp2); if (pOp3) FindGlobalRefSet(pFunc, pOp3); } } void CHtvDesign::FindWriteRefSets(CHtvIdent *pHier) { // create identifier write list for each statement, include pHier for local variables for (CHtvStatement *pStatement = (CHtvStatement *)pHier->GetStatementList(); pStatement; pStatement = pStatement->GetNext()) { switch (pStatement->GetStType()) { case st_compound: { CAlwaysType alwaysType = FindWriteRefVars(pHier, pStatement, pStatement->GetCompound1()); if (alwaysType.IsError()) ParseMsg(PARSE_ERROR, pStatement->GetLineInfo(), "Mix of register and non-register assignments in compound statement"); } break; case st_assign: case st_return: { // scPrims do not get a write ref list to avoid primitive ending up in always at blocks CAlwaysType alwaysType = FindWriteRefVars(pHier, pStatement, pStatement->GetExpr()); if (alwaysType.IsError()) ParseMsg(PARSE_ERROR, pStatement->GetLineInfo(), "Mix of register and non-register assignments in assignment statement"); } break; case st_if: { CAlwaysType alwaysType = FindWriteRefVars(pHier, pStatement, pStatement->GetCompound1()); alwaysType += FindWriteRefVars(pHier, pStatement, pStatement->GetCompound2()); if (alwaysType.IsError()) ParseMsg(PARSE_ERROR, pStatement->GetLineInfo(), "Mix of register and non-register assignments in if statement"); if (!alwaysType.IsClocked()) FindWriteRefVars(pHier, pStatement, pStatement->GetExpr()); } break; case st_switch: { CAlwaysType alwaysType = FindWriteRefVars(pHier, pStatement, pStatement->GetCompound1()); if (alwaysType.IsError()) ParseMsg(PARSE_ERROR, pStatement->GetLineInfo(), "Mix of register and non-register assignments in switch statement"); if (!alwaysType.IsClocked()) FindWriteRefVars(pHier, pStatement, pStatement->GetExpr()); } break; //case st_case: // FindWriteRefVars(pHier, pStatement, pStatement->GetExpr()); // FindWriteRefVars(pHier, pStatement, pStatement->GetCompound1()); // break; //case st_default: // FindWriteRefVars(pHier, pStatement, pStatement->GetCompound1()); // break; case st_null: case st_break: break; default: Assert(0); } } // create synthesize statement lists int synSetId = 0; for (CHtvStatement *pStatement = (CHtvStatement *)pHier->GetStatementList() ; pStatement; pStatement = pStatement->GetNext()) { if (pStatement->IsSynthesized()) continue; if (IsAssignToHtPrimOutput(pStatement)) continue; synSetId += 1; // find set of variables that must be handled together int synSetSize = 1; pStatement->SetIsInSynSet(); bool bIsAllAssignConst = true; // Scan statements to merge all statements with common write references MergeWriteRefSets(bIsAllAssignConst, synSetSize, pStatement); // Must scan twice due to indexed variables that may cause missed statements MergeWriteRefSets(bIsAllAssignConst, synSetSize, pStatement); pStatement->SetSynSetSize(synSetSize); if (bIsAllAssignConst) { CHtvOperand * pOp = pStatement->GetExpr()->GetOperand1(); pOp->GetMember()->SetIsAssignOutput(pOp); } if (pStatement->IsScPrim()) { if (synSetSize > 1) ParseMsg(PARSE_ERROR, pStatement->GetExpr()->GetLineInfo(), "sc_prim output assigned outside of primitive"); continue; } CHtIdentElem clockElem(pHier->GetClockIdent(), 0); bool bClockedAlwaysAt = pStatement->GetWriteRefSet().size() == 1 && pStatement->GetWriteRefSet()[0] == clockElem; if (bClockedAlwaysAt) pStatement->SetIsClockedAlwaysAt(); FindWriteRefSets(pStatement, synSetId, synSetSize, bClockedAlwaysAt); } } bool CHtvDesign::IsAssignToHtPrimOutput(CHtvStatement * pStatement) { Assert(pStatement); if (pStatement->GetStType() != st_assign) return false; CHtvOperand * pExpr = pStatement->GetExpr(); if (pExpr == 0 || pExpr->GetOperator() != tk_equal) return false; CHtvOperand * pOp1 = pExpr->GetOperand1(); CHtvOperand * pOp2 = pExpr->GetOperand2(); if (!pOp2 || !pOp2->IsConstValue() || pOp2->GetConstValue().GetSint64() != 0) return false; if (!pOp1 || !pOp1->IsLeaf() || pOp1->GetMember() == 0 || pOp1->GetMember()->GetId() != CHtvIdent::id_variable) return false; int elemIdx = pOp1->GetMember()->GetDimenElemIdx(pOp1); return pOp1->GetMember()->IsHtPrimOutput(elemIdx); } void CHtvDesign::MergeWriteRefSets(bool &bIsAllAssignConst, int &synSetSize, CHtvStatement * pStatement) { bIsAllAssignConst &= IsRightHandSideConst(pStatement); unsigned i; bool bAddedNew = true; while (bAddedNew) { bAddedNew = false; for (CHtvStatement * pStatement2 = pStatement->GetNext(); pStatement2; pStatement2 = pStatement2->GetNext()) { if (pStatement2->IsSynthesized() || pStatement2->IsInSynSet() || pStatement2->IsScPrim()) continue; if (IsAssignToHtPrimOutput(pStatement2)) continue; vector<CHtIdentElem> &writeRefSet2 = pStatement2->GetWriteRefSet(); for (i = 0; i < writeRefSet2.size(); i += 1) { if (pStatement->IsInWriteRefSet(writeRefSet2[i])) break; } if (i == writeRefSet2.size()) continue; for (i = 0; i < writeRefSet2.size(); i += 1) pStatement->AddWriteRef(writeRefSet2[i]); pStatement2->SetIsInSynSet(); synSetSize += 1; bAddedNew = true; bIsAllAssignConst &= IsRightHandSideConst(pStatement2); } } } bool CHtvDesign::IsRightHandSideConst(CHtvStatement * pStatement) { bool bIsRightHandSideConst = pStatement->GetStType() == st_assign && !pStatement->IsScPrim() && !pStatement->GetExpr()->IsLeaf() && pStatement->GetExpr()->GetOperand2()->IsConstValue() && pStatement->GetExpr()->GetOperand1()->GetSubFieldWidth() == pStatement->GetExpr()->GetOperand1()->GetMember()->GetWidth(); if (!bIsRightHandSideConst) return false; // now check if left hand side has non-constant indexing for (size_t idx = 0; idx < pStatement->GetExpr()->GetOperand1()->GetIndexList().size(); idx += 1) { CHtvOperand *pIndexOp = pStatement->GetExpr()->GetOperand1()->GetIndex(idx); if (!pIndexOp->IsLeaf() || !pIndexOp->IsConstValue()) return false; } return bIsRightHandSideConst; } void CHtvDesign::FindWriteRefSets(CHtvStatement *pStatement, int synSetId, int synSetSize, bool bClockedAlwaysAt) { for (CHtvStatement *pStatement2 = (CHtvStatement *)pStatement; pStatement2; pStatement2 = pStatement2->GetNext()) { if (!pStatement2->IsInSynSet() || pStatement2->IsSynthesized()) continue; pStatement2->SetSynSetId(synSetId); switch (pStatement2->GetStType()) { case st_assign: break; case st_compound: FindWriteRefSets(pStatement2->GetCompound1(), synSetId, synSetSize, bClockedAlwaysAt); break; case st_switch: break; case st_if: case st_null: break; default: Assert(0); } pStatement2->SetIsSynthesized(); } } void CHtvDesign::FindXilinxFdPrims(CHtvIdent *pHier, CHtvObject * pObj) { if (!g_htvArgs.GetXilinxFdPrims()) return; // Find register assignment states that will be translated to FD prims FindXilinxFdPrims(pObj, (CHtvStatement *)pHier->GetStatementList()); } void CHtvDesign::FindXilinxFdPrims(CHtvObject * pObj, CHtvStatement *pStatement) { for ( ; pStatement; pStatement = pStatement->GetNext()) { if (pStatement->IsScPrim()) continue; switch (pStatement->GetStType()) { case st_assign: IsXilinxClockedPrim(pObj, pStatement); break; case st_if: IsXilinxClockedPrim(pObj, pStatement); break; case st_switch: break; case st_compound: FindXilinxFdPrims(pObj, pStatement->GetCompound1()); break; case st_null: break; default: Assert(0); } } } void CHtvDesign::SynIndividualStatements(CHtvIdent *pHier, CHtvObject * pObj, CHtvObject * pRtnObj) { // synthesize statements for (CHtvStatement *pStatement = (CHtvStatement *)pHier->GetStatementList() ; pStatement; pStatement = pStatement->GetNext()) { int synSetSize = pStatement->GetSynSetSize(); if (synSetSize == 0) continue; // not first statement in writeRefSet // find set of variables that must be handled together if (pStatement->IsScPrim()) { Assert(synSetSize == 1); SynScPrim(pHier, pObj, pStatement); continue; } m_bClockedAlwaysAt = pStatement->IsClockedAlwaysAt(); bool bAlwaysAtNeeded = true; if (m_bClockedAlwaysAt && g_htvArgs.GetXilinxFdPrims()) { // first translate assignments to Xilinx register bAlwaysAtNeeded = false; SynXilinxRegisters(pHier, pObj, pStatement, bAlwaysAtNeeded); } if (!bAlwaysAtNeeded) { // all register assignments were translated to primitives m_bClockedAlwaysAt = false; continue; } synSetSize = 2; // assign to 2 to force always @ block if (m_bClockedAlwaysAt) GenAlwaysAtHeader(pHier->GetClockIdent()); else if (synSetSize > 1) { if (HandleAllConstantAssignments(pHier, pObj, pRtnObj, pStatement, synSetSize)) continue; GenAlwaysAtHeader(true); RemoveWrDataMux(pStatement, synSetSize); } SynIndividualStatements(pHier, pObj, pRtnObj, pStatement, synSetSize); if (m_bClockedAlwaysAt || synSetSize > 1) GenAlwaysAtTrailer(true); m_bClockedAlwaysAt = false; } } void CHtvDesign::SynScPrim(CHtvIdent *pHier, CHtvObject * pObj, CHtvStatement *pStatement) { CHtvOperand *pExpr = pStatement->GetExpr(); CHtvIdent *pFunc = pExpr->GetMember(); int firstOutput; for (firstOutput = 0; firstOutput < pExpr->GetParamListCnt(); firstOutput += 1) if (!pFunc->GetParamIsConst(firstOutput)) break; Assert(firstOutput < pExpr->GetParamListCnt()); CHtvOperand * pParamOp = pExpr->GetParam(firstOutput); int elemIdx = pParamOp->GetMember()->GetDimenElemIdx(pParamOp); string str = pParamOp->GetMember()->GetVerilogName(elemIdx) + "_"; if (m_prmFp) fprintf(m_prmFp, "%s %s\n", str.c_str(), pFunc->GetName().c_str()); m_vFile.Print("\n%s %s (\n", pFunc->GetName().c_str(), str.c_str()); m_vFile.IncIndentLevel(); // verify that function that calls primitive has a unique instance CHtvIdent * pCaller = pHier; while (pCaller->IsFunction() && !pCaller->IsMethod()) { if (pCaller->GetWriterListCnt() > 1) ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "clocked ht_prim %s was called from a non-unique function instance", pFunc->GetName().c_str()); pCaller = pCaller->GetWriterList(0); } if (pFunc->GetHtPrimClkList().size() > 0) { if (!pCaller->GetClockIdent()) ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "clocked ht_prim %s was called from non-clocked function", pFunc->GetName().c_str()); string callerName = pCaller->GetClockIdent()->GetName(); size_t len = callerName.size(); int callerRate = -1; if (callerName[len-1] == 'x' && isdigit(callerName[len-2])) { callerRate = callerName[len-2]-'0'; callerName = callerName.substr(0, len-2); } vector<string> & clkList = pFunc->GetHtPrimClkList(); for (size_t i = 0; i < clkList.size(); i += 1) { string primClkName = clkList[i]; len = primClkName.size(); int primClkRate = -1; if (len >= 2 && clkList[i][len-1] == 'x' && isdigit(clkList[i][len-2])) primClkRate = clkList[i][len-2]-'0'; bool bHtlClk = primClkName == "intfClk1x" || primClkName == "intfClk2x" || primClkName == "intfClk4x" || primClkName == "clk1x" || primClkName == "clk2x" || primClkName == "clk4x"; if (primClkName.substr(0, 5) == "clkhx") { m_vFile.Print(".%s(i_clockhx),\n", primClkName.c_str()); } else if (!bHtlClk) { m_vFile.Print(".%s(%s),\n", primClkName.c_str(), pCaller->GetClockIdent()->GetName().c_str()); } else if (primClkName.substr(0, 7) == "intfClk" && primClkRate > 0 && callerRate > 0) { if (callerRate * primClkRate > 4) ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "unable to generate clock for ht_prim %s, prim clock %s with interface clock %s", pFunc->GetName().c_str(), primClkName.c_str(), pCaller->GetClockIdent()->GetName().c_str()); else if (callerRate * primClkRate == 4) ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "ht_prim %s requires unsupported 4x clock, prim clock %s with interface clock %s", pFunc->GetName().c_str(), primClkName.c_str(), pCaller->GetClockIdent()->GetName().c_str()); m_vFile.Print(".%s(%s%dx),\n", primClkName.c_str(), callerName.c_str(), callerRate * primClkRate); } else if (primClkName.substr(0, 3) == "clk" && primClkRate > 0 && callerRate > 0) { m_vFile.Print(".%s(%s%dx),\n", primClkName.c_str(), callerName.c_str(), primClkRate); } } } char *pFirst = ""; for (unsigned i = 0; i < pExpr->GetParamCnt(); i += 1) { if (!pFunc->GetParamIsScState(i)) { if (pExpr->GetParam(i)->IsConstValue()) { m_vFile.Print("%s.%s(", pFirst, pFunc->GetParamName(i).c_str()); if (pExpr->GetParam(i)->GetConstValue().IsSigned()) { if (pExpr->GetParam(i)->GetConstValue().IsPos()) m_vFile.Print("%d'd%lld", pFunc->GetParamType(i)->GetWidth(), pExpr->GetParam(i)->GetConstValue().GetSint64()); else m_vFile.Print("-%d'd%lld", pFunc->GetParamType(i)->GetWidth(), - pExpr->GetParam(i)->GetConstValue().GetSint64()); } else m_vFile.Print("%d'h%llx", pFunc->GetParamType(i)->GetWidth(), pExpr->GetParam(i)->GetConstValue().GetSint64()); m_vFile.Print(")"); pFirst = ",\n"; continue; } CHtvOperand * pArgOp = pExpr->GetParam(i); int elemIdx = pArgOp->GetMember()->GetDimenElemIdx(pArgOp); string argStr = pArgOp->GetMember()->GetVerilogName(elemIdx); m_vFile.Print("%s.%s(%s", pFirst, pFunc->GetParamName(i).c_str(), argStr.c_str()); if (pExpr->GetParam(i)->IsSubFieldValid()) { int lowBit, width; bool bIsConst = GetSubFieldRange(pExpr->GetParam(i), lowBit, width, false); Assert(pExpr->GetParam(i)->GetVerWidth() <= width); if (!bIsConst) ParseMsg(PARSE_FATAL, pExpr->GetParam(i)->GetLineInfo(), "non-constant bit range specifier in primitive parameters"); if (width == 1) m_vFile.Print("[%d]", lowBit); else m_vFile.Print("[%d:%d]", lowBit + width - 1, lowBit); } m_vFile.Print(")"); pFirst = ",\n"; } } m_vFile.DecIndentLevel(); m_vFile.Print("\n);\n"); } void CHtvDesign::SynXilinxRegisters(CHtvIdent *pHier, CHtvObject * pObj, CHtvStatement *pStatement, bool &bAlwaysAtNeeded) { for (CHtvStatement *pStatement2 = pStatement; pStatement2; pStatement2 = pStatement2->GetNext()) { if (pStatement->GetSynSetId() != pStatement2->GetSynSetId()) continue; switch (pStatement2->GetStType()) { case st_compound: SynXilinxRegisters(pHier, pObj, pStatement2->GetCompound1(), bAlwaysAtNeeded); break; case st_assign: if (!pStatement2->IsXilinxFdPrim() || !GenXilinxClockedPrim(pHier, pObj, pStatement2)) bAlwaysAtNeeded = true; break; case st_if: if (!GenXilinxClockedPrim(pHier, pObj, pStatement2)) bAlwaysAtNeeded = true; break; case st_switch: bAlwaysAtNeeded = true; break; default: Assert(0); } } } bool CHtvDesign::HandleAllConstantAssignments(CHtvIdent *pHier, CHtvObject * pObj, CHtvObject * pRtnObj, CHtvStatement *pStatement, int synSetSize) { CHtvStatement *pLastStatement = 0; for (CHtvStatement *pStatement2 = pStatement; pStatement2; pStatement2 = pStatement2->GetNext()) { if (pStatement->GetSynSetId() != pStatement2->GetSynSetId()) continue; if (pStatement2->GetStType() != st_assign) return false; CHtvOperand *pExpr = pStatement2->GetExpr(); if (pExpr->IsLeaf() || !pExpr->GetOperand2()->IsConstValue()) // right hand side was not a constant return false; for (size_t idx = 0; idx < pExpr->GetOperand1()->GetIndexList().size(); idx += 1) { CHtvOperand *pIndexOp = pExpr->GetOperand1()->GetIndex(idx); if (!pIndexOp->IsLeaf() || !pIndexOp->IsConstValue())
return false; } pLastStatement = pStatement2; } CHtvOperand *pExpr = pLastStatement->GetExpr(); // all right hand sides of assignment states were constants // all left hand sides are the same variable if (pExpr->GetOperand1()->GetSubFieldWidth() == pExpr->GetOperand1()->GetMember()->GetWidth()) { SynIndividualStatements(pHier, pObj, pRtnObj, pLastStatement, 1); return true; } // found one, create new variable pExpr = pStatement->GetExpr(); string wireName = "w$" + pExpr->GetOperand1()->GetMember()->GetName(); CHtvIdent *pWire = pHier->InsertIdent(wireName)->GetFlatIdent(); pWire->SetId(CHtvIdent::id_variable); pWire->SetWidth(pExpr->GetOperand1()->GetWidth()); pExpr->GetOperand2()->SetMinWidth(pExpr->GetOperand1()->GetWidth()); m_vFile.Print("wire %s = ", pWire->GetName().c_str()); GenSubExpr(pObj, pRtnObj, pExpr->GetOperand2()); m_vFile.Print(";\n"); pExpr->GetOperand2()->SetIsConstValue(false); pExpr->GetOperand2()->SetMember(pWire); return false; } struct CMemVarIndexList { void operator = (vector<CHtfeOperand *> & opList) { for (size_t i = 0; i < opList.size(); i += 1) { if (opList[i]->IsConstValue()) { int idx = opList[i]->GetConstValue().GetSint32(); m_indexList.push_back(idx); } else Assert(0); } } bool operator == (vector<CHtfeOperand *> & opList) { Assert(opList.size() == m_indexList.size()); for (size_t i = 0; i < opList.size(); i += 1) { if (opList[i]->IsConstValue()) { int idx = opList[i]->GetConstValue().GetSint32(); if (m_indexList[i] != idx) return false; } else Assert(0); } return true; } vector<int> m_indexList; }; struct CMemVarInfo { CMemVarInfo() { m_pMemVar = 0; m_bWrEnInit = false; m_bWrDataInit = false; m_bWrEnSet = false; m_wrEnSize = 0; m_bConvert = true; } CHtvIdent * m_pMemVar; bool m_bWrEnInit; bool m_bWrDataInit; bool m_bWrEnSet; vector<int> m_wrEnLowBit; int m_wrEnSize; bool m_bConvert; CMemVarIndexList m_indexList; }; void CHtvDesign::RemoveWrDataMux(CHtvStatement *pStatement, int synSetSize) { //if (GetAlwaysBlockIdx() == 4) // bool stop = true; vector<CMemVarInfo> memVarList; for (CHtvStatement ** ppStatement2 = &pStatement; *ppStatement2; ppStatement2 = (*ppStatement2)->GetPNext()) { if (pStatement->GetSynSetId() != (*ppStatement2)->GetSynSetId()) continue; switch ((*ppStatement2)->GetStType()) { case st_assign: { if ((*ppStatement2)->GetExpr()->IsLeaf()) break; CHtvOperand * pOp1 = (*ppStatement2)->GetExpr()->GetOperand1(); CHtvIdent * pIdent = pOp1->GetMember(); if (pIdent->IsMemVarWrData() || pIdent->IsMemVarWrEn()) { CHtvIdent * pMemVar = pIdent->GetMemVar(); CMemVarInfo * pMemVarInfo = 0; for (size_t i = 0; i < memVarList.size(); i += 1) { if (memVarList[i].m_pMemVar == pMemVar && memVarList[i].m_indexList == pOp1->GetIndexList()) { pMemVarInfo = &memVarList[i]; break; } } if (pMemVarInfo == 0) { memVarList.push_back(CMemVarInfo()); pMemVarInfo = &memVarList.back(); pMemVarInfo->m_pMemVar = pMemVar; pMemVarInfo->m_indexList = pOp1->GetIndexList(); } CHtvOperand * pOp2 = (*ppStatement2)->GetExpr()->GetOperand2(); if (pOp2->IsConstValue() && pOp2->GetConstValue().IsZero()) { if (pIdent->IsMemVarWrData()) { if (pMemVarInfo->m_bWrDataInit) pMemVarInfo->m_bConvert = false; else pMemVarInfo->m_bWrDataInit = true; } else { if (pMemVarInfo->m_bWrEnInit) pMemVarInfo->m_bConvert = false; else pMemVarInfo->m_bWrEnInit = true; } } } break; } case st_if: { bool bConvert = true; if ((*ppStatement2)->GetCompound2()) return; for (CHtvStatement **ppStatement3 = (*ppStatement2)->GetPCompound1(); *ppStatement3; ) { if ((*ppStatement3)->GetStType() != st_assign) return; CHtvOperand * pOp1 = (*ppStatement3)->GetExpr()->GetOperand1(); if (pOp1 == 0) return; // function call CHtvIdent * pIdent = pOp1->GetMember(); if (pIdent->IsMemVarWrData() || pIdent->IsMemVarWrEn()) { CHtvIdent * pMemVar = pIdent->GetMemVar(); size_t k; for (k = 0; k < pOp1->GetIndexList().size(); k += 1) { if (!pOp1->GetIndexList()[k]->IsConstValue()) break; } if (k < pOp1->GetIndexList().size()) { for (size_t i = 0; i < memVarList.size(); i += 1) { if (memVarList[i].m_pMemVar == pMemVar) memVarList[i].m_bConvert = false; } ppStatement3 = (*ppStatement3)->GetPNext(); continue; } CMemVarInfo * pMemVarInfo = 0; for (size_t i = 0; i < memVarList.size(); i += 1) { if (memVarList[i].m_pMemVar == pMemVar && memVarList[i].m_indexList == pOp1->GetIndexList()) { pMemVarInfo = &memVarList[i]; break; } } if (pMemVarInfo == 0) { ppStatement3 = (*ppStatement3)->GetPNext(); continue; } CHtvOperand * pOp2 = (*ppStatement3)->GetExpr()->GetOperand2(); if (pIdent->IsMemVarWrEn()) { if (pOp2->IsConstValue() && pOp2->GetConstValue().GetUint64() == 1) { if (!pMemVarInfo->m_bWrEnInit || pMemVarInfo->m_bWrEnSet) pMemVarInfo->m_bConvert = false; else { int highBit, lowBit; pOp1->GetDistRamWeWidth(highBit, lowBit); if (highBit == -1 && lowBit == -1) { if (pMemVarInfo->m_wrEnSize == 0) pMemVarInfo->m_bWrEnSet = true; else pMemVarInfo->m_bConvert = false; } else { size_t i; for (i = 0; i < pMemVarInfo->m_wrEnLowBit.size(); i += 1) { if (lowBit == pMemVarInfo->m_wrEnLowBit[i]) { pMemVarInfo->m_bConvert = false; break; } } if (i == pMemVarInfo->m_wrEnLowBit.size()) { pMemVarInfo->m_wrEnLowBit.push_back(lowBit); pMemVarInfo->m_wrEnSize += highBit - lowBit + 1; if (pMemVarInfo->m_wrEnSize == pMemVar->GetWidth()) pMemVarInfo->m_bWrEnSet = true; } } } } } if (pIdent->IsMemVarWrData()) { if (pMemVarInfo->m_bWrEnInit && pMemVarInfo->m_bWrDataInit && pMemVarInfo->m_bWrEnSet && pMemVarInfo->m_bConvert && bConvert) { // Do the conversion CHtvStatement * pStatement3 = *ppStatement3; *ppStatement3 = (*ppStatement3)->GetNext(); pStatement3->SetNext(*ppStatement2); *ppStatement2 = pStatement3; ppStatement2 = (*ppStatement2)->GetPNext(); pStatement3->SetSynSetId(pStatement->GetSynSetId()); pMemVarInfo->m_bConvert = false; continue; } else pMemVarInfo->m_bConvert = false; } } else bConvert = false; ppStatement3 = (*ppStatement3)->GetPNext(); } break; } default: return; } } } void CHtvDesign::SynIndividualStatements(CHtvIdent *pHier, CHtvObject * pObj, CHtvObject * pRtnObj, CHtvStatement *pStatement, int synSetSize) { for (CHtvStatement *pStatement2 = pStatement; pStatement2; pStatement2 = pStatement2->GetNext()) { if (pStatement->GetSynSetId() != pStatement2->GetSynSetId()) continue; switch (pStatement2->GetStType()) { case st_compound: SynIndividualStatements(pHier, pObj, pRtnObj, pStatement2->GetCompound1(), synSetSize); break; case st_assign: { if (pStatement2->IsXilinxFdPrim()) break; CHtvOperand *pExpr = pStatement2->GetExpr(); if (pExpr->IsLeaf() && pExpr->GetMember() != 0 && pExpr->GetMember()->IsMethod()) // Remove UpdateOutputs() break; bool bIsTask = IsTask(pStatement); if (bIsTask && synSetSize == 1) GenAlwaysAtHeader(false); SynAssignmentStatement(pHier, pObj, pRtnObj, pStatement2, bIsTask || synSetSize > 1 || m_bClockedAlwaysAt); if (bIsTask && synSetSize == 1) GenAlwaysAtTrailer(false); } break; case st_switch: if (synSetSize == 1) GenAlwaysAtHeader(false); SynSwitchStatement(pHier, pObj, pRtnObj, pStatement2); if (synSetSize == 1) GenAlwaysAtTrailer(false); break; case st_if: if (pStatement2->IsXilinxFdPrim()) break; if (synSetSize == 1) GenAlwaysAtHeader(pStatement2->GetCompound2() != 0); SynIfStatement(pHier, pObj, pRtnObj, pStatement2); if (synSetSize == 1) GenAlwaysAtTrailer(pStatement2->GetCompound2() != 0); break; case st_null: break; default: Assert(0); break; } } } void CHtvDesign::SynScLocalAlways(CHtvIdent *pMethod, CHtvObject * pObj) { // first check if there are any local variables CHtvIdentTblIter identIter(pMethod->GetIdentTbl()); for (identIter.Begin(); !identIter.End(); identIter++) if (identIter->IsVariable() && !identIter->IsParam() && identIter->IsScLocal()) break; if (identIter.End()) return; // no local variables GenAlwaysAtHeader(false); // blocks with local variables must be named string name = pMethod->GetName(); name.insert(name.size(), "$"); m_vFile.Print("begin : %s\n", name.c_str()); m_vFile.IncIndentLevel(); // now declare local variables m_vFile.SetVarDeclLines(true); for ( ; !identIter.End(); identIter++) { if (identIter->IsVariable() && !identIter->IsParam() && identIter->IsScLocal()) { string bitRange; if (identIter->GetWidth() > 1) bitRange = VA("[%d:0] ", identIter->GetWidth()-1); m_vFile.Print("reg %s%s;\n", bitRange.c_str(), identIter->GetName().c_str()); } } m_vFile.Print("\n"); m_vFile.SetVarDeclLines(false); SynCompoundStatement(pMethod, pObj, 0, false, true); m_vFile.DecIndentLevel(); // always } void CHtvDesign::SynCompoundStatement(CHtvIdent *pHier, CHtvObject * pObj, CHtvObject * pRtnObj, bool bForceSyn, bool bDeclareLocalVariables) { if (bDeclareLocalVariables) { // blocks with local variables must be named m_vFile.Print("begin : %s$\n", pHier->GetName().c_str()); } else m_vFile.Print("begin\n"); m_vFile.IncIndentLevel(); if (bDeclareLocalVariables) { // now declare temps CHtvIdentTblIter identIter(pHier->GetFlatIdentTbl()); for (identIter.Begin(); !identIter.End(); identIter++) { for (int elemIdx = 0; elemIdx < identIter->GetDimenElemCnt(); elemIdx += 1) { if (identIter->IsVariable() && !identIter->IsParam() && !identIter->IsRegClkEn() && !identIter->IsHtPrimOutput(elemIdx)) { string bitRange; if (identIter->GetWidth() > 1) bitRange = VA("[%d:0] ", identIter->GetWidth()-1); //vector<int> refList(identIter->GetDimenCnt(), 0); //do { string identName = identIter->GetVerilogName(elemIdx); //string identName = GenVerilogIdentName(identIter->GetName(), refList); GenHtAttributes(identIter(), identName); m_vFile.Print("reg %s%s;\n", bitRange.c_str(), identName.c_str()); } //while (!identIter->DimenIter(refList)); } } } SynStatementList(pHier, pObj, pRtnObj, (CHtvStatement *)pHier->GetStatementList()); m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } void CHtvDesign::SynStatementList(CHtvIdent *pHier, CHtvObject * pObj, CHtvObject * pRtnObj, CHtvStatement *pStatement) { if (pStatement == 0) return; for ( ; pStatement; pStatement = pStatement->GetNext()) { switch (pStatement->GetStType()) { case st_compound: SynStatementList(pHier, pObj, pRtnObj, pStatement->GetCompound1()); break; case st_assign: SynAssignmentStatement(pHier, pObj, pRtnObj, pStatement); break; case st_switch: SynSwitchStatement(pHier, pObj, pRtnObj, pStatement); break; case st_if: SynIfStatement(pHier, pObj, pRtnObj, pStatement); break; case st_break: break; case st_return: SynReturnStatement(pHier, pObj, pRtnObj, pStatement); break; default: Assert(0); break; } } } void CHtvDesign::SynReturnStatement(CHtvIdent *pFunc, CHtvObject * pObj, CHtvObject * pRtnObj, CHtvStatement *pStatement) { Assert(pFunc->IsFunction()); CHtvOperand * pExpr = PrependObjExpr(pObj, pStatement->GetExpr()); if (pExpr == 0) return; if (pFunc->IsReturnRef()) { Assert(pRtnObj && !pRtnObj->m_pOp); bool bFoundSubExpr = false; bool bWriteIndex = false; if (pExpr->GetOperator() == tk_period && pExpr->GetOperand2()->IsFunction()) { FindSubExpr(pObj, pRtnObj, pExpr, bFoundSubExpr, bWriteIndex, false); pRtnObj->m_pOp = pExpr->GetTempOp(); } else { pExpr->SetTempOpSubGened(false); pRtnObj->m_pOp = pExpr; } if (bFoundSubExpr) { m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } return; } // used for translating return statements to 'function = expression' CHtvOperand *pRslt = new CHtvOperand; pRslt->SetLineInfo(pExpr->GetLineInfo()); pRslt->SetMember(pFunc); pRslt->SetMinWidth(pFunc->GetWidth()); pRslt->SetVerWidth(pFunc->GetWidth()); pRslt->SetIsLeaf(); CHtvOperand *pEqual = new CHtvOperand; pEqual->SetLineInfo(pExpr->GetLineInfo()); pEqual->SetOperator(tk_equal); pEqual->SetOperand1(pRslt); pEqual->SetOperand2(pExpr); pEqual->SetVerWidth(pRslt->GetVerWidth()); bool bFoundSubExpr; bool bWriteIndex; FindSubExpr(pObj, 0, pEqual, bFoundSubExpr, bWriteIndex, false); if (!pFunc->IsReturnRef()) { PrintSubExpr(pObj, 0, pEqual); m_vFile.Print(";\n"); } if (bFoundSubExpr) { m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } } void CHtvDesign::SynAssignmentStatement(CHtvIdent *pHier, CHtvObject * pObj, CHtvObject * pRtnObj, CHtvStatement *pStatement, bool bIsAlwaysAt) { if (pStatement->IsXilinxFdPrim()) return; if (pStatement->IsScPrim()) { m_vFile.SetHtPrimLines(true); SynScPrim(pHier, pObj, pStatement); m_vFile.SetHtPrimLines(false); return; } if (pStatement->IsInitStatement()) { CHtvOperand * pOp1 = pStatement->GetExpr()->GetOperand1(); int elemIdx = pOp1->GetMember()->GetDimenElemIdx(pOp1); if (pOp1->GetMember()->IsHtPrimOutput(elemIdx)) return; } #ifdef _WIN32 if (pStatement->GetExpr()->GetLineInfo().m_lineNum == 619) bool stop = true; #endif CHtvOperand *pExpr = PrependObjExpr(pObj, pStatement->GetExpr()); // handle distributed ram write enables if (!pExpr->IsLeaf() && pExpr->GetOperator() == tk_equal) { CHtvOperand * pLeftOfEqualOp = pExpr->GetOperand1(); if (pLeftOfEqualOp->IsLeaf() && pLeftOfEqualOp->IsVariable()) { CHtvIdent * pLeftOfEqualIdent = pLeftOfEqualOp->GetMember(); if (pLeftOfEqualIdent->GetHtDistRamWeWidth() != 0) { SynHtDistRamWe(pHier, pObj, pRtnObj, pExpr, bIsAlwaysAt); return; } } } if (!bIsAlwaysAt) m_vFile.Print("assign "); bool bFoundSubExpr = false; bool bWriteIndex = false; FindSubExpr(pObj, pRtnObj, pExpr, bFoundSubExpr, bWriteIndex); if (!pExpr->IsLeaf() && pExpr->GetOperator() != tk_period && !bWriteIndex || !bFoundSubExpr) GenSubExpr(pObj, pRtnObj, pExpr, false, false); if (!pExpr->IsLeaf() && pExpr->GetOperator() != tk_period && !bWriteIndex) m_vFile.Print(";\n"); if (bFoundSubExpr) { m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } } void CHtvDesign::SynIfStatement(CHtvIdent *pHier, CHtvObject * pObj, CHtvObject * pRtnObj, CHtvStatement *pStatement) { // check if statement is a memory write CHtvStatement **ppIfList = pStatement->GetPCompound1(); RemoveMemoryWriteStatements(ppIfList); if (*ppIfList == 0 && pStatement->GetCompound2() == 0) return; // remove if statement CHtvOperand *pExpr = PrependObjExpr(pObj, pStatement->GetExpr()); bool bFoundSubExpr; bool bWriteIndex; FindSubExpr(pObj, pRtnObj, pExpr, bFoundSubExpr, bWriteIndex); m_vFile.Print("if ("); PrintSubExpr(pObj, pRtnObj, pExpr, false, false, false, "", tk_toe); m_vFile.Print(")\n"); m_vFile.IncIndentLevel(); m_vFile.Print("begin\n"); m_vFile.IncIndentLevel(); SynStatementList(pHier, pObj, pRtnObj, pStatement->GetCompound1()); m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); m_vFile.DecIndentLevel(); if (pStatement->GetCompound2()) { m_vFile.Print("else\n"); m_vFile.IncIndentLevel(); m_vFile.Print("begin\n"); m_vFile.IncIndentLevel(); SynStatementList(pHier, pObj, pRtnObj, pStatement->GetCompound2()); m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); m_vFile.DecIndentLevel(); } if (bFoundSubExpr) { m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } } void CHtvDesign::SynSwitchStatement(CHtvIdent *pHier, CHtvObject * pObj, CHtvObject * pRtnObj, CHtvStatement *pSwitch) { if (SynXilinxRom(pHier, pSwitch)) return; CHtvOperand *pSwitchOperand = PrependObjExpr(pObj, pSwitch->GetExpr()); bool bForceTemp = !pSwitchOperand->IsLeaf(); bool bFoundSubExpr; bool bWriteIndex; FindSubExpr(pObj, pRtnObj, pSwitchOperand, bFoundSubExpr, bWriteIndex, bForceTemp); m_vFile.Print("case ("); int caseWidth = max(pSwitchOperand->GetMinWidth(), pSwitchOperand->GetSigWidth()); if (pSwitchOperand->HasExprTempVar()) pSwitchOperand->SetExprTempVarWidth( caseWidth ); PrintSubExpr(pObj, pRtnObj, pSwitchOperand); m_vFile.Print(")\n"); m_vFile.IncIndentLevel(); CHtvStatement *pDefaultStatement = 0; CHtvOperand *pCaseOperand; CHtvStatement *pStatement = pSwitch->GetCompound1(); for (; pStatement ; pStatement = pStatement->GetNext()) { // if a combination of case and default for same statement then drop case entry points and use default entry. bool bFoundDefault = false; for (CHtvStatement *pStatement2 = pStatement;; pStatement2 = pStatement2->GetNext()) { bFoundDefault |= pStatement2->GetStType() == st_default; if (pStatement2->GetCompound1() != 0 || pStatement2->GetNext() == 0) { if (bFoundDefault) pStatement = pStatement2; break; } } if (bFoundDefault) { pDefaultStatement = pStatement; continue; } else { for(;; pStatement = pStatement->GetNext()) { pCaseOperand = PrependObjExpr(pObj, pStatement->GetExpr()); bool bFoundSubExpr; bool bWriteIndex; FindSubExpr(pObj, pRtnObj, pCaseOperand, bFoundSubExpr, bWriteIndex); if (bFoundSubExpr) ParseMsg(PARSE_FATAL, "functions in case values not supported"); if (pCaseOperand->IsConstValue()) pCaseOperand->SetOpWidth( caseWidth ); GenSubExpr(pObj, pRtnObj, pCaseOperand, false, false); if (pStatement->GetCompound1() != 0) { m_vFile.Print(":\n"); break; } else m_vFile.Print(", "); } } m_vFile.IncIndentLevel(); m_vFile.Print("begin\n"); m_vFile.IncIndentLevel(); SynStatementList(p
Hier, pObj, pRtnObj, pStatement->GetCompound1()); m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); m_vFile.DecIndentLevel(); } // default statement must be at the end of the case statement if (pDefaultStatement && pDefaultStatement->GetCompound1() && pDefaultStatement->GetCompound1()->GetStType() != st_break) { m_vFile.Print("default:\n"); m_vFile.IncIndentLevel(); m_vFile.Print("begin\n"); m_vFile.IncIndentLevel(); SynStatementList(pHier, pObj, pRtnObj, pDefaultStatement->GetCompound1()); m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); m_vFile.DecIndentLevel(); } m_vFile.DecIndentLevel(); m_vFile.Print("endcase\n"); if (bFoundSubExpr) { m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } } CHtvOperand * CHtvDesign::CreateTempOp(CHtvOperand * pOp, string const &tempName) { CHtvIdent * pIdent = new CHtvIdent; pIdent->SetName(tempName); pIdent->SetType(pOp->GetMember()->GetType()); pIdent->SetId(CHtfeIdent::id_variable); pIdent->SetLineInfo(pOp->GetLineInfo()); pIdent->SetPrevHier(GetTopHier()); CHtvOperand * pTempOp = new CHtvOperand; pTempOp->InitAsIdentifier(pOp->GetLineInfo(), pIdent); return pTempOp; } // Create a new operand node with the appended subfield list from a second node CHtvOperand * CHtvDesign::CreateObject(CHtvOperand * pObj, CHtvOperand * pOp) { CHtvOperand * pNewObj = new CHtvOperand; pNewObj->InitAsIdentifier(pOp->GetLineInfo(), pObj->GetMember()); pNewObj->SetIndexList(pObj->GetIndexList()); if (pNewObj->IsLinkedOp()) Assert(0); // copy subField list CScSubField * pSubField = pObj->GetSubField(); CScSubField ** pNewSubField = pNewObj->GetSubFieldP(); for (; pSubField; pSubField = pSubField->m_pNext) { CScSubField * pSf = new CScSubField; *pSf = *pSubField; *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } // append new subField to list if (pOp->GetSubField() == 0) { CScSubField * pSf = new CScSubField; pSf->m_pIdent = pOp->GetMember(); pSf->m_indexList = pOp->GetIndexList(); pSf->m_bBitIndex = false; pSf->m_subFieldWidth = pOp->GetMember()->GetWidth(); pSf->m_pNext = 0; *pNewSubField = pSf; } else { pSubField = pOp->GetSubField(); for (; pSubField; pSubField = pSubField->m_pNext) { CScSubField * pSf = new CScSubField; *pSf = *pSubField; *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } } return pNewObj; } void CHtvDesign::GenSubObject(CHtvObject * pSubObj, CHtvObject * pObj, CHtvOperand * pOp) { if (!pOp->GetMember()->IsStruct()) { pSubObj->m_pOp = pOp; } else { Assert(pObj); // found a member, prepend the object CHtvOperand * pNewOp = new CHtvOperand; pNewOp->InitAsIdentifier(pOp->GetLineInfo(), pObj->m_pOp->GetMember()); pNewOp->SetIndexList(pObj->m_pOp->GetIndexList()); if (pNewOp->IsLinkedOp()) Assert(0); // copy subField list CScSubField * pSubField = pObj->m_pOp->GetSubField(); CScSubField ** pNewSubField = pNewOp->GetSubFieldP(); for (; pSubField; pSubField = pSubField->m_pNext) { CScSubField * pSf = new CScSubField; *pSf = *pSubField; *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } // append new subField to list if (pOp->GetSubField() == 0) { CScSubField * pSf = new CScSubField; pSf->m_pIdent = pOp->GetMember(); pSf->m_indexList = pOp->GetIndexList(); pSf->m_bBitIndex = false; pSf->m_subFieldWidth = pOp->GetMember()->GetWidth(); pSf->m_pNext = 0; *pNewSubField = pSf; } else { pSubField = pOp->GetSubField(); for (; pSubField; pSubField = pSubField->m_pNext) { CScSubField * pSf = new CScSubField; *pSf = *pSubField; *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } } } } CHtvOperand * CHtvDesign::PrependObjExpr(CHtvObject * pObj, CHtvOperand * pExpr) { // Recursively decend expression tree and duplicate tree. References to members // are replaced with obj.member if (pObj == 0 || pExpr == 0) return pExpr; if (pExpr->IsLeaf()) { if (pExpr->IsConstValue()) return pExpr; CHtvIdent *pIdent = pExpr->GetMember(); if (pIdent->IsFunction()) { // methods do not get a prepended object but it's parameter do if (pExpr->GetParamCnt() > 0) { CHtvOperand * pNewExpr = new CHtvOperand; pNewExpr->InitAsFunction(pExpr->GetLineInfo(), pExpr->GetMember()); pNewExpr->SetType(pExpr->GetType()); for (size_t paramIdx = 0; paramIdx < pExpr->GetParamCnt(); paramIdx += 1) { CHtvOperand * pParamOp = pExpr->GetParam(paramIdx); pNewExpr->GetParamList().push_back(PrependObjExpr(pObj, pParamOp)); } return pNewExpr; } return pExpr; } if (pIdent->GetPrevHier() && !pIdent->GetPrevHier()->IsStruct()) return pExpr; // found a member, prepend the object return PrependObjExpr(pObj, pObj->m_pOp, pExpr); } else { EToken tk = pExpr->GetOperator(); CHtvOperand *pOp1 = PrependObjExpr(pObj, pExpr->GetOperand1()); CHtvOperand *pOp2 = PrependObjExpr(pObj, pExpr->GetOperand2()); CHtvOperand *pOp3 = PrependObjExpr(pObj, pExpr->GetOperand3()); CHtvOperand * pNewExpr = new CHtvOperand; pNewExpr->InitAsOperator(pExpr->GetLineInfo(), tk, pOp1, pOp2, pOp3); pNewExpr->SetType(pExpr->GetType()); pNewExpr->SetIsParenExpr(pExpr->IsParenExpr()); return pNewExpr; } } CHtvOperand * CHtvDesign::PrependObjExpr(CHtvObject * pObj, CHtvOperand * pObjOp, CHtvOperand * pExpr) { // replicate pObjOp and append pExpr's subField list to each identifier if (pObjOp->IsLeaf() && pObjOp->IsConstValue()) return pObjOp; if (pObjOp->IsLeaf() || pObjOp->GetOperator() == tk_period) { CHtvOperand * pNewExpr = new CHtvOperand; pNewExpr->InitAsIdentifier(pExpr->GetLineInfo(), pObjOp->GetMember()); pNewExpr->SetType(pObjOp->GetType()); pNewExpr->SetIndexList(pObjOp->GetIndexList()); if (pNewExpr->IsLinkedOp()) Assert(0); // copy subField list CScSubField * pSubField = pObjOp->GetSubField(); CScSubField ** pNewSubField = pNewExpr->GetSubFieldP(); for (; pSubField; pSubField = pSubField->m_pNext) { CScSubField * pSf = new CScSubField; *pSf = *pSubField; *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } // add expr's member as a subfield if (pExpr->GetSubField() == 0 || pExpr->GetSubField()->m_pIdent != pExpr->GetMember()) { CScSubField * pSf = new CScSubField; pSf->m_pIdent = pExpr->GetMember(); pSf->m_indexList = pExpr->GetIndexList(); pSf->m_bBitIndex = false; pSf->m_subFieldWidth = pExpr->GetMember()->GetWidth(); pSf->m_pNext = 0; *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } // append new subField to list if (pExpr->GetSubField() != 0) { pSubField = pExpr->GetSubField(); for (; pSubField; pSubField = pSubField->m_pNext) { CScSubField * pSf = new CScSubField; pSf->m_pIdent = pSubField->m_pIdent; pSf->m_subFieldWidth = pSubField->m_subFieldWidth; pSf->m_bBitIndex = pSubField->m_bBitIndex; pSf->m_pNext = 0; for (size_t idx = 0; idx < pSubField->m_indexList.size(); idx += 1) { CHtvOperand * pIndexOp = (CHtvOperand *)pSubField->m_indexList[idx]; pSf->m_indexList.push_back(PrependObjExpr(pObj, pIndexOp)); } *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } } return pNewExpr; } else { EToken tk = pObjOp->GetOperator(); Assert(tk == tk_question); CHtvOperand *pObjOp1 = pObjOp->GetOperand1(); CHtvOperand *pObjOp2 = pObjOp->GetOperand2(); CHtvOperand *pObjOp3 = pObjOp->GetOperand3(); CHtvOperand *pNewOp1 = pObjOp1;// ? PrependObjExpr(pObj, pObjOp1, pExpr) : 0; CHtvOperand *pNewOp2 = pObjOp2 ? PrependObjExpr(pObj, pObjOp2, pExpr) : 0; CHtvOperand *pNewOp3 = pObjOp3 ? PrependObjExpr(pObj, pObjOp3, pExpr) : 0; CHtvOperand * pNewExpr = new CHtvOperand; pNewExpr->InitAsOperator(pExpr->GetLineInfo(), tk, pNewOp1, pNewOp2, pNewOp3); pNewExpr->SetType(pObjOp->GetType()); pNewExpr->SetIsParenExpr(pExpr->IsParenExpr()); return pNewExpr; } } void CHtvDesign::FindSubExpr(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr, bool &bFoundSubExpr, bool &bWriteIndex, bool bForceTemp, bool bOutputParam) { vector<CHtvDesign::CTempVar> tempVarList; #ifdef WIN32 if (pExpr->GetLineInfo().m_lineNum == 37)// || pExpr->GetLineInfo().m_lineNum == 18) bool stop = true; #endif //string exprBlockId = GetNextExprBlockId(pExpr); //if (exprBlockId == "17$109") // bool stop = true; SetOpWidthAndSign(pExpr); bFoundSubExpr = FindIfSubExprRequired(pExpr, bOutputParam, false, false, false) || bForceTemp; if (bFoundSubExpr) { string exprBlockId = GetNextExprBlockId(pExpr); #ifdef WIN32 if (exprBlockId == "20$37") bool stop = true; #endif m_vFile.Print("begin : Block$%s // %s:%d\n", exprBlockId.c_str(), pExpr->GetLineInfo().m_fileName.c_str(), pExpr->GetLineInfo().m_lineNum); m_vFile.IncIndentLevel(); } if (bForceTemp && !pExpr->HasExprTempVar()) { string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); pExpr->SetIsSubExprRequired(true); pExpr->SetExprTempVar( tempVarName, pExpr->IsSigned()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } if (bFoundSubExpr) MarkSubExprTempVars(pObj, pExpr, tempVarList, tk_eof, true, false); bWriteIndex = false; if (!pExpr->IsLeaf() && pExpr->GetOperator() == tk_equal) { CHtvOperand * pLeftOfEqualOp = pExpr->GetOperand1(); if (pLeftOfEqualOp->IsLeaf() && pLeftOfEqualOp->IsVariable()) bWriteIndex = pLeftOfEqualOp->HasArrayTempVar(); } if (bFoundSubExpr) { m_vFile.SetVarDeclLines(true); for (size_t i = 0; i < tempVarList.size(); i += 1) { switch (tempVarList[i].m_tempType) { case eTempVar: { int width = tempVarList[i].m_width; string bitRange; if (width > 1) bitRange = VA("[%d:0] ", width-1); tempVarList[i].m_declWidth = width; m_vFile.Print("reg %-10s %s;\n", bitRange.c_str(), tempVarList[i].m_name.c_str()); m_vFile.PrintVarInit("%s = 32'h0;\n", tempVarList[i].m_name.c_str()); } break; case eTempArrIdx: { CHtvOperand *pOp = tempVarList[i].m_pOperand; CHtvIdent *pIdent = pOp->GetMember(); HtfeOperandList_t &indexList = pOp->GetIndexList(); int idxBits = 0; for (size_t j = 0; j < indexList.size(); j += 1) { if (indexList[j]->IsConstValue()) continue; int idxWidth; if (!GetFieldWidthFromDimen( pIdent->GetDimenList()[j], idxWidth )) ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "invalid array index (32K limit)"); idxBits += idxWidth; } tempVarList[i].m_declWidth = idxBits; string bitRange; if (idxBits > 1) bitRange = VA("[%d:0] ", idxBits-1); m_vFile.Print("reg %-10s %s;\n", bitRange.c_str(), tempVarList[i].m_name.c_str()); m_vFile.PrintVarInit("%s = 32'h0;\n", tempVarList[i].m_name.c_str()); } break; case eTempFldIdx: { int width; if (!GetFieldWidthFromDimen( tempVarList[i].m_width, width )) ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "invalid field index (32K limit)"); string bitRange; if (width > 1) bitRange = VA("[%d:0] ", width-1); tempVarList[i].m_declWidth = width; m_vFile.Print("reg %-10s %s;\n", bitRange.c_str(), tempVarList[i].m_name.c_str()); m_vFile.PrintVarInit("%s = 32'h0;\n", tempVarList[i].m_name.c_str()); } break; } m_tempVarMap.insert(TempVarMap_ValuePair(tempVarList[i].m_name, tempVarList[i].m_declWidth) ); } m_vFile.SetVarDeclLines(false); } // generate sub expressions GenSubExpr(pObj, pRtnObj, pExpr, false, false, true); return; } bool CHtvDesign::FindIfSubExprRequired(CHtvOperand *pExpr, bool bIsLeftOfEqual, bool bPrevTkIsEqual, bool bIsFuncParam, bool bHasObj) { // recursively decend expression tree looking for function calls and ++/-- // mark nodes from the function/++/-- to the top of the tree with IsSubExprRequired Assert(pExpr != 0); bool bSubExprFound = false; pExpr->SetIsSubExprRequired(false); pExpr->SetIsSubExprGenerated(false); pExpr->SetArrayTempGenerated(false); pExpr->SetFieldTempGenerated(false); pExpr->SetIsFuncGenerated(false); pExpr->SetExprTempVar("", false); pExpr->SetArrayTempVar(""); pExpr->SetFieldTempVar(""); pExpr->SetFuncTempVar("", false); pExpr->SetTempOp(0); if (pExpr->IsLeaf()) { if (pExpr->IsConstValue()) { pExpr->SetVerWidth(pExpr->GetOpWidth()); return false; } CHtvIdent *pIdent = pExpr->GetMember(); bSubExprFound = !bIsLeftOfEqual && pIdent->IsFunction() && pIdent->GetType() != GetVoidType(); pExpr->SetIsSubExprRequired(bSubExprFound); if (pIdent->IsFunction() && !bIsLeftOfEqual) { bool bMemberFunc = pIdent->GetPrevHier() && pIdent->GetPrevHier()->IsStruct(); if (pIdent->GetGlobalRefSet().size() == 0 || bMemberFunc) { // find subExpr in function parameters for (size_t i = 0; i < pExpr->GetParamCnt(); i += 1) { if (FindIfSubExprRequired(pExpr->GetParam(i), false, false, true, false)) { pExpr->SetIsSubExprRequired(true); bSubExprFound = true; } } } } if (pIdent->IsVariable() || pIdent->IsFunction() && !bIsLeftOfEqual && pExpr->GetType() != GetVoidType()) { // find sub expression in variable indexes for (size_t i = 0; i < pExpr->GetIndexCnt(); i += 1) { int idxDimen = (int)pExpr->GetMember()->GetDimenList()[i]; int idxWidth; if (!GetFieldWidthFromDimen( idxDimen, idxWidth )) ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "invalid variable index (32K limit)"); pExpr->GetIndex(i)->SetVerWidth( idxWidth ); if (pExpr->GetIndex(i)->IsConstValue()) continue; pExpr->SetIsSubExprRequired(true); pExpr->GetIndex(i)->SetIsSubExprRequired(true); bSubExprFound = true; FindIfSubExprRequired(pExpr->GetIndex(i), false, false, false, false); } // check if a non-const sub-field index exists int lowBit; if (g_htvArgs.IsVivadoEnabled() && /*!pExpr->IsLinkedOp() &&*/ !bIsFuncParam && pIdent->IsVariable() && !bHasObj && (!IsConstSubFieldRange(pExpr, lowBit) || lowBit > 0) && !bPrevTkIsEqual && !bIsLeftOfEqual) { pExpr->SetIsSubExprRequired(true); bSubExprFound = true; } for (CScSubField *pSubField = pExpr->GetSubField() ; pSubField; pSubField = pSubField->m_pNext) { for (size_t i = 0; i < pSubField->m_indexList.size(); i += 1) { CConstValue value; if (!EvalConstantExpr(pSubField->m_indexList[i], value)) { bSubExprFound = true; pExpr->SetIsSubExprRequired(true); FindIfSubExprRequired((CHtvOperand *)pSubField->m_indexList[i], false, false, false, false); break; } } } pExpr->SetVerWidth( pExpr->GetSubFieldWidth() ); } if (pIdent->IsType()) pExpr->SetVerWidth( pIdent->GetWidth() ); } else if (pExpr->GetOperator() == tk_period) { CHtvOperand *pOp1 = pExpr->GetOperand1(); CHtvOperand *pOp2 = pExpr->GetOperand2(); Assert(pOp2->IsLeaf() && pOp2->GetMember()->IsFunction()); bool bSubExprFound1 = false; if (pOp1->GetOperator() == tk_period) bSubExprFound1 = FindIfSubExprRequired(pOp1, false, false, false, true); bool bSubExprFound2 = FindIfSubExprRequired(pOp2, false, false, false, true); bSubExprFound = bSubExprFound1 || bSubExprFound2; pExpr->SetIsSubExprRequired(bSubExprFound); } else { CHtvOperand *pOp1 = pExpr->GetOperand1(); CHtvOperand *pOp2 = pExpr->GetOperand2(); CHtvOperand *pOp3 = pExpr->GetOperand3(); EToken tk = pExpr->GetOperator(); if (tk == tk_preInc || tk == tk_preDec || tk == tk_postInc || tk == tk_postDec) bSubExprFound = true; bool bSubExprFound1 = false; bool bSubExprFound2 = false; bool bSubExprFound3 = false; if (pOp1) bSubExprFound1 = FindIfSubExprRequired(pOp1, tk == tk_equal, false, false, bHasObj); if (pOp2) bSubExprFound2 = FindIfSubExprRequired(pOp2, false, tk == tk_equal, false, bHasObj); if (pOp3) bSubExprFound3 = FindIfSubExprRequired(pOp3, false, false, false, bHasObj); bSubExprFound = bSubExprFound1 || bSubExprFound2 || bSubExprFound3 || bSubExprFound; int verWidth1 = 0; int verWidth2 = 0; if (pOp1) verWidth1 = min( pExpr->GetOperand1()->GetVerWidth(), pExpr->GetOperand1()->GetOpWidth() ); if (pOp2) verWidth2 = min( pExpr->GetOperand2()->GetVerWidth(), pExpr->GetOperand2()->GetOpWidth() ); if (tk != tk_equal && tk != tk_typeCast && pExpr->GetOpWidth() != 1 && pOp2 != 0) { if (pOp1 && pOp1->IsSigned() && pOp1->GetVerWidth() < pExpr->GetOpWidth() && (!pOp1->IsConstValue() || pOp1->GetOpWidth() < pExpr->GetOpWidth()) && !pOp1->IsLinkedOp() && !bIsLeftOfEqual) bSubExprFound = true; if (pOp2 && pOp2->IsSigned() && pOp2->GetVerWidth() < pExpr->GetOpWidth() && (!pOp2->IsConstValue() || pOp2->GetOpWidth() < pExpr->GetOpWidth()) && !pOp2->IsLinkedOp()) bSubExprFound = true; if (pOp3 && pOp3->IsSigned() && pOp3->GetVerWidth() < pExpr->GetOpWidth() && (!pOp3->IsConstValue() || pOp3->GetOpWidth() < pExpr->GetOpWidth())) bSubExprFound = true; } switch (tk) { case tk_preInc: case tk_preDec: case tk_postInc: case tk_postDec: pExpr->SetVerWidth( pExpr->GetOpWidth() ); bSubExprFound = true; break; case tk_unaryPlus: case tk_unaryMinus: case tk_tilda: pExpr->SetVerWidth( pExpr->GetOpWidth() ); if (pOp1->GetVerWidth() < pExpr->GetOpWidth()) bSubExprFound = true; break; case tk_equal: // set to operand 1's verWidth pExpr->SetVerWidth(verWidth1); if (verWidth1 > pOp2->GetOpWidth() && !pOp2->IsConstValue()) bSubExprFound = true; break; case tk_typeCast: // set to operand 1's verWidth pExpr->SetVerWidth(verWidth1); if (verWidth1 != pOp2->GetOpWidth()) bSubExprFound = true; break; case tk_less: case tk_greater: case tk_lessEqual: case tk_greaterEqual: // set to one pExpr->SetVerWidth(1); break; case tk_bang: case tk_vbarVbar: case tk_ampersandAmpersand: case tk_equalEqual: case tk_bangEqual: // set to one pExpr->SetVerWidth(1); break; case tk_plus: case tk_minus: case tk_vbar: case tk_ampersand: case tk_carot: case tk_asterisk: case tk_percent: case tk_slash:
pExpr->SetVerWidth( pExpr->GetOpWidth() ); if (pOp1->GetVerWidth() < pExpr->GetOpWidth() && (!pOp1->IsConstValue() || pOp1->GetOpWidth() < pExpr->GetOpWidth()) && pOp2->GetVerWidth() < pExpr->GetOpWidth() && (!pOp2->IsConstValue() || pOp2->GetOpWidth() < pExpr->GetOpWidth())) bSubExprFound = true; break; case tk_comma: // sum of operands 1 & 2 pExpr->SetVerWidth(min(pExpr->GetOpWidth(), verWidth1 + verWidth2)); break; case tk_lessLess: case tk_greaterGreater: pExpr->SetVerWidth( pExpr->GetOpWidth() ); if (pOp1->GetVerWidth() < pExpr->GetOpWidth()) bSubExprFound = true; if (!pOp2->IsConstValue() && (pOp2->IsSigned() || pOp2->GetVerWidth() > 6)) bSubExprFound = true; break; case tk_question: // maximum of operands 2 & 3 pExpr->SetVerWidth( pExpr->GetOpWidth() ); if (pOp2->GetVerWidth() < pExpr->GetOpWidth() && pOp3->GetVerWidth() < pExpr->GetOpWidth()) bSubExprFound = true; if (pOp2->IsSubExprRequired() || pOp3->IsSubExprRequired()) bSubExprFound = true; break; default: Assert(0); } pExpr->SetIsSubExprRequired(bSubExprFound); } return bSubExprFound; } void CHtvDesign::MarkSubExprTempVars(CHtvObject * &pObj, CHtvOperand *pExpr, vector<CTempVar> &tempVarList, EToken prevTk, bool bParentNotLogical, bool bIsLeftOfEqual, bool bIsFuncParam) { // recursively desend expression tree looking for function calls and conditional expressions (?:) // Mark expression node and all assencing nodes where found // generate list of temporary variables needed for expression // Temp needed for: // 1. function with non-boolean returned value // 2. && or || node where parent node is not && or || // 3. ?: node with subexpr function call Assert(pExpr != 0); if (pExpr->IsLeaf()) { if (pExpr->IsConstValue()) return; CHtvIdent *pIdent = pExpr->GetMember(); if (pIdent->IsFunction() && !bIsLeftOfEqual) { if (pExpr->GetType() != GetVoidType() && !pExpr->GetMember()->IsReturnRef()) { pExpr->SetIsSubExprRequired(true); pExpr->SetFuncTempVar(GetTempVarName(GetExprBlockId(), tempVarList.size()), pIdent->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pIdent->GetWidth())); } bool bMemberFunc = pIdent->GetPrevHier() && pIdent->GetPrevHier()->IsStruct(); if (pIdent->GetGlobalRefSet().size() == 0 || bMemberFunc) { // find temps in function parameters for non-inlined function for (size_t i = 0; i < pExpr->GetParamCnt(); i += 1) { MarkSubExprTempVars(pObj, pExpr->GetParam(i), tempVarList, tk_eof, true, false, true); CHtvOperand * pOp = pExpr->GetParam(i); if (!pOp->HasExprTempVar() && (bMemberFunc ? !pOp->IsConstValue() : (!pOp->IsLeaf() || pOp->HasArrayTempVar() || pOp->HasFieldTempVar()))) { pOp->SetIsSubExprRequired(true); pOp->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pExpr->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pOp->GetVerWidth())); } } } } if (pIdent->IsVariable() || pIdent->IsFunction() && !bIsLeftOfEqual) { // mark sub expression in variable indexes for (size_t i = 0; i < pExpr->GetIndexCnt(); i += 1) { if (pExpr->GetIndex(i)->IsConstValue()) continue; // mark array variable as needing a temp if (!pExpr->HasExprTempVar()) { pExpr->SetIsSubExprRequired(true); pExpr->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pExpr->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetVerWidth())); } // mark index variable as needing a temp if (!pExpr->HasArrayTempVar()) { pExpr->SetIsSubExprRequired(true); pExpr->SetArrayTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()) ); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempArrIdx, tempVarName, -1, pExpr)); } // check if index has sub expressions MarkSubExprTempVars(pObj, pExpr->GetIndex(i), tempVarList, pExpr->GetOperator(), true); } // mark sub expression in field indexing bool bIsSigned = false; bool bHasNonConstIndex = false; int tempVarWidth = 0; for (CScSubField *pSubField = pExpr->GetSubField() ; pSubField; pSubField = pSubField->m_pNext) { for (size_t i = 0; i < pSubField->m_indexList.size(); i += 1) { CConstValue value; if (!EvalConstantExpr(pSubField->m_indexList[i], value)) { //if (!pSubField->m_indexList[i]->IsConstValue()) { bHasNonConstIndex = true; // mark field index expression as needing a temp if (!pExpr->HasFieldTempVar()) { pExpr->SetIsSubExprRequired(true); pExpr->SetFieldTempVar(GetTempVarName(GetExprBlockId(), tempVarList.size())); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); int width; if (pObj) { CHtvOperand * pOp = pObj->m_pOp; while (!pOp->IsLeaf()) { Assert(pOp->GetOperator() == tk_question); pOp = pOp->GetOperand2(); } width = pOp->GetWidth(); } else { CHtvIdent * pIdent = pExpr->GetMember(); while (pIdent->GetPrevHier()->GetId() == CHtfeIdent::id_struct) pIdent = pIdent->GetPrevHier(); width = pIdent->GetWidth(); } tempVarList.push_back(CTempVar(eTempFldIdx, tempVarName, width)); } // check if index has sub expressions MarkSubExprTempVars(pObj, (CHtvOperand *)pSubField->m_indexList[i], tempVarList, pExpr->GetOperator(), true); } } bIsSigned = pSubField->m_pIdent && pSubField->m_pIdent->GetType()->IsSigned(); if (bIsSigned) tempVarWidth = pSubField->m_pIdent->GetWidth(); } if (bIsSigned && bHasNonConstIndex && !bIsLeftOfEqual && !pExpr->HasExprTempVar()) { // Signed subfield, use temp to avoid simv bug pExpr->SetIsSubExprRequired(true); pExpr->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), true); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, tempVarWidth, pExpr)); } int lowBit; if (g_htvArgs.IsVivadoEnabled() && /*!pExpr->IsLinkedOp() &&*/ !bIsFuncParam && pIdent->IsVariable() && pObj == 0 && (!IsConstSubFieldRange(pExpr, lowBit) || lowBit > 0) && !bIsLeftOfEqual && !pExpr->HasExprTempVar() && prevTk != tk_equal) { // use temp to avoid vivado very wide math operations pExpr->SetIsSubExprRequired(true); pExpr->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), bIsSigned); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetVerWidth(), pExpr)); } } return; } else if (pExpr->GetOperator() == tk_period) { CHtvOperand *pOp1 = pExpr->GetOperand1(); CHtvOperand *pOp2 = pExpr->GetOperand2(); Assert(pOp2->IsLeaf() && pOp2->GetMember()->IsFunction()); CHtvObject * pOrigObj = pObj; CHtvObject obj; if (prevTk != tk_period && pObj == 0) { obj.m_pOp = 0; pObj = &obj; } if (pOp1->IsLeaf() && pObj->m_pOp == 0) pObj->m_pOp = pOp1; // Functions that return a reference must have a field index temp if (pOp1->IsFunction() && pOp1->GetMember()->IsReturnRef()) { pOp1->SetFieldTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()) ); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); int width; if (pObj) width = pObj->m_pOp->GetWidth(); else { CHtvIdent * pIdent = pOp1->GetMember(); while (pIdent->GetPrevHier()->GetId() == CHtfeIdent::id_struct) pIdent = pIdent->GetPrevHier(); width = pIdent->GetWidth(); } tempVarList.push_back(CTempVar(eTempFldIdx, tempVarName, width)); } MarkSubExprTempVars(pObj, pOp1, tempVarList, tk_period, true, false); if (pOp2->IsFunction() && pOp2->GetMember()->IsReturnRef()) { pOp2->SetFieldTempVar(GetTempVarName(GetExprBlockId(), tempVarList.size())); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); int width; if (pObj) width = pObj->m_pOp->GetWidth(); else { CHtvIdent * pIdent = pOp2->GetMember(); while (pIdent->GetPrevHier()->GetId() == CHtfeIdent::id_struct) pIdent = pIdent->GetPrevHier(); width = pIdent->GetWidth(); } tempVarList.push_back(CTempVar(eTempFldIdx, tempVarName, width)); } MarkSubExprTempVars(pObj, pOp2, tempVarList, tk_period, true, false); if (prevTk != tk_period) pObj = pOrigObj; } else { CHtvOperand *pOp1 = pExpr->GetOperand1(); CHtvOperand *pOp2 = pExpr->GetOperand2(); CHtvOperand *pOp3 = pExpr->GetOperand3(); EToken tk = pExpr->GetOperator(); bool bLogical = tk == tk_ampersandAmpersand || tk == tk_vbarVbar; if (bLogical && pExpr->IsSubExprRequired()) { if (bParentNotLogical) { if (!pExpr->HasExprTempVar()) { pExpr->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pExpr->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } } pOp1->SetIsSubExprRequired(true); pOp1->SetExprTempVar(pExpr->GetExprTempVar(), pOp1->IsSigned()); pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar(pExpr->GetExprTempVar(), pOp2->IsSigned()); } if (tk != tk_typeCast && pOp1) { MarkSubExprTempVars(pObj, pOp1, tempVarList, tk, !bLogical, tk == tk_equal); if (tk == tk_equal && pOp1->HasExprTempVar()) { // array indexing on left of equal, use same temp for right of equal Assert(!pOp2->HasExprTempVar()); pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar(pOp1->GetExprTempVar(), pOp2->IsSigned()); } if (tk == tk_equal && pOp1->HasFieldTempVar() && !pOp2->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp2->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pOp2->GetOpWidth())); } } if (pOp2) MarkSubExprTempVars(pObj, pOp2, tempVarList, tk, !bLogical, false); if (pOp3) MarkSubExprTempVars(pObj, pOp3, tempVarList, tk, !bLogical); if (tk != tk_equal && tk != tk_typeCast && pExpr->GetOpWidth() != 1 && pOp2 != 0) { if (pOp1 && pOp1->IsSigned() && pOp1->GetVerWidth() < pExpr->GetOpWidth() && (!pOp1->IsConstValue() || pOp1->GetOpWidth() < pExpr->GetOpWidth()) && !pOp1->IsLinkedOp() && !bIsLeftOfEqual) { if (!pOp1->HasExprTempVar()) { // insert temp if signed operand is narrower than opWidth pOp1->SetIsSubExprRequired(true); pOp1->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp1->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } else { pOp1->SetIsExprTempVarSigned(pOp1->IsSigned()); // find existing temp in list for (size_t i = 0; i < tempVarList.size(); i += 1) if (tempVarList[i].m_name == pOp1->GetExprTempVar()) { tempVarList[i].m_width = pExpr->GetOpWidth(); break; } } } if (pOp2 && pOp2->IsSigned() && pOp2->GetVerWidth() < pExpr->GetOpWidth() && (!pOp2->IsConstValue() || pOp2->GetOpWidth() < pExpr->GetOpWidth()) && !pOp2->IsLinkedOp()) { if (!pOp2->HasExprTempVar()) { // insert temp if signed operand is narrower than opWidth pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp2->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } else { pOp2->SetIsExprTempVarSigned(pOp2->IsSigned()); // find existing temp in list for (size_t i = 0; i < tempVarList.size(); i += 1) if (tempVarList[i].m_name == pOp2->GetExprTempVar()) { tempVarList[i].m_width = pExpr->GetOpWidth(); break; } } } if (pOp3 && pOp3->IsSigned() && pOp3->GetVerWidth() < pExpr->GetOpWidth() && (!pOp3->IsConstValue() || pOp3->GetOpWidth() < pExpr->GetOpWidth())) { if (!pOp3->HasExprTempVar()) { // insert temp if signed operand is narrower than opWidth pOp3->SetIsSubExprRequired(true); pOp3->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp3->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } else { pOp3->SetIsExprTempVarSigned(pOp3->IsSigned()); // find existing temp in list for (size_t i = 0; i < tempVarList.size(); i += 1) if (tempVarList[i].m_name == pOp3->GetExprTempVar()) { tempVarList[i].m_width = pExpr->GetOpWidth(); break; } } } } switch (tk) { case tk_preInc: case tk_preDec: case tk_postInc: case tk_postDec: if (!pExpr->HasExprTempVar()) { pExpr->SetIsSubExprRequired(true); pExpr->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pExpr->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } pOp1->SetIsSubExprRequired(true); pOp1->SetExprTempVar(pExpr->GetExprTempVar(), pOp1->IsSigned()); break; case tk_unaryPlus: case tk_unaryMinus: case tk_tilda: if (pOp1->GetVerWidth() < pExpr->GetOpWidth() && !pOp1->HasExprTempVar()) { pOp1->SetIsSubExprRequired(true); pOp1->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp1->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } break; case tk_equal: if (pOp1->GetVerWidth() > pOp2->GetOpWidth() && !pOp2->IsConstValue()) { if (!pOp2->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp2->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pOp2->GetOpWidth())); } } break; case tk_typeCast: if (pExpr->GetVerWidth() > pOp2->GetOpWidth() && pExpr->GetVerWidth() < pExpr->GetOpWidth() && !pExpr->IsSigned() && pOp2->IsSigned()) { // must insert cast operator to get another temp CHtvOperand * pNewType = new CHtvOperand; pNewType->SetLineInfo(pOp2->GetLineInfo()); pNewType->SetIsLeaf(); pNewType->SetMember(pOp1->GetType()); CHtvOperand * pNewCast = new CHtvOperand; pNewCast->SetLineInfo(pOp2->GetLineInfo()); pNewCast->SetOperator(tk_typeCast); pNewCast->SetOperand1(pNewType); pNewCast->SetOperand2(pOp2); pExpr->SetOperand2(pNewCast); // reduced range temp string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); if (!pOp2->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( tempVarName, pOp2->IsSigned()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pOp2->GetOpWidth())); } else { pOp2->SetIsExprTempVarSigned(pOp2->IsSigned()); // find existing temp in list for (size_t i = 0; i < tempVarList.size(); i += 1) if (tempVarList[i].m_name == pOp2->GetExprTempVar()) { tempVarList[i].m_width = pOp2->GetOpWidth(); break; } } // expand range temp pNewCast->SetIsSubExprRequired(true); pNewCast->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pExpr->IsSigned()); pNewCast->SetExprTempVarWidth(pExpr->GetVerWidth()); tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetVerWidth())); } else if (pExpr->GetVerWidth() > pOp2->GetOpWidth() && pExpr->IsSigned() && !pOp2->IsSigned()) { // casting an unsigned value to a wider signed value // add unsigned temp to width of cast string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); int castWidth = pExpr->GetVerWidth(); if (!pOp2->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( tempVarName, false); tempVarList.push_back(CTempVar(eTempVar, tempVarName, castWidth)); } else { pOp2->SetIsExprTempVarSigned(false); // find existing temp in list for (size_t i = 0; i < tempVarList.size(); i += 1) if (tempVarList[i].m_name == pOp2->GetExprTempVar()) { tempVarList[i].m_width = castWidth; break; } } } else if (pExpr->GetVerWidth() > pOp2->GetOpWidth() && pExpr->IsSigned() == pOp2->IsSigned() && pOp2->IsLeaf()) { // casting to a wider width string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); int castWidth = pExpr->GetVerWidth(); if (!pOp2->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( tempVarName, pExpr->IsSigned()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, castWidth)); } else { pOp2->SetIsExprTempVarSigned(pExpr->IsSigned()); // find existing temp in list for (size_t i = 0; i < tempVarList.size(); i += 1) if (tempVarList[i].m_name == pOp2->GetExprTempVar()) { tempVarList[i].m_width = castWidth; break; } } } else if (pExpr->GetVerWidth() != pOp2->GetOpWidth() || pExpr->IsSigned() != pOp2->IsSigned()) { string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); int castWidth = min(pExpr->GetVerWidth(), pOp2->GetOpWidth()); if (!pOp2->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( tempVarName, pExpr->IsSigned()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, castWidth)); } else { pOp2->SetIsExprTempVarSigned(pExpr->IsSigned()); // find existing temp in list for (size_t i = 0; i < tempVarList.size(); i += 1) if (tempVarList[i].m_name == pOp2->GetExprTempVar()) { tempVarList[i].m_width = castWidth; break; } } } break; case tk_less: case tk_greater: case tk_lessEqual: case tk_greaterEqual: break; case tk_bang: case tk_vbarVbar: case tk_ampersandAmpersand: case tk_equalEqual: case tk_bangEqual: break; case tk_plus: case tk_minus: case tk_vbar: case tk_ampersand: case tk_carot: case tk_asterisk: case tk_percent: case tk_slash: if (pOp1->GetVerWidth() < pExpr->GetOpWidth() && (!pOp1->IsConstValue() || pOp1->GetOpWidth() < pExpr->GetOpWidth()) && pOp2->GetVerWidth() < pExpr->GetOpWidth() && (!pOp2->IsConstValue() || pOp2->GetOpWidth() < pExpr->GetOpWidth()) && !pOp1->HasExprTempVar() && !pOp2->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp2->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempV
arName, pExpr->GetOpWidth())); } break; case tk_comma: break; case tk_lessLess: case tk_greaterGreater: if (pOp1->GetVerWidth() < pExpr->GetOpWidth() && !pOp1->HasExprTempVar()) { pOp1->SetIsSubExprRequired(true); pOp1->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp1->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } break; case tk_question: if (pOp2->GetVerWidth() < pExpr->GetOpWidth() && pOp3->GetVerWidth() < pExpr->GetOpWidth() && !pOp2->HasExprTempVar() && !pOp3->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar( GetTempVarName(GetExprBlockId(), tempVarList.size()), pOp2->IsSigned()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } if (pOp2->IsSubExprRequired() || pOp3->IsSubExprRequired()) { // first check if op2 or op3 has temp with correct width string tempVar; if (pOp2->HasExprTempVar() && pExpr->GetOpWidth() == tempVarList[ GetTempVarIdx(pOp2->GetExprTempVar()) ].m_width) tempVar = pOp2->GetExprTempVar(); else if (pOp3->HasExprTempVar() && pExpr->GetOpWidth() == tempVarList[ GetTempVarIdx(pOp3->GetExprTempVar()) ].m_width) tempVar = pOp3->GetExprTempVar(); else if (pExpr->HasExprTempVar()) tempVar = pExpr->GetExprTempVar(); else { tempVar = GetTempVarName(GetExprBlockId(), tempVarList.size()); string tempVarName = GetTempVarName(GetExprBlockId(), tempVarList.size()); tempVarList.push_back(CTempVar(eTempVar, tempVarName, pExpr->GetOpWidth())); } // pre nodes with common temp if (!pExpr->HasExprTempVar()) { pExpr->SetIsSubExprRequired(true); pExpr->SetExprTempVar( tempVar, pExpr->IsSigned()); } if (!pOp2->HasExprTempVar()) { pOp2->SetIsSubExprRequired(true); pOp2->SetExprTempVar(tempVar, pOp2->IsSigned()); } if (!pOp3->HasExprTempVar()) { pOp3->SetIsSubExprRequired(true); pOp3->SetExprTempVar(tempVar, pOp3->IsSigned()); } } break; default: Assert(0); } if (pOp1 && pOp1->IsSubExprRequired() || pOp2 && pOp2->IsSubExprRequired() || pOp3 && pOp3->IsSubExprRequired()) pExpr->SetIsSubExprRequired(true); } } bool CHtvDesign::SynXilinxRom(CHtvIdent *pHier, CHtvStatement *pSwitch) { // First check if switch width is eight and all case statements are constants CHtvOperand *pSwitchOperand = pSwitch->GetExpr(); if (!pHier->IsMethod()) return false; // functions and tasks can not instanciate primitives if (pSwitchOperand->GetVerWidth() != 8) return false; // Only 256 entry Roms CHtvIdent *pInputIdent = pSwitchOperand->GetMember(); // verify right side of statements are constant CHtvIdent *pOutputIdent = 0; int romWidth = 0; uint64 romTable[256]; bool romTableAssigned[256]; for (int i = 0; i < 256; i += 1) romTableAssigned[i] = false; bool bDefaultFound = false; uint64 defaultValue = 0; CHtvStatement *pStatement = pSwitch->GetCompound1(); for (; pStatement ; pStatement = pStatement->GetNext()) { int64_t romTableIdx; if (pStatement->GetStType() == st_default) { romTableIdx = 0; bDefaultFound = true; } else { CHtvOperand *pCaseOperand = pStatement->GetExpr(); if (!pCaseOperand->IsConstValue()) return false; romTableIdx = pCaseOperand->GetConstValue().GetUint64(); if (romTableIdx >= 256) return false; } CHtvStatement *pCaseStatement = pStatement->GetCompound1(); if (pCaseStatement == 0) return false; if (pCaseStatement->GetStType() != st_assign) return false; CHtvOperand *pAssignExpr = pCaseStatement->GetExpr(); if (pAssignExpr->IsLeaf() || pAssignExpr->GetOperator() != tk_equal) return false; CHtvOperand *pAssignLeftExpr = pAssignExpr->GetOperand1(); if (pOutputIdent == 0) { pOutputIdent = pAssignLeftExpr->GetMember(); romWidth = pOutputIdent->GetWidth(); if (romWidth > 64) return false; } else { if (pOutputIdent != pAssignLeftExpr->GetMember()) return false; } CHtvOperand *pAssignRightExpr = pAssignExpr->GetOperand2(); if (!pAssignRightExpr->IsConstValue()) return false; if (pStatement->GetStType() == st_default) { defaultValue = pAssignRightExpr->GetConstValue().GetUint64(); } else { if (romTableAssigned[romTableIdx]) return false; romTableAssigned[romTableIdx] = true; romTable[romTableIdx] = pAssignRightExpr->GetConstValue().GetUint64(); } } if (bDefaultFound) { for (int idx = 0; idx < 256; idx += 1) if (!romTableAssigned[idx]) romTable[idx] = defaultValue; } else { for (int idx = 0; idx < 256; idx += 1) if (!romTableAssigned[idx]) return false; } // Valid 256 entry rom table found, generate Xilinx primitives for (int lutIdx = 0; lutIdx < 4; lutIdx += 1) m_vFile.Print("wire [%d:0] %s_L%d;\n", romWidth-1, pOutputIdent->GetName().c_str(), lutIdx); for (int muxIdx = 0; muxIdx < 2; muxIdx += 1) m_vFile.Print("reg [%d:0] %s_M%d;\n", romWidth-1, pOutputIdent->GetName().c_str(), muxIdx); for (int bit = 0; bit < romWidth; bit += 1) { int romData = 0; for (int romIdx = 255; romIdx >= 0; romIdx -= 1) { romData <<= 1; romData |= (romTable[romIdx] >> bit) & 1; if ((romIdx & 0x3f) == 0x3f) { if (romIdx != 255) m_vFile.Print(";\n"); m_vFile.Print("defparam %s_L%d$%d.INIT = 64'h", pOutputIdent->GetName().c_str(), romIdx >> 6, bit); } if ((romIdx & 3) == 0) { m_vFile.Print("%x", romData); romData = 0; } } m_vFile.Print(";\n"); for (int lutIdx = 3; lutIdx >= 0; lutIdx -= 1) { m_vFile.Print("LUT6 %s_L%d$%d ( .O(%s_L%d[%d])", pOutputIdent->GetName().c_str(), lutIdx, bit, pOutputIdent->GetName().c_str(), lutIdx, bit); for (int addrBit = 5; addrBit >= 0; addrBit -= 1) m_vFile.Print(", .I%d(%s[%d])", addrBit, pInputIdent->GetName().c_str(), addrBit); m_vFile.Print(" );\n"); } m_vFile.Print("MUXF7 %s_M0$%d ( .O(%s_M0[%d]), .I0(%s_L0[%d]), .I1(%s_L1[%d]), .S(%s[6]) );\n", pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pInputIdent->GetName().c_str() ); m_vFile.Print("MUXF7 %s_M1$%d ( .O(%s_M1[%d]), .I0(%s_L2[%d]), .I1(%s_L3[%d]), .S(%s[6]) );\n", pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pInputIdent->GetName().c_str() ); m_vFile.Print("MUXF8 %s_M2$%d ( .O(%s[%d]), .I0(%s_M0[%d]), .I1(%s_M1[%d]), .S(%s[7]) );\n", pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pOutputIdent->GetName().c_str(), bit, pInputIdent->GetName().c_str() ); } return true; } void CHtvDesign::RemoveMemoryWriteStatements(CHtvStatement **ppIfList) { while (*ppIfList) { EStType stType = (*ppIfList)->GetStType(); if (stType == st_null) { // delete null statements *ppIfList = (*ppIfList)->GetNext(); continue; } CHtvOperand *pExpr = (*ppIfList)->GetExpr(); if (stType != st_assign || pExpr == 0 || pExpr->GetOperator() != tk_equal) { ppIfList = (*ppIfList)->GetPNext(); continue; } pExpr = pExpr->GetOperand1(); ppIfList = (*ppIfList)->GetPNext(); } } ///////////////////////////////////////////////////////////////////// // Generation routines #if !defined(VERSION) #define VERSION "unknown" #endif #if !defined(BLDDTE) #define BLDDTE "unknown" #endif #if !defined(VCSREV) #define VCSREV "unknown" #endif void CHtvDesign::GenVFileHeader() { m_vFile.Print("/*****************************************************************************/\n"); m_vFile.Print("// Generated with htv %s-%s (%s)\n", VERSION, VCSREV, BLDDTE); m_vFile.Print("//\n"); m_vFile.Print("/*****************************************************************************/\n"); m_vFile.Print("`timescale 1ns / 1ps\n\n"); } void CHtvDesign::GenHtAttributes(CHtvIdent * pIdent, string instName) { if (pIdent->GetFlatIdent()) { GenHtAttributes(pIdent->GetFlatIdent(), instName); return; } for (int i = 0; i < pIdent->GetScAttribCnt(); i += 1) { CHtAttrib htAttrib = pIdent->GetScAttrib(i); bool skip = false; string name = htAttrib.m_name; string value = htAttrib.m_value; // Quartus hacks FIXME if (g_htvArgs.IsQuartusEnabled()) { if (name == "keep_hierarchy") skip = true; if (name == "equivalent_register_removal") { name = "syn_preserve"; value = "true"; } if (name == "keep") name = "noprune"; } if ((instName.size() == 0 || instName == htAttrib.m_inst) && !skip) { size_t found = value.find("INT_ONLY_"); if (found != string::npos) { value.erase(0,9); m_vFile.Print("(* %s = %s *)\n", name.c_str(), value.c_str()); } else { m_vFile.Print("(* %s = \"%s\" *)\n", name.c_str(), value.c_str()); } } } } void CHtvDesign::GenModuleHeader(CHtvIdent *pModule) { CHtvIdentTblIter moduleIter(pModule->GetFlatIdentTbl()); m_vFile.SetIndentLevel(0); if (g_htvArgs.IsLedaEnabled()) m_vFile.Print("`include \"leda_header.vh\"\n\n"); m_vFile.Print("`define HTDLY\n\n"); if (g_htvArgs.IsKeepHierarchyEnabled()) m_vFile.Print("(* keep_hierarchy = \"true\" *)\n"); GenHtAttributes(pModule); m_vFile.Print("module %s (", pModule->GetName().c_str()); m_vFile.IncIndentLevel(); m_vFile.SetVarDeclLines(true); // declare outputs bool bFirst = true; char *pFirstStr = "\n// Outputs\n"; for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (moduleIter->GetPortDir() == port_out) { string bitRange; if (moduleIter->GetWidth() > 1) bitRange = VA("[%d:0]", moduleIter->GetWidth()-1); // iterate through array elements for (int elemIdx = 0; elemIdx < moduleIter->GetDimenElemCnt(); elemIdx += 1) { bool bWire = moduleIter->IsAssignOutput(elemIdx); string identName = moduleIter->GetVerilogName(elemIdx); m_vFile.Print("%s", pFirstStr); GenHtAttributes(moduleIter(), identName); m_vFile.Print("output %s %-10s %s", bWire ? " " : "reg", bitRange.c_str(), identName.c_str()); bFirst = false; pFirstStr = ",\n"; } } } // declare inputs if (bFirst) pFirstStr = "\n\n// Inputs\n"; else pFirstStr = ",\n\n// Inputs\n"; bFirst = true; for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (moduleIter->GetPortDir() == port_in) { string bitRange; if (moduleIter->GetWidth() > 1) bitRange = VA("[%d:0]", moduleIter->GetWidth()-1); // iterate through array elements vector<int> refList(moduleIter->GetDimenCnt(), 0); do { string identName = GenVerilogIdentName(moduleIter->GetName(), refList); m_vFile.Print("%s", pFirstStr); GenHtAttributes(moduleIter(), identName); m_vFile.Print("input %-10s %s", bitRange.c_str(), identName.c_str()); bFirst = false; pFirstStr = ",\n"; } while (!moduleIter->DimenIter(refList)); } } m_vFile.Print("\n);\n"); // builtin constants bool bBuiltinComment = true; CHtvIdentTblIter topIter(GetTopHier()->GetFlatIdentTbl()); for (topIter.Begin(); !topIter.End(); topIter++) { if (topIter->GetId() != CHtvIdent::id_const) continue; if (bBuiltinComment) { m_vFile.Print("\n// builtin constants\n"); bBuiltinComment = false; } if (topIter->IsReadRef(0)) m_vFile.Print("wire %s = %d'h%x;\n", topIter->GetName().c_str(), topIter->GetWidth(), topIter->GetConstValue().GetSint64()); } // global enum constants CHtvIdentTblIter globalIdentIter(pModule->GetPrevHier()->GetIdentTbl()); for (globalIdentIter.Begin(); !globalIdentIter.End(); globalIdentIter++) { if (!globalIdentIter->IsIdEnumType()) continue; m_vFile.Print("\n// enum %s\n", globalIdentIter->GetName().c_str()); string bitRange; if (globalIdentIter->GetWidth() > 1) bitRange = VA("[%d:0]", globalIdentIter->GetWidth()-1); CHtvIdentTblIter enumIter(globalIdentIter->GetFlatIdentTbl()); for (enumIter.Begin(); !enumIter.End(); enumIter++) { if (enumIter->GetId() != CHtvIdent::id_enum || globalIdentIter->GetThis() != enumIter->GetType()) continue; //if (enumIter->IsReadRef(0)) m_vFile.Print("wire %-10s %s = %d'h%x;\n", bitRange.c_str(), enumIter->GetName().c_str(), globalIdentIter->GetWidth(), enumIter->GetConstValue().GetSint64()); } } // enum constants CHtvIdentTblIter moduleIdentIter(pModule->GetIdentTbl()); for (moduleIdentIter.Begin(); !moduleIdentIter.End(); moduleIdentIter++) { if (!moduleIdentIter->IsIdEnumType()) continue; m_vFile.Print("\n// enum %s\n", moduleIdentIter->GetName().c_str()); string bitRange; if (moduleIdentIter->GetWidth() > 1) bitRange = VA("[%d:0]", moduleIdentIter->GetWidth()-1); CHtvIdentTblIter enumIter(moduleIdentIter->GetFlatIdentTbl()); for (enumIter.Begin(); !enumIter.End(); enumIter++) { if (enumIter->GetId() != CHtvIdent::id_enum || moduleIdentIter->GetThis() != enumIter->GetType()) continue; //if (enumIter->IsReadRef(0)) m_vFile.Print("wire %-10s %s = %d'h%x;\n", bitRange.c_str(), enumIter->GetName().c_str(), moduleIdentIter->GetWidth(), enumIter->GetConstValue().GetSint64()); } } if (g_htvArgs.IsSynXilinxPrims()) return; // declare variables pFirstStr = "\n// variables\n"; for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { // skip references if (moduleIter->IsVariable() && !moduleIter->IsPort() && !moduleIter->IsScState() && !moduleIter->IsReference() && !moduleIter->IsHtQueue() && !moduleIter->IsHtMemory()) { if (moduleIter->GetHierIdent()->IsRemoveIfWriteOnly() && !moduleIter->GetHierIdent()->IsReadRef()) continue; string bitRange; vector<CHtDistRamWeWidth> *pWeWidth = moduleIter->GetHtDistRamWeWidth(); if (pWeWidth == 0) { if (moduleIter->GetWidth() > 1) bitRange = VA("[%d:0]", moduleIter->GetWidth()-1); // iterate through array elements for (int elemIdx = 0; elemIdx < moduleIter->GetDimenElemCnt(); elemIdx += 1) { bool bWire = moduleIter->IsAssignOutput(elemIdx) || moduleIter->IsHtPrimOutput(elemIdx) || moduleIter->IsPrimOutput(); string identName = moduleIter->GetVerilogName(elemIdx); GenHtAttributes(moduleIter(), identName); m_vFile.Print("%s%s %-10s %s", pFirstStr, bWire ? "wire" : "reg ", bitRange.c_str(), identName.c_str()); m_vFile.Print(";\n"); pFirstStr = ""; } } else if (pWeWidth->size() == 1) { // iterate through array elements for (int elemIdx = 0; elemIdx < moduleIter->GetDimenElemCnt(); elemIdx += 1) { bool bWire = moduleIter->IsAssignOutput(elemIdx) || moduleIter->IsHtPrimOutput(elemIdx) || moduleIter->IsPrimOutput(); string identName = moduleIter->GetVerilogName(elemIdx); GenHtAttributes(moduleIter(), identName); m_vFile.Print("%s%s %-10s %s", pFirstStr, bWire ? "wire" : "reg ", "", identName.c_str()); m_vFile.Print(";\n"); pFirstStr = ""; } } else for (size_t j = 0; j < pWeWidth->size(); j += 1) { int highBit = (*pWeWidth)[j].m_highBit; int lowBit = (*pWeWidth)[j].m_lowBit; // iterate through array elements for (int elemIdx = 0; elemIdx < moduleIter->GetDimenElemCnt(); elemIdx += 1) { bool bWire = moduleIter->IsAssignOutput(elemIdx) || moduleIter->IsHtPrimOutput(elemIdx) || moduleIter->IsPrimOutput(); string dimStr = moduleIter->GetVerilogName(elemIdx, false); string name = VA("%s_%d_%d%s", moduleIter->GetName().c_str(), highBit, lowBit, dimStr.c_str()); GenHtAttributes(moduleIter(), name.c_str()); m_vFile.Print("%s%s %-10s %s;\n", pFirstStr, bWire ? "wire" : "reg ", "", name.c_str()); pFirstStr = ""; } } } } m_vFile.SetVarDeclLines(false); // write instantiated primitives for (moduleIter.Begin(); !moduleIter.End(); moduleIter++) { if (moduleIter->GetId() != CHtvIdent::id_variable || !moduleIter->IsReference()) continue; int elemIdx = moduleIter->GetElemIdx(); CHtvIdent *pBaseIdent; if (moduleIter->GetPrevHier()->IsArrayIdent()) pBaseIdent = moduleIter->GetPrevHier(); else pBaseIdent = moduleIter(); Assert(moduleIter->GetInstanceName() == pBaseIdent->GetInstanceName(elemIdx)); m_vFile.Print("\n %s ", moduleIter->GetType()->GetName().c_str()); m_vFile.Print("%s(\n", moduleIter->GetInstanceName().c_str()); pFirstStr = ""; CHtvIdent *pInstance = moduleIter(); CHtvIdentTblIter portIter(pInstance->GetIdentTbl()); for (portIter.Begin(); !portIter.End(); portIter++) { m_vFile.Print("%s .%s(%s)", pFirstStr, portIter->GetName().c_str(), portIter->GetPortSignal()->GetName().c_str()); pFirstStr = ",\n"; } m_vFile.Print("\n );\n"); } } void CHtvDesign::GenModuleTrailer() { m_vFile.DecIndentLevel(); m_vFile.Print("endmodule\n"); } void CHtvDesign::GenFunction(CHtvIdent *pFunction, CHtvObject * pObj, CHtvObject * pRtnObj) { if (!pFunction->IsBodyDefined()) return; if (pFunction->IsInlinedCall()) return; m_vFile.Print("\ntask %s;\n", pFunction->GetName().c_str()); m_vFile.IncIndentLevel(); m_vFile.SetInTask(true); if (pFunction->GetType() != GetVoidType()) { // function return string bitRange; if (pFunction->GetWidth() > 1) bitRange = VA("[%d:0] ", pFunction->GetWidth()-1); m_vFile.Print("output %s\\%s$Rtn ;\n", bitRange.c_str(), pFunction->GetName().c_str()); } // list parameters for (int paramId = 0; paramId < pFunction->GetParamCnt(); paramId += 1) { CHtvIdent *pParamType = pFunction->GetParamType(paramId); st
ring bitRange; if (pParamType->GetWidth() > 1) bitRange = VA("[%d:0] ", pParamType->GetWidth()-1); string identName = pFunction->GetParamName(paramId); CHtvIdent *pParamIdent = pFunction->FindIdent(identName); if (pParamIdent->IsReadOnly()) { GenHtAttributes(pParamIdent, identName); m_vFile.Print("input %s%s;\n", bitRange.c_str(), identName.c_str()); } else { // list as output GenHtAttributes(pParamIdent, identName); m_vFile.Print("input %s%s$In;\n", bitRange.c_str(), identName.c_str()); GenHtAttributes(pParamIdent, identName); m_vFile.Print("output %s%s$Out;\n", bitRange.c_str(), identName.c_str()); } } // list global variables for (size_t refIdx = 0; refIdx < pFunction->GetGlobalRefSet().size(); refIdx += 1) { CHtIdentElem &identElem = pFunction->GetGlobalRefSet()[refIdx]; string bitRange; if (identElem.m_pIdent->GetWidth() > 1) bitRange = VA("[%d:0] ", identElem.m_pIdent->GetWidth()-1); vector<CHtDistRamWeWidth> *pWeWidth = identElem.m_pIdent->GetHtDistRamWeWidth(); int startIdx = pWeWidth == 0 ? -1 : 0; int lastIdx = pWeWidth == 0 ? 0 : (int)(*pWeWidth).size(); for (int rangeIdx = startIdx; rangeIdx < lastIdx; rangeIdx += 1) { string identName = GenVerilogIdentName(identElem, rangeIdx); GenHtAttributes((CHtvIdent *)identElem.m_pIdent, identName); if (identElem.m_pIdent->IsHtPrimOutput(identElem.m_elemIdx)) m_vFile.Print("input %s%s;\n", bitRange.c_str(), identName.c_str()); else m_vFile.Print("input %s%s_global;\n", bitRange.c_str(), identName.c_str()); } } // list input/output parameters as local register variable for (int paramId = 0; paramId < pFunction->GetParamCnt(); paramId += 1) { CHtvIdent *pParamType = pFunction->GetParamType(paramId); string bitRange; if (pParamType->GetWidth() > 1) bitRange = VA("[%d:0] ", pParamType->GetWidth()-1); string identName = pFunction->GetParamName(paramId); CHtvIdent *pParamIdent = pFunction->FindIdent(identName); GenHtAttributes(pParamIdent, identName); if (!pParamIdent->IsReadOnly()) m_vFile.Print("reg %s%s;\n", bitRange.c_str(), identName.c_str()); } m_vFile.Print("begin : %s$\n", pFunction->GetName().c_str()); m_vFile.IncIndentLevel(); m_vFile.VarInitOpen(); m_bInAlwaysAtBlock = true; // gen input parameter assignments for (int paramId = 0; paramId < pFunction->GetParamCnt(); paramId += 1) { CHtvIdent *pParamIdent = pFunction->FindIdent(pFunction->GetParamName(paramId)); if (!pParamIdent->IsReadOnly()) { // list as input m_vFile.Print("%s = %s$In;\n", pFunction->GetParamName(paramId).c_str(), pFunction->GetParamName(paramId).c_str()); } } SynCompoundStatement(pFunction, pObj, pRtnObj, true, true); // gen output parameter assignments for (int paramId = 0; paramId < pFunction->GetParamCnt(); paramId += 1) { CHtvIdent *pParamIdent = pFunction->FindIdent(pFunction->GetParamName(paramId)); if (!pParamIdent->IsReadOnly()) { // list as output m_vFile.Print("%s$Out = %s;\n", pFunction->GetParamName(paramId).c_str(), pFunction->GetParamName(paramId).c_str()); } } m_vFile.VarInitClose(); m_bInAlwaysAtBlock = false; m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); m_vFile.SetInTask(false); m_vFile.DecIndentLevel(); m_vFile.Print("endtask\n"); } void CHtvDesign::GenMethod(CHtvIdent *pMethod, CHtvObject * pObj) { SynIndividualStatements(pMethod, pObj, 0); } void CHtvDesign::GenAlwaysAtHeader(bool bBeginEnd) { // Always @ block m_vFile.Print("\nalways @(*)\n"); m_vFile.IncIndentLevel(); if (bBeginEnd) { m_vFile.Print("begin : Always$%d\n", GetNextAlwaysBlockIdx()); m_vFile.IncIndentLevel(); // begin m_vFile.VarInitOpen(); m_bInAlwaysAtBlock = true; } } void CHtvDesign::GenAlwaysAtHeader(CHtvIdent *pIdent) { // Always @ block m_vFile.Print("\nalways @(posedge %s)\n", pIdent->GetName().c_str()); m_vFile.IncIndentLevel(); m_vFile.Print("begin : Always$%d\n", GetNextAlwaysBlockIdx()); m_vFile.IncIndentLevel(); // begin m_vFile.VarInitOpen(); m_bInAlwaysAtBlock = true; } void CHtvDesign::GenAlwaysAtTrailer(bool bBeginEnd) { if (bBeginEnd) { m_vFile.DecIndentLevel(); // begin m_vFile.Print("end\n"); m_vFile.VarInitClose(); m_bInAlwaysAtBlock = false; } m_vFile.DecIndentLevel(); // always } void CHtvDesign::GenArrayIndexingSubExpr(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand * pOperand, bool bLeftOfEqual) { CHtvIdent * pIdent = pOperand->GetMember(); pOperand->SetIsSubExprGenerated(true); // determine number of bits for single case index Assert(pOperand->GetIndexCnt() > 0); Assert(pOperand->HasArrayTempVar()); vector<int> fieldWidthList(pOperand->GetIndexCnt(), 0); vector<bool> fieldConstList(pOperand->GetIndexCnt(), false); vector<int> refList(pOperand->GetIndexCnt(), 0); int idxBits = 0; for (size_t j = 0; j < pOperand->GetIndexCnt(); j += 1) { fieldConstList[j] = pOperand->GetIndex(j)->IsConstValue(); if (pOperand->GetIndex(j)->IsConstValue()) { refList[j] = pOperand->GetIndex(j)->GetConstValue().GetSint32(); continue; } int idxWidth; if (!GetFieldWidthFromDimen(pIdent->GetDimenList()[j], idxWidth)) ParseMsg(PARSE_FATAL, pOperand->GetLineInfo(), "invalid array index (32K limit)"); idxBits += fieldWidthList[j] = idxWidth; } int bitPos = idxBits-1; for (size_t j = 0; j < pOperand->GetIndexCnt(); j += 1) { if (pOperand->GetIndex(j)->IsConstValue()) continue; // gen sub expressions GenSubExpr(pObj, pRtnObj, pOperand->GetIndex(j), false, false, true); m_vFile.Print("%s", pOperand->GetArrayTempVar().c_str()); if (idxBits > 1) { if (bitPos == bitPos - fieldWidthList[j]+1) m_vFile.Print("[%d]", bitPos); else m_vFile.Print("[%d:%d]", bitPos, bitPos - fieldWidthList[j]+1); } m_vFile.Print(" = "); GenSubExpr(pObj, pRtnObj, pOperand->GetIndex(j)); m_vFile.Print(";\n"); bitPos -= fieldWidthList[j]; } m_vFile.Print("case (%s)\n", pOperand->GetArrayTempVar().c_str()); m_vFile.IncIndentLevel(); int caseCnt = 0; do { int j = 0; for (size_t i = 0; i < pOperand->GetIndexCnt(); i += 1) { j <<= fieldWidthList[i]; if (fieldConstList[i]) continue; j |= refList[i]; } m_vFile.Print("%d'h%x: ", idxBits, j); if (!bLeftOfEqual) m_vFile.Print("%s = ", pOperand->GetExprTempVar().c_str()); m_vFile.Print("%s", GenVerilogIdentName(pIdent->GetName(), refList).c_str() ); GenSubExpr(pObj, pRtnObj, pOperand, false, true); if (bLeftOfEqual) m_vFile.Print(" = %s", pOperand->GetExprTempVar().c_str()); m_vFile.Print(";\n"); caseCnt += 1; } while (!pIdent->DimenIter(refList, fieldConstList)); if (caseCnt < (1 << idxBits) && !bLeftOfEqual) m_vFile.Print("default: %s = %d'h0;\n", pOperand->GetExprTempVar().c_str(), pIdent->GetWidth()); m_vFile.DecIndentLevel(); m_vFile.Print("endcase\n"); } void CHtvDesign::GenSubExpr(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr, bool bIsLeftOfEqual, bool bArrayIndexing, bool bGenSubExpr, EToken prevTk) { Assert(pExpr); #ifdef WIN32 if (pExpr->GetLineInfo().m_lineNum == 337) bool stop = true; #endif if (bGenSubExpr) { // walk expression tree down to leaves // on the way back up, generate expressions for each temp variable if (!pExpr->IsSubExprRequired()) return; if (!pExpr->IsLeaf() && !pExpr->IsSubExprGenerated()) { // decend EToken tk = pExpr->GetOperator(); CHtvOperand *pOp1 = pExpr->GetOperand1(); CHtvOperand *pOp2 = pExpr->GetOperand2(); CHtvOperand *pOp3 = pExpr->GetOperand3(); if ((tk == tk_ampersandAmpersand || tk == tk_vbarVbar) && (pOp1->IsSubExprRequired() || pOp2->IsSubExprRequired())) { PrintLogicalSubExpr(pObj, pRtnObj, pExpr); return; } if (tk == tk_question && (pOp2->IsSubExprRequired() || pOp3->IsSubExprRequired())) { PrintQuestionSubExpr(pObj, pRtnObj, pExpr); return; } if (tk == tk_preInc || tk == tk_postInc || tk == tk_preDec || tk == tk_postDec) { // increment/decrement PrintIncDecSubExpr(pObj, pRtnObj, pExpr); return; } if (tk == tk_period) { CHtvObject subObj; if (pOp1->GetOperator() == tk_period) { GenSubExpr(pObj, &subObj, pOp1, false, false, true, tk); subObj.m_pOp = pOp1->GetTempOp(); } else { GenSubObject(&subObj, pObj, pOp1); } CHtvObject rtnObj2; CHtvObject * pRtnObj2 = pOp2->IsFunction() && pOp2->GetType() == GetVoidType() ? 0 : &rtnObj2; GenSubExpr(&subObj, pRtnObj2, pOp2, false, false, true, tk); if (pExpr->HasExprTempVar() && (pExpr->GetExprTempVar() != pExpr->GetOperand2()->GetExprTempVar() || pExpr->GetOperand2()->HasFuncTempVar() )) { m_vFile.Print("%s = ", pExpr->GetExprTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand2()); m_vFile.Print(";\n"); } if (pRtnObj2 && pRtnObj2->m_pOp) { pExpr->SetTempOp(pRtnObj2->m_pOp); if (prevTk != tk_period && !pRtnObj2->m_pOp->IsTempOpSubGened()) { bool bFoundSubExpr = false; bool bWriteIndex = false; FindSubExpr(0, 0, pRtnObj2->m_pOp, bFoundSubExpr, bWriteIndex); pRtnObj2->m_pOp->SetTempOpSubGened(true); if (bFoundSubExpr) { m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } } } pExpr->SetIsSubExprGenerated(true); return; } if (pOp1 && tk != tk_equal) GenSubExpr(pObj, pRtnObj, pOp1, false, false, true, tk); if (pOp2) GenSubExpr(pObj, pRtnObj, pOp2, false, false, true, tk); if (pOp3) GenSubExpr(pObj, pRtnObj, pOp3, false, false, true, tk); if (pOp1 && tk == tk_equal) { if (!pOp1->HasArrayTempVar()) GenSubExpr(pObj, pRtnObj, pOp1, true, false, true, tk); else PrintArrayIndex(pObj, 0, pExpr, true); } } else { // at a leaf node, check if field indexing is needed if (pExpr->IsFunction()) { for (size_t i = 0; i < pExpr->GetParamCnt(); i += 1) // gen sub expressions GenSubExpr(0, 0, pExpr->GetParam(i), false, false, true); // generate function call if (pExpr->HasFuncTempVar() || pExpr->HasFieldTempVar()) { PrintSubExpr(pObj, pRtnObj, pExpr, bIsLeftOfEqual, true); if (pExpr->GetSubField()) { // Append subfield to result if (pRtnObj && pRtnObj->m_pOp) pRtnObj->m_pOp = CreateObject(pRtnObj->m_pOp, pExpr); else if (pExpr->GetTempOp()) pExpr->SetTempOp(CreateObject(pExpr->GetTempOp(), pExpr)); } } } if (pExpr->IsVariable() || pExpr->IsFunction() && !bIsLeftOfEqual && !pExpr->GetMember()->IsReturnRef()) { if (pExpr->HasFieldTempVar()) { if (!pExpr->IsFieldTempGenerated()) { // non-constant field indexing, check for subexpressions CScSubField * pSubField = pExpr->GetSubField(); for ( ; pSubField; pSubField = pSubField->m_pNext) { for (size_t i = 0; i < pSubField->m_indexList.size(); i += 1) { if (!pSubField->m_indexList[i]->IsConstValue()) GenSubExpr(pObj, 0, (CHtvOperand *)pSubField->m_indexList[i], false, false, true); } } PrintFieldIndex(pObj, pRtnObj, pExpr); // generate shift amount expression pExpr->SetFieldTempGenerated(true); } } if (pExpr->HasArrayTempVar()) { if (!pExpr->IsArrayTempGenerated() && bIsLeftOfEqual) { // non-constant array indexing, check for subexpressions for (size_t j = 0; j < pExpr->GetIndexCnt(); j += 1) { if (!pExpr->GetIndex(j)->IsConstValue()) GenSubExpr(pObj, 0, pExpr->GetIndex(j), false, false, true); } } if (!bIsLeftOfEqual) { PrintArrayIndex(pObj, pRtnObj, pExpr, bIsLeftOfEqual); // generate read case statement pExpr->SetArrayTempGenerated(true); } return; } if (!pExpr->HasExprTempVar() && !pExpr->IsFunction()) return; } } } // generate an expression, start at current node and decend until a temp variable or leaf node is found if (!bGenSubExpr || pExpr->HasExprTempVar() || pExpr->IsLeaf() && pExpr->IsFunction() && pExpr->GetType() == GetVoidType()) { PrintSubExpr(pObj, pRtnObj, pExpr, bIsLeftOfEqual, true); } } void CHtvDesign::PrintArrayIndex(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand * pOperand, bool bLeftOfEqual) { bool bUseExpr = bLeftOfEqual && pOperand->GetOperator() == tk_equal; CHtvOperand *pExpr = 0; if (bUseExpr) { pExpr = pOperand; pOperand = pExpr->GetOperand1(); } CHtvIdent * pIdent = pOperand->GetMember(); pOperand->SetIsSubExprGenerated(true); // handle field indexing if (pOperand->HasFieldTempVar() && !pOperand->IsFieldTempGenerated()) { // non-constant field indexing, check for subexpressions CScSubField * pSubField = pOperand->GetSubField(); for ( ; pSubField; pSubField = pSubField->m_pNext) { for (size_t i = 0; i < pSubField->m_indexList.size(); i += 1) { if (!pSubField->m_indexList[i]->IsConstValue()) GenSubExpr(pObj, 0, (CHtvOperand *)pSubField->m_indexList[i], false, false, true); } } PrintFieldIndex(pObj, 0, pOperand); // generate shift amount expression pOperand->SetFieldTempGenerated(true); } // determine number of bits for single case index Assert(pOperand->GetIndexCnt() > 0); Assert(pOperand->HasArrayTempVar()); vector<int> fieldWidthList(pOperand->GetIndexCnt(), 0); vector<bool> fieldConstList(pOperand->GetIndexCnt(), false); vector<int> refList(pOperand->GetIndexCnt(), 0); int idxBits = 0; for (size_t j = 0; j < pOperand->GetIndexCnt(); j += 1) { fieldConstList[j] = pOperand->GetIndex(j)->IsConstValue(); if (pOperand->GetIndex(j)->IsConstValue()) { refList[j] = pOperand->GetIndex(j)->GetConstValue().GetSint32(); continue; } int idxWidth; if (!GetFieldWidthFromDimen(pIdent->GetDimenList()[j], idxWidth)) ParseMsg(PARSE_FATAL, pOperand->GetLineInfo(), "invalid array index (32K limit)"); idxBits += fieldWidthList[j] = idxWidth; } if (!pOperand->IsArrayTempGenerated()) { int bitPos = idxBits-1; for (size_t j = 0; j < pOperand->GetIndexCnt(); j += 1) { if (pOperand->GetIndex(j)->IsConstValue()) continue; GenSubExpr(pObj, 0, pOperand->GetIndex(j), false, false, true); m_vFile.Print("%s", pOperand->GetArrayTempVar().c_str()); if (idxBits > 1) { if (bitPos == bitPos - fieldWidthList[j]+1) m_vFile.Print("[%d]", bitPos); else m_vFile.Print("[%d:%d]", bitPos, bitPos - fieldWidthList[j]+1); } m_vFile.Print(" = "); PrintSubExpr(pObj, 0, pOperand->GetIndex(j)); m_vFile.Print(";\n"); bitPos -= fieldWidthList[j]; } } m_vFile.Print("case (%s)\n", pOperand->GetArrayTempVar().c_str()); m_vFile.IncIndentLevel(); int caseCnt = 0; do { int j = 0; for (size_t i = 0; i < pOperand->GetIndexCnt(); i += 1) { j <<= fieldWidthList[i]; if (fieldConstList[i]) continue; j |= refList[i]; } m_vFile.Print("%d'h%x: ", idxBits, j); if (!bLeftOfEqual) m_vFile.Print("%s = ", pOperand->GetExprTempVar().c_str()); string arrayName = GenVerilogIdentName(pIdent->GetName(), refList); //m_vFile.Print("%s", arrayName.c_str() ); PrintSubExpr(pObj, 0, bUseExpr ? pExpr : pOperand, bLeftOfEqual, false, true, arrayName); if (bLeftOfEqual && !pOperand->HasFieldTempVar()) { m_vFile.Print(" = "); PrintSubExpr(pObj, 0, bUseExpr ? pExpr->GetOperand2() : pOperand, false); //m_vFile.Print(" = temp$%s$%d", pOperand->GetExprBlockId().c_str(), pOperand->GetSubExprTempVarIdx()); } m_vFile.Print(";\n"); caseCnt += 1; } while (!pIdent->DimenIter(refList, fieldConstList)); if (caseCnt < (1 << idxBits) && !bLeftOfEqual) m_vFile.Print("default: %s = %d'h0;\n", pOperand->GetExprTempVar().c_str(), pIdent->GetWidth()); if (pRtnObj) pRtnObj->m_pOp = 0; m_vFile.DecIndentLevel(); m_vFile.Print("endcase\n"); } void CHtvDesign::PrintLogicalSubExpr(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr) { // a function call exists in the expression, and there are && or || operators. Must us if statement to // conditionally execute expression to mimic C/C++ behavior if (pExpr->GetOperand1()->IsSubExprRequired()) { EToken tk1 = pExpr->GetOperand1()->GetOperator(); bool bLogical1 = tk1 == tk_ampersandAmpersand || tk1 == tk_vbarVbar; if (bLogical1) PrintLogicalSubExpr(pObj, pRtnObj, pExpr->GetOperand1()); else { GenSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), false, false, true); if (pExpr->GetOperand1()->HasFieldTempVar()) PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), false, true); } } else PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), false, true); if (pExpr->GetOperator() == tk_ampersandAmpersand) m_vFile.Print("if (%s)", pExpr->GetExprTempVar().c_str()); else m_vFile.Print("if (!%s)", pExpr->GetExprTempVar().c_str()); m_vFile.IncIndentLevel(); if (pExpr->GetOperand2()->IsSubExprRequired()) { EToken tk2 = pExpr->GetOperand2()->GetOperator(); bool bLogical2 = tk2 == tk_ampersandAmpersand || tk2 == tk_vbarVbar; CHtvOperand * pOp2 = pExpr->GetOperand2(); bool bBeginEnd = !pOp2->IsLeaf() || pOp2->HasFuncTempVar() && pOp2->HasExprTempVar() || pOp2->HasArrayTempVar() || pOp2->HasFieldTempVar(); if (bBeginEnd) m_vFile.Print(" begin\n"); else m_vFile.Print("\n"); if (bLogical2) PrintLogicalSubExpr(pObj, pRtnObj, pExpr->GetOperand2()); else { GenSubExpr(pObj, pRtnObj, pExpr->GetOperand2(), false, false, true); if (pExpr->GetOperand2()->Ha
sFieldTempVar()) PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand2(), false, true); } m_vFile.DecIndentLevel(); if (bBeginEnd) m_vFile.Print("end\n"); } else { m_vFile.Print("\n"); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand2(), false, true); m_vFile.DecIndentLevel(); } pExpr->SetIsSubExprGenerated(true); } void CHtvDesign::PrintQuestionSubExpr(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr) { // conditional expression with function call // must use if/else statement if (pExpr->GetOperand1()->IsSubExprRequired()) GenSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), false, false, true); if (pExpr->GetOperand1()->HasExprTempVar()) { GenSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), false, false, true); m_vFile.Print("if (%s)", pExpr->GetOperand1()->GetExprTempVar().c_str()); } else { m_vFile.Print("if ("); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand1()); m_vFile.Print(")"); } m_vFile.IncIndentLevel(); if (pExpr->GetOperand2()->IsSubExprRequired()) { bool bBeginEnd = !pExpr->GetOperand2()->IsLeaf() || pExpr->GetOperand2()->IsFunction() || pExpr->GetExprTempVar() != pExpr->GetOperand2()->GetExprTempVar() || pExpr->GetOperand2()->HasArrayTempVar() || pExpr->GetOperand2()->HasFieldTempVar(); if (bBeginEnd) m_vFile.Print(" begin\n"); else m_vFile.Print("\n"); GenSubExpr(pObj, pRtnObj, pExpr->GetOperand2(), false, false, true); if (pExpr->GetExprTempVar() != pExpr->GetOperand2()->GetExprTempVar() /*|| pExpr->GetOperand2()->HasFieldTempVar()*/) { m_vFile.Print("%s = ", pExpr->GetExprTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand2()); m_vFile.Print(";\n"); } m_vFile.DecIndentLevel(); if (bBeginEnd) m_vFile.Print("end\n"); } else { m_vFile.Print("\n"); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand2(), false, true); m_vFile.DecIndentLevel(); } m_vFile.Print("else"); m_vFile.IncIndentLevel(); if (pExpr->GetOperand3()->IsSubExprRequired()) { bool bBeginEnd = !pExpr->GetOperand3()->IsLeaf() || pExpr->GetOperand3()->IsFunction() || pExpr->GetExprTempVar() != pExpr->GetOperand3()->GetExprTempVar() || pExpr->GetOperand3()->HasArrayTempVar() || pExpr->GetOperand3()->HasFieldTempVar(); if (bBeginEnd) m_vFile.Print(" begin\n"); else m_vFile.Print("\n"); GenSubExpr(pObj, pRtnObj, pExpr->GetOperand3(), false, false, true); if (pExpr->GetExprTempVar() != pExpr->GetOperand3()->GetExprTempVar() /*|| pExpr->GetOperand3()->HasFieldTempVar()*/) { m_vFile.Print("%s = ", pExpr->GetExprTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand3()); m_vFile.Print(";\n"); } m_vFile.DecIndentLevel(); if (bBeginEnd) m_vFile.Print("end\n"); } else { m_vFile.Print("\n"); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand3(), false, true); m_vFile.DecIndentLevel(); } pExpr->SetIsSubExprGenerated(true); } void CHtvDesign::PrintIncDecSubExpr(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr) { EToken tk = pExpr->GetOperator(); if (tk == tk_postInc || tk == tk_postDec) { // copy variable to temp pExpr->GetOperand1()->SetIsSubExprRequired(true); GenSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), false, false, true); } // perform inc/dec bool bSavedFlag = pExpr->GetOperand1()->IsSubExprGenerated(); pExpr->GetOperand1()->SetIsSubExprGenerated(false); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), true, false, false, "", tk, true); m_vFile.Print(" = "); pExpr->GetOperand1()->SetIsSubExprGenerated(false); PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), false, false, false, "", tk, true); m_vFile.Print(tk == tk_preInc || tk == tk_postInc ? " + " : " - "); m_vFile.Print(pExpr->GetOperand1()->IsSigned() ? "2'sd1;\n" : "1'h1;\n"); pExpr->GetOperand1()->SetIsSubExprGenerated(bSavedFlag); if (tk == tk_preInc || tk == tk_preDec) // copy variable to temp PrintSubExpr(pObj, pRtnObj, pExpr->GetOperand1(), false, true); pExpr->SetIsSubExprGenerated(true); } string CHtvDesign::GetHexMask(int width) { string mask; switch (width % 4) { case 0: break; case 1: mask = "1"; break; case 2: mask = "3"; break; case 3: mask = "7"; break; } width -= width % 4; for (int i = 0; i < width; i += 4) mask += "f"; return mask; } void CHtvDesign::PrintSubExpr(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr, bool bIsLeftOfEqual, bool bEntry, bool bArrayIndexing, string arrayName, EToken prevTk, bool bIgnoreExprWidth) { #ifdef WIN32 if (pExpr->GetLineInfo().m_lineNum == 26) bool stop = true; #endif bool bTempAssignment = bEntry && pExpr->HasExprTempVar() && (!pExpr->IsFunction() || pExpr->IsFuncGenerated()); if (bTempAssignment) { m_vFile.Print("%s = ", pExpr->GetExprTempVar().c_str()); prevTk = tk_equal; } if (pExpr->GetTempOp()) pExpr = pExpr->GetTempOp(); if (!pExpr->IsLeaf() && (!pExpr->IsSubExprGenerated() || !pExpr->HasExprTempVar())) { EToken tk = pExpr->GetOperator(); CHtvOperand * pOp1 = pExpr->GetOperand1(); CHtvOperand * pOp2 = pExpr->GetOperand2(); CHtvOperand * pOp3 = pExpr->GetOperand3(); bool bParenExpr = pExpr->IsParenExpr() && !(prevTk == tk_toe || prevTk == tk_equal) || tk == tk_bang && prevTk == tk_bang; if (pOp2 == 0) { // unary operator if (bParenExpr) m_vFile.Print("("); m_vFile.Print("%s", GetTokenString(pExpr->GetOperator()).c_str()); PrintSubExpr(pObj, pRtnObj, pOp1, false, false, false, "", tk); if (bParenExpr) m_vFile.Print(")"); } else if (pOp3 == 0) { // binary operator bool bSigWidth = tk == tk_comma; if (!bSigWidth && bParenExpr) m_vFile.Print("("); if (bSigWidth) m_vFile.Print("{"); if (tk != tk_typeCast) { if (tk == tk_equal && pOp1->HasFieldTempVar()) { // generate a left of equal field indexing assignment Assert(pOp2->HasExprTempVar()); PrintSubExpr(pObj, pRtnObj, pOp1, true, false, bArrayIndexing, arrayName, tk, bIgnoreExprWidth); m_vFile.Print(" = ("); pOp1->SetIsSubExprGenerated(false); PrintSubExpr(pObj, pRtnObj, pOp1, true, false, bArrayIndexing, arrayName, tk, bIgnoreExprWidth); int maskWidth = pOp1->GetVerWidth(); uint64_t mask = maskWidth == 64 ? ~0ull : ((1ull << maskWidth)-1); m_vFile.Print(" & ~(%d'h%llx << %s)) | ((%s & %d'h%llx) << %s)", pOp1->GetVerWidth(), mask, pOp1->GetFieldTempVar().c_str(), pOp2->GetExprTempVar().c_str(), pOp1->GetVerWidth(), mask, pOp1->GetFieldTempVar().c_str()); } else if (tk == tk_period) { CHtvObject rtnObj; CHtvOperand * pNewOp; if (pOp1->GetOperator() == tk_period) PrintSubExpr(pObj, &rtnObj, pOp1, false, false, false, "", tk); else { if (pOp1->GetMember()->GetPrevHier()->IsStruct()) { pNewOp = new CHtvOperand; *pNewOp = *pObj->m_pOp; // copy subField list CScSubField * pSubField = pObj->m_pOp->GetSubField(); CScSubField ** pNewSubField = pNewOp->GetSubFieldP(); for (; pSubField; pSubField = pSubField->m_pNext) { CScSubField * pSf = new CScSubField; *pSf = *pSubField; *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } // append new subField to list if (pOp1->GetSubField() == 0) { CScSubField * pSf = new CScSubField; pSf->m_pIdent = pOp1->GetMember(); pSf->m_indexList = pOp1->GetIndexList(); pSf->m_bBitIndex = false; pSf->m_subFieldWidth = pOp1->GetMember()->GetWidth(); pSf->m_pNext = 0; *pNewSubField = pSf; } else { pSubField = pOp1->GetSubField(); for (; pSubField; pSubField = pSubField->m_pNext) { CScSubField * pSf = new CScSubField; *pSf = *pSubField; *pNewSubField = pSf; pNewSubField = &pSf->m_pNext; } } // create rtnObj rtnObj.m_pOp = pNewOp; } else { rtnObj.m_pOp = pOp1; } } if (prevTk != tk_period) PrintSubExpr(&rtnObj, 0, pOp2, false, false, false, "", tk); if (!pOp2->GetMember()->IsReturnRef()) { rtnObj.m_pOp = 0; if (pOp2->HasExprTempVar()) { Assert(0); } } if (prevTk == tk_period && pRtnObj) *pRtnObj = rtnObj; } else { PrintSubExpr(pObj, pRtnObj, pOp1, tk == tk_equal, false, bArrayIndexing, arrayName, tk); // don't generate equal for left side indexed variable if (tk != tk_equal || !pOp1->HasExprTempVar()) { if (m_bClockedAlwaysAt && tk == tk_equal) m_vFile.Print(" <= `HTDLY "); else if (pExpr->GetOperator() == tk_greaterGreater && (!pOp1->IsLeaf() && pOp1->IsSigned() || pOp1->IsLeaf() && pOp1->GetMember() == 0 && pOp1->IsSigned() || pOp1->IsLeaf() && pOp1->GetMember() && pOp1->GetType()->IsSigned())) { // must use arithmetic shift right if op1 is signed m_vFile.Print(" >>> "); } else m_vFile.Print(" %s ", GetTokenString(pExpr->GetOperator()).c_str()); PrintSubExpr(pObj, pRtnObj, pOp2, false, false, false, "", tk); } } } else { PrintSubExpr(pObj, pRtnObj, pOp2, false, false, false, "", tk); } if (!bSigWidth && bParenExpr) m_vFile.Print(")"); if (bSigWidth) m_vFile.Print("}"); } else { // ? : m_vFile.Print("("); PrintSubExpr(pObj, pRtnObj, pOp1); m_vFile.Print(" ? "); PrintSubExpr(pObj, pRtnObj, pOp2); m_vFile.Print(" : "); PrintSubExpr(pObj, pRtnObj, pOp3); m_vFile.Print(")"); } pExpr->SetIsSubExprGenerated(true); } else { // print leaf node CHtvIdent *pIdent = pExpr->GetMember(); if (pExpr->IsConstValue() && (!pExpr->HasExprTempVar() || !pExpr->IsSubExprGenerated())) { if (pIdent && (pIdent->GetId() == CHtvIdent::id_const || pIdent->GetId() == CHtvIdent::id_enum)) { m_vFile.Print("%s", pIdent->GetName().c_str()); } else if (pExpr->GetVerWidth() > 0) { const char *format = pExpr->IsScX() ? "%s%d'hx" : (pExpr->IsSigned() ? "%s%d'sd%lld" : "%s%d'h%llx"); int constWidth = pExpr->GetOpWidth(); //int constWidth = max(pExpr->GetVerWidth(), pExpr->GetConstValue().GetMinWidth()); uint64_t mask = ~0ull >> (64 - constWidth); if (pExpr->GetConstValue().IsNeg()) m_vFile.Print(format, "-", constWidth, -pExpr->GetConstValue().GetSint64() & mask); else m_vFile.Print(format, "", constWidth, pExpr->GetConstValue().GetUint64() & mask); } else { const char *format = pExpr->IsScX() ? "'hx" : (pExpr->IsSigned() ? "'sd%lld" : "'h%llx"); m_vFile.Print(format, pExpr->GetConstValue().GetUint64()); } pExpr->SetIsSubExprGenerated(true); } else if (pExpr->IsVariable() || pExpr->IsFunction() && bIsLeftOfEqual || pExpr->IsFunction() && pExpr->IsFuncGenerated() || pExpr->IsSubExprGenerated() && pExpr->HasExprTempVar()) { string name; bool bTempVar; bool bSubField; int subFieldLowBit; int subFieldWidth; string fieldPosName; EIdentFmt identFmt = FindIdentFmt(pObj, pRtnObj, pExpr, prevTk, bIsLeftOfEqual, bArrayIndexing, arrayName, bIgnoreExprWidth, name, bTempVar, bSubField, subFieldLowBit, subFieldWidth, fieldPosName); CHtvIdent *pType = pExpr->GetCastType() ? pExpr->GetCastType() : pExpr->GetType(); bool bSigned = !bIsLeftOfEqual && ((bTempVar && !bArrayIndexing) ? pExpr->IsExprTempVarSigned() : pType && pType->IsSigned()); if (bSigned) m_vFile.Print("$signed("); switch (identFmt) { case eShfFldTmpAndVerMask: m_vFile.Print("((%s >> %s) & {%d{1'b1}})", name.c_str(), pExpr->GetFieldTempVar().c_str(), pExpr->GetVerWidth()); break; case eName: m_vFile.Print("%s", name.c_str()); break; case eShfLowBitAndVerMask: m_vFile.Print("((%s >> %d) & {%d{1'b1}}", name.c_str(), subFieldLowBit, pExpr->GetVerWidth()); break; case eNameAndVerRng: m_vFile.Print("%s[%d:%d]", name.c_str(), subFieldLowBit + pExpr->GetVerWidth()-1, subFieldLowBit ); break; case eShfLowBitAndMask1: m_vFile.Print("((%s >> %d) & 1'b1)", name.c_str(), subFieldLowBit); break; case eNameAndConstBit: m_vFile.Print("%s[%d]", name.c_str(), subFieldLowBit); break; case eNameAndVarBit: m_vFile.Print("%s[%s]", name.c_str(), fieldPosName.c_str() ); break; case eShfLowBitAndSubMask: m_vFile.Print("((%s >> %d) & {%d{1'b1}})", name.c_str(), subFieldLowBit, subFieldWidth); break; case eNameAndSubRng: m_vFile.Print("%s[%d:%d]", name.c_str(), subFieldLowBit + subFieldWidth-1, subFieldLowBit); break; case eShfFldPosAndSubMask: m_vFile.Print("((%s >> %s) & {%d{1'b1}})", name.c_str(), fieldPosName.c_str(), subFieldWidth); break; case eNameAndCondTmpRng: m_vFile.Print("%s", name.c_str()); if (g_htvArgs.IsVivadoEnabled() && !bIsLeftOfEqual) { // this is a hack for vivado int width = pExpr->GetVerWidth(); if (name[0] == 't') { TempVarMap_Iter iter = m_tempVarMap.find(name); if (iter != m_tempVarMap.end()) width = iter->second; } if (width > 1) m_vFile.Print("[%d:0]", width-1 ); } break; default: Assert(0); } if (bSigned) m_vFile.Print(")"); pExpr->SetIsSubExprGenerated(true); } else if (pExpr->IsFunction()) { GenVerilogFunctionCall(pObj, pRtnObj, pExpr); if (pExpr->GetType() != GetVoidType()) pExpr->SetIsFuncGenerated(true); } } if (bTempAssignment) m_vFile.Print(";\n"); } CHtvDesign::EIdentFmt CHtvDesign::FindIdentFmt(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr, EToken prevTk, bool bIsLeftOfEqual, bool bArrayIndexing, string arrayName, bool bIgnoreExprWidth, string &name, bool &bTempVar, bool &bSubField, int &subFieldLowBit, int &subFieldWidth, string &fieldPosName) { EIdentFmt identFmt = eInvalid; bSubField = false; subFieldLowBit = 0; subFieldWidth = pExpr->GetMember() ? pExpr->GetMember()->GetWidth() : pExpr->GetVerWidth(); bool bConstRange = true; CHtvOperand * pOp = pExpr; bool bUseObjStk = false; bTempVar = pOp->IsSubExprGenerated() && pOp->HasExprTempVar() && !bArrayIndexing; CHtvIdent *pIdent = pExpr->GetMember(); if (pExpr->HasFieldTempVar()) fieldPosName = pExpr->GetFieldTempVar(); if (bArrayIndexing) { // generate variable without variable name (just array indexing) bConstRange = GetSubFieldRange(pExpr, subFieldLowBit, subFieldWidth, false); bSubField = subFieldWidth < pExpr->GetMember()->GetWidth(); name = arrayName; } else if (bTempVar) { if (!bArrayIndexing) name = pOp->GetExprTempVar(); if (false && pOp->GetMember()) { bConstRange = GetSubFieldRange(pExpr, subFieldLowBit, subFieldWidth, false); bSubField = subFieldWidth < pExpr->GetMember()->GetWidth(); } } else if (pExpr->HasArrayTempVar()) { GenArrayIndexingSubExpr(pObj, pRtnObj, pExpr, bIsLeftOfEqual); } else { if (pIdent->IsFunction() && pExpr->IsFuncGenerated()) name = pOp->GetFuncTempVar(); else name = GenVerilogIdentName(pIdent->GetName(pExpr), pExpr->GetIndexList()); bConstRange = GetSubFieldRange(pExpr, subFieldLowBit, subFieldWidth, false); bSubField = subFieldWidth < pExpr->GetMember()->GetWidth(); } if (!pExpr->IsSubExprGenerated() && pIdent->IsFunction() && bIsLeftOfEqual) name = "\\" + name + "$Rtn"; if (bTempVar && pExpr->IsExprTempVarWidth() && pExpr->GetExprTempVarWidth() < subFieldWidth) { bSubField = true; subFieldWidth = pExpr->GetExprTempVarWidth(); } identFmt = eInvalid; if (!bTempVar || pExpr->IsExprTempVarWidth() || bUseObjStk && bTempVar && bSubField) { if (!bIgnoreExprWidth && pExpr->GetVerWidth() > 0 && pExpr->GetVerWidth() < subFieldWidth) { if (!bConstRange) { if (!bIsLeftOfEqual) { identFmt = eShfFldTmpAndVerMask; } else identFmt = eName; } else { if (g_htvArgs.IsVivadoEnabled() && !bIsLeftOfEqual && subFieldLowBit > 0 && prevTk != tk_comma) { identFmt = eShfLowBitAndVerMask; } else identFmt = eNameAndVerRng; } } else if (bSubField) { if (subFieldWidth == 1 && (bConstRange || !bIsLeftOfEqual)) { if (bConstRange) { if (g_htvArgs.IsVivadoEnabled() && !bIsLeftOfEqual && subFieldLowBit > 0 && prevTk != tk_comma) identFmt = eShfLowBitAndMask1; else if (bTempVar && pExpr->IsExprTempVarWidth() && pExpr->GetExprTempVarWidth() == 1) identFmt = eName; else identFmt = eNameAndConstBit; } else identFmt = eNameAndVarBit; } else { if (bConstRange) { if (g_htvArgs.IsVivadoEnabled() && !bIsLeftOfEqual && subFieldLowBit > 0 && prevTk != tk_comma) { identFmt = eShfLowBitAndSubMask; } else identFmt = eNameAndSubRng; } else if (!bIsLeftOfEqual) { identFmt = eShfFldPosAndSubMask; } else identFmt = eName; } } else identFmt = eNameAndCondTmpRng; } else identFmt = eNameAndCondTmpRng; return identFmt; } void CHtvDesign::PrintFieldIndex(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr) { // found non-constant sub-field index, generate index equation m_vFile.Print("%s =", pExpr->GetFieldTempVar().c_str()); char *pPrefix = " "; for (CScSubField * pSubField = pExpr->GetSubField(); pSubField; pSubField = pSubField->m_pNext) { if (pSubField->m_pIdent && pSubField->m_pIdent->GetStructPos() > 0) { m_vFile.Print("%s%d", pPrefix, pSubField->m_pIdent->GetStructPos()); pPrefix = " + "; } // check if all indecies are constants int idxBase = 1; for (size_t i = 0; i < pSubField->m_indexList.size(); i += 1) idxBase *= pSubField->m_pIdent ? pSubField->m_pIdent->GetDimenList()[i] : 1; int idx = 0; for (size_t i = 0; i < pSubField->m_indexList.size(); i += 1) { idxBase /= pSubField->m_pIdent ? pSubField->m_pIdent->GetDimenList()[i] : 1; if (pSubField->m_indexList[i]->IsConstValue()) { if (pSubField->m_indexList[i]->GetConstValue().GetSint32() * idxBase > 0) { m_vFile.Print("%s%d * %s%d", pPrefix, pSubField->m_subFieldWidth, g_htvArgs.IsQuartusEnabled() ? "(* multstyle = \"logic\" *) " : "", pSubField->m_indexList[i]->GetConstValue().GetSint3
2() * idxBase); idx += pSubField->m_indexList[i]->GetConstValue().GetSint32() * idxBase; pPrefix = " + "; } } else { m_vFile.Print("%s%d * %s(", pPrefix, pSubField->m_subFieldWidth * idxBase, g_htvArgs.IsQuartusEnabled() ? "(* multstyle = \"logic\" *) " : ""); PrintSubExpr(pObj, pRtnObj, (CHtvOperand *)pSubField->m_indexList[i]); m_vFile.Print(")"); pPrefix = " + "; } } if (!pSubField->m_pIdent) m_vFile.Print("%s%d", pPrefix, idx); pPrefix = " + "; } m_vFile.Print(";\n"); } void CHtvDesign::GenVerilogFunctionCall(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr) { CHtvIdent *pIdent = pExpr->GetMember(); if (!pIdent->IsBodyDefined() && !pIdent->GetType()->IsUserDefinedType()) { SynBuiltinFunctionCall(pObj, pRtnObj, pExpr); } else if (!pIdent->IsInlinedCall()) { m_vFile.Print("%s", pIdent->GetName().c_str()); if (pExpr->GetParamCnt() > 0 || pIdent->GetGlobalRefSet().size() > 0 || pExpr->HasFuncTempVar()) { char *pSeparater = "("; if (pExpr->HasFuncTempVar()) { m_vFile.Print("(%s", pExpr->GetFuncTempVar().c_str()); pSeparater = ", "; } for (int paramId = 0; paramId < pIdent->GetParamCnt(); paramId += 1) { CHtvIdent *pParamIdent = pIdent->FindIdent(pIdent->GetParamName(paramId)); m_vFile.Print(pSeparater); PrintSubExpr(pObj, pRtnObj, pExpr->GetParam(paramId), false, false, false, "", tk_equal); pSeparater = ", "; if (!pParamIdent->IsReadOnly()) { // list as output m_vFile.Print(pSeparater); PrintSubExpr(pObj, pRtnObj, pExpr->GetParam(paramId), true, false, false, "", tk_equal); pSeparater = ", "; } } for (size_t i = 0; i < pIdent->GetGlobalRefSet().size(); i += 1) { CHtIdentElem &identElem = pIdent->GetGlobalRefSet()[i]; vector<CHtDistRamWeWidth> *pWeWidth = identElem.m_pIdent->GetHtDistRamWeWidth(); int startIdx = pWeWidth == 0 || (*pWeWidth).size() == 1 ? -1 : 0; int lastIdx = pWeWidth == 0 || (*pWeWidth).size() == 1 ? 0 : (int)(*pWeWidth).size(); for (int rangeIdx = startIdx; rangeIdx < lastIdx; rangeIdx += 1) { m_vFile.Print("%s%s", pSeparater, GenVerilogIdentName(identElem, rangeIdx).c_str()); pSeparater = ", "; } } m_vFile.Print(");\n"); } else m_vFile.Print(";\n"); // generate array indexed output assignments for (int paramId = 0; paramId < pIdent->GetParamCnt(); paramId += 1) { CHtvIdent *pParamIdent = pIdent->FindIdent(pIdent->GetParamName(paramId)); if (!pParamIdent->IsReadOnly()) { static CHtvOperand * pEqualOp = 0; if (pEqualOp == 0) { pEqualOp = new CHtvOperand; pEqualOp->InitAsOperator(GetLineInfo(), tk_equal); } pEqualOp->SetOperand1(pExpr->GetParam(paramId)); pEqualOp->SetOperand2(pExpr->GetParam(paramId)); pEqualOp->SetExprTempVar("", false); pEqualOp->SetArrayTempVar(""); pEqualOp->SetFieldTempVar(""); pEqualOp->SetFuncTempVar("", false); if (pExpr->GetParam(paramId)->HasArrayTempVar()) { PrintArrayIndex(pObj, pRtnObj, pEqualOp, true); } else if (pExpr->GetParam(paramId)->HasFieldTempVar()) { pExpr->GetParam(paramId)->SetIsSubExprGenerated(false); PrintSubExpr(pObj, pRtnObj, pEqualOp, true); m_vFile.Print(";\n"); } } } } else { // Inline function call SynInlineFunctionCall(pObj, pRtnObj, pExpr); } } void CHtvDesign::SynInlineFunctionCall(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand *pExpr) { CHtvIdent *pFunc = pExpr->GetMember(); if (pRtnObj && !pFunc->IsReturnRef()) pRtnObj->m_pOp = CreateTempOp(pExpr, pExpr->GetFuncTempVar()); // blocks with local variables must be named #ifdef WIN32 if (pExpr->GetLineInfo().m_lineNum == 48) bool stop = true; #endif if (pFunc->GetPrevHier()->IsStruct()) { m_vFile.Print("begin : \\%s.%s$%d // %s:%d\n", pFunc->GetPrevHier()->GetName().c_str(), pFunc->GetName().c_str(), pFunc->GetNextBeginBlockId(), pExpr->GetLineInfo().m_fileName.c_str(), pExpr->GetLineInfo().m_lineNum); } else { m_vFile.Print("begin : \\%s$%d // %s:%d\n", pFunc->GetName().c_str(), pFunc->GetNextBeginBlockId(), pExpr->GetLineInfo().m_fileName.c_str(), pExpr->GetLineInfo().m_lineNum); } m_vFile.IncIndentLevel(); GenFuncVarDecl(pFunc); if (pFunc->GetType() != GetVoidType() && !pFunc->IsReturnRef()) { string bitRange; if (pFunc->GetWidth() > 1) bitRange = VA("[%d:0] ", pFunc->GetWidth()-1); m_vFile.Print("reg %s\\%s$Rtn ;\n", bitRange.c_str(), pFunc->GetName().c_str()); m_vFile.Print("\n"); } // enum constants CHtvIdentTblIter identIter(pFunc->GetFlatIdentTbl()); bool bEnumFound = false; for (identIter.Begin(); !identIter.End(); identIter++) { if (!identIter->IsIdEnum()) continue; if (!bEnumFound) { m_vFile.Print("// initialization of enum constants\n"); bEnumFound = true; } //if (enumIter->IsReadRef(0)) m_vFile.Print("%s = %d'h%x;\n", identIter->GetName().c_str(), identIter->GetType()->GetWidth(), identIter->GetConstValue().GetSint64()); } if (bEnumFound) m_vFile.Print("\n"); // initialize input parameters for (int paramIdx = 0; paramIdx < pFunc->GetParamCnt(); paramIdx += 1) { CHtvIdent * pParamIdent = pFunc->GetParamIdent(paramIdx); CHtvOperand *pParam = pExpr->GetParam(paramIdx); if (pFunc->GetGlobalRefSet().size() == 0 || pFunc->IsStructMember()) { m_vFile.Print("%s = ", pParamIdent->GetFlatIdent()->GetName().c_str()); PrintSubExpr(0, 0, pParam); m_vFile.Print(";\n"); } else { bool bFoundSubExpr; bool bWriteIndex; FindSubExpr(0, 0, pParam, bFoundSubExpr, bWriteIndex); m_vFile.Print("%s = ", pParamIdent->GetFlatIdent()->GetName().c_str()); PrintSubExpr(0, 0, pParam); m_vFile.Print(";\n"); if (bFoundSubExpr) { m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } } } SynStatementList(pFunc, pObj, pRtnObj, (CHtvStatement *)pFunc->GetStatementList()); // assign outputs parameters for (int paramIdx = 0; paramIdx < pFunc->GetParamCnt(); paramIdx += 1) { if (pFunc->GetParamIsConst(paramIdx)) continue; CHtvOperand * pOp2 = new CHtvOperand; pOp2->InitAsIdentifier(GetLineInfo(), pFunc->GetParamIdent(paramIdx)->GetFlatIdent()); CHtvOperand * pEqualOp = new CHtvOperand; pEqualOp->InitAsOperator(GetLineInfo(), tk_equal, pExpr->GetParam(paramIdx), pOp2); bool bFoundSubExpr; bool bWriteIndex; FindSubExpr(pObj, pRtnObj, pEqualOp, bFoundSubExpr, bWriteIndex, false, true); if (!bWriteIndex || !bFoundSubExpr) GenSubExpr(pObj, pRtnObj, pEqualOp, false, false); if (!bWriteIndex) m_vFile.Print(";\n"); if (bFoundSubExpr) { m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } } if (pFunc->GetType() != GetVoidType() && !pFunc->IsReturnRef()) { m_vFile.Print("%s = \\%s$Rtn ;\n", pExpr->GetFuncTempVar().c_str(), pFunc->GetName().c_str()); pExpr->SetTempOp(CreateTempOp(pExpr, pExpr->GetFuncTempVar())); } m_vFile.DecIndentLevel(); m_vFile.Print("end\n"); } void CHtvDesign::GenFuncVarDecl(CHtvIdent * pFunc) { // enum constants CHtvIdentTblIter identIter(pFunc->GetFlatIdentTbl()); for (identIter.Begin(); !identIter.End(); identIter++) { if (!identIter->IsIdEnum()) continue; string bitRange; if (identIter->GetType()->GetWidth() > 1) bitRange = VA("[%d:0] ", identIter->GetType()->GetWidth()-1); //if (enumIter->IsReadRef(0)) m_vFile.Print("reg %s%s;\n", bitRange.c_str(), identIter->GetName().c_str(), identIter->GetType()->GetWidth(), identIter->GetConstValue().GetSint64()); } // declare temps for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsVariable() && !identIter->IsRegClkEn() /*&& !identIter->IsScPrimOutput()*/) { string bitRange; if (identIter->GetWidth() > 1) bitRange = VA("[%d:0] ", identIter->GetWidth()-1); vector<int> refList(identIter->GetDimenCnt(), 0); CHtvIdent * pFlatIdent = m_pInlineHier->InsertFlatIdent( identIter->GetHierIdent(), identIter->GetHierIdent()->GetName() ); pFlatIdent->SetId(CHtvIdent::id_variable); identIter->SetInlineName(pFlatIdent->GetName()); for (int elemIdx = 0; elemIdx < identIter->GetDimenElemCnt(); elemIdx += 1) { bool bWire = identIter->IsAssignOutput(elemIdx) || identIter->IsHtPrimOutput(elemIdx) || identIter->IsPrimOutput(); string identName = identIter->GetVerilogName(elemIdx); m_vFile.SetVarDeclLines(true); GenHtAttributes(identIter(), identName); m_vFile.Print("%s %-10s %s;\n", bWire ? "wire" : "reg ", bitRange.c_str(), identName.c_str()); if (!bWire && m_bInAlwaysAtBlock) m_vFile.PrintVarInit("%s = 32'h0;\n", identName.c_str()); m_vFile.SetVarDeclLines(false); } } } } void CHtvDesign::SynBuiltinFunctionCall(CHtvObject * pObj, CHtvObject * pRtnObj, CHtvOperand * pExpr) { CHtvIdent * pFunc = pExpr->GetMember(); switch (pFunc->GetFuncId()) { case CHtvIdent::fid_and_reduce: GenSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp, false, false, true); m_vFile.Print("%s = & ", pExpr->GetFuncTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp); m_vFile.Print(";\n"); break; case CHtvIdent::fid_nand_reduce: GenSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp, false, false, true); m_vFile.Print("%s = ~& ", pExpr->GetFuncTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp); m_vFile.Print(";\n"); break; case CHtvIdent::fid_or_reduce: GenSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp, false, false, true); m_vFile.Print("%s = | ", pExpr->GetFuncTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp); m_vFile.Print(";\n"); break; case CHtvIdent::fid_nor_reduce: GenSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp, false, false, true); m_vFile.Print("%s = ~| ", pExpr->GetFuncTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp); m_vFile.Print(";\n"); break; case CHtvIdent::fid_xor_reduce: GenSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp, false, false, true); m_vFile.Print("%s = ^ ", pExpr->GetFuncTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp); m_vFile.Print(";\n"); break; case CHtvIdent::fid_xnor_reduce: GenSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp, false, false, true); m_vFile.Print("%s = ~^ ", pExpr->GetFuncTempVar().c_str()); PrintSubExpr(pObj, pRtnObj, (CHtvOperand *)pObj->m_pOp); m_vFile.Print(";\n"); break; default: ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "internal error - unknown builtin function"); } } const char * CHtvDesign::GenVerilogName(const char *pOrigName, const char *pPrefix) { static char buf[1024]; strcpy(buf, g_htvArgs.GetDesignPrefixString().c_str()); char *pBuf = buf + strlen(buf); if (pPrefix) { *pBuf++ = '_'; strcpy(pBuf, pPrefix); pBuf += strlen(pPrefix); } const char *pOrig = pOrigName; if (*pOrig == 'C') pOrig += 1; bool bFirstChar = true; while (*pOrig) { if (isupper(*pOrig) && !bFirstChar) *pBuf++ = '_'; bFirstChar = false; *pBuf++ = tolower(*pOrig++); } *pBuf = '\0'; return buf; } void CHtvDesign::PrintHotStatesCaseItem(CHtvOperand *pExpr, CHtvIdent *pCaseIdent, int hotStatesWidth) { if (hotStatesWidth > 1) m_vFile.Print("{"); int exprWidth = pExpr->GetMinWidth(); int64_t caseItemValue = pExpr->GetConstValue().GetSint64(); bool first = true; for (int i = exprWidth-1; i >= 0; i -= 1) { if (caseItemValue & (((uint64)1)<<i)) { m_vFile.Print("%s%s[%d]", first ? "" : ", ", pCaseIdent->GetName().c_str(), i); first = false; } } if (hotStatesWidth > 1) m_vFile.Print("}"); if (pExpr->GetMember()) m_vFile.Print(" /* %s */ ", pExpr->GetMember()->GetName().c_str()); } CHtvDesign::EAlwaysType CHtvDesign::FindWriteRefVars(CHtvIdent *pHier, CHtvStatement *pStatement, CHtvOperand *pExpr, bool bIsLeftSideOfEqual, bool bFunction) { // recursively desend expression tree CAlwaysType alwaysType; Assert(pExpr != 0); if (pExpr->IsLeaf()) { CHtvIdent *pIdent = pExpr->GetMember(); if (pIdent == 0 || pIdent->IsScState()) return atUnknown; int elemIdx = CalcElemIdx(pIdent, pExpr->GetIndexList()); CHtIdentElem identElem(pIdent, elemIdx); if (bIsLeftSideOfEqual) { Assert(pIdent && pIdent->GetId() == CHtvIdent::id_variable); if (pIdent->IsRegister() && !pStatement->IsScPrim()) { CHtIdentElem clockElem(pHier->GetClockIdent(), 0); pStatement->AddWriteRef(clockElem); alwaysType = atClocked; // register assignment } else { if (pIdent->IsVariable() && !pIdent->IsRegister() && !pIdent->IsPort() && !pIdent->IsParam() && (!pIdent->IsLocal() || !bFunction)) { if (!pStatement->IsScPrim()) pStatement->AddWriteRef(identElem); } alwaysType = atNotClocked; } } else { if (pIdent->IsScLocal()) { if (!pStatement->IsScPrim()) pStatement->AddWriteRef(identElem); } if (pIdent->GetId() == CHtvIdent::id_function) { // count function parameter references for (unsigned int i = 0; i < pExpr->GetParamCnt(); i += 1) { bool bIsReadOnly = pIdent->GetParamIsConst(i); if (bIsReadOnly && pIdent->IsScPrim()) continue; CAlwaysType paramType = FindWriteRefVars(pHier, pStatement, pExpr->GetParam(i), !bIsReadOnly, bFunction); if (!bIsReadOnly) alwaysType += paramType; } if (alwaysType.IsError()) ParseMsg(PARSE_FATAL, pExpr->GetLineInfo(), "Mix of register and non-register outputs"); if (!pIdent->IsMethod()) // Count references in called function (but not function UpdateOutput) alwaysType += FindWriteRefVars(pHier, pIdent->IsScPrim() ? 0 : pStatement, (CHtvStatement *)pIdent->GetStatementList(), true); } else if (pIdent->IsVariable() && !pIdent->IsRegister() && !pIdent->IsPort() && !pIdent->IsParam() && (!pIdent->IsLocal() || !bFunction)) { if (!pStatement->IsScPrim()) pStatement->AddWriteRef(identElem); alwaysType = atNotClocked; } } } else { CHtvOperand *pOp1 = pExpr->GetOperand1(); CHtvOperand *pOp2 = pExpr->GetOperand2(); CHtvOperand *pOp3 = pExpr->GetOperand3(); if (pExpr->GetOperator() == tk_equal) { alwaysType += FindWriteRefVars(pHier, pStatement, pOp1, true, bFunction); if (alwaysType.IsClocked()) // Found register on left of equal, ignore right side // Fixme - must check right side of equal in case a function is called and assigns a non-register return atClocked; alwaysType += FindWriteRefVars(pHier, pStatement, pOp2, false, bFunction); } else { if (pOp1) alwaysType += FindWriteRefVars(pHier, pStatement, pOp1, false, bFunction); if (pOp2) alwaysType += FindWriteRefVars(pHier, pStatement, pOp2, false, bFunction); if (pOp3) alwaysType += FindWriteRefVars(pHier, pStatement, pOp3, false, bFunction); } } return alwaysType; } CHtvDesign::EAlwaysType CHtvDesign::FindWriteRefVars(CHtvIdent *pHier, CHtvStatement *pEntryBaseStatement, CHtvStatement *pStatement, bool bFunction) { CAlwaysType alwaysType; for ( ; pStatement; pStatement = pStatement->GetNext()) { CHtvStatement *pBaseStatement = pEntryBaseStatement ? pEntryBaseStatement : pStatement; switch (pStatement->GetStType()) { case st_compound: alwaysType += FindWriteRefVars(pHier, pBaseStatement, pStatement->GetCompound1(), bFunction); break; case st_return: if (pStatement->GetExpr() == 0) break; // else fall into st_assign case st_assign: alwaysType += FindWriteRefVars(pHier, pBaseStatement, pStatement->GetExpr(), false, bFunction); break; case st_if: alwaysType += FindWriteRefVars(pHier, pBaseStatement, pStatement->GetCompound1(), bFunction); alwaysType += FindWriteRefVars(pHier, pBaseStatement, pStatement->GetCompound2(), bFunction); if (!alwaysType.IsClocked()) FindWriteRefVars(pHier, pBaseStatement, pStatement->GetExpr(), false, bFunction); break; case st_switch: case st_case: alwaysType += FindWriteRefVars(pHier, pBaseStatement, pStatement->GetCompound1(), bFunction); if (!alwaysType.IsClocked()) FindWriteRefVars(pHier, pBaseStatement, pStatement->GetExpr(), false, bFunction); break; case st_default: alwaysType += FindWriteRefVars(pHier, pBaseStatement, pStatement->GetCompound1(), bFunction); break; case st_null: case st_break: break; default: Assert(0); } } return alwaysType; } bool CHtvDesign::IsExpressionEquivalent(CHtvOperand * pExpr1, CHtvOperand * pExpr2) { // determine if the two expressions are equivalent if (pExpr1->IsLeaf() != pExpr2->IsLeaf()) return false; // recursively walk expression if (pExpr1->IsLeaf()) { CHtvIdent *pIdent1 = pExpr1->GetMember(); CHtvIdent *pIdent2 = pExpr2->GetMember(); if (pIdent1 != pIdent2 || pExpr1->IsConstValue() != pExpr2->IsConstValue()) return false; if (pExpr1->IsConstValue()) { if (!CConstValue::IsEquivalent(pExpr1->GetConstValue(), pExpr2->GetConstValue())) return false; } else { Assert(pIdent1); // check index lists for (size_t i = 0; i < pExpr1->GetIndexCnt(); i += 1) if (!IsExpressionEquivalent(pExpr1->GetIndex(i), pExpr2->GetIndex(i))) return false; return true; } } else { if (pExpr1->GetOperator() != pExpr2->GetOperator()) return false; CHtvOperand *pOp11 = pExpr1->GetOperand1(); CHtvOperand *pOp12 = pExpr1->GetOperand2();
CHtvOperand *pOp13 = pExpr1->GetOperand3(); CHtvOperand *pOp21 = pExpr2->GetOperand1(); CHtvOperand *pOp22 = pExpr2->GetOperand2(); CHtvOperand *pOp23 = pExpr2->GetOperand3(); if (pOp11 && !!IsExpressionEquivalent(pOp11, pOp21)) return false; if (pOp12 && !!IsExpressionEquivalent(pOp12, pOp22)) return false; if (pOp13 && !!IsExpressionEquivalent(pOp13, pOp23)) return false; } return false; } string CHtvDesign::GenVerilogIdentName(CHtIdentElem & identElem, int distRamWrEnRangeIdx) { string dimenName = identElem.m_pIdent->GetName(); if (distRamWrEnRangeIdx >= 0) { CHtDistRamWeWidth &weWidth = (*identElem.m_pIdent->GetHtDistRamWeWidth())[distRamWrEnRangeIdx]; dimenName += VA("_%d_%d", weWidth.m_highBit, weWidth.m_lowBit); } int elemIdx = identElem.m_elemIdx; vector<int> & dimenList = identElem.m_pIdent->GetDimenList(); for (size_t i = 0; i < dimenList.size(); i += 1) { int dimIdx = elemIdx % dimenList[i]; elemIdx /= dimenList[i]; dimenName += VA("$%d", dimIdx); } return dimenName; } string CHtvDesign::GenVerilogIdentName(const string &name, const vector<int> &refList) { string identName = name; for (size_t i = 0; i < refList.size(); i += 1) identName += VA("$%d", refList[i]); return identName; } string CHtvDesign::GenVerilogIdentName(const string &name, const HtfeOperandList_t &indexList) { string identName = name; for (size_t i = 0; i < indexList.size(); i += 1) { Assert(indexList[i]->IsConstValue()); identName += VA("$%d", indexList[i]->GetConstValue().GetSint32()); } return identName; } string CHtvDesign::GenVerilogArrayIdxName(const string &name, int idx) { string indexName; if (name.substr(0, 2) == "r_") indexName = "c_" + name.substr(2) + "$r$AI" + FormatString("%d", idx); else indexName = name + "$AI" + FormatString("%d", idx); return indexName; } string CHtvDesign::GenVerilogFieldIdxName(const string &name, int idx) { string indexName; if (name.substr(0, 2) == "r_") indexName = "c_" + name.substr(2) + "$r$FI" + FormatString("%d", idx); else indexName = name + "$FI" + FormatString("%d", idx); return indexName; } bool CHtvDesign::GenXilinxClockedPrim(CHtvIdent *pHier, CHtvObject * pObj, CHtvStatement *pStatement, CHtvOperand *pEnable, bool bCheckOnly) { if (pStatement->GetStType() == st_if) { if (pStatement->GetCompound1() == 0 || pStatement->GetCompound2() != 0) return false; CHtvOperand *pIfExpr = pStatement->GetExpr(); if (!pIfExpr->IsLeaf() || pIfExpr->GetMember() == 0 || pIfExpr->GetVerWidth() != 1) return false; bool bAllXilinxFdPrims = true; for (CHtvStatement *pStatement2 = pStatement->GetCompound1(); pStatement2; pStatement2 = pStatement2->GetNext()) bAllXilinxFdPrims &= GenXilinxClockedPrim(pHier, pObj, pStatement2, pStatement->GetExpr(), bCheckOnly); if (bCheckOnly && bAllXilinxFdPrims) pStatement->SetIsXilinxFdPrim(); return bAllXilinxFdPrims; } if (pStatement->GetStType() == st_switch) return false; Assert (pStatement->GetStType() == st_assign); if (!bCheckOnly && !pStatement->IsXilinxFdPrim()) return false; CHtvOperand *pExpr = pStatement->GetExpr(); CHtvOperand *pOp1 = pExpr->GetOperand1(); if (pOp1 == 0 || pOp1->IsLeaf() && pOp1->GetMember()->GetId() == CHtvIdent::id_function) return false; Assert(pExpr->IsLeaf() == false && pExpr->GetOperator() == tk_equal); if (!pOp1->GetMember()->IsRegister()) return false; //if (pOp1->GetMember()->IsHtQueueRam()) // return true; CHtvOperand *pOp2 = pExpr->GetOperand2(); if (IsConcatLeaves(pOp2)) { // FD / FDE if (bCheckOnly) { pStatement->SetIsXilinxFdPrim(); pOp1->GetMember()->SetIsHtPrimOutput(pOp1); return true; } int op1BaseIdx = pOp1->IsSubFieldValid() ? GetSubFieldLowBit(pOp1) : 0; for (int i = 0; i < pExpr->GetVerWidth(); i += 1) { if (pExpr->GetVerWidth() == 1 && !pOp1->IsSubFieldValid()) m_vFile.Print("%s %s_ ( ", pEnable ? "FDE" : "FD", pOp1->GetMember()->GetVerilogName().c_str()); else m_vFile.Print("%s %s_%d_ ( ", pEnable ? "FDE" : "FD", pOp1->GetMember()->GetVerilogName().c_str(), op1BaseIdx+i); if (pOp1->GetMember()->GetType()->GetWidth() == 1) m_vFile.Print(".Q(%s), ", pOp1->GetMember()->GetName().c_str() ); else m_vFile.Print(".Q(%s[%d]), ", pOp1->GetMember()->GetName().c_str(), op1BaseIdx+i ); int bitIdx; bool bDimen; string name = GetConcatLeafName(i, pOp2, bDimen, bitIdx); if (!bDimen) m_vFile.Print(".D(%s), ", name.c_str() ); else m_vFile.Print(".D(%s[%d]), ", name.c_str(), bitIdx ); if (pEnable) { if (pEnable->IsSubFieldValid()) m_vFile.Print(".CE(%s[%d]), ", pEnable->GetMember()->GetName(pEnable).c_str(), GetSubFieldLowBit(pEnable)); else m_vFile.Print(".CE(%s), ", pEnable->GetMember()->GetName().c_str() ); } m_vFile.Print(".C(%s));\n", pHier->GetClockIdent()->GetName().c_str()); } return true; } else if (pOp2->GetOperator() == tk_question) { CHtvOperand *pExpr2 = pOp2; CHtvOperand *pOp2_1 = pExpr2->GetOperand1(); CHtvOperand *pOp2_2 = pExpr2->GetOperand2(); CHtvOperand *pOp2_3 = pExpr2->GetOperand3(); if (pOp2_3->IsLeaf()) { // Operand 1 must be an identifier with width 1 if (!pOp2_1->IsLeaf() || pOp2_1->GetMember() == 0) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } // Operand 2 must be a constant of zero or all ones if (!pOp2_2->IsLeaf() || !pOp2_2->IsConstValue()) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } if (pOp2_3->IsLeaf() && pOp2_3->GetMember()) { if (bCheckOnly) { pStatement->SetIsXilinxFdPrim(); pOp1->GetMember()->SetIsHtPrimOutput(pOp1); return true; } // FDR / FDRE / FDSE int op1BaseIdx = pOp1->IsSubFieldValid() ? GetSubFieldLowBit(pOp1) : 0; int op2_1BaseIdx = pOp2_1->IsSubFieldValid() ? GetSubFieldLowBit(pOp2_1) : 0; int op2_3BaseIdx = pOp2_3->IsSubFieldValid() ? GetSubFieldLowBit(pOp2_3) : 0; uint64 constValue = pOp2_2->GetConstValue().GetUint64(); for (int i = 0; i < pExpr->GetVerWidth(); i += 1) { bool bIsFDRE = ((constValue >> i) & 1) == 0; if (bIsFDRE) { if (pExpr->GetVerWidth() == 1 && !pOp1->IsSubFieldValid()) m_vFile.Print("%s %s_ ( ", pEnable ? "FDRE" : "FDR", pOp1->GetMember()->GetVerilogName().c_str(), op1BaseIdx+i); else m_vFile.Print("%s %s_%d_ ( ", pEnable ? "FDRE" : "FDR", pOp1->GetMember()->GetVerilogName().c_str(), op1BaseIdx+i); } else { if (pExpr->GetVerWidth() == 1 && !pOp1->IsSubFieldValid()) m_vFile.Print("%s %s_ ( ", pEnable ? "FDSE" : "FDS", pOp1->GetMember()->GetVerilogName().c_str(), op1BaseIdx+i); else m_vFile.Print("%s %s_%d_ ( ", pEnable ? "FDSE" : "FDS", pOp1->GetMember()->GetVerilogName().c_str(), op1BaseIdx+i); } if (pOp1->GetMember()->GetType()->GetWidth() == 1) m_vFile.Print(".Q( %s ), ", pOp1->GetMember()->GetName(pOp1).c_str() ); else m_vFile.Print(".Q( %s[%d] ), ", pOp1->GetMember()->GetName(pOp1).c_str(), op1BaseIdx+i ); if (pOp2_3->GetMember()->GetType()->GetWidth() == 1) m_vFile.Print(".D( %s ), ", pOp2_3->GetMember()->GetName(pOp2_3).c_str() ); else m_vFile.Print(".D( %s[%d] ), ", pOp2_3->GetMember()->GetName(pOp2_3).c_str(), op2_3BaseIdx+i ); if (pOp2_1->GetMember()->GetType()->GetWidth() == 1) m_vFile.Print(".%c( %s ), ", bIsFDRE ? 'R' : 'S', pOp2_1->GetMember()->GetName(pOp2_1).c_str() ); else m_vFile.Print(".%c( %s[%d] ), ", bIsFDRE ? 'R' : 'S', pOp2_1->GetMember()->GetName(pOp2_1).c_str(), op2_1BaseIdx ); if (pEnable) { if (pEnable->IsSubFieldValid()) m_vFile.Print(".CE( %s[%d] ), ", pEnable->GetMember()->GetName(pEnable).c_str(), GetSubFieldLowBit(pEnable)); else m_vFile.Print(".CE( %s ), ", pEnable->GetMember()->GetName(pEnable).c_str() ); } m_vFile.Print(".C( %s ) );\n", pHier->GetClockIdent()->GetName().c_str()); } return true; } } else { // Check for FDRS / FDRSE // Operand 1 must be an identifier with width 1 if (!pOp2_1->IsLeaf() || pOp2_1->GetMember() == 0) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } // Operand 2 must be a constant of zero if (!pOp2_2->IsLeaf() || !pOp2_2->IsConstValue()) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } uint64 constValue = pOp2_2->GetConstValue().GetUint64(); if (constValue != 0) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } if (pOp2_3->GetOperator() != tk_question) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } CHtvOperand *pExpr2_3 = pOp2_3; CHtvOperand *pOp2_3_1 = pExpr2_3->GetOperand1(); CHtvOperand *pOp2_3_2 = pExpr2_3->GetOperand2(); CHtvOperand *pOp2_3_3 = pExpr2_3->GetOperand3(); // Operand 1 must be an identifier with width 1 if (!pOp2_3_1->IsLeaf() || pOp2_3_1->GetMember() == 0) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } // Operand 2 must be a constant of zero of all ones if (!pOp2_3_2->IsLeaf() || !pOp2_3_2->IsConstValue()) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } constValue = pOp2_3_2->GetConstValue().GetUint64(); uint64 constOnes = (uint64)0xffffffffffffffffLL >> (64 - pOp2_3_2->GetVerWidth()); if (constValue != constOnes) { ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } if (pOp2_3_3->IsLeaf() && pOp2_3_3->GetMember()) { if (bCheckOnly) { pStatement->SetIsXilinxFdPrim(); pOp1->GetMember()->SetIsHtPrimOutput(pOp1); return true; } // FDRS / FDRSE int op1BaseIdx = pOp1->IsSubFieldValid() ? GetSubFieldLowBit(pOp1) : 0; int op2_1BaseIdx = pOp2_1->IsSubFieldValid() ? GetSubFieldLowBit(pOp2_1) : 0; int op2_3_1BaseIdx = pOp2_3_1->IsSubFieldValid() ? GetSubFieldLowBit(pOp2_3_1) : 0; int op2_3_3BaseIdx = pOp2_3_3->IsSubFieldValid() ? GetSubFieldLowBit(pOp2_3_3) : 0; for (int i = 0; i < pExpr->GetVerWidth(); i += 1) { if (pExpr->GetVerWidth() == 1 && !pOp1->IsSubFieldValid()) m_vFile.Print("%s %s_ ( ", pEnable ? "FDRSE" : "FDRS", pOp1->GetMember()->GetVerilogName().c_str(), op1BaseIdx+i); else m_vFile.Print("%s %s_%d_ ( ", pEnable ? "FDRSE" : "FDRS", pOp1->GetMember()->GetVerilogName().c_str(), op1BaseIdx+i); if (pOp1->GetMember()->GetType()->GetWidth() == 1) m_vFile.Print(".Q( %s ), ", pOp1->GetMember()->GetName(pOp1).c_str() ); else m_vFile.Print(".Q( %s[%d] ), ", pOp1->GetMember()->GetName(pOp1).c_str(), op1BaseIdx+i ); if (pOp2_3_3->GetMember()->GetType()->GetWidth() == 1) m_vFile.Print(".D( %s ), ", pOp2_3_3->GetMember()->GetName(pOp2_3_3).c_str() ); else m_vFile.Print(".D( %s[%d] ), ", pOp2_3_3->GetMember()->GetName(pOp2_3_3).c_str(), op2_3_3BaseIdx+i ); if (pOp2_1->GetMember()->GetType()->GetWidth() == 1) m_vFile.Print(".R( %s ), ", pOp2_1->GetMember()->GetName(pOp2_1).c_str() ); else m_vFile.Print(".R( %s[%d] ), ", pOp2_1->GetMember()->GetName(pOp2_1).c_str(), op2_1BaseIdx ); if (pOp2_3_1->GetMember()->GetType()->GetWidth() == 1) m_vFile.Print(".S( %s ), ", pOp2_3_1->GetMember()->GetName(pOp2_3_1).c_str() ); else m_vFile.Print(".S( %s[%d] ), ", pOp2_3_1->GetMember()->GetName(pOp2_3_1).c_str(), op2_3_1BaseIdx ); if (pEnable) { if (pEnable->IsSubFieldValid()) m_vFile.Print(".CE( %s[%d] ), ", pEnable->GetMember()->GetName(pEnable).c_str(), GetSubFieldLowBit(pEnable)); else m_vFile.Print(".CE( %s ), ", pEnable->GetMember()->GetName(pEnable).c_str() ); } m_vFile.Print(".C( %s ) );\n", pHier->GetClockIdent()->GetName().c_str()); } return true; } } } ParseMsg(PARSE_WARNING, pExpr->GetLineInfo(), "Unable to translate statement to Xilinx FD Primitive(s)"); Assert(bCheckOnly); return false; } bool CHtvDesign::IsConcatLeaves(CHtvOperand *pOperand) { // a single leaf is considered a concatenated leaf if (pOperand->IsLeaf()) return true; if (pOperand->GetOperator() == tk_comma) return IsConcatLeaves(pOperand->GetOperand1()) && IsConcatLeaves(pOperand->GetOperand2()); return false; } string CHtvDesign::GetConcatLeafName(int exprIdx, CHtvOperand *pExpr, bool &bDimen, int &bitIdx) { if (pExpr->IsLeaf()) { bDimen = pExpr->GetMember()->GetWidth() > 1;//GetDimenCnt() != 0; int baseIdx = pExpr->IsSubFieldValid() ? GetSubFieldLowBit(pExpr) : 0; bitIdx = baseIdx + exprIdx; return pExpr->GetMember()->GetName(pExpr); } Assert(pExpr->GetOperator() == tk_comma); if (exprIdx < pExpr->GetOperand2()->GetMinWidth()) return GetConcatLeafName(exprIdx, pExpr->GetOperand2(), bDimen, bitIdx); else return GetConcatLeafName(exprIdx - pExpr->GetOperand2()->GetMinWidth(), pExpr->GetOperand1(), bDimen, bitIdx); } void CHtvDesign::GenFixtureFiles(CHtvIdent *pModule) { GenRandomH(); GenRandomCpp(); GenScMainCpp(); GenFixtureH(pModule); GenFixtureCpp(pModule); GenFixtureModelH(pModule); GenFixtureModelCpp(pModule); GenSandboxVpp(pModule); } FILE * CHtvDesign::BackupAndOpen(const string &fileName) { // first backup old file string originalName = m_pathName + fileName; string backupName = m_backupPath + fileName; rename(originalName.c_str(), backupName.c_str()); FILE *fp; if (!(fp = fopen(originalName.c_str(), "w"))) { printf("Could not open '%s' for writing\n", originalName.c_str()); ErrorExit(); } return fp; } void CHtvDesign::PrintHeader(FILE *fp, char *pComment) { fprintf(fp, "// %s\n", pComment); fprintf(fp, "//\n"); fprintf(fp, "//////////////////////////////////////////////////////////////////////\n"); fprintf(fp, "\n"); } void CHtvDesign::GenRandomH() { string fileName = m_pathName + "Random.h"; FILE *fp; if (fp = fopen(fileName.c_str(), "r")) { fclose(fp); return; } if (!(fp = fopen(fileName.c_str(), "w"))) { printf("Could not open '%s' for writing\n", fileName.c_str()); ErrorExit(); } PrintHeader(fp, "Random.h: Header for random number generator"); fprintf(fp, "#pragma once\n"); fprintf(fp, "\n"); fprintf(fp, "class CRandom;\n"); fprintf(fp, "\n"); fprintf(fp, "class CRndGen\n"); fprintf(fp, "{\n"); fprintf(fp, "public:\n"); fprintf(fp, "\tCRndGen(unsigned long init=1);\n"); fprintf(fp, "\tvirtual ~CRndGen();\n"); fprintf(fp, "\n"); fprintf(fp, "\tuint32_t AsUint32();\n"); fprintf(fp, "\tuint64_t AsUint64() { return ((uint64_t)AsUint32() << 32) | AsUint32(); }\n"); fprintf(fp, "\tint64_t AsSint64() { return (int64_t)(((uint64_t)AsUint32() << 32) | AsUint32()); }\n"); fprintf(fp, "\tdouble AsDouble();\n"); fprintf(fp, "\tfloat AsFloat();\n"); fprintf(fp, "\tunsigned int GetSeed() { return initialSeed; }\n"); fprintf(fp, "\tvoid Seed(unsigned int init);\n"); fprintf(fp, "\n"); fprintf(fp, "private:\n"); fprintf(fp, "\tvoid ResetRndGen();\n"); fprintf(fp, "\n"); fprintf(fp, "private:\n"); fprintf(fp, "\tunion PrivateDoubleType { // used to access doubles as unsigneds\n"); fprintf(fp, "\t\tdouble d;\n"); fprintf(fp, "\t\tuint32_t u[2];\n"); fprintf(fp, "\t};\n"); fprintf(fp, "\tPrivateDoubleType doubleMantissa;\n"); fprintf(fp, "\n"); fprintf(fp, "\tunion PrivateFloatType { // used to access floats as unsigneds\n"); fprintf(fp, "\t\tfloat f;\n"); fprintf(fp, "\t\tunsigned long u;\n"); fprintf(fp, "\t};\n"); fprintf(fp, "\tPrivateFloatType floatMantissa;\n"); fprintf(fp, "\n"); fprintf(fp, "\t// struct defines a knot of the circular queue\n"); fprintf(fp, "\t// used by the lagged Fibonacci algorithm\n"); fprintf(fp, "\tstruct Vknot {\n"); fprintf(fp, "\t\tVknot() { v = 0; vnext = 0; }\n"); fprintf(fp, "\t\tunsigned long v;\n"); fprintf(fp, "\t\tVknot *vnext;\n"); fprintf(fp, "\t} m_Vknot[97];\n"); fprintf(fp, "\tunsigned long initialSeed; // start value of initialization routine\n"); fprintf(fp, "\tunsigned long Xn; // generated value\n"); fprintf(fp, "\tunsigned long cn, Vn; // temporary values\n"); fprintf(fp, "\tVknot *V33, *V97, *Vanker; // some pointers to the queue\n"); fprintf(fp, "};\n"); fprintf(fp, "\n"); fprintf(fp, "class CRandom\n"); fprintf(fp, "{\n");
fprintf(fp, "\tfriend class CRndGen;\n"); fprintf(fp, "public:\n"); fprintf(fp, "\tCRandom() {}\n"); fprintf(fp, "\t// ~CRandom() {};\n"); fprintf(fp, "\tvoid Seed(unsigned int init) { m_rndGen.Seed(init); }\n"); fprintf(fp, "\n"); fprintf(fp, "\tbool RndBool() { return (m_rndGen.AsUint32() & 1) == 1; }\n"); fprintf(fp, "\n"); fprintf(fp, "\tint32_t RndSint32() { return m_rndGen.AsUint32(); }\n"); fprintf(fp, "\n"); fprintf(fp, "\tuint32_t RndUint32() { return m_rndGen.AsUint32(); }\n"); fprintf(fp, "\n"); fprintf(fp, "\tuint32_t RndUint32(uint32_t low, uint32_t high)\n"); fprintf(fp, "\t{ return (m_rndGen.AsUint32() %% (high-low+1)) + low; }\n"); fprintf(fp, "\n"); fprintf(fp, "\tuint64_t RndSint64(int64_t low, int64_t high)\n"); fprintf(fp, "\t{ return (m_rndGen.AsUint64() %% (high-low+1)) + low; }\n"); fprintf(fp, "\n"); fprintf(fp, "\tuint32_t RndSint32(int low, int high)\n"); fprintf(fp, "\t{ return (m_rndGen.AsUint32() %% (high-low+1)) + low; }\n"); fprintf(fp, "\n"); fprintf(fp, "\tuint64_t RndUint64() { return m_rndGen.AsUint64(); }\n"); fprintf(fp, "\n"); fprintf(fp, "\tuint64_t RndUint64(uint64_t low, uint64_t high)\n"); fprintf(fp, "\t{ return (m_rndGen.AsUint64() %% (high-low+1)) + low; }\n"); fprintf(fp, "\n"); fprintf(fp, "\tdouble RndUniform(double pLow=0.0, double pHigh=1.0)\n"); fprintf(fp, "\t{ return pLow + (pHigh - pLow) * m_rndGen.AsDouble(); }\n"); fprintf(fp, "\n"); fprintf(fp, "\tfloat RndUniform(float pLow, float pHigh=1.0)\n"); fprintf(fp, "\t{ return pLow + (pHigh - pLow) * m_rndGen.AsFloat(); }\n"); fprintf(fp, "\n"); fprintf(fp, "\tdouble RndPercent() { return RndUniform(0.0, 99.999999999); }\n"); fprintf(fp, "\n"); fprintf(fp, "\t// double RndNegExp(double mean)\n"); fprintf(fp, "\t// { return(-mean * log(m_rndGen.AsDouble())); }\n"); fprintf(fp, "\n"); fprintf(fp, "private:\n"); fprintf(fp, "\tCRndGen m_rndGen;\n"); fprintf(fp, "};\n"); } void CHtvDesign::GenRandomCpp() { string fileName = m_pathName + "Random.cpp"; FILE *fp; if (fp = fopen(fileName.c_str(), "r")) { fclose(fp); return; } if (!(fp = fopen(fileName.c_str(), "w"))) { printf("Could not open '%s' for writing\n", fileName.c_str()); ErrorExit(); } PrintHeader(fp, "Random.cpp: Random number generator for fixture"); fprintf(fp, "#include <stdint.h>\n"); fprintf(fp, "#include \"Random.h\"\n"); fprintf(fp, "\n"); fprintf(fp, "//////////////////////////////////////////////////////////////////////\n"); fprintf(fp, "// Construction/Destruction\n"); fprintf(fp, "//////////////////////////////////////////////////////////////////////\n"); fprintf(fp, "\n"); fprintf(fp, "CRndGen::CRndGen(unsigned long init)\n"); fprintf(fp, "{\n"); fprintf(fp, "\t// create a 97 element circular queue\n"); fprintf(fp, "\tVknot *Vhilf;\n"); fprintf(fp, "\tVanker = V97 = Vhilf = &m_Vknot[0];\n"); fprintf(fp, "\n"); fprintf(fp, "\tfor( short i=96; i>0; i-- ) {\n"); fprintf(fp, "\t\tVhilf->vnext = &m_Vknot[i];\n"); fprintf(fp, "\t\tVhilf = Vhilf->vnext;\n"); fprintf(fp, "\t\tif (i == 33)\n"); fprintf(fp, "\t\t\tV33 = Vhilf;\n"); fprintf(fp, "\t}\n"); fprintf(fp, "\n"); fprintf(fp, "\tVhilf->vnext = Vanker;\n"); fprintf(fp, "\n"); fprintf(fp, "\tinitialSeed = init;\n"); fprintf(fp, "\n"); fprintf(fp, "\tResetRndGen();\n"); fprintf(fp, "\n"); fprintf(fp, "\t// initialize mantissa to all ones\n"); fprintf(fp, "\tdoubleMantissa.d = 1.0;\n"); fprintf(fp, "\tdoubleMantissa.u[0] ^= 0xffffffff;\n"); fprintf(fp, "\tdoubleMantissa.u[1] ^= 0x3fffffff;\n"); fprintf(fp, "\n"); fprintf(fp, "\t// initialize mantissa to all ones\n"); fprintf(fp, "\tfloatMantissa.f = 1.0;\n"); fprintf(fp, "\tfloatMantissa.u ^= 0x3fffffff;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "CRndGen::~CRndGen()\n"); fprintf(fp, "{\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "void\n"); fprintf(fp, "CRndGen::Seed(unsigned int init)\n"); fprintf(fp, "{\n"); fprintf(fp, "\tinitialSeed = init;\n"); fprintf(fp, "\n"); fprintf(fp, "\tResetRndGen();\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "void\n"); fprintf(fp, "CRndGen::ResetRndGen()\n"); fprintf(fp, "{\n"); fprintf(fp, "\t// initialise FIBOG like RANMAR (or IMAV)\n"); fprintf(fp, "\tVknot *Vhilf = V97;\n"); fprintf(fp, "\n"); fprintf(fp, "\tlong ijkl = 54217137;\n"); fprintf(fp, "\tif (initialSeed >0 && initialSeed <= 0x7fffffff) ijkl = initialSeed;\n"); fprintf(fp, "\tlong ij = ijkl / 30082;\n"); fprintf(fp, "\tlong kl = ijkl - 30082 * ij;\n"); fprintf(fp, "\tlong i = (ij/177) %% 177 + 2;\n"); fprintf(fp, "\tlong j = ij %% 177 + 2;\n"); fprintf(fp, "\tlong k = (kl/169) %% 178 + 1;\n"); fprintf(fp, "\tlong l = kl %% 169;\n"); fprintf(fp, "\tlong s, t;\n"); fprintf(fp, "\tfor( int ii=0; ii<97; ii++) {\n"); fprintf(fp, "\t\ts = 0; t = 0x80000000;\n"); fprintf(fp, "\t\tfor( int jj=0; jj<32; jj++) {\n"); fprintf(fp, "\t\t\tlong m = (((i * j) %% 179) * k) %% 179;\n"); fprintf(fp, "\t\t\ti = j; j = k; k = m;\n"); fprintf(fp, "\t\t\tl = (53 * l + 1) %% 169;\n"); fprintf(fp, "\t\t\tif ((l * m) %% 64 >= 32) s = s + t;\n"); fprintf(fp, "\t\t\tt /= 2;\n"); fprintf(fp, "\t\t}\n"); fprintf(fp, "\n"); fprintf(fp, "\t\tVhilf->v = s;\n"); fprintf(fp, "\t\tVhilf = Vhilf->vnext;\n"); fprintf(fp, "\t}\n"); fprintf(fp, "\n"); fprintf(fp, "\tcn = 15362436;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "uint32_t\n"); fprintf(fp, "CRndGen::AsUint32()\n"); fprintf(fp, "{\n"); fprintf(fp, "\tVn = (V97->v - V33->v) & 0xffffffff; // (x & 2^32) might be faster \n"); fprintf(fp, "\tcn = (cn + 362436069) & 0xffffffff; // than (x %% 2^32)\n"); fprintf(fp, "\tXn = (Vn - cn) & 0xffffffff;\n"); fprintf(fp, "\n"); fprintf(fp, "\tV97->v = Vn;\n"); fprintf(fp, "\tV97 = V97->vnext;\n"); fprintf(fp, "\tV33 = V33->vnext;\n"); fprintf(fp, "\n"); fprintf(fp, "\treturn Xn;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "double\n"); fprintf(fp, "CRndGen::AsDouble()\n"); fprintf(fp, "{\n"); fprintf(fp, "\tPrivateDoubleType result;\n"); fprintf(fp, "\tresult.d = 1.0;\n"); fprintf(fp, "\tresult.u[1] |= (AsUint32() & doubleMantissa.u[1]);\n"); fprintf(fp, "\tresult.u[0] |= (AsUint32() & doubleMantissa.u[0]);\n"); fprintf(fp, "\tresult.d -= 1.0;\n"); fprintf(fp, "\treturn( result.d );\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "float\n"); fprintf(fp, "CRndGen::AsFloat()\n"); fprintf(fp, "{\n"); fprintf(fp, "\tPrivateFloatType result;\n"); fprintf(fp, "\tresult.f = 1.0;\n"); fprintf(fp, "\tresult.u |= (AsUint32() & floatMantissa.u);\n"); fprintf(fp, "\tresult.f -= 1.0;\n"); fprintf(fp, "\treturn( result.f );\n"); fprintf(fp, "}\n"); fclose(fp); } void CHtvDesign::GenScMainCpp() { string fileName = m_pathName + "ScMain.cpp"; FILE *fp; if (fp = fopen(fileName.c_str(), "r")) { fclose(fp); return; } if (!(fp = fopen(fileName.c_str(), "w"))) { printf("Could not open '%s' for writing\n", fileName.c_str()); ErrorExit(); } PrintHeader(fp, "ScMain.cpp: Entry point for program"); fprintf(fp, "#include <stdint.h>\n"); fprintf(fp, "#include \"FixtureTop.h\"\n"); fprintf(fp, "\n"); fprintf(fp, "int\n"); fprintf(fp, "sc_main(int argc, char *argv[])\n"); fprintf(fp, "{\n"); fprintf(fp, "\tCFixtureTop FixtureTop(\"FixtureTop\");\n"); fprintf(fp, "\n"); fprintf(fp, "\tsc_start();\n"); fprintf(fp, "\n"); fprintf(fp, "\treturn 0;\n"); fprintf(fp, "}\n"); fclose(fp); } void CHtvDesign::GenFixtureH(CHtvIdent *pModule) { FILE *fp; string readName = m_pathName + "Fixture.h"; vector<string> userLines; int userLinesCnt[2] = { 0, 0 }; int regionCnt = 0; if (fp = fopen(readName.c_str(), "r")) { char lineBuf[512]; while (regionCnt < 2 && fgets(lineBuf, 512, fp)) { if (strncmp(lineBuf, "//>>", 4) == 0) { while (fgets(lineBuf, 512, fp)) { if (strncmp(lineBuf, "//<<", 4) == 0) { userLinesCnt[regionCnt++] = userLines.size(); break; } userLines.push_back(lineBuf); } } } fclose(fp); } CFileBkup fb(m_pathName, "Fixture", "h"); fb.PrintHeader("Fixture.h: Top level fixture include file"); fb.Print("#pragma once\n"); fb.Print("\n"); fb.Print("#ifdef __SYSTEM_C__\n"); fb.Print("#include <SystemC.h>\n"); fb.Print("#else\n"); fb.Print("#include \"acc_user.h\"\n"); fb.Print("extern \"C\" int InitFixture();\n"); fb.Print("extern \"C\" int Fixture();\n"); fb.Print("#endif\n"); fb.Print("\n"); fb.Print("#ifndef _SC_LINT\n"); fb.Print("#include <time.h>\n"); fb.Print("#include <stdint.h>\n"); fb.Print("#include \"Random.h\"\n"); fb.Print("#include \"FixtureModel.h\"\n"); fb.Print("\n"); fb.Print("extern CRandom cnyRnd;\n"); fb.Print("\n"); fb.Print("struct CFixtureTest {\n"); fb.Print("\tCFixtureTest() { }\n"); fb.Print("\tCFixtureTest(uint64_t clkCnt, uint64_t testCnt) : m_clkCnt(clkCnt), m_testCnt(testCnt) { }\n"); fb.Print("\n"); fb.Print("\tCFixtureTest &Test("); CHtvIdentTblIter identIter(pModule->GetIdentTbl()); int cnt = 0; if (pModule->GetClockListCnt() > 1) { cnt += 1; string clkName = pModule->GetClockList()[1]->GetName(); fb.Print("uint32_t phase%sCnt", clkName.c_str()+3); } for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { if (cnt > 0) fb.Print((cnt % 5 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; const string portName = identIter->GetName(); if (identIter->GetType()->GetType()->IsStruct()) fb.Print("%s %s", identIter->GetType()->GetType()->GetName().c_str(), portName.c_str()); else fb.Print("uint%d_t %s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } fb.Print(") {\n"); fb.Print("\n"); fb.Print("\t\tm_pModel->Model("); cnt = 0; if (pModule->GetClockListCnt() > 1) { cnt += 1; string clkName = pModule->GetClockList()[1]->GetName(); fb.Print("phase%sCnt", clkName.c_str()+3); } for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { if (cnt > 0) fb.Print((cnt % 8 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; const string portName = identIter->GetName(); fb.Print("%s", portName.c_str()); } } for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { if (cnt > 0) fb.Print((cnt % 8 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; const string portName = identIter->GetName(); fb.Print("m_%s", portName.c_str()); } } fb.Print(");\n"); fb.Print("\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("\t\tm_%s = %s;\n", portName.c_str(), portName.c_str()); } } fb.Print("\n"); fb.Print("\t\treturn *this;\n"); fb.Print("\t}\n"); fb.Print("\tCFixtureTest & End() {\n"); fb.Print("\t\tm_testCnt = 0xffffffffffffffffLL;\n"); fb.Print("\t\treturn *this;\n"); fb.Print("\t}\n"); fb.Print("\n"); fb.Print("\tbool IsEnd() { return m_testCnt == 0xffffffffffffffffLL; }\n"); fb.Print("\n"); fb.Print("static void SetModel(CFixtureModel *pModel) { m_pModel = pModel; }\n"); fb.Print("\n"); fb.Print("\tuint64_t \tm_clkCnt;\n"); fb.Print("\tuint64_t \tm_testCnt;\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if ((identIter->IsOutPort() || identIter->IsInPort()) && !identIter->IsClock()) { char typeName[128]; if (identIter->GetType()->GetType()->IsStruct()) sprintf(typeName, "%s", identIter->GetType()->GetType()->GetName().c_str()); else sprintf(typeName, "uint%d_t", identIter->GetWidth() <= 32 ? 32 : 64); const string portName = identIter->GetName(); fb.Print("\t%-12s\tm_%s;\n", typeName, portName.c_str()); } } fb.Print("\n"); fb.Print("\tstatic CFixtureModel *\tm_pModel;\n"); fb.Print("};\n"); fb.Print("\n"); fb.Print("#include <queue>\n"); fb.Print("using namespace std;\n"); fb.Print("\n"); fb.Print("typedef queue<CFixtureTest> CTestQue;\n"); fb.Print("\n"); fb.Print("#define TEST_CNT 1000000000000LL\n"); fb.Print("#define sc_fixture\n"); fb.Print("#define sc_fixture_top\n"); fb.Print("\n"); fb.Print("#endif\n"); fb.Print("\n"); fb.Print("#ifdef __SYSTEM_C__\n"); fb.Print("sc_fixture\n"); fb.Print("SC_MODULE(CFixture) {\n"); if (pModule->GetClockList().size() == 0) { fprintf(stderr, "Clock signal not found for generating 'Fixture.h'\n"); ErrorExit(); } fb.Print("\tsc_in<bool> \ti_%s;\n", pModule->GetClockList()[0]->GetName().c_str()); fb.Print("\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() || identIter->IsInPort()) { const string portName = identIter->GetName(); char typeName[128]; if (identIter->IsInPort()) sprintf(typeName, "sc_in<%s>", identIter->GetType()->GetType()->GetName().c_str()); else sprintf(typeName, "sc_out<%s>", identIter->GetType()->GetType()->GetName().c_str()); if (identIter->IsInPort()) fb.Print("\t%-20s \ti_%s;\n", typeName, portName.c_str()); else fb.Print("\t%-20s \to_%s;\n", typeName, portName.c_str()); } } fb.Print("\n"); fb.Print("#else // __SYSTEM_C__\n"); fb.Print("class CFixture {\n"); fb.Print("public:\n"); fb.Print("#endif // __SYSTEM_C__\n"); fb.Print("\n"); fb.Print("#ifndef _SC_LINT\n"); fb.Print("\n"); fb.Print("\tCFixtureModel\t\t\tm_model;\n"); fb.Print("\tvector<CFixtureTest>\tm_directedTests;\n"); fb.Print("\n"); fb.Print("\tuint64_t r_clkCnt;\n"); fb.Print("\tint r_inCnt;\n"); fb.Print("\tint r_outCnt;\n"); fb.Print("\tuint64_t r_testCnt;\n"); fb.Print("\n"); fb.Print("\ttime_t startTime;\n"); fb.Print("\n"); fb.Print("\tCTestQue m_testQue;\n"); fb.Print("\n"); fb.Print("\tCRndGen\tm_rndGen;\n"); fb.Print("\tint\t\tm_randomSeed;\n"); fb.Print("\n"); if (pModule->GetClockListCnt() > 1) fb.Print("\tuint32_t\tr_phase%sCnt;\n", pModule->GetClockList()[1]->GetName().c_str()+3); if (pModule->GetClockListCnt() > 2) fb.Print("\tbool\t\tr_phase%s;\n", pModule->GetClockList()[2]->GetName().c_str()+3); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("\tuint32_t\tm_stage_%s;\n", portName.c_str()); } } fb.Print("\n"); fb.Print("//////////////////////////////////////\n"); fb.Print("// Fixture specific declarations\n"); fb.Print("//>>\n"); if (regionCnt > 0) { for (int i = 0; i < userLinesCnt[0]; i += 1) fb.Write(userLines[i].c_str()); } fb.Print("//<<\n"); fb.Print("// Fixture specific declarations\n"); fb.Print("//////////////////////////////////////\n"); fb.Print("\n"); fb.Print("#endif\n"); fb.Print("\n"); fb.Print("\tvoid Fixture();\n"); fb.Print("\tvoid DelayEarlyOutputs();\n"); fb.Print("\tvoid GetOutputs("); cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fb.Print((cnt % 5 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; fb.Print("uint%d_t &%s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } fb.Print(");\n"); fb.Print("\tvoid GenRandomInputs("); cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fb.Print((cnt % 5 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; if (identIter->GetType()->GetType()->IsStruct()) fb.Print("%s &%s", identIter->GetType()->GetType()->GetName().c_str(), portName.c_str()); else fb.Print("uint%d_t &%s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } fb.Print(");\n"); fb.Print("\n"); fb.Print("#ifndef _SC_LINT\n"); fb.Print("\tvoid InitTest();\n"); fb.Print("#endif\n"); fb.Print("\n"); fb.Print("\t// Constructor\n"); fb.Print("#ifdef __SYSTEM_C__\n"); fb.Print("\t#ifndef _SC_LINT\n"); fb.Print("\t\tsc_clock *pClock;\n"); fb.Print("\t\tvoid Clock() {\n"); fb.Print("\t\t\tbool %s = *pClock;\n", pModule->GetClockList()[0]->GetName().c_str()); string clkName; string clkhxName; if (pModule->GetClockListCnt() > 1) { clkName = pModule->GetClockList()[1]->GetName(); fb.Print("\t\t\tif (%s) {\n", pModule->GetClockList()[0]->GetName().c_str()); fb.Print("\t\t\t\tr_phase%sCnt = (r_phase%sCnt + 1) & PHASE_CNT_MASK;\n", clkName.c_str()+3, clkName.c_str()+3); if (pModule->GetClockListCnt() > 2) { clkhxName = pModule->GetClockList()[2]->GetName(); fb.Print("\t\t\t\tif (r_phase%sCnt == 0)\n", clkName.c_str()+3); fb.Print("\t\t\t\t\tr_phase%s = !r_phase%s;\n", clkhxName.c_str()+3, clkhxName.c_str()+3); } fb.Print("\t\t\t}\n"); } fb.Print("\t\t\to_%s = %s;\n", pModule->GetClockList()[0]->GetName().c_str(), pModule->GetClockList()[0]->GetName().c_str()); if (pModule->GetClockListCnt() > 1) fb.Print("\t\t\to_%s = r_phase%sCnt == 0;\n", pModule->GetClockList()[1]->GetName().c_str(), clkName.c_str()+3); if (pModule->GetClockListCnt() > 2) fb.Print("\t\t\to_%s = r_phase%s;\n", pModule->GetClockList()[2]->GetName().c_str(), clkhxName.c_str()+3); fb.Print("\t\t}\n"); fb.Print("\t#endif\n"); fb.Print("\n"); fb.Print("\tSC_CTOR(CFixture) {\n"); fb.Print("\t\tSC_METHOD(Fixture);\n"); fb.Print("\t\tsensitive << i_%s.neg();\n", pModule->GetClockList()[0]->GetName().c_str()); fb.Print("\n"); fb.Print("#ifndef _SC_LINT\n"); fb.Print("\n"); fb.Print("\tpClock = new sc_clock(\"%s\", sc_time(10.0, SC_NS), 0.5, SC_ZERO_TIME, true);\n", pModule->GetClockList()[0]->GetName().c_str()); fb.Print("\n"); fb.Print("\tSC_METHOD(Clock);\n"); fb.Print("\tsensitive << *pClock;\n"); fb.Print("\n"); fb.Print("\t#endif // _SC_LINT\n"); fb.Print("#else // __SYSTEM_C__\n"); fb.Print(
"\tCFixture() {\n"); fb.Print("#endif// __SYSTEM_C__\n"); fb.Print("\n"); fb.Print("\t#ifndef _SC_LINT\n"); fb.Print("\n"); fb.Print("\tCFixtureTest::SetModel(&m_model);\n"); fb.Print("\n"); if (pModule->GetClockListCnt() > 1) { string clkName = pModule->GetClockList()[1]->GetName(); fb.Print("\tr_phase%sCnt = 0;\n", clkName.c_str()+3); } fb.Print("\tr_clkCnt = 0;\n"); fb.Print("\tr_inCnt = 0;\n"); fb.Print("\tr_outCnt = 0;\n"); fb.Print("\tr_testCnt = 0;\n"); fb.Print("\n"); fb.Print("\ttime(&startTime);\n"); fb.Print("\n"); fb.Print("\tInitTest();\n"); fb.Print("\n"); fb.Print("///////////////////////////////////////////\n"); fb.Print("// Fixture specific state initialization\n"); fb.Print("//>>\n"); if (regionCnt > 1) { for (int i = userLinesCnt[0]; i < userLinesCnt[1]; i += 1) fb.Write(userLines[i].c_str()); } fb.Print("//<<\n"); fb.Print("// Fixture specific state initialization\n"); fb.Print("///////////////////////////////////////////\n"); fb.Print("\n"); fb.Print("#endif\n"); fb.Print("}\n"); fb.Print("\n"); fb.Print("#ifndef _SC_LINT\n"); fb.Print("\t// I/O access routines\n"); fb.Print("\tbool ClockFallingEdge() {\n"); fb.Print("\t\t#ifdef __SYSTEM_C__\n"); fb.Print("\t\t\treturn true;\n"); fb.Print("\t\t#else\n"); fb.Print("\t\t\tp_acc_value pAccValue;\n"); fb.Print("\t\t\tchar *pCk = acc_fetch_value(sig.m_ck, \"%%x\", pAccValue);\n"); fb.Print("\t\t\treturn *pCk == '0';\n"); fb.Print("\t\t#endif\n"); fb.Print("\t}\n"); fb.Print("\t\n"); for (identIter.Begin(); !identIter.End(); identIter++) { const string portName = identIter->GetName(); if (identIter->IsOutPort() && !identIter->IsClock()) { int portWidth = identIter->GetWidth(); if (identIter->GetType()->GetType()->IsStruct()) fb.Print("\tvoid SetSig_%s(%s %s) {\n", portName.c_str(), identIter->GetType()->GetType()->GetName().c_str(), portName.c_str()); else fb.Print("\tvoid SetSig_%s(uint64_t %s) {\n", portName.c_str(), portName.c_str()); fb.Print("\t\t#ifdef __SYSTEM_C__\n"); fb.Print("\t\t\to_%s = %s;\n", portName.c_str(), portName.c_str()); fb.Print("\t\t#else\n"); if (portWidth > 32) { fb.Print("\t\t\tSetSigValue(sig.m_%sU, (uint32_t)(%s >> 32));\n", portName.c_str(), portName.c_str()); fb.Print("\t\t\tSetSigValue(sig.m_%sL, (uint32_t)%s);\n", portName.c_str(), portName.c_str()); } else { fb.Print("\t\t\tSetSigValue(sig.m_%s, %s);\n", portName.c_str(), portName.c_str()); } fb.Print("\t\t#endif\n"); fb.Print("\t}\n"); } else if (identIter->IsInPort() && !identIter->IsClock()) { int portWidth = identIter->GetWidth(); fb.Print("\tuint%d_t GetSig_%s() {\n", portWidth <= 32 ? 32 : 64, portName.c_str()); fb.Print("\t\t#ifdef __SYSTEM_C__\n"); if (identIter->GetType()->GetType()->IsStruct()) fb.Print("\t\t\treturn i_%s.read();\n", portName.c_str()); else fb.Print("\t\t\treturn (uint%d_t)i_%s.read();\n", portWidth <= 32 ? 32 : 64, portName.c_str()); fb.Print("\t\t#else\n"); if (portWidth > 32) fb.Print("\t\t\treturn ((uint64_t)GetSigValue(sig.m_%sU, \"%sU\") << 32) | GetSigValue(sig.m_%sL, \"%sL\");\n", portName.c_str(), portName.c_str(), portName.c_str(), portName.c_str()); else fb.Print("\t\t\treturn GetSigValue(sig.m_%s, \"%s\");\n", portName.c_str(), portName.c_str()); fb.Print("\t\t#endif\n"); fb.Print("\t}\n"); } } fb.Print("\n"); fb.Print("\t#ifndef __SYSTEM_C__\n"); fb.Print("\n"); fb.Print("\t\tstruct CHandles {\n"); fb.Print("\t\t\thandle m_ck;\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() || identIter->IsInPort()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); if (portWidth <= 32) fb.Print("\t\t\thandle m_%s;\n", portName.c_str()); else { fb.Print("\t\t\thandle m_%sU;\n", portName.c_str()); fb.Print("\t\t\thandle m_%sL;\n", portName.c_str()); } } } fb.Print("\t\t} sig;\n"); fb.Print("\n"); fb.Print("\t\tvoid SetSigValue(handle sig, uint32_t value) {\n"); fb.Print("\t\t\ts_setval_value value_s;\n"); fb.Print("\t\t\tvalue_s.format = accIntVal;\n"); fb.Print("\t\t\tvalue_s.value.integer = value;\n"); fb.Print("\n"); fb.Print("\t\t\ts_setval_delay delay_s;\n"); fb.Print("\t\t\tdelay_s.model = accNoDelay;\n"); fb.Print("\t\t\tdelay_s.time.type = accTime;\n"); fb.Print("\t\t\tdelay_s.time.low = 0;\n"); fb.Print("\t\t\tdelay_s.time.high = 0;\n"); fb.Print("\n"); fb.Print("\t\t\tacc_set_value(sig, &value_s, &delay_s);\n"); fb.Print("\t\t}\n"); fb.Print("\n"); fb.Print("\t\tuint32_t GetSigValue(handle sig, char *pName) {\n"); fb.Print("\t\t\tp_acc_value pAccValue;\n"); fb.Print("\t\t\tconst char *pNum = acc_fetch_value(sig, \"%%x\", pAccValue);\n"); fb.Print("\t\t\tconst char *pNum2 = pNum;\n"); fb.Print("\n"); fb.Print("\t\t\tuint32_t value = 0;\n"); fb.Print("\t\t\twhile (isdigit(*pNum) || tolower(*pNum) >= 'a' && tolower(*pNum) <= 'f')\n"); fb.Print("\t\t\t\tvalue = value * 16 + (isdigit(*pNum) ? (*pNum++ - '0') : (tolower(*pNum++) - 'a' + 10));\n"); fb.Print("\n"); fb.Print("\t\t\tif (*pNum != '\\0')\n"); fb.Print("\t\t\t\tprintf(\" Signal '%%s' had value '%%s'\\n\", pName, pNum2);\n"); fb.Print("\n"); fb.Print("\t\t\treturn value;\n"); fb.Print("\t\t}\n"); fb.Print("\n"); fb.Print("\t\tvoid InitFixture() {\n"); fb.Print("\t\t\tacc_initialize();\n"); fb.Print("\t\t\tint i = 1;\n"); bool bFoundCk = false; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); if (strcmp(portName.c_str(), "clock") == 0) { if (!bFoundCk) fb.Print("\t\t\tsig.m_ck = acc_handle_tfarg(i++);\n"); bFoundCk = true; } else if (portWidth <= 32) fb.Print("\t\t\tsig.m_%s = acc_handle_tfarg(i++);\n", portName.c_str()); else { fb.Print("\t\t\tsig.m_%sL = acc_handle_tfarg(i++);\n", portName.c_str()); fb.Print("\t\t\tsig.m_%sU = acc_handle_tfarg(i++);\n", portName.c_str()); } } } for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); if (identIter->IsClock()) { if (!bFoundCk) fb.Print("\t\t\tsig.m_ck = acc_handle_tfarg(i++);\n"); bFoundCk = true; } else if (portWidth <= 32) fb.Print("\t\t\tsig.m_%s = acc_handle_tfarg(i++);\n", portName.c_str()); else { fb.Print("\t\t\tsig.m_%sL = acc_handle_tfarg(i++);\n", portName.c_str()); fb.Print("\t\t\tsig.m_%sU = acc_handle_tfarg(i++);\n", portName.c_str()); } } } fb.Print("\t\t\tacc_vcl_add(sig.m_ck, ::Fixture, null, vcl_verilog_logic);\n"); fb.Print("\t\t\tacc_close();\n"); fb.Print("\n"); fb.Print("\t\t\ttime(&startTime);\n"); fb.Print("\n"); fb.Print("\t\t\tInitTest();\n"); fb.Print("\t\t}\n"); fb.Print("\t#endif // __SYSTEM_C__\n"); fb.Print("#endif // _SC_LINT\n"); fb.Print("\n"); fb.Print("};\n"); fb.Close(); } void CHtvDesign::GenFixtureCpp(CHtvIdent *pModule) { string fileName = m_pathName + "Fixture.cpp"; FILE *fp = fopen(fileName.c_str(), "r"); vector<string> userLines; int userLinesBegin[8] = { 0, 0, 0, 0, 0, 0 }; int userLinesEnd[8] = { 0, 0, 0, 0, 0, 0 }; if (fp) { char lineBuf[512]; while (fgets(lineBuf, 512, fp)) { char *pStr = lineBuf; while (pStr[0] == ' ' || pStr[0] == '\t') pStr++; if (strncmp(pStr, "//>>", 4) == 0) { int regionId = pStr[4] - '1'; if (regionId > 7) continue; userLinesBegin[regionId] = userLines.size(); while (fgets(lineBuf, 512, fp)) { char *pStr = lineBuf; while (pStr[0] == ' ' || pStr[0] == '\t') pStr++; if (strncmp(pStr, "//<<", 4) == 0) { userLinesEnd[regionId] = userLines.size(); break; } userLines.push_back(lineBuf); } } } fclose(fp); } CFileBkup fb(m_pathName, "Fixture", "cpp"); fb.PrintHeader("Fixture.cpp: Fixture method file"); fb.Print("#include <Assert.h>\n"); fb.Print("#include <stdint.h>\n"); fb.Print("#include \"Random.h\"\n"); //fb.Print("#include \"%sOpcodes.h\"\n", m_pHierTop->GetName().c_str()); fb.Print("#include \"Fixture.h\"\n"); fb.Print("\n"); fb.Print("CRandom cnyRnd;\n"); fb.Print("CFixtureModel * CFixtureTest::m_pModel;\n"); fb.Print("\n"); fb.Print("#ifndef __SYSTEM_C__\n"); fb.Print("CFixture fixture;\n"); fb.Print("\n"); fb.Print("extern \"C\" int InitFixture() {\n"); fb.Print("\tfixture.InitFixture();\n"); fb.Print("}\n"); fb.Print("\n"); fb.Print("extern \"C\" int Fixture() {\n"); fb.Print("\tfixture.Fixture();\n"); fb.Print("}\n"); fb.Print("#endif\n"); fb.Print("\n"); fb.Print("void\n"); fb.Print("CFixture::Fixture()\n"); fb.Print("{\n"); fb.Print("\tif (!ClockFallingEdge())\n"); fb.Print("\t\treturn;\n"); fb.Print("\n"); fb.Print("\tr_clkCnt += 1;\n"); fb.Print("\n"); fb.Print("\tDelayEarlyOutputs();\n"); fb.Print("\n"); fb.Print("\tif (r_clkCnt <= 32) {\n"); fb.Print("\n"); fb.Print("\t\t// SetSig_reset(r_clkCnt <= 2 ? 1 : 0);\n"); fb.Print("\t\t// SetSig_active(1);\n"); CHtvIdentTblIter identIter(pModule->GetIdentTbl()); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("\t\tSetSig_%s(m_directedTests[0].m_%s);\n", portName.c_str(), portName.c_str()); } } fb.Print("\n"); fb.Print("\t} else {\n"); fb.Print("\t\tif (!m_directedTests[r_inCnt].IsEnd()) {\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("\t\t\tSetSig_%s(m_directedTests[r_inCnt].m_%s);\n", portName.c_str(), portName.c_str()); } } fb.Print("\n"); fb.Print("\t\t\tm_directedTests[r_inCnt].m_clkCnt = r_clkCnt;\n"); fb.Print("\t\t\tm_directedTests[r_inCnt].m_testCnt = r_testCnt++;\n"); fb.Print("\n"); fb.Print("\t\t\tm_testQue.push(m_directedTests[r_inCnt]);\n"); fb.Print("\t\t\tr_inCnt += 1;\n"); fb.Print("\n"); fb.Print("\t\t} else if (r_testCnt != TEST_CNT) {\n"); fb.Print("\n"); fb.Print("\t\t\tCFixtureTest test(r_clkCnt, r_testCnt);\n"); fb.Print("\n"); fb.Print("\t\t\t//>>1\tSet rsltDly to appropriate value for design\n"); if (userLinesBegin[0] == userLinesEnd[0]) { fb.Print("\t\t\t//if (r_testCnt == 847)\n"); fb.Print("\t\t\t//\tbool stop = true;\n"); } else { for (int i = userLinesBegin[0]; i < userLinesEnd[0]; i += 1) fb.Write(userLines[i].c_str()); } fb.Print("\t\t\t//<<\n"); fb.Print("\n"); fb.Print("\t\t\t// Generate random inputs\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); if (identIter->GetType()->GetType()->IsStruct()) fb.Print("\t\t\t%s %s;\n", identIter->GetType()->GetType()->GetName().c_str(), portName.c_str()); else fb.Print("\t\t\tuint%d_t %s;\n", portWidth <= 32 ? 32 : 64, portName.c_str()); } } fb.Print("\n"); fb.Print("\t\t\tGenRandomInputs("); int cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fb.Print((cnt % 8 != 0) ? ", " : ",\n\t\t\t\t\t"); cnt += 1; fb.Print("%s", portName.c_str()); } } fb.Print(");\n"); fb.Print("\n"); fb.Print("\t\t\ttest.Test("); cnt = 0; if (pModule->GetClockListCnt() > 1) { cnt += 1; string clkName = pModule->GetClockList()[1]->GetName(); fb.Print("r_phase%sCnt", clkName.c_str()+3); } for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fb.Print((cnt % 8 != 0) ? ", " : ",\n\t\t\t\t\t"); cnt += 1; fb.Print("%s", portName.c_str()); } } fb.Print(");\n"); fb.Print("\n"); fb.Print("\t\t\tm_testQue.push(test);\n"); fb.Print("\t\t\tr_testCnt += 1;\n"); fb.Print("\n"); fb.Print("\t\t\tif (r_testCnt %% 1000000 == 0) {\n"); fb.Print("\t\t\t\ttime_t endTime;\n"); fb.Print("\t\t\t\ttime(&endTime);\n"); fb.Print("\t\t\t\ttime_t deltaTime = endTime - startTime;\n"); fb.Print("\t\t\t\tprintf(\"%%d (%%d sec)\\n\", (int)r_testCnt, (unsigned)(deltaTime));\n"); fb.Print("\t\t\t\tstartTime = endTime;\n"); fb.Print("\t\t\t}\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("\t\t\tSetSig_%s(test.m_%s);\n", portName.c_str(), portName.c_str()); } } fb.Print("\t\t}\n"); fb.Print("\n"); fb.Print("\t\t//>>2\tSet rsltDly to appropriate value for design\n"); if (userLinesBegin[1] == userLinesEnd[1]) fb.Print("\t\tint rsltDly = 17;\n"); else { for (int i = userLinesBegin[1]; i < userLinesEnd[1]; i += 1) fb.Write(userLines[i].c_str()); } fb.Print("\t\t//<<\n"); fb.Print("\n"); fb.Print("\t\tif (!m_testQue.empty() && m_testQue.front().m_clkCnt == r_clkCnt-rsltDly) {\n"); fb.Print("\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); fb.Print("\t\t\tuint%d_t %s;\n", portWidth <= 32 ? 32 : 64, portName.c_str()); } } fb.Print("\n"); fb.Print("\t\t\tGetOutputs("); cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fb.Print((cnt % 8 != 0) ? ", " : ",\n\t\t\t\t\t"); cnt += 1; fb.Print("%s", portName.c_str()); } } fb.Print(");\n"); fb.Print("\n"); fb.Print("\t\t\t// check random test\n"); fb.Print("\t\t\tCFixtureTest test = m_testQue.front();\n"); fb.Print("\t\t\tm_testQue.pop();\n"); fb.Print("\n"); fb.Print("\t\t\t//>>3\tDesign specific difference reporting qualifications\n"); if (userLinesBegin[2] == userLinesEnd[2]) fb.Print("\t\t\tif (test.m_testCnt > 2 && (\n"); else { for (int i = userLinesBegin[2]; i < userLinesEnd[2]; i += 1) fb.Write(userLines[i].c_str()); } fb.Print("\t\t\t//<<\n\t\t\t\t"); cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fb.Print(" ||\n\t\t\t\t"); cnt += 1; fb.Print("%s != test.m_%s", portName.c_str(), portName.c_str()); } } fb.Print("\n\t\t\t\t)) {\n"); fb.Print("\n"); fb.Print("\t\t\t\tprintf(\"%%lld:\\n\", test.m_testCnt);\n"); fb.Print("\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); fb.Print("\t\t\t\tprintf(\" %-28s = 0x%%0%dllx\\n\", (uint64_t)test.m_%s%s);\n", portName.c_str(), (portWidth+3)/4, portName.c_str(), identIter->GetType()->GetType()->IsStruct() ? ".m_data" : ""); } } fb.Print("\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); fb.Print("\t\t\t\tprintf(\" %-19s Expected = 0x%%0%dllx\\n\", (uint64_t)test.m_%s%s);\n", portName.c_str(), (portWidth+3)/4, portName.c_str(), identIter->GetType()->GetType()->IsStruct() ? ".m_data" : ""); fb.Print("\t\t\t\tif (%s != test.m_%s)\n", portName.c_str(), portName.c_str()); fb.Print("\t\t\t\t\tprintf(\" Actual = 0x%%0%dllx\\n\", (uint64_t)%s%s);\n", (portWidth+3)/4, portName.c_str(), identIter->GetType()->GetType()->IsStruct() ? ".m_data" : ""); fb.Print("\n"); } } fb.Print("\t\t\t\tprintf(\"\\tm_directedTests.push_back(test.Test("); const char *pSeparator = ""; int sepCnt = 4; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); fb.Print("%s0x%%0%dllx%s", pSeparator, (portWidth+3)/4, portWidth > 32 ? "LL" : ""); if (sepCnt == 8) { pSeparator = ", \"\n\t\t\t\t\t\""; sepCnt = 0; } else { pSeparator = ", "; sepCnt += 1; } } } fb.Print("));\\n\","); pSeparator = "\n\t\t\t\t\t"; sepCnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("%s(uint64_t)test.m_%s", pSeparator, portName.c_str()); if (identIter->GetType()->GetType()->IsStruct()) fb.Print(".m_data"); if (sepCnt == 4) { pSeparator = ",\n\t\t\t\t\t"; sepCnt = 0; } else { pSeparator = ", "; sepCnt += 1; } } } fb.Print(");\n"); fb.Print("\n"); fb.Print("\t\t\t\tbool stop = true;\n"); fb.Print("\t\t\t\t//>>4\tSet what to do on error\n");
if (userLinesBegin[3] == userLinesEnd[3]) { fb.Print("\t\t\t\texit(0);\n"); } else { for (int i = userLinesBegin[3]; i < userLinesEnd[3]; i += 1) fb.Write(userLines[i].c_str()); } fb.Print("\t\t\t\t//<<\n"); fb.Print("\t\t\t}\n"); fb.Print("\n"); fb.Print("\t\t} else if (!m_testQue.empty() && m_testQue.front().m_clkCnt <= r_clkCnt-32)\n"); fb.Print("\t\t\tassert(0);\n"); fb.Print("\n"); fb.Print("\t\tif (m_testQue.empty() && r_testCnt == TEST_CNT) {\n"); fb.Print("\t\t\tprintf(\"Tests passed\\n\");\n"); fb.Print("\t\t\texit(0);\n"); fb.Print("\t\t}\n"); fb.Print("\n"); fb.Print("\t}\n"); fb.Print("}\n"); fb.Print("\n"); fb.Print("void\n"); fb.Print("CFixture::GenRandomInputs("); cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fb.Print((cnt % 5 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; if (identIter->GetType()->GetType()->IsStruct()) fb.Print("%s &%s", identIter->GetType()->GetType()->GetName().c_str(), portName.c_str()); else fb.Print("uint%d_t &%s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } fb.Print(")\n"); fb.Print("{\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); int portWidth = identIter->GetWidth(); fb.Print("\t%s%s = cnyRnd.RndUint%d() & 0x%llx%s;\n", portName.c_str(), identIter->GetType()->GetType()->IsStruct() ? ".m_data" : "", portWidth <= 32 ? 32 : 64, ~(~(uint64)0 << portWidth), portWidth > 32 ? "LL" : ""); } } fb.Print("\n"); fb.Print("\t//>>5\tOverride random input generation\n"); for (int i = userLinesBegin[4]; i < userLinesEnd[4]; i += 1) fb.Write(userLines[i].c_str()); fb.Print("\t//<<\n"); fb.Print("}\n"); fb.Print("\n"); fb.Print("void\n"); fb.Print("CFixture::DelayEarlyOutputs()\n"); fb.Print("{\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("\tm_stage_%s = (m_stage_%s << 1) | (GetSig_%s() & 1);\n", portName.c_str(), portName.c_str(), portName.c_str()); } } fb.Print("}\n"); fb.Print("\n"); fb.Print("void\n"); fb.Print("CFixture::GetOutputs("); cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fb.Print((cnt % 5 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; fb.Print("uint%d_t &%s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } fb.Print(")\n"); fb.Print("{\n"); fb.Print("\t//>>6\tGet output values\n"); if (userLinesBegin[5] == userLinesEnd[5]) { for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("\t%s = GetSig_%s();\n", portName.c_str(), portName.c_str()); } } fb.Print("\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fb.Print("\t//%s = (m_stage_%s >> 0) & 1;\n", portName.c_str(), portName.c_str()); } } } else { for (int i = userLinesBegin[5]; i < userLinesEnd[5]; i += 1) fb.Write(userLines[i].c_str()); } fb.Print("\t//<<\n"); fb.Print("}\n"); fb.Print("\n"); fb.Print("void\n"); fb.Print("CFixture::InitTest()\n"); fb.Print("{\n"); fb.Print("\tCFixtureTest test;\n"); fb.Print("\n"); fb.Print("\t//>>7\tDirected tests\n"); if (userLinesBegin[6] == userLinesEnd[6]) { fb.Print("\t//m_directedTests.push_back(test.Test(...));\n"); } else { for (int i = userLinesBegin[6]; i < userLinesEnd[6]; i += 1) fb.Write(userLines[i].c_str()); } fb.Print("\t//<<\n"); fb.Print("\n"); fb.Print("\tm_directedTests.push_back(test.End());\n"); fb.Print("}\n"); fb.Print("\n"); fb.Print("//>>8 Fixture specific methods\n"); for (int i = userLinesBegin[7]; i < userLinesEnd[7]; i += 1) fb.Write(userLines[i].c_str()); fb.Print("//<<\n"); fb.Close(); } void CHtvDesign::GenScCodeFiles(const string &cppFileName) { // ScLint was requested to generate a .v file. The .cpp source file does not exist. // This routine generates a framework .cpp file as a starting point. This routine // will also generate a .h file if one does not exist. // check if .h file exists string hFileName = cppFileName; int periodPos = hFileName.find_last_of("."); if (periodPos > 0) hFileName.erase(periodPos+1); hFileName += "h"; // use file name for module name string baseName = cppFileName; if (periodPos > 0) baseName.erase(periodPos); int slashPos = baseName.find_last_of("\\/"); baseName.erase(0, slashPos+1); FILE *pCppFile; if (!(pCppFile = fopen(cppFileName.c_str(), "w"))) { printf(" Could not open input file '%s' for writing, exiting\n", cppFileName.c_str()); ErrorExit(); } fprintf(pCppFile, "#include <stdint.h>\n"); fprintf(pCppFile, "#include \"%s.h\"\n", baseName.c_str()); fprintf(pCppFile, "//#include \"%sPrims.h\"\n", baseName.c_str()); fprintf(pCppFile, "\n"); if (OpenInputFile(hFileName)) { // .h file exists, parse file and extract info needed to produce framework cpp file do { if (GetNextToken() == tk_SC_CTOR) { GetNextToken(); // '(' if (GetNextToken() == tk_identifier) { const string moduleName = GetString(); do { if (GetNextToken() == tk_SC_METHOD) { GetNextToken(); // '(' if (GetNextToken() == tk_identifier) { const string methodName = GetString(); fprintf(pCppFile, "void\n"); fprintf(pCppFile, "%s::%s()\n", moduleName.c_str(), methodName.c_str()); fprintf(pCppFile, "{\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "#ifndef _SC_LINT\n"); fprintf(pCppFile, "\tsc_time time = sc_time_stamp();\n"); fprintf(pCppFile, "\tif (time == sc_time(3790, SC_NS))\n"); fprintf(pCppFile, "\t\tbool stop = true;\n"); fprintf(pCppFile, "#endif\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "\t//zero = 0;\n"); fprintf(pCppFile, "\t//one = ~zero;\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "\t///////////////////////\n"); fprintf(pCppFile, "\t// Combinatorial logic\n"); fprintf(pCppFile, "\t//\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "\t///////////////////////\n"); fprintf(pCppFile, "\t// Register assignments\n"); fprintf(pCppFile, "\t//\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "\t///////////////////////\n"); fprintf(pCppFile, "\t// Update outputs\n"); fprintf(pCppFile, "\t//\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "#ifndef _SC_LINT\n"); fprintf(pCppFile, "\tif (time == sc_time(190, SC_NS))\n"); fprintf(pCppFile, "\t\tbool stop = true;\n"); fprintf(pCppFile, "#endif\n"); fprintf(pCppFile, "}\n"); } } } while (GetToken() != tk_eof); } } } while (GetToken() != tk_eof); } else { // neither .h or .cpp file exists, create files with default names fprintf(pCppFile, "void\n"); fprintf(pCppFile, "C%s::%s()\n", baseName.c_str(), baseName.c_str()); fprintf(pCppFile, "{\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "#ifndef _SC_LINT\n"); fprintf(pCppFile, "\tint time = (int)sc_simulation_time();\n"); fprintf(pCppFile, "\tif (time == 3790)\n"); fprintf(pCppFile, "\t\tbool stop = true;\n"); fprintf(pCppFile, "#endif\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "\t//zero = 0;\n"); fprintf(pCppFile, "\t//one = ~zero;\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "\t///////////////////////\n"); fprintf(pCppFile, "\t// Combinatorial logic\n"); fprintf(pCppFile, "\t//\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "\t///////////////////////\n"); fprintf(pCppFile, "\t// Register assignments\n"); fprintf(pCppFile, "\t//\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "\t///////////////////////\n"); fprintf(pCppFile, "\t// Update outputs\n"); fprintf(pCppFile, "\t//\n"); fprintf(pCppFile, "\n"); fprintf(pCppFile, "#ifndef _SC_LINT\n"); fprintf(pCppFile, "\tif (time == 190)\n"); fprintf(pCppFile, "\t\tbool stop = true;\n"); fprintf(pCppFile, "#endif\n"); fprintf(pCppFile, "}\n"); FILE *pIncFile; if (!(pIncFile = fopen(hFileName.c_str(), "w"))) { printf(" Could not open input file '%s' for writing, exiting\n", cppFileName.c_str()); ErrorExit(); } fprintf(pIncFile, "#pragma once\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "#include <SystemC.h>\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "#ifndef _SC_LINT\n"); fprintf(pIncFile, "#include \"ScPrims.h\"\n"); fprintf(pIncFile, "#endif\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "//#include \"%sOpcodes.h\"\n", baseName.c_str()); fprintf(pIncFile, "//#include \"%sPrims.h\"\n", baseName.c_str()); fprintf(pIncFile, "\n"); fprintf(pIncFile, "SC_MODULE(C%s) {\n", baseName.c_str()); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\t//sc_uint<64> zero;\n"); fprintf(pIncFile, "\t//sc_uint<64> one;\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\t///////////////////////\n"); fprintf(pIncFile, "\t// Port declarations\n"); fprintf(pIncFile, "\t//\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\t//sc_in<bool>\t\t\ti_clock;\n"); fprintf(pIncFile, "\t//sc_in<sc_uint<32> >\ti_data;\n"); fprintf(pIncFile, "\t//sc_out<sc_uint<32> >\to_rslt;\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\t///////////////////////\n"); fprintf(pIncFile, "\t// State declarations\n"); fprintf(pIncFile, "\t//\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\t// state for first clock\n"); fprintf(pIncFile, "\t// sc_uint<1> r1_vm;\n"); fprintf(pIncFile, "\t// sc_uint<32> r1_data;\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\t// state for second clock\n"); fprintf(pIncFile, "\t// sc_uint<32> r2_rslt;\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\t///////////////////////\n"); fprintf(pIncFile, "\t// Method declarations\n"); fprintf(pIncFile, "\t//\n"); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\tvoid %s();\n", baseName.c_str()); fprintf(pIncFile, "\n"); fprintf(pIncFile, "\tSC_CTOR(C%s) {\n", baseName.c_str()); fprintf(pIncFile, "\t\tSC_METHOD(%s);\n", baseName.c_str()); fprintf(pIncFile, "\t\t//sensitive << i_clock.pos();\n"); fprintf(pIncFile, "\t}\n"); fprintf(pIncFile, "};\n"); fclose(pIncFile); } fclose(pCppFile); OpenInputFile(cppFileName); } void CHtvDesign::GenFixtureModelH(CHtvIdent *pModule) { string fileName = m_pathName + "FixtureModel.h"; FILE *fp; if (fp = fopen(fileName.c_str(), "r")) { fclose(fp); return; } if (!(fp = fopen(fileName.c_str(), "w"))) { printf("Could not open '%s' for writing\n", fileName.c_str()); ErrorExit(); } PrintHeader(fp, "FixtureModel.h: Fixture model include file"); fprintf(fp, "#pragma once\n"); fprintf(fp, "\n"); fprintf(fp, "#include <stdint.h>\n"); fprintf(fp, "\n"); fprintf(fp, "class CFixtureModel\n"); fprintf(fp, "{\n"); fprintf(fp, "public:\n"); fprintf(fp, "\n"); fprintf(fp, "\tCFixtureModel(void)\n"); fprintf(fp, "\t{\n"); fprintf(fp, "\t}\n"); fprintf(fp, "\n"); fprintf(fp, "\t~CFixtureModel(void)\n"); fprintf(fp, "\t{\n"); fprintf(fp, "\t}\n"); fprintf(fp, "\n"); fprintf(fp, "\tvoid Model("); CHtvIdentTblIter identIter(pModule->GetIdentTbl()); int cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fprintf(fp, (cnt % 5 != 0) ? ", " : ",\n\t\t\t"); cnt += 1; fprintf(fp, "uint%d_t %s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fprintf(fp, (cnt % 5 != 0) ? ", " : ",\n\t\t\t"); cnt += 1; fprintf(fp, "uint%d_t &%s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } fprintf(fp, ");\n"); fprintf(fp, "\n"); fprintf(fp, "private:\n"); fprintf(fp, "\n"); fprintf(fp, "};\n"); fclose(fp); } void CHtvDesign::GenFixtureModelCpp(CHtvIdent *pModule) { string fileName = m_pathName + "FixtureModel.cpp"; FILE *fp; if (fp = fopen(fileName.c_str(), "r")) { fclose(fp); return; } if (!(fp = fopen(fileName.c_str(), "w"))) { printf("Could not open '%s' for writing\n", fileName.c_str()); ErrorExit(); } PrintHeader(fp, "FixtureModel.cpp: Fixture model method file"); fprintf(fp, "\n"); fprintf(fp, "#include \"FixtureModel.h\"\n"); fprintf(fp, "\n"); fprintf(fp, "void\n"); fprintf(fp, "CFixtureModel::Model(\n\t\t\t\t"); CHtvIdentTblIter identIter(pModule->GetIdentTbl()); int cnt = 0; for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsOutPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fprintf(fp, (cnt % 5 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; if (identIter->GetType()->GetType()->IsStruct()) fprintf(fp, "%s %s", identIter->GetType()->GetType()->GetName().c_str(), portName.c_str()); else fprintf(fp, "uint%d_t %s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); if (cnt > 0) fprintf(fp, (cnt % 5 != 0) ? ", " : ",\n\t\t\t\t"); cnt += 1; fprintf(fp, "uint%d_t &%s", identIter->GetWidth() <= 32 ? 32 : 64, portName.c_str()); } } fprintf(fp, ")\n"); fprintf(fp, "{\n"); for (identIter.Begin(); !identIter.End(); identIter++) { if (identIter->IsInPort() && !identIter->IsClock()) { const string portName = identIter->GetName(); fprintf(fp, "\t %s = 0;\n", portName.c_str()); } } fprintf(fp, "}\n"); fclose(fp); } void CHtvDesign::GenSandboxVpp(CHtvIdent *pModule) { string fileName = m_pathName + "sandbox.vpp"; FILE *fp; if (!(fp = fopen(fileName.c_str(), "w"))) { printf("Could not open '%s' for writing\n", fileName.c_str()); ErrorExit(); } PrintHeader(fp, "sandbox.vpp: Xilinx sandbox file"); fprintf(fp, "(* keep_hierarchy = \"true\" *)\n"); fprintf(fp, "module sandbox (\n"); fprintf(fp, "input\t\tclk, clkhx, clkqx,\n"); fprintf(fp, "input\t\treset,\n"); fprintf(fp, "input\t[511:0]\tins,\n"); fprintf(fp, "output\t[511:0]\touts\n"); fprintf(fp, ");\n"); fprintf(fp, "\t(* keep = \"true\" *) wire r_reset, phase;\n"); fprintf(fp, "\tDFFS_KEEP (1, rst, clkhx, reset, 1'd0, r_reset);\n"); fprintf(fp, "\tPHASEGEN (1, phs, clkhx, clk, r_reset, phase, noconn);\n"); fprintf(fp, "\n"); fprintf(fp, "\t%s dut (\n", "spfd_mul"); int insCnt = 0; int outsCnt = 0; const char *pSeparator = "\n\t\t"; CHtvIdentTblIter identIter(pModule->GetFlatIdentTbl()); for (identIter.Begin(); !identIter.End(); identIter++) { if (!identIter->IsOutPort() && !identIter->IsInPort()) continue; bool bIsClock = identIter->IsClock(); bool bIsInput = identIter->IsInPort(); int portWidth = identIter->GetWidth(); const string portName = identIter->GetName(); if (bIsClock) { fprintf(fp, "%s.i_%s(clk)", pSeparator, portName.c_str()); } else if (bIsInput) { fprintf(fp, "%s.i_%s(ins[%d:%d])", pSeparator, portName.c_str(), insCnt + portWidth - 1, insCnt); insCnt += portWidth; } else { fprintf(fp, "%s.o_%s(outs[%d:%d])", pSeparator, portName.c_str(), outsCnt + portWidth - 1, outsCnt); outsCnt += portWidth; } pSeparator = ",\n\t\t"; } fprintf(fp, "\n\t);\n\nendmodule\n"); fprintf(fp, "`include ./%s.v\n", "spfd_mul"); fprintf(fp, "`include ./ScPrims.v\n"); fclose(fp); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_divider_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { tensor_divider tensor_divider("TENSOR_ADDER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; tensor_divider.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { tensor_divider.data_a_in[i][j][k](data_a_in[i][j][k]); tensor_divider.data_b_in[i][j][k](data_b_in[i][j][k]); tensor_divider.data_out[i][j][k](data_out[i][j][k]); } } } for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { data_a_in[i][j][k] = i + j + k; data_b_in[i][j][k] = i - j + k; } } } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl; } } } return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_divider_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { tensor_divider tensor_divider("TENSOR_ADDER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; tensor_divider.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { tensor_divider.data_a_in[i][j][k](data_a_in[i][j][k]); tensor_divider.data_b_in[i][j][k](data_b_in[i][j][k]); tensor_divider.data_out[i][j][k](data_out[i][j][k]); } } } for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { data_a_in[i][j][k] = i + j + k; data_b_in[i][j][k] = i - j + k; } } } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl; } } } return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_divider_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { tensor_divider tensor_divider("TENSOR_ADDER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; tensor_divider.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { tensor_divider.data_a_in[i][j][k](data_a_in[i][j][k]); tensor_divider.data_b_in[i][j][k](data_b_in[i][j][k]); tensor_divider.data_out[i][j][k](data_out[i][j][k]); } } } for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { data_a_in[i][j][k] = i + j + k; data_b_in[i][j][k] = i - j + k; } } } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl; } } } return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_divider_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { tensor_divider tensor_divider("TENSOR_ADDER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; tensor_divider.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { tensor_divider.data_a_in[i][j][k](data_a_in[i][j][k]); tensor_divider.data_b_in[i][j][k](data_b_in[i][j][k]); tensor_divider.data_out[i][j][k](data_out[i][j][k]); } } } for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { data_a_in[i][j][k] = i + j + k; data_b_in[i][j][k] = i - j + k; } } } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl; } } } return 0; }
/***************************************************************************** The following code is derived, directly or indirectly, from the SystemC source code Copyright (c) 1996-2014 by all Contributors. All Rights reserved. The contents of this file are subject to the restrictions and limitations set forth in the SystemC Open Source License (the "License"); You may not use this file except in compliance with such restrictions and limitations. You may obtain instructions on how to receive a copy of the License at http://www.accellera.org/. Software distributed by Contributors under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. *****************************************************************************/ /***************************************************************************** pic.cpp -- Programmable Interrupt Unit. Original Author: Martin Wang, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "pic.h" void pic::entry(){ if (ireq0.read() == true) { intreq.write(true); vectno.write(0); } else if (ireq1.read() == true) { intreq.write(true); vectno.write(1); } else if (ireq2.read() == true) { intreq.write(true); vectno.write(2); } else if (ireq3.read() == true) { intreq.write(true); vectno.write(2); } else { } if ((intack_cpu.read() == true) && (cs.read() == true)) { intreq.write(false); } } // EOF
#include <systemc.h> SC_MODULE (events) { sc_in<bool> clock; sc_event e1; sc_event e2; void do_test1() { while (true) { // Wait for posedge of clock wait(); cout << "@" << sc_time_stamp() <<" Starting test"<<endl; // Wait for posedge of clock wait(); cout << "@" << sc_time_stamp() <<" Triggering e1"<<endl; // Trigger event e1 e1.notify(5,SC_NS); // Wait for posedge of clock wait(); // Wait for event e2 wait(e2); cout << "@" << sc_time_stamp() <<" Got Trigger e2"<<endl; // Wait for posedge of clock wait(); cout<<"Terminating Simulation"<<endl; sc_stop(); // sc_stop triggers end of simulation } } void do_test2() { while (true) { // Wait for event e2 wait(e1); cout << "@" << sc_time_stamp() <<" Got Trigger e1"<<endl; // Wait for 3 posedge of clock wait(3); cout << "@" << sc_time_stamp() <<" Triggering e2"<<endl; // Trigger event e2 e2.notify(); } } SC_CTOR(events) { SC_CTHREAD(do_test1,clock.pos()); SC_CTHREAD(do_test2,clock.pos()); } }; int sc_main (int argc, char* argv[]) { sc_clock clock ("my_clock",1,0.5); events object("events"); object.clock (clock); // sc_start(0); // First time called will init schedular sc_start(); // Run the simulation till sc_stop is encountered return 0;// Terminate simulation }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }