1 /*
2  * Copyright (c) 1998-2020 Stephen Williams (steve@icarus.com)
3  * Copyright CERN 2013 / Stephen Williams (steve@icarus.com)
4  *
5  *    This source code is free software; you can redistribute it
6  *    and/or modify it in source code form under the terms of the GNU
7  *    General Public License as published by the Free Software
8  *    Foundation; either version 2 of the License, or (at your option)
9  *    any later version.
10  *
11  *    This program is distributed in the hope that it will be useful,
12  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *    GNU General Public License for more details.
15  *
16  *    You should have received a copy of the GNU General Public License
17  *    along with this program; if not, write to the Free Software
18  *    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  */
20 
21 # include "config.h"
22 
23 # include  "compiler.h"
24 # include  "pform.h"
25 # include  "parse_misc.h"
26 # include  "parse_api.h"
27 # include  "PClass.h"
28 # include  "PEvent.h"
29 # include  "PPackage.h"
30 # include  "PUdp.h"
31 # include  "PGenerate.h"
32 # include  "PModport.h"
33 # include  "PSpec.h"
34 # include  "discipline.h"
35 # include  <list>
36 # include  <map>
37 # include  <cassert>
38 # include  <stack>
39 # include  <typeinfo>
40 # include  <sstream>
41 # include  <cstring>
42 # include  <cstdlib>
43 # include  <cctype>
44 
45 # include  "ivl_assert.h"
46 # include  "ivl_alloc.h"
47 
48 /*
49  * The "// synthesis translate_on/off" meta-comments cause this flag
50  * to be turned off or on. The pform_make_behavior and similar
51  * functions look at this flag and may choose to add implicit ivl
52  * synthesis flags.
53  */
54 static bool pform_mc_translate_flag = true;
pform_mc_translate_on(bool flag)55 void pform_mc_translate_on(bool flag) { pform_mc_translate_flag = flag; }
56 
57 /*
58  * The pform_modules is a map of the modules that have been defined in
59  * the top level. This should not contain nested modules/programs.
60  * pform_primitives is similar, but for UDP primitives.
61  */
62 map<perm_string,Module*> pform_modules;
63 map<perm_string,PUdp*> pform_primitives;
64 
65 /*
66  * The pform_units is a list of the SystemVerilog compilation unit scopes.
67  * The current compilation unit is the last element in the list. All items
68  * declared or defined at the top level (outside any design element) are
69  * added to the current compilation unit scope.
70  */
71 vector<PPackage*> pform_units;
72 
is_compilation_unit(LexicalScope * scope)73 static bool is_compilation_unit(LexicalScope*scope)
74 {
75 	// A compilation unit is the only scope that doesn't have a parent.
76       assert(scope);
77       return scope->parent_scope() == 0;
78 }
79 
get_fileline() const80 std::string vlltype::get_fileline() const
81 {
82       ostringstream buf;
83       buf << (text? text : "") << ":" << first_line;
84       string res = buf.str();
85       return res;
86 
87 }
88 
is_hex_digit_str(const char * str)89 static bool is_hex_digit_str(const char *str)
90 {
91       while (*str) {
92 	    if (!isxdigit(*str)) return false;
93 	    str++;
94       }
95       return true;
96 }
97 
is_dec_digit_str(const char * str)98 static bool is_dec_digit_str(const char *str)
99 {
100       while (*str) {
101 	    if (!isdigit(*str)) return false;
102 	    str++;
103       }
104       return true;
105 }
106 
is_oct_digit_str(const char * str)107 static bool is_oct_digit_str(const char *str)
108 {
109       while (*str) {
110 	    if (*str < '0' || *str > '7') return false;
111 	    str++;
112       }
113       return true;
114 }
115 
is_bin_digit_str(const char * str)116 static bool is_bin_digit_str(const char *str)
117 {
118       while (*str) {
119 	    if (*str != '0' && *str != '1') return false;
120 	    str++;
121       }
122       return true;
123 }
124 
125 /*
126  * Parse configuration file with format <key>=<value>, where key
127  * is the hierarchical name of a valid parameter name, and value
128  * is the value user wants to assign to. The value should be constant.
129  */
parm_to_defparam_list(const string & param)130 void parm_to_defparam_list(const string&param)
131 {
132     char* key;
133     char* value;
134     unsigned off = param.find('=');
135     if (off > param.size()) {
136         key = strdup(param.c_str());
137         value = (char*)malloc(1);
138         *value = '\0';
139 
140     } else {
141         key = strdup(param.substr(0, off).c_str());
142         value = strdup(param.substr(off+1).c_str());
143     }
144 
145     // Resolve hierarchical name for defparam. Remember
146     // to deal with bit select for generate scopes. Bit
147     // select expression should be constant integer.
148     pform_name_t name;
149     char *nkey = key;
150     char *ptr = strchr(key, '.');
151     while (ptr != 0) {
152         *ptr++ = '\0';
153         // Find if bit select is applied, this would be something
154         // like - scope[2].param = 10
155         char *bit_l = strchr(nkey, '[');
156         if (bit_l !=0) {
157             *bit_l++ = '\0';
158             char *bit_r = strchr(bit_l, ']');
159             if (bit_r == 0) {
160                 cerr << "<command line>: error: missing ']' for defparam: " << nkey << endl;
161                 free(key);
162                 free(value);
163                 return;
164             }
165             *bit_r = '\0';
166             int i = 0;
167             while (*(bit_l+i) != '\0')
168                 if (!isdigit(*(bit_l+i++))) {
169                     cerr << "<command line>: error: scope index expression is not constant: " << nkey << endl;
170                     free(key);
171                     free(value);
172                     return;
173                 }
174             name_component_t tmp(lex_strings.make(nkey));
175             index_component_t index;
176             index.sel = index_component_t::SEL_BIT;
177             verinum *seln = new verinum(atoi(bit_l));
178             PENumber *sel = new PENumber(seln);
179             index.msb = sel;
180             index.lsb = sel;
181             tmp.index.push_back(index);
182             name.push_back(tmp);
183         }
184         else    // no bit select
185             name.push_back(name_component_t(lex_strings.make(nkey)));
186 
187         nkey = ptr;
188         ptr = strchr(nkey, '.');
189     }
190     name.push_back(name_component_t(lex_strings.make(nkey)));
191     free(key);
192 
193     // Resolve value to PExpr class. Should support all kind of constant
194     // format including based number, dec number, real number and string.
195 
196     // Is it a string?
197     if (*value == '"') {
198 	char *buf = strdup (value);
199 	char *buf_ptr = buf+1;
200 	// Parse until another '"' or '\0'
201 	while (*buf_ptr != '"' && *buf_ptr != '\0') {
202 	    buf_ptr++;
203 	    // Check for escape, especially '\"', which does not mean the
204 	    // end of string.
205 	    if (*buf_ptr == '\\' && *(buf_ptr+1) != '\0')
206 		buf_ptr += 2;
207 	}
208 	if (*buf_ptr == '\0')	// String end without '"'
209 	    cerr << "<command line>: error: missing close quote of string for defparam: " << name << endl;
210 	else if (*(buf_ptr+1) != 0) { // '"' appears within string with no escape
211 	    cerr << buf_ptr << endl;
212 	    cerr << "<command line>: error: \'\"\' appears within string value for defparam: " << name
213 		 << ". Ignore characters after \'\"\'" << endl;
214 	}
215 
216 	*buf_ptr = '\0';
217 	buf_ptr = buf+1;
218 	// Remember to use 'new' to allocate string for PEString
219 	// because 'delete' is used by its destructor.
220 	char *nchar = strcpy(new char [strlen(buf_ptr)+1], buf_ptr);
221 	PExpr* ndec = new PEString(nchar);
222 	Module::user_defparms.push_back( make_pair(name, ndec) );
223 	free(buf);
224 	free(value);
225 	return;
226     }
227 
228     // Is it a based number?
229     char *num = strchr(value, '\'');
230     if (num != 0) {
231 	verinum *val;
232 	const char *base = num + 1;
233 	if (*base == 's' || *base == 'S')
234 	    base++;
235 	switch (*base) {
236 	  case 'h':
237 	  case 'H':
238 	    if (is_hex_digit_str(base+1)) {
239 		val = make_unsized_hex(num);
240 	    } else {
241 		cerr << "<command line>: error: invalid digit in hex value specified for defparam: " << name << endl;
242 		free(value);
243 		return;
244 	    }
245 	    break;
246 	  case 'd':
247 	  case 'D':
248 	    if (is_dec_digit_str(base+1)) {
249 		val = make_unsized_dec(num);
250 	    } else {
251 		cerr << "<command line>: error: invalid digit in decimal value specified for defparam: " << name << endl;
252 		free(value);
253 		return;
254 	    }
255 	    break;
256 	  case 'o':
257 	  case 'O':
258 	    if (is_oct_digit_str(base+1)) {
259 		val = make_unsized_octal(num);
260 	    } else {
261 		cerr << "<command line>: error: invalid digit in octal value specified for defparam: " << name << endl;
262 		free(value);
263 		return;
264 	    }
265 	    break;
266 	  case 'b':
267 	  case 'B':
268 	    if (is_bin_digit_str(base+1)) {
269 		val = make_unsized_binary(num);
270 	    } else {
271 		cerr << "<command line>: error: invalid digit in binary value specified for defparam: " << name << endl;
272 		free(value);
273 		return;
274 	    }
275 	    break;
276 	  default:
277 	    cerr << "<command line>: error: invalid numeric base specified for defparam: " << name << endl;
278 	    free(value);
279 	    return;
280 	}
281 	if (num != value) {  // based number with size
282 	    *num = 0;
283 	    if (is_dec_digit_str(value)) {
284 		verinum *siz = make_unsized_dec(value);
285 		val = pform_verinum_with_size(siz, val, "<command line>", 0);
286 	    } else {
287 		cerr << "<command line>: error: invalid size for value specified for defparam: " << name << endl;
288 		free(value);
289 		return;
290 	    }
291 	}
292 	PExpr* ndec = new PENumber(val);
293 	Module::user_defparms.push_back( make_pair(name, ndec) );
294 	free(value);
295 	return;
296     }
297 
298     // Is it a decimal number?
299     num = (value[0] == '-') ? value + 1 : value;
300     if (is_dec_digit_str(num)) {
301 	verinum *val = make_unsized_dec(num);
302 	if (value[0] == '-') *val = -(*val);
303 	PExpr* ndec = new PENumber(val);
304 	Module::user_defparms.push_back( make_pair(name, ndec) );
305 	free(value);
306 	return;
307     }
308 
309     // Is it a real number?
310     char *end = 0;
311     double rval = strtod(value, &end);
312     if (end != value && *end == 0) {
313 	verireal *val = new verireal(rval);
314 	PExpr* nreal = new PEFNumber(val);
315 	Module::user_defparms.push_back( make_pair(name, nreal) );
316 	free(value);
317 	return;
318     }
319 
320     // None of the above.
321     cerr << "<command line>: error: invalid value specified for defparam: " << name << endl;
322     free(value);
323 }
324 
325 /*
326  * The lexor accesses the vl_* variables.
327  */
328 string vl_file = "";
329 
330 extern int VLparse();
331 
332   /* This tracks the current module being processed. There can only be
333      exactly one module currently being parsed, since Verilog does not
334      allow nested module definitions. */
335 static list<Module*>pform_cur_module;
336 
337 bool pform_library_flag = false;
338 
339 /*
340  * Give each unnamed block that has a variable declaration a unique name.
341  */
342 static unsigned scope_unnamed_block_with_decl = 1;
343 
344   /* increment this for generate schemes within a module, and set it
345      to zero when a new module starts. */
346 static unsigned scope_generate_counter = 1;
347 
348   /* This tracks the current generate scheme being processed. This is
349      always within a module. */
350 static PGenerate*pform_cur_generate = 0;
351 
352   /* Blocks within the same conditional generate construct may have
353      the same name. Here we collect the set of names used in each
354      construct, so they can be added to the local scope without
355      conflicting with each other. Generate constructs may nest, so
356      we need a stack. */
357 static list<set<perm_string> > conditional_block_names;
358 
359   /* This tracks the current modport list being processed. This is
360      always within an interface. */
361 static PModport*pform_cur_modport = 0;
362 
363 static NetNet::Type pform_default_nettype = NetNet::WIRE;
364 
365 /*
366  * These variables track the time scale set by the most recent `timescale
367  * directive. Time scales set by SystemVerilog timeunit and timeprecision
368  * declarations are stored directly in the current lexical scope.
369  */
370 static int pform_time_unit;
371 static int pform_time_prec;
372 
373 /*
374  * These variables track where the most recent `timescale directive
375  * occurred. This allows us to warn about time scales that are inherited
376  * from another file.
377  */
378 static char*pform_timescale_file = 0;
379 static unsigned pform_timescale_line;
380 
381 /*
382  * These variables track whether we can accept new timeunits declarations.
383  */
384 bool allow_timeunit_decl = true;
385 bool allow_timeprec_decl = true;
386 
FILE_NAME(LineInfo * obj,const char * file,unsigned lineno)387 static inline void FILE_NAME(LineInfo*obj, const char*file, unsigned lineno)
388 {
389       obj->set_lineno(lineno);
390       obj->set_file(filename_strings.make(file));
391 }
392 
393 /*
394  * The lexical_scope keeps track of the current lexical scope that is
395  * being parsed. The lexical scope may stack, so the current scope may
396  * have a parent, that is restored when the current scope ends.
397  *
398  * Items that have scoped names are put in the lexical_scope object.
399  */
400 static LexicalScope* lexical_scope = 0;
401 
pform_peek_scope(void)402 LexicalScope* pform_peek_scope(void)
403 {
404       assert(lexical_scope);
405       return lexical_scope;
406 }
407 
pform_pop_scope()408 void pform_pop_scope()
409 {
410       LexicalScope*scope = lexical_scope;
411       assert(scope);
412 
413       map<perm_string,PPackage*>::const_iterator cur;
414       for (cur = scope->possible_imports.begin(); cur != scope->possible_imports.end(); ++cur) {
415             if (scope->local_symbols.find(cur->first) == scope->local_symbols.end())
416                   scope->explicit_imports[cur->first] = cur->second;
417       }
418       scope->possible_imports.clear();
419 
420       lexical_scope = scope->parent_scope();
421       assert(lexical_scope);
422 }
423 
find_lifetime(LexicalScope::lifetime_t lifetime)424 static LexicalScope::lifetime_t find_lifetime(LexicalScope::lifetime_t lifetime)
425 {
426       if (lifetime != LexicalScope::INHERITED)
427 	    return lifetime;
428 
429       return lexical_scope->default_lifetime;
430 }
431 
find_nearest_scopex(LexicalScope * scope)432 static PScopeExtra* find_nearest_scopex(LexicalScope*scope)
433 {
434       PScopeExtra*scopex = dynamic_cast<PScopeExtra*> (scope);
435       while (scope && !scopex) {
436 	    scope = scope->parent_scope();
437 	    scopex = dynamic_cast<PScopeExtra*> (scope);
438       }
439       return scopex;
440 }
441 
add_local_symbol(LexicalScope * scope,perm_string name,PNamedItem * item)442 static void add_local_symbol(LexicalScope*scope, perm_string name, PNamedItem*item)
443 {
444       assert(scope);
445 
446 	// Check for conflict with another local symbol.
447       map<perm_string,PNamedItem*>::const_iterator cur_sym
448 	    = scope->local_symbols.find(name);
449       if (cur_sym != scope->local_symbols.end()) {
450 	    cerr << item->get_fileline() << ": error: "
451 		    "'" << name << "' has already been declared "
452 		    "in this scope." << endl;
453 	    cerr << cur_sym->second->get_fileline() << ":      : "
454 		    "It was declared here as "
455 		 << cur_sym->second->symbol_type() << "." << endl;
456 	    error_count += 1;
457 	    return;
458       }
459 
460 	// Check for conflict with an explicit import.
461       map<perm_string,PPackage*>::const_iterator cur_pkg
462 	    = scope->explicit_imports.find(name);
463       if (cur_pkg != scope->explicit_imports.end()) {
464 	    cerr << item->get_fileline() << ": error: "
465 		    "'" << name << "' has already been "
466 		    "imported into this scope from package '"
467 		 << cur_pkg->second->pscope_name() << "'." << endl;
468 	    error_count += 1;
469 	    return;
470       }
471 
472       scope->local_symbols[name] = item;
473 }
474 
find_potential_import(const struct vlltype & loc,LexicalScope * scope,perm_string name,bool tf_call,bool make_explicit)475 static PPackage*find_potential_import(const struct vlltype&loc, LexicalScope*scope,
476 				      perm_string name, bool tf_call, bool make_explicit)
477 {
478       assert(scope);
479 
480       PPackage*found_pkg = 0;
481       for (set<PPackage*>::const_iterator cur_pkg = scope->potential_imports.begin();
482 	      cur_pkg != scope->potential_imports.end(); ++cur_pkg) {
483 	    PPackage*search_pkg = *cur_pkg;
484 	    map<perm_string,PNamedItem*>::const_iterator cur_sym
485 		= search_pkg->local_symbols.find(name);
486 	    if (cur_sym != search_pkg->local_symbols.end()) {
487 		  if (found_pkg && make_explicit) {
488 			cerr << loc.get_fileline() << ": error: "
489 				"Ambiguous use of '" << name << "'. "
490 				"It is exported by both '"
491 			      << found_pkg->pscope_name()
492 			      << "' and by '"
493 			      << search_pkg->pscope_name()
494 			      << "'." << endl;
495 			error_count += 1;
496 		  } else {
497 			found_pkg = search_pkg;
498 			if (make_explicit) {
499                               if (tf_call)
500 			            scope->possible_imports[name] = found_pkg;
501                               else
502 			            scope->explicit_imports[name] = found_pkg;
503                         }
504 		  }
505 	    }
506       }
507       return found_pkg;
508 }
509 
check_potential_imports(const struct vlltype & loc,perm_string name,bool tf_call)510 static void check_potential_imports(const struct vlltype&loc, perm_string name, bool tf_call)
511 {
512       LexicalScope*scope = lexical_scope;
513       while (scope) {
514 	    if (scope->local_symbols.find(name) != scope->local_symbols.end())
515 		  return;
516 	    if (scope->explicit_imports.find(name) != scope->explicit_imports.end())
517 		  return;
518 	    if (find_potential_import(loc, scope, name, tf_call, true))
519 		  return;
520 
521 	    scope = scope->parent_scope();
522       }
523 }
524 
525 /*
526  * Set the local time unit/precision. This version is used for setting
527  * the time scale for design elements (modules, packages, etc.) and is
528  * called after any initial timeunit and timeprecision declarations
529  * have been parsed.
530  */
pform_set_scope_timescale(const struct vlltype & loc)531 void pform_set_scope_timescale(const struct vlltype&loc)
532 {
533       PScopeExtra*scope = dynamic_cast<PScopeExtra*>(lexical_scope);
534       assert(scope);
535 
536       PScopeExtra*parent = find_nearest_scopex(scope->parent_scope());
537 
538       bool used_global_timescale = false;
539       if (scope->time_unit_is_default) {
540             if (is_compilation_unit(scope)) {
541                   scope->time_unit = def_ts_units;
542             } else if (!is_compilation_unit(parent)) {
543                   scope->time_unit = parent->time_unit;
544                   scope->time_unit_is_default = parent->time_unit_is_default;
545             } else if (pform_timescale_file != 0) {
546                   scope->time_unit = pform_time_unit;
547                   scope->time_unit_is_default = false;
548                   used_global_timescale = true;
549             } else /* parent is compilation unit */ {
550                   scope->time_unit = parent->time_unit;
551                   scope->time_unit_is_default = parent->time_unit_is_default;
552             }
553       }
554       if (scope->time_prec_is_default) {
555             if (is_compilation_unit(scope)) {
556                   scope->time_precision = def_ts_prec;
557             } else if (!is_compilation_unit(parent)) {
558                   scope->time_precision = parent->time_precision;
559                   scope->time_prec_is_default = parent->time_prec_is_default;
560             } else if (pform_timescale_file != 0) {
561                   scope->time_precision = pform_time_prec;
562                   scope->time_prec_is_default = false;
563                   used_global_timescale = true;
564             } else {
565                   scope->time_precision = parent->time_precision;
566                   scope->time_prec_is_default = parent->time_prec_is_default;
567             }
568       }
569 
570       if (gn_system_verilog() && (scope->time_unit < scope->time_precision)) {
571 	    if (scope->time_unit_is_local || scope->time_prec_is_local) {
572 		  VLerror("error: a timeprecision is missing or is too large!");
573 	    }
574       } else {
575             assert(scope->time_unit >= scope->time_precision);
576       }
577 
578       if (warn_timescale && used_global_timescale
579 	  && (strcmp(pform_timescale_file, loc.text) != 0)) {
580 
581 	    cerr << loc.get_fileline() << ": warning: "
582 		 << "timescale for " << scope->pscope_name()
583 		 << " inherited from another file." << endl;
584 	    cerr << pform_timescale_file << ":" << pform_timescale_line
585 		 << ": ...: The inherited timescale is here." << endl;
586       }
587 
588       allow_timeunit_decl = false;
589       allow_timeprec_decl = false;
590 }
591 
592 /*
593  * Set the local time unit/precision. This version is used for setting
594  * the time scale for subsidiary items (classes, subroutines, etc.),
595  * which simply inherit their time scale from their parent scope.
596  */
pform_set_scope_timescale(PScope * scope,const PScope * parent)597 static void pform_set_scope_timescale(PScope*scope, const PScope*parent)
598 {
599       scope->time_unit            = parent->time_unit;
600       scope->time_precision       = parent->time_precision;
601       scope->time_unit_is_default = parent->time_unit_is_default;
602       scope->time_prec_is_default = parent->time_prec_is_default;
603 }
604 
pform_push_class_scope(const struct vlltype & loc,perm_string name,LexicalScope::lifetime_t lifetime)605 PClass* pform_push_class_scope(const struct vlltype&loc, perm_string name,
606 			       LexicalScope::lifetime_t lifetime)
607 {
608       PClass*class_scope = new PClass(name, lexical_scope);
609       class_scope->default_lifetime = find_lifetime(lifetime);
610       FILE_NAME(class_scope, loc);
611 
612       PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
613       assert(scopex);
614       assert(!pform_cur_generate);
615 
616       pform_set_scope_timescale(class_scope, scopex);
617 
618       scopex->classes[name] = class_scope;
619       scopex->classes_lexical .push_back(class_scope);
620 
621       lexical_scope = class_scope;
622       return class_scope;
623 }
624 
pform_push_package_scope(const struct vlltype & loc,perm_string name,LexicalScope::lifetime_t lifetime)625 PPackage* pform_push_package_scope(const struct vlltype&loc, perm_string name,
626 				   LexicalScope::lifetime_t lifetime)
627 {
628       PPackage*pkg_scope = new PPackage(name, lexical_scope);
629       pkg_scope->default_lifetime = find_lifetime(lifetime);
630       FILE_NAME(pkg_scope, loc);
631 
632       allow_timeunit_decl = true;
633       allow_timeprec_decl = true;
634 
635       lexical_scope = pkg_scope;
636       return pkg_scope;
637 }
638 
pform_push_task_scope(const struct vlltype & loc,char * name,LexicalScope::lifetime_t lifetime)639 PTask* pform_push_task_scope(const struct vlltype&loc, char*name,
640 			     LexicalScope::lifetime_t lifetime)
641 {
642       perm_string task_name = lex_strings.make(name);
643 
644       LexicalScope::lifetime_t default_lifetime = find_lifetime(lifetime);
645       bool is_auto = default_lifetime == LexicalScope::AUTOMATIC;
646 
647       PTask*task = new PTask(task_name, lexical_scope, is_auto);
648       task->default_lifetime = default_lifetime;
649       FILE_NAME(task, loc);
650 
651       PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
652       assert(scopex);
653       if (is_compilation_unit(scopex) && !gn_system_verilog()) {
654 	    cerr << task->get_fileline() << ": error: task declarations "
655 		  "must be contained within a module." << endl;
656 	    error_count += 1;
657       }
658 
659       pform_set_scope_timescale(task, scopex);
660 
661       if (pform_cur_generate) {
662 	    add_local_symbol(pform_cur_generate, task_name, task);
663 	    pform_cur_generate->tasks[task_name] = task;
664       } else {
665 	    add_local_symbol(scopex, task_name, task);
666 	    scopex->tasks[task_name] = task;
667       }
668 
669       lexical_scope = task;
670 
671       return task;
672 }
673 
pform_push_function_scope(const struct vlltype & loc,const char * name,LexicalScope::lifetime_t lifetime)674 PFunction* pform_push_function_scope(const struct vlltype&loc, const char*name,
675                                      LexicalScope::lifetime_t lifetime)
676 {
677       perm_string func_name = lex_strings.make(name);
678 
679       LexicalScope::lifetime_t default_lifetime = find_lifetime(lifetime);
680       bool is_auto = default_lifetime == LexicalScope::AUTOMATIC;
681 
682       PFunction*func = new PFunction(func_name, lexical_scope, is_auto);
683       func->default_lifetime = default_lifetime;
684       FILE_NAME(func, loc);
685 
686       PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
687       assert(scopex);
688       if (is_compilation_unit(scopex) && !gn_system_verilog()) {
689 	    cerr << func->get_fileline() << ": error: function declarations "
690 		  "must be contained within a module." << endl;
691 	    error_count += 1;
692       }
693 
694       pform_set_scope_timescale(func, scopex);
695 
696       if (pform_cur_generate) {
697 	    add_local_symbol(pform_cur_generate, func_name, func);
698 	    pform_cur_generate->funcs[func_name] = func;
699 
700       } else {
701 	    add_local_symbol(scopex, func_name, func);
702 	    scopex->funcs[func_name] = func;
703       }
704 
705       lexical_scope = func;
706 
707       return func;
708 }
709 
pform_push_block_scope(const struct vlltype & loc,char * name,PBlock::BL_TYPE bt)710 PBlock* pform_push_block_scope(const struct vlltype&loc, char*name,
711 			       PBlock::BL_TYPE bt)
712 {
713       perm_string block_name;
714       if (name) block_name = lex_strings.make(name);
715       else {
716 	      // Create a unique name for this unnamed block.
717 	    char tmp[32];
718 	    snprintf(tmp, sizeof tmp, "$unm_blk_%u",
719 	             scope_unnamed_block_with_decl);
720 	    block_name = lex_strings.make(tmp);
721 	    scope_unnamed_block_with_decl += 1;
722       }
723 
724       PBlock*block = new PBlock(block_name, lexical_scope, bt);
725       FILE_NAME(block, loc);
726       block->default_lifetime = find_lifetime(LexicalScope::INHERITED);
727       if (name) add_local_symbol(lexical_scope, block_name, block);
728       lexical_scope = block;
729 
730       return block;
731 }
732 
733 /*
734  * Create a new identifier.
735  */
pform_new_ident(const struct vlltype & loc,const pform_name_t & name)736 PEIdent* pform_new_ident(const struct vlltype&loc, const pform_name_t&name)
737 {
738       if (gn_system_verilog())
739 	    check_potential_imports(loc, name.front().name, false);
740 
741       return new PEIdent(name);
742 }
743 
pform_new_trigger(const struct vlltype & loc,PPackage * pkg,const pform_name_t & name)744 PTrigger* pform_new_trigger(const struct vlltype&loc, PPackage*pkg,
745 			    const pform_name_t&name)
746 {
747       if (gn_system_verilog())
748 	    check_potential_imports(loc, name.front().name, false);
749 
750       PTrigger*tmp = new PTrigger(pkg, name);
751       FILE_NAME(tmp, loc);
752       return tmp;
753 }
754 
pform_parent_generate(void)755 PGenerate* pform_parent_generate(void)
756 {
757       return pform_cur_generate;
758 }
759 
pform_bind_attributes(map<perm_string,PExpr * > & attributes,list<named_pexpr_t> * attr,bool keep_attrs)760 void pform_bind_attributes(map<perm_string,PExpr*>&attributes,
761 			   list<named_pexpr_t>*attr, bool keep_attrs)
762 {
763       if (attr == 0)
764 	    return;
765 
766       while (! attr->empty()) {
767 	    named_pexpr_t tmp = attr->front();
768 	    attr->pop_front();
769 	    attributes[tmp.name] = tmp.parm;
770       }
771       if (!keep_attrs)
772 	    delete attr;
773 }
774 
pform_in_program_block()775 bool pform_in_program_block()
776 {
777       if (pform_cur_module.empty())
778 	    return false;
779       if (pform_cur_module.front()->program_block)
780 	    return true;
781       return false;
782 }
783 
pform_in_interface()784 bool pform_in_interface()
785 {
786       if (pform_cur_module.empty())
787 	    return false;
788       if (pform_cur_module.front()->is_interface)
789 	    return true;
790       return false;
791 }
792 
pform_at_module_level()793 static bool pform_at_module_level()
794 {
795       return (lexical_scope == pform_cur_module.front())
796           || (lexical_scope == pform_cur_generate);
797 }
798 
pform_get_wire_in_scope(perm_string name)799 PWire*pform_get_wire_in_scope(perm_string name)
800 {
801       return lexical_scope->wires_find(name);
802 }
803 
pform_put_wire_in_scope(perm_string name,PWire * net)804 static void pform_put_wire_in_scope(perm_string name, PWire*net)
805 {
806       add_local_symbol(lexical_scope, name, net);
807       lexical_scope->wires[name] = net;
808 }
809 
pform_put_enum_type_in_scope(enum_type_t * enum_set)810 static void pform_put_enum_type_in_scope(enum_type_t*enum_set)
811 {
812       if (lexical_scope->enum_sets.count(enum_set))
813             return;
814 
815       set<perm_string> enum_names;
816       list<named_pexpr_t>::const_iterator cur;
817       for (cur = enum_set->names->begin(); cur != enum_set->names->end(); ++cur) {
818 	    if (enum_names.count(cur->name)) {
819 		  cerr << enum_set->get_fileline() << ": error: "
820 			  "Duplicate enumeration name '"
821 		       << cur->name << "'." << endl;
822 		  error_count += 1;
823 	    } else {
824 		  add_local_symbol(lexical_scope, cur->name, enum_set);
825 		  enum_names.insert(cur->name);
826 	    }
827       }
828 
829       lexical_scope->enum_sets.insert(enum_set);
830 }
831 
pform_get_make_wire_in_scope(const struct vlltype &,perm_string name,NetNet::Type net_type,NetNet::PortType port_type,ivl_variable_type_t vt_type)832 PWire*pform_get_make_wire_in_scope(const struct vlltype&, perm_string name,
833                                    NetNet::Type net_type, NetNet::PortType port_type,
834                                    ivl_variable_type_t vt_type)
835 {
836       PWire*cur = pform_get_wire_in_scope(name);
837 
838 	// If the wire already exists and is fully defined, this
839 	// must be a redeclaration. Start again with a new wire.
840 	// The error will be reported when we add the new wire
841 	// to the scope. Do not delete the old wire - it will
842 	// remain in the local symbol map.
843       if (cur && cur->get_data_type() != IVL_VT_NO_TYPE)
844             cur = 0;
845 
846       if (cur == 0) {
847 	    cur = new PWire(name, net_type, port_type, vt_type);
848 	    pform_put_wire_in_scope(name, cur);
849       } else {
850 	    bool rc = cur->set_wire_type(net_type);
851 	    assert(rc);
852 	    rc = cur->set_data_type(vt_type);
853 	    assert(rc);
854       }
855 
856       return cur;
857 }
858 
pform_set_typedef(perm_string name,data_type_t * data_type,std::list<pform_range_t> * unp_ranges)859 void pform_set_typedef(perm_string name, data_type_t*data_type, std::list<pform_range_t>*unp_ranges)
860 {
861       if(unp_ranges)
862 	    data_type = new uarray_type_t(data_type, unp_ranges);
863 
864       add_local_symbol(lexical_scope, name, data_type);
865 
866       data_type_t*&ref = lexical_scope->typedefs[name];
867 
868       ivl_assert(*data_type, ref == 0);
869       ref = data_type;
870       ref->name = name;
871 
872       if (enum_type_t*enum_type = dynamic_cast<enum_type_t*>(data_type))
873 	    pform_put_enum_type_in_scope(enum_type);
874 }
875 
pform_set_type_referenced(const struct vlltype & loc,const char * name)876 void pform_set_type_referenced(const struct vlltype&loc, const char*name)
877 {
878       perm_string lex_name = lex_strings.make(name);
879       check_potential_imports(loc, lex_name, false);
880 }
881 
pform_test_type_identifier(const struct vlltype & loc,const char * txt)882 data_type_t* pform_test_type_identifier(const struct vlltype&loc, const char*txt)
883 {
884       perm_string name = lex_strings.make(txt);
885 
886       LexicalScope*cur_scope = lexical_scope;
887       do {
888 	    map<perm_string,data_type_t*>::iterator cur;
889 
890 	      // First look to see if this identifier is imported from
891 	      // a package. If it is, see if it is a type in that
892 	      // package. If it is, then great. If imported as
893 	      // something other than a type, then give up now because
894 	      // the name has at least shadowed any other possible
895 	      // meaning for this name.
896 	    map<perm_string,PPackage*>::iterator cur_pkg;
897 	    cur_pkg = cur_scope->explicit_imports.find(name);
898 	    if (cur_pkg != cur_scope->explicit_imports.end()) {
899 		  PPackage*pkg = cur_pkg->second;
900 		  cur = pkg->typedefs.find(name);
901 		  if (cur != pkg->typedefs.end())
902 			return cur->second;
903 
904 		    // Not a type. Give up.
905 		  return 0;
906 	    }
907 
908 	    cur = cur_scope->typedefs.find(name);
909 	    if (cur != cur_scope->typedefs.end())
910 		  return cur->second;
911 
912             PPackage*pkg = find_potential_import(loc, cur_scope, name, false, false);
913             if (pkg) {
914 	          cur = pkg->typedefs.find(name);
915 	          if (cur != pkg->typedefs.end())
916 		        return cur->second;
917 
918 		    // Not a type. Give up.
919 		  return 0;
920             }
921 
922 	    cur_scope = cur_scope->parent_scope();
923       } while (cur_scope);
924 
925       return 0;
926 }
927 
928 /*
929  * The parser uses this function to test if the name is a typedef in
930  * the current scope. We use this to know if we can override the
931  * definition because it shadows a containing scope.
932  */
pform_test_type_identifier_local(perm_string name)933 bool pform_test_type_identifier_local(perm_string name)
934 {
935       LexicalScope*cur_scope = lexical_scope;
936 
937       map<perm_string,data_type_t*>::iterator cur;
938 
939       cur = cur_scope->typedefs.find(name);
940       if (cur != cur_scope->typedefs.end())
941 	    return true;
942 
943       return false;
944 }
945 
pform_make_call_function(const struct vlltype & loc,const pform_name_t & name,const list<PExpr * > & parms)946 PECallFunction* pform_make_call_function(const struct vlltype&loc,
947 					 const pform_name_t&name,
948 					 const list<PExpr*>&parms)
949 {
950       if (gn_system_verilog())
951 	    check_potential_imports(loc, name.front().name, true);
952 
953       PECallFunction*tmp = new PECallFunction(name, parms);
954       FILE_NAME(tmp, loc);
955       return tmp;
956 }
957 
pform_make_call_task(const struct vlltype & loc,const pform_name_t & name,const list<PExpr * > & parms)958 PCallTask* pform_make_call_task(const struct vlltype&loc,
959 				const pform_name_t&name,
960 				const list<PExpr*>&parms)
961 {
962       if (gn_system_verilog())
963 	    check_potential_imports(loc, name.front().name, true);
964 
965       PCallTask*tmp = new PCallTask(name, parms);
966       FILE_NAME(tmp, loc);
967       return tmp;
968 }
969 
pform_make_foreach_declarations(const struct vlltype & loc,std::list<perm_string> * loop_vars)970 void pform_make_foreach_declarations(const struct vlltype&loc,
971 				     std::list<perm_string>*loop_vars)
972 {
973       static const struct str_pair_t str = { IVL_DR_STRONG, IVL_DR_STRONG };
974 
975       list<decl_assignment_t*>assign_list;
976       for (list<perm_string>::const_iterator cur = loop_vars->begin()
977 		 ; cur != loop_vars->end() ; ++ cur) {
978 	    decl_assignment_t*tmp_assign = new decl_assignment_t;
979 	    tmp_assign->name = lex_strings.make(*cur);
980 	    assign_list.push_back(tmp_assign);
981       }
982 
983       pform_makewire(loc, 0, str, &assign_list, NetNet::REG, &size_type);
984 }
985 
pform_make_foreach(const struct vlltype & loc,char * name,list<perm_string> * loop_vars,Statement * stmt)986 PForeach* pform_make_foreach(const struct vlltype&loc,
987 			     char*name,
988 			     list<perm_string>*loop_vars,
989 			     Statement*stmt)
990 {
991       perm_string use_name = lex_strings.make(name);
992       delete[]name;
993 
994       if (loop_vars==0 || loop_vars->empty()) {
995 	    cerr << loc.get_fileline() << ": error: "
996 		 << "No loop variables at all in foreach index." << endl;
997 	    error_count += 1;
998       }
999 
1000       ivl_assert(loc, loop_vars);
1001       PForeach*fe = new PForeach(use_name, *loop_vars, stmt);
1002       FILE_NAME(fe, loc);
1003 
1004       delete loop_vars;
1005 
1006       return fe;
1007 }
1008 
pform_put_behavior_in_scope(PProcess * pp)1009 static void pform_put_behavior_in_scope(PProcess*pp)
1010 {
1011       lexical_scope->behaviors.push_back(pp);
1012 }
1013 
pform_put_behavior_in_scope(AProcess * pp)1014 void pform_put_behavior_in_scope(AProcess*pp)
1015 {
1016       lexical_scope->analog_behaviors.push_back(pp);
1017 }
1018 
pform_set_default_nettype(NetNet::Type type,const char * file,unsigned lineno)1019 void pform_set_default_nettype(NetNet::Type type,
1020 			       const char*file, unsigned lineno)
1021 {
1022       pform_default_nettype = type;
1023 
1024       if (! pform_cur_module.empty()) {
1025 	    cerr << file<<":"<<lineno << ": error: "
1026 		 << "`default_nettype directives must appear" << endl;
1027 	    cerr << file<<":"<<lineno << ":      : "
1028 		 << "outside module definitions. The containing" << endl;
1029 	    cerr << file<<":"<<lineno << ":      : "
1030 		 << "module " << pform_cur_module.back()->mod_name()
1031 		 << " starts on line "
1032 		 << pform_cur_module.back()->get_fileline() << "." << endl;
1033 	    error_count += 1;
1034       }
1035 }
1036 
pform_declare_implicit_nets(PExpr * expr)1037 static void pform_declare_implicit_nets(PExpr*expr)
1038 {
1039 	/* If implicit net creation is turned off, then stop now. */
1040       if (pform_default_nettype == NetNet::NONE)
1041 	    return;
1042 
1043       if (expr)
1044             expr->declare_implicit_nets(lexical_scope, pform_default_nettype);
1045 }
1046 
1047 /*
1048  * The lexor calls this function to set the active timescale when it
1049  * detects a `timescale directive. The function saves the directive
1050  * values (for use by subsequent design elements) and if warnings are
1051  * enabled checks to see if some design elements have no timescale.
1052  */
pform_set_timescale(int unit,int prec,const char * file,unsigned lineno)1053 void pform_set_timescale(int unit, int prec,
1054 			 const char*file, unsigned lineno)
1055 {
1056       assert(unit >= prec);
1057       pform_time_unit = unit;
1058       pform_time_prec = prec;
1059 
1060       if (pform_timescale_file) {
1061 	    free(pform_timescale_file);
1062       }
1063 
1064       if (file) pform_timescale_file = strdup(file);
1065       else pform_timescale_file = 0;
1066       pform_timescale_line = lineno;
1067 }
1068 
get_time_unit(const char * cp,int & unit)1069 bool get_time_unit(const char*cp, int &unit)
1070 {
1071 	const char *c;
1072 	bool        rc = true;
1073 
1074 	if (strchr(cp, '_')) {
1075 		VLerror(yylloc, "Invalid timeunit constant ('_' is not "
1076 				"supported).");
1077 		return false;
1078 	}
1079 
1080 	c = strpbrk(cp, "munpfs");
1081 	if (!c)
1082 		return false;
1083 
1084 	if (*c == 's')
1085 		unit = 0;
1086 	else if (!strncmp(c, "ms", 2))
1087 		unit = -3;
1088 	else if (!strncmp(c, "us", 2))
1089 		unit = -6;
1090 	else if (!strncmp(c, "ns", 2))
1091 		unit = -9;
1092 	else if (!strncmp(c, "ps", 2))
1093 		unit = -12;
1094 	else if (!strncmp(c, "fs", 2))
1095 		unit = -15;
1096 	else {
1097 		rc = false;
1098 
1099 		ostringstream msg;
1100 		msg << "Invalid timeunit scale '" << cp << "'.";
1101 		VLerror(msg.str().c_str());
1102 	}
1103 
1104 	return rc;
1105 }
1106 
1107 /*
1108  * Get a timeunit or timeprecision value from a string.  This is
1109  * similar to the code in lexor.lex for the `timescale directive.
1110  */
get_time_unit_prec(const char * cp,int & res,bool is_unit)1111 static bool get_time_unit_prec(const char*cp, int &res, bool is_unit)
1112 {
1113 	/* We do not support a '_' in these time constants. */
1114       if (strchr(cp, '_')) {
1115 	    if (is_unit) {
1116 		  VLerror(yylloc, "Invalid timeunit constant ('_' is not "
1117 		                  "supported).");
1118 	    } else {
1119 		  VLerror(yylloc, "Invalid timeprecision constant ('_' is not "
1120 		                  "supported).");
1121 	    }
1122 	    return true;
1123       }
1124 
1125 	/* Check for the 1 digit. */
1126       if (*cp != '1') {
1127 	    if (is_unit) {
1128 		  VLerror(yylloc, "Invalid timeunit constant (1st digit).");
1129 	    } else {
1130 		  VLerror(yylloc, "Invalid timeprecision constant (1st digit).");
1131 	    }
1132 	    return true;
1133       }
1134       cp += 1;
1135 
1136 	/* Check the number of zeros after the 1. */
1137       res = strspn(cp, "0");
1138       if (res > 2) {
1139 	    if (is_unit) {
1140 		  VLerror(yylloc, "Invalid timeunit constant (number of "
1141 		                  "zeros).");
1142 	    } else {
1143 		  VLerror(yylloc, "Invalid timeprecision constant (number of "
1144 		                  "zeros).");
1145 	    }
1146 	    return true;
1147       }
1148       cp += res;
1149 
1150 	/* Now process the scaling string. */
1151       if (strncmp("s", cp, 1) == 0) {
1152 	    res -= 0;
1153 	    return false;
1154 
1155       } else if (strncmp("ms", cp, 2) == 0) {
1156 	    res -= 3;
1157 	    return false;
1158 
1159       } else if (strncmp("us", cp, 2) == 0) {
1160 	    res -= 6;
1161 	    return false;
1162 
1163       } else if (strncmp("ns", cp, 2) == 0) {
1164 	    res -= 9;
1165 	    return false;
1166 
1167       } else if (strncmp("ps", cp, 2) == 0) {
1168 	    res -= 12;
1169 	    return false;
1170 
1171       } else if (strncmp("fs", cp, 2) == 0) {
1172 	    res -= 15;
1173 	    return false;
1174 
1175       }
1176 
1177       ostringstream msg;
1178       msg << "Invalid ";
1179       if (is_unit) msg << "timeunit";
1180       else msg << "timeprecision";
1181       msg << " scale '" << cp << "'.";
1182       VLerror(msg.str().c_str());
1183       return true;
1184 }
1185 
pform_set_timeunit(const char * txt,bool initial_decl)1186 void pform_set_timeunit(const char*txt, bool initial_decl)
1187 {
1188       int val;
1189 
1190       if (get_time_unit_prec(txt, val, true)) return;
1191 
1192       PScopeExtra*scope = dynamic_cast<PScopeExtra*>(lexical_scope);
1193       assert(scope);
1194 
1195       if (initial_decl) {
1196             scope->time_unit = val;
1197             scope->time_unit_is_local = true;
1198             scope->time_unit_is_default = false;
1199             allow_timeunit_decl = false;
1200       } else if (!scope->time_unit_is_local) {
1201             VLerror(yylloc, "error: repeat timeunit found and the initial "
1202                             "timeunit for this scope is missing.");
1203       } else if (scope->time_unit != val) {
1204             VLerror(yylloc, "error: repeat timeunit does not match the "
1205                             "initial timeunit for this scope.");
1206       }
1207 }
1208 
pform_get_timeunit()1209 int pform_get_timeunit()
1210 {
1211       PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
1212       assert(scopex);
1213       return scopex->time_unit;
1214 }
1215 
pform_set_timeprec(const char * txt,bool initial_decl)1216 void pform_set_timeprec(const char*txt, bool initial_decl)
1217 {
1218       int val;
1219 
1220       if (get_time_unit_prec(txt, val, false)) return;
1221 
1222       PScopeExtra*scope = dynamic_cast<PScopeExtra*>(lexical_scope);
1223       assert(scope);
1224 
1225       if (initial_decl) {
1226             scope->time_precision = val;
1227             scope->time_prec_is_local = true;
1228             scope->time_prec_is_default = false;
1229             allow_timeprec_decl = false;
1230       } else if (!scope->time_prec_is_local) {
1231             VLerror(yylloc, "error: repeat timeprecision found and the initial "
1232                             "timeprecision for this scope is missing.");
1233       } else if (scope->time_precision != val) {
1234             VLerror(yylloc, "error: repeat timeprecision does not match the "
1235                             "initial timeprecision for this scope.");
1236       }
1237 }
1238 
pform_verinum_with_size(verinum * siz,verinum * val,const char * file,unsigned lineno)1239 verinum* pform_verinum_with_size(verinum*siz, verinum*val,
1240 				 const char*file, unsigned lineno)
1241 {
1242       assert(siz->is_defined());
1243       unsigned long size = siz->as_ulong();
1244 
1245       if (size == 0) {
1246 	    cerr << file << ":" << lineno << ": error: Sized numeric constant "
1247 		    "must have a size greater than zero." << endl;
1248 	    error_count += 1;
1249       }
1250 
1251       verinum::V pad;
1252 
1253       if (val->len() == 0) {
1254 	    pad = verinum::Vx;
1255       } else {
1256 
1257 	    switch (val->get(val->len()-1)) {
1258 		case verinum::Vz:
1259 		  pad = verinum::Vz;
1260 		  break;
1261 		case verinum::Vx:
1262 		  pad = verinum::Vx;
1263 		  break;
1264 		default:
1265 		  pad = verinum::V0;
1266 		  break;
1267 	    }
1268       }
1269 
1270       verinum*res = new verinum(pad, size, true);
1271 
1272       unsigned copy = val->len();
1273       if (res->len() < copy)
1274 	    copy = res->len();
1275 
1276       for (unsigned idx = 0 ;  idx < copy ;  idx += 1) {
1277 	    res->set(idx, val->get(idx));
1278       }
1279 
1280       res->has_sign(val->has_sign());
1281 
1282       bool trunc_flag = false;
1283       for (unsigned idx = copy ;  idx < val->len() ;  idx += 1) {
1284 	    if (val->get(idx) != pad) {
1285 		  trunc_flag = true;
1286 		  break;
1287 	    }
1288       }
1289 
1290       if (trunc_flag) {
1291 	    cerr << file << ":" << lineno << ": warning: Numeric constant "
1292 		 << "truncated to " << copy << " bits." << endl;
1293       }
1294 
1295       delete siz;
1296       delete val;
1297       return res;
1298 }
1299 
pform_startmodule(const struct vlltype & loc,const char * name,bool program_block,bool is_interface,LexicalScope::lifetime_t lifetime,list<named_pexpr_t> * attr)1300 void pform_startmodule(const struct vlltype&loc, const char*name,
1301 		       bool program_block, bool is_interface,
1302 		       LexicalScope::lifetime_t lifetime,
1303 		       list<named_pexpr_t>*attr)
1304 {
1305       if (! pform_cur_module.empty() && !gn_system_verilog()) {
1306 	    cerr << loc << ": error: Module definition " << name
1307 		 << " cannot nest into module " << pform_cur_module.front()->mod_name() << "." << endl;
1308 	    error_count += 1;
1309       }
1310 
1311       if (lifetime != LexicalScope::INHERITED && !gn_system_verilog()) {
1312 	    cerr << loc << ": error: Default subroutine lifetimes "
1313 		    "require SystemVerilog." << endl;
1314 	    error_count += 1;
1315       }
1316 
1317       if (gn_system_verilog() && ! pform_cur_module.empty()) {
1318 	    if (pform_cur_module.front()->program_block) {
1319 		  cerr << loc << ": error: module, program, or interface "
1320 				 "declarations are not allowed in program "
1321 				 "blocks." << endl;
1322 		  error_count += 1;
1323 	    }
1324 	    if (pform_cur_module.front()->is_interface
1325 		&& !(program_block || is_interface)) {
1326 		  cerr << loc << ": error: module declarations are not "
1327 				 "allowed in interfaces." << endl;
1328 		  error_count += 1;
1329 	    }
1330       }
1331 
1332       perm_string lex_name = lex_strings.make(name);
1333       Module*cur_module = new Module(lexical_scope, lex_name);
1334       cur_module->program_block = program_block;
1335       cur_module->is_interface = is_interface;
1336       cur_module->default_lifetime = find_lifetime(lifetime);
1337 
1338       FILE_NAME(cur_module, loc);
1339 
1340       cur_module->library_flag = pform_library_flag;
1341 
1342       pform_cur_module.push_front(cur_module);
1343 
1344       allow_timeunit_decl = true;
1345       allow_timeprec_decl = true;
1346 
1347       add_local_symbol(lexical_scope, lex_name, cur_module);
1348 
1349       lexical_scope = cur_module;
1350 
1351 	/* The generate scheme numbering starts with *1*, not
1352 	   zero. That's just the way it is, thanks to the standard. */
1353       scope_generate_counter = 1;
1354 
1355       pform_bind_attributes(cur_module->attributes, attr);
1356 }
1357 
1358 /*
1359  * This function is called by the parser to make a simple port
1360  * reference. This is a name without a .X(...), so the internal name
1361  * should be generated to be the same as the X.
1362  */
pform_module_port_reference(perm_string name,const char * file,unsigned lineno)1363 Module::port_t* pform_module_port_reference(perm_string name,
1364 					    const char*file,
1365 					    unsigned lineno)
1366 {
1367       Module::port_t*ptmp = new Module::port_t;
1368       PEIdent*tmp = new PEIdent(name);
1369       FILE_NAME(tmp, file, lineno);
1370       ptmp->name = name;
1371       ptmp->expr.push_back(tmp);
1372 
1373       return ptmp;
1374 }
1375 
pform_module_set_ports(vector<Module::port_t * > * ports)1376 void pform_module_set_ports(vector<Module::port_t*>*ports)
1377 {
1378       assert(! pform_cur_module.empty());
1379 
1380 	/* The parser parses ``module foo()'' as having one
1381 	   unconnected port, but it is really a module with no
1382 	   ports. Fix it up here. */
1383       if (ports && (ports->size() == 1) && ((*ports)[0] == 0)) {
1384 	    delete ports;
1385 	    ports = 0;
1386       }
1387 
1388       if (ports != 0) {
1389 	    pform_cur_module.front()->ports = *ports;
1390 	    delete ports;
1391       }
1392 }
1393 
pform_endmodule(const char * name,bool inside_celldefine,Module::UCDriveType uc_drive_def)1394 void pform_endmodule(const char*name, bool inside_celldefine,
1395                      Module::UCDriveType uc_drive_def)
1396 {
1397 	// The parser will not call pform_endmodule() without first
1398 	// calling pform_startmodule(). Thus, it is impossible for the
1399 	// pform_cur_module stack to be empty at this point.
1400       assert(! pform_cur_module.empty());
1401       Module*cur_module  = pform_cur_module.front();
1402       pform_cur_module.pop_front();
1403       perm_string mod_name = cur_module->mod_name();
1404 
1405 	// Oops, there may be some sort of nesting problem. If
1406 	// SystemVerilog is activated, it is possible for modules to
1407 	// be nested. But if the nested module is broken, the parser
1408 	// will recover and treat is as an invalid module item,
1409 	// leaving the pform_cur_module stack in an inconsistent
1410 	// state. For example, this:
1411 	//    module foo;
1412 	//      module bar blah blab blah error;
1413 	//    endmodule
1414 	// may leave the pform_cur_module stack with the dregs of the
1415 	// bar module. Try to find the foo module in the stack, and
1416 	// print error messages as we go.
1417       if (strcmp(name, mod_name) != 0) {
1418 	    while (pform_cur_module.size() > 0) {
1419 		  Module*tmp_module = pform_cur_module.front();
1420 		  perm_string tmp_name = tmp_module->mod_name();
1421 		  pform_cur_module.pop_front();
1422 		  ostringstream msg;
1423 		  msg << "Module " << mod_name
1424 		      << " was nested within " << tmp_name
1425 		      << " but broken.";
1426 		  VLerror(msg.str().c_str());
1427 
1428 		  ivl_assert(*cur_module, lexical_scope == cur_module);
1429 		  pform_pop_scope();
1430 		  delete cur_module;
1431 
1432 		  cur_module = tmp_module;
1433 		  mod_name = tmp_name;
1434 		  if (strcmp(name, mod_name) == 0)
1435 			break;
1436 	    }
1437       }
1438       assert(strcmp(name, mod_name) == 0);
1439 
1440       cur_module->is_cell = inside_celldefine;
1441       cur_module->uc_drive = uc_drive_def;
1442 
1443 	// If this is a root module, then there is no parent module
1444 	// and we try to put this newly defined module into the global
1445 	// root list of modules. Otherwise, this is a nested module
1446 	// and we put it into the parent module scope to be elaborated
1447 	// if needed.
1448       map<perm_string,Module*>&use_module_map = (pform_cur_module.empty())
1449 	    ? pform_modules
1450 	    : pform_cur_module.front()->nested_modules;
1451 
1452       map<perm_string,Module*>::const_iterator test =
1453 	    use_module_map.find(mod_name);
1454 
1455       if (test != use_module_map.end()) {
1456 	    ostringstream msg;
1457 	    msg << "Module " << name << " was already declared here: "
1458 		<< test->second->get_fileline() << endl;
1459 	    VLerror(msg.str().c_str());
1460       } else {
1461 	    use_module_map[mod_name] = cur_module;
1462       }
1463 
1464 	// The current lexical scope should be this module by now.
1465       ivl_assert(*cur_module, lexical_scope == cur_module);
1466       pform_pop_scope();
1467 }
1468 
pform_genvars(const struct vlltype & li,list<perm_string> * names)1469 void pform_genvars(const struct vlltype&li, list<perm_string>*names)
1470 {
1471       list<perm_string>::const_iterator cur;
1472       for (cur = names->begin(); cur != names->end() ; *cur++) {
1473 	    PGenvar*genvar = new PGenvar();
1474 	    FILE_NAME(genvar, li);
1475 
1476 	    if (pform_cur_generate) {
1477 		  add_local_symbol(pform_cur_generate, *cur, genvar);
1478 		  pform_cur_generate->genvars[*cur] = genvar;
1479 	    } else {
1480 		  add_local_symbol(pform_cur_module.front(), *cur, genvar);
1481 		  pform_cur_module.front()->genvars[*cur] = genvar;
1482 	    }
1483       }
1484 
1485       delete names;
1486 }
1487 
pform_start_generate_for(const struct vlltype & li,bool local_index,char * ident1,PExpr * init,PExpr * test,char * ident2,PExpr * next)1488 void pform_start_generate_for(const struct vlltype&li,
1489 			      bool local_index,
1490 			      char*ident1, PExpr*init,
1491 			      PExpr*test,
1492 			      char*ident2, PExpr*next)
1493 {
1494       PGenerate*gen = new PGenerate(lexical_scope, scope_generate_counter++);
1495       lexical_scope = gen;
1496 
1497       FILE_NAME(gen, li);
1498 
1499       pform_cur_generate = gen;
1500 
1501       pform_cur_generate->scheme_type = PGenerate::GS_LOOP;
1502 
1503       pform_cur_generate->local_index = local_index;
1504       pform_cur_generate->loop_index = lex_strings.make(ident1);
1505       pform_cur_generate->loop_init = init;
1506       pform_cur_generate->loop_test = test;
1507       pform_cur_generate->loop_step = next;
1508 
1509       delete[]ident1;
1510       delete[]ident2;
1511 }
1512 
pform_start_generate_if(const struct vlltype & li,PExpr * test)1513 void pform_start_generate_if(const struct vlltype&li, PExpr*test)
1514 {
1515       PGenerate*gen = new PGenerate(lexical_scope, scope_generate_counter++);
1516       lexical_scope = gen;
1517 
1518       FILE_NAME(gen, li);
1519 
1520       pform_cur_generate = gen;
1521 
1522       pform_cur_generate->scheme_type = PGenerate::GS_CONDIT;
1523 
1524       pform_cur_generate->loop_init = 0;
1525       pform_cur_generate->loop_test = test;
1526       pform_cur_generate->loop_step = 0;
1527 
1528       conditional_block_names.push_front(set<perm_string>());
1529 }
1530 
pform_start_generate_else(const struct vlltype & li)1531 void pform_start_generate_else(const struct vlltype&li)
1532 {
1533       assert(pform_cur_generate);
1534       assert(pform_cur_generate->scheme_type == PGenerate::GS_CONDIT);
1535 
1536       PGenerate*cur = pform_cur_generate;
1537       pform_endgenerate(false);
1538 
1539       PGenerate*gen = new PGenerate(lexical_scope, scope_generate_counter++);
1540       lexical_scope = gen;
1541 
1542       FILE_NAME(gen, li);
1543 
1544       pform_cur_generate = gen;
1545 
1546       pform_cur_generate->scheme_type = PGenerate::GS_ELSE;
1547 
1548       pform_cur_generate->loop_init = 0;
1549       pform_cur_generate->loop_test = cur->loop_test;
1550       pform_cur_generate->loop_step = 0;
1551 }
1552 
1553 /*
1554  * The GS_CASE version of the PGenerate contains only case items. The
1555  * items in turn contain the generated items themselves.
1556  */
pform_start_generate_case(const struct vlltype & li,PExpr * expr)1557 void pform_start_generate_case(const struct vlltype&li, PExpr*expr)
1558 {
1559       PGenerate*gen = new PGenerate(lexical_scope, scope_generate_counter++);
1560       lexical_scope = gen;
1561 
1562       FILE_NAME(gen, li);
1563 
1564       pform_cur_generate = gen;
1565 
1566       pform_cur_generate->scheme_type = PGenerate::GS_CASE;
1567 
1568       pform_cur_generate->loop_init = 0;
1569       pform_cur_generate->loop_test = expr;
1570       pform_cur_generate->loop_step = 0;
1571 
1572       conditional_block_names.push_front(set<perm_string>());
1573 }
1574 
1575 /*
1576  * The named block generate case.
1577  */
pform_start_generate_nblock(const struct vlltype & li,char * name)1578 void pform_start_generate_nblock(const struct vlltype&li, char*name)
1579 {
1580       PGenerate*gen = new PGenerate(lexical_scope, scope_generate_counter++);
1581       lexical_scope = gen;
1582 
1583       FILE_NAME(gen, li);
1584 
1585       pform_cur_generate = gen;
1586 
1587       pform_cur_generate->scheme_type = PGenerate::GS_NBLOCK;
1588 
1589       pform_cur_generate->loop_init = 0;
1590       pform_cur_generate->loop_test = 0;
1591       pform_cur_generate->loop_step = 0;
1592 
1593       pform_cur_generate->scope_name = lex_strings.make(name);
1594       delete[]name;
1595 
1596       add_local_symbol(pform_cur_generate->parent_scope(),
1597                        pform_cur_generate->scope_name,
1598                        pform_cur_generate);
1599 }
1600 
1601 /*
1602  * The generate case item is a special case schema that takes its id
1603  * from the case schema that it is a part of. The idea is that the
1604  * case schema can only instantiate exactly one item, so the items
1605  * need not have a unique number.
1606  */
pform_generate_case_item(const struct vlltype & li,list<PExpr * > * expr_list)1607 void pform_generate_case_item(const struct vlltype&li, list<PExpr*>*expr_list)
1608 {
1609       assert(pform_cur_generate);
1610       assert(pform_cur_generate->scheme_type == PGenerate::GS_CASE);
1611 
1612       PGenerate*gen = new PGenerate(lexical_scope, pform_cur_generate->id_number);
1613       lexical_scope = gen;
1614 
1615       FILE_NAME(gen, li);
1616 
1617       pform_cur_generate = gen;
1618 
1619       pform_cur_generate->scheme_type = PGenerate::GS_CASE_ITEM;
1620 
1621       pform_cur_generate->loop_init = 0;
1622       pform_cur_generate->loop_test = 0;
1623       pform_cur_generate->loop_step = 0;
1624 
1625       if (expr_list != 0) {
1626 	    list<PExpr*>::iterator expr_cur = expr_list->begin();
1627 	    pform_cur_generate->item_test.resize(expr_list->size());
1628 	    for (unsigned idx = 0 ; idx < expr_list->size() ; idx += 1) {
1629 		  pform_cur_generate->item_test[idx] = *expr_cur;
1630 		  ++ expr_cur;
1631 	    }
1632 	    assert(expr_cur == expr_list->end());
1633       }
1634 }
1635 
pform_generate_block_name(char * name)1636 void pform_generate_block_name(char*name)
1637 {
1638       assert(pform_cur_generate != 0);
1639       assert(pform_cur_generate->scope_name == 0);
1640       perm_string scope_name = lex_strings.make(name);
1641       pform_cur_generate->scope_name = scope_name;
1642 
1643       if (pform_cur_generate->scheme_type == PGenerate::GS_CONDIT
1644        || pform_cur_generate->scheme_type == PGenerate::GS_ELSE
1645        || pform_cur_generate->scheme_type == PGenerate::GS_CASE_ITEM) {
1646 
1647             if (conditional_block_names.front().count(scope_name))
1648                   return;
1649 
1650             conditional_block_names.front().insert(scope_name);
1651       }
1652 
1653       LexicalScope*parent_scope = pform_cur_generate->parent_scope();
1654       assert(parent_scope);
1655       if (pform_cur_generate->scheme_type == PGenerate::GS_CASE_ITEM)
1656 	      // Skip over the PGenerate::GS_CASE container.
1657 	    parent_scope = parent_scope->parent_scope();
1658 
1659       add_local_symbol(parent_scope, scope_name, pform_cur_generate);
1660 }
1661 
pform_endgenerate(bool end_conditional)1662 void pform_endgenerate(bool end_conditional)
1663 {
1664       assert(pform_cur_generate != 0);
1665       assert(! pform_cur_module.empty());
1666 
1667       if (end_conditional)
1668             conditional_block_names.pop_front();
1669 
1670 	// If there is no explicit block name then generate a temporary
1671 	// name. This will be replaced by the correct name later, once
1672 	// we know all the explicit names in the surrounding scope. If
1673 	// the naming scheme used here is changed, PGenerate::elaborate
1674 	// must be changed to match.
1675       if (pform_cur_generate->scope_name == 0) {
1676 	    char tmp[16];
1677 	    snprintf(tmp, sizeof tmp, "$gen%u", pform_cur_generate->id_number);
1678 	    pform_cur_generate->scope_name = lex_strings.make(tmp);
1679       }
1680 
1681 	// The current lexical scope should be this generate construct by now
1682       ivl_assert(*pform_cur_generate, lexical_scope == pform_cur_generate);
1683       pform_pop_scope();
1684 
1685       PGenerate*parent_generate = dynamic_cast<PGenerate*>(lexical_scope);
1686       if (parent_generate) {
1687 	    assert(pform_cur_generate->scheme_type == PGenerate::GS_CASE_ITEM
1688 		   || parent_generate->scheme_type != PGenerate::GS_CASE);
1689 	    parent_generate->generate_schemes.push_back(pform_cur_generate);
1690       } else {
1691 	    assert(pform_cur_generate->scheme_type != PGenerate::GS_CASE_ITEM);
1692 	    pform_cur_module.front()->generate_schemes.push_back(pform_cur_generate);
1693       }
1694       pform_cur_generate = parent_generate;
1695 }
1696 
1697 MIN_TYP_MAX min_typ_max_flag = TYP;
1698 unsigned min_typ_max_warn = 10;
1699 
pform_select_mtm_expr(PExpr * min,PExpr * typ,PExpr * max)1700 PExpr* pform_select_mtm_expr(PExpr*min, PExpr*typ, PExpr*max)
1701 {
1702       PExpr*res = 0;
1703 
1704       switch (min_typ_max_flag) {
1705 	  case MIN:
1706 	    res = min;
1707 	    delete typ;
1708 	    delete max;
1709 	    break;
1710 	  case TYP:
1711 	    res = typ;
1712 	    delete min;
1713 	    delete max;
1714 	    break;
1715 	  case MAX:
1716 	    res = max;
1717 	    delete min;
1718 	    delete typ;
1719 	    break;
1720       }
1721 
1722       if (min_typ_max_warn > 0) {
1723 	    cerr << res->get_fileline() << ": warning: choosing ";
1724 	    switch (min_typ_max_flag) {
1725 		case MIN:
1726 		  cerr << "min";
1727 		  break;
1728 		case TYP:
1729 		  cerr << "typ";
1730 		  break;
1731 		case MAX:
1732 		  cerr << "max";
1733 		  break;
1734 	    }
1735 
1736 	    cerr << " expression." << endl;
1737 	    min_typ_max_warn -= 1;
1738       }
1739 
1740       return res;
1741 }
1742 
svector(unsigned size)1743 template <> inline svector<perm_string>::svector(unsigned size)
1744 : nitems_(size), items_(new perm_string[size])
1745 {
1746 }
1747 
process_udp_table(PUdp * udp,list<string> * table,const char * file,unsigned lineno)1748 static void process_udp_table(PUdp*udp, list<string>*table,
1749 			      const char*file, unsigned lineno)
1750 {
1751       const bool synchronous_flag = udp->sequential;
1752 
1753 	/* Interpret and check the table entry strings, to make sure
1754 	   they correspond to the inputs, output and output type. Make
1755 	   up vectors for the fully interpreted result that can be
1756 	   placed in the PUdp object.
1757 
1758 	   The table strings are made up by the parser to be two or
1759 	   three substrings separated by ';', i.e.:
1760 
1761 	   0101:1:1  (synchronous device entry)
1762 	   0101:0    (combinational device entry)
1763 
1764 	   The parser doesn't check that we got the right kind here,
1765 	   so this loop must watch out. */
1766       svector<string> input   (table->size());
1767       svector<char>   current (table->size());
1768       svector<char>   output  (table->size());
1769       { unsigned idx = 0;
1770         for (list<string>::iterator cur = table->begin()
1771 		   ; cur != table->end() ; ++ cur , idx += 1) {
1772 	      string tmp = *cur;
1773 
1774 		/* Pull the input values from the string. */
1775 	      assert(tmp.find(':') == (udp->ports.count() - 1));
1776 	      input[idx] = tmp.substr(0, udp->ports.count()-1);
1777 	      tmp = tmp.substr(udp->ports.count()-1);
1778 
1779 	      assert(tmp[0] == ':');
1780 
1781 		/* If this is a synchronous device, get the current
1782 		   output string. */
1783 	      if (synchronous_flag) {
1784 		    if (tmp.size() != 4) {
1785 			  cerr << file<<":"<<lineno << ": error: "
1786 			       << "Invalid table format for"
1787 			       << " sequential primitive." << endl;
1788 			  error_count += 1;
1789 			  break;
1790 		    }
1791 		    assert(tmp.size() == 4);
1792 		    current[idx] = tmp[1];
1793 		    tmp = tmp.substr(2);
1794 
1795 	      } else if (tmp.size() != 2) {
1796 		  cerr << file<<":"<<lineno << ": error: "
1797 		       << "Invalid table format for"
1798 		       << " combinational primitive." << endl;
1799 		  error_count += 1;
1800 		  break;
1801 	      }
1802 
1803 		/* Finally, extract the desired output. */
1804 	      assert(tmp.size() == 2);
1805 	      output[idx] = tmp[1];
1806 	}
1807       }
1808 
1809       udp->tinput   = input;
1810       udp->tcurrent = current;
1811       udp->toutput  = output;
1812 }
1813 
pform_make_udp(perm_string name,list<perm_string> * parms,vector<PWire * > * decl,list<string> * table,Statement * init_expr,const char * file,unsigned lineno)1814 void pform_make_udp(perm_string name, list<perm_string>*parms,
1815 		    vector<PWire*>*decl, list<string>*table,
1816 		    Statement*init_expr,
1817 		    const char*file, unsigned lineno)
1818 {
1819       unsigned local_errors = 0;
1820       assert(!parms->empty());
1821 
1822       assert(decl);
1823 
1824 	/* Put the declarations into a map, so that I can check them
1825 	   off with the parameters in the list. If the port is already
1826 	   in the map, merge the port type. I will rebuild a list
1827 	   of parameters for the PUdp object. */
1828       map<perm_string,PWire*> defs;
1829       for (unsigned idx = 0 ;  idx < decl->size() ;  idx += 1) {
1830 
1831 	    perm_string port_name = (*decl)[idx]->basename();
1832 
1833 	    if (PWire*cur = defs[port_name]) {
1834 		  bool rc = true;
1835 		  assert((*decl)[idx]);
1836 		  if ((*decl)[idx]->get_port_type() != NetNet::PIMPLICIT) {
1837 			rc = cur->set_port_type((*decl)[idx]->get_port_type());
1838 			assert(rc);
1839 		  }
1840 		  if ((*decl)[idx]->get_wire_type() != NetNet::IMPLICIT) {
1841 			rc = cur->set_wire_type((*decl)[idx]->get_wire_type());
1842 			assert(rc);
1843 		  }
1844 
1845 	    } else {
1846 		  defs[port_name] = (*decl)[idx];
1847 	    }
1848       }
1849 
1850 
1851 	/* Put the parameters into a vector of wire descriptions. Look
1852 	   in the map for the definitions of the name. In this loop,
1853 	   the parms list in the list of ports in the port list of the
1854 	   UDP declaration, and the defs map maps that name to a
1855 	   PWire* created by an input or output declaration. */
1856       svector<PWire*> pins (parms->size());
1857       svector<perm_string> pin_names (parms->size());
1858       { list<perm_string>::iterator cur;
1859         unsigned idx;
1860         for (cur = parms->begin(), idx = 0
1861 		   ; cur != parms->end()
1862 		   ; ++ idx, ++ cur) {
1863 	      pins[idx] = defs[*cur];
1864 	      pin_names[idx] = *cur;
1865 	}
1866       }
1867 
1868 	/* Check that the output is an output and the inputs are
1869 	   inputs. I can also make sure that only the single output is
1870 	   declared a register, if anything. The possible errors are:
1871 
1872 	      -- an input port (not the first) is missing an input
1873 	         declaration.
1874 
1875 	      -- An input port is declared output.
1876 
1877 	*/
1878       assert(pins.count() > 0);
1879       do {
1880 	    if (pins[0] == 0) {
1881 		  cerr << file<<":"<<lineno << ": error: "
1882 		       << "Output port of primitive " << name
1883 		       << " missing output declaration." << endl;
1884 		  cerr << file<<":"<<lineno << ":      : "
1885 		       << "Try: output " << pin_names[0] << ";"
1886 		       << endl;
1887 		  error_count += 1;
1888 		  local_errors += 1;
1889 		  break;
1890 	    }
1891 	    if (pins[0]->get_port_type() != NetNet::POUTPUT) {
1892 		  cerr << file<<":"<<lineno << ": error: "
1893 		       << "The first port of a primitive"
1894 		       << " must be an output." << endl;
1895 		  cerr << file<<":"<<lineno << ":      : "
1896 		       << "Try: output " << pin_names[0] << ";"
1897 		       << endl;
1898 		  error_count += 1;
1899 		  local_errors += 1;
1900 		  break;;
1901 	    }
1902       } while (0);
1903 
1904       for (unsigned idx = 1 ;  idx < pins.count() ;  idx += 1) {
1905 	    if (pins[idx] == 0) {
1906 		  cerr << file<<":"<<lineno << ": error: "
1907 		       << "Port " << (idx+1)
1908 		       << " of primitive " << name << " missing"
1909 		       << " input declaration." << endl;
1910 		  cerr << file<<":"<<lineno << ":      : "
1911 		       << "Try: input " << pin_names[idx] << ";"
1912 		       << endl;
1913 		  error_count += 1;
1914 		  local_errors += 1;
1915 		  continue;
1916 	    }
1917 	    if (pins[idx]->get_port_type() != NetNet::PINPUT) {
1918 		  cerr << file<<":"<<lineno << ": error: "
1919 		       << "Input port " << (idx+1)
1920 		       << " of primitive " << name
1921 		       << " has an output (or missing) declaration." << endl;
1922 		  cerr << file<<":"<<lineno << ":      : "
1923 		       << "Note that only the first port can be an output."
1924 		       << endl;
1925 		  cerr << file<<":"<<lineno << ":      : "
1926 		       << "Try \"input " << name << ";\""
1927 		       << endl;
1928 		  error_count += 1;
1929 		  local_errors += 1;
1930 		  continue;
1931 	    }
1932 
1933 	    if (pins[idx]->get_wire_type() == NetNet::REG) {
1934 		  cerr << file<<":"<<lineno << ": error: "
1935 		       << "Port " << (idx+1)
1936 		       << " of primitive " << name << " is an input port"
1937 		       << " with a reg declaration." << endl;
1938 		  cerr << file<<":"<<lineno << ":      : "
1939 		       << "primitive inputs cannot be reg."
1940 		       << endl;
1941 		  error_count += 1;
1942 		  local_errors += 1;
1943 		  continue;
1944 	    }
1945       }
1946 
1947       if (local_errors > 0) {
1948 	    delete parms;
1949 	    delete decl;
1950 	    delete table;
1951 	    delete init_expr;
1952 	    return;
1953       }
1954 
1955 
1956 	/* Verify the "initial" statement, if present, to be sure that
1957 	   it only assigns to the output and the output is
1958 	   registered. Then save the initial value that I get. */
1959       verinum::V init = verinum::Vx;
1960       if (init_expr) {
1961 	      // XXXX
1962 	    assert(pins[0]->get_wire_type() == NetNet::REG);
1963 
1964 	    PAssign*pa = dynamic_cast<PAssign*>(init_expr);
1965 	    assert(pa);
1966 
1967 	    const PEIdent*id = dynamic_cast<const PEIdent*>(pa->lval());
1968 	    assert(id);
1969 
1970 	      // XXXX
1971 	      //assert(id->name() == pins[0]->name());
1972 
1973 	    const PENumber*np = dynamic_cast<const PENumber*>(pa->rval());
1974 	    assert(np);
1975 
1976 	    init = np->value()[0];
1977       }
1978 
1979 	// Put the primitive into the primitives table
1980       if (pform_primitives[name]) {
1981 	    VLwarn("UDP primitive already exists.");
1982 
1983       } else {
1984 	    PUdp*udp = new PUdp(name, parms->size());
1985 	    FILE_NAME(udp, file, lineno);
1986 
1987 	      // Detect sequential udp.
1988 	    if (pins[0]->get_wire_type() == NetNet::REG)
1989 		  udp->sequential = true;
1990 
1991 	      // Make the port list for the UDP
1992 	    for (unsigned idx = 0 ;  idx < pins.count() ;  idx += 1)
1993 		  udp->ports[idx] = pins[idx]->basename();
1994 
1995 	    process_udp_table(udp, table, file, lineno);
1996 	    udp->initial  = init;
1997 
1998 	    pform_primitives[name] = udp;
1999       }
2000 
2001 
2002 	/* Delete the excess tables and lists from the parser. */
2003       delete parms;
2004       delete decl;
2005       delete table;
2006       delete init_expr;
2007 }
2008 
pform_make_udp(perm_string name,bool synchronous_flag,perm_string out_name,PExpr * init_expr,list<perm_string> * parms,list<string> * table,const char * file,unsigned lineno)2009 void pform_make_udp(perm_string name, bool synchronous_flag,
2010 		    perm_string out_name, PExpr*init_expr,
2011 		    list<perm_string>*parms, list<string>*table,
2012 		    const char*file, unsigned lineno)
2013 {
2014 
2015       svector<PWire*> pins(parms->size() + 1);
2016 
2017 	/* Make the PWire for the output port. */
2018       pins[0] = new PWire(out_name,
2019 			  synchronous_flag? NetNet::REG : NetNet::WIRE,
2020 			  NetNet::POUTPUT, IVL_VT_LOGIC);
2021       FILE_NAME(pins[0], file, lineno);
2022 
2023 	/* Make the PWire objects for the input ports. */
2024       { list<perm_string>::iterator cur;
2025         unsigned idx;
2026         for (cur = parms->begin(), idx = 1
2027 		   ;  cur != parms->end()
2028 		   ;  idx += 1, ++ cur) {
2029 	      assert(idx < pins.count());
2030 	      pins[idx] = new PWire(*cur, NetNet::WIRE,
2031 				    NetNet::PINPUT, IVL_VT_LOGIC);
2032 	      FILE_NAME(pins[idx], file, lineno);
2033 	}
2034 	assert(idx == pins.count());
2035       }
2036 
2037 	/* Verify the initial expression, if present, to be sure that
2038 	   it only assigns to the output and the output is
2039 	   registered. Then save the initial value that I get. */
2040       verinum::V init = verinum::Vx;
2041       if (init_expr) {
2042 	      // XXXX
2043 	    assert(pins[0]->get_wire_type() == NetNet::REG);
2044 
2045 	    PAssign*pa = dynamic_cast<PAssign*>(init_expr);
2046 	    assert(pa);
2047 
2048 	    const PEIdent*id = dynamic_cast<const PEIdent*>(pa->lval());
2049 	    assert(id);
2050 
2051 	      // XXXX
2052 	      //assert(id->name() == pins[0]->name());
2053 
2054 	    const PENumber*np = dynamic_cast<const PENumber*>(pa->rval());
2055 	    assert(np);
2056 
2057 	    init = np->value()[0];
2058       }
2059 
2060 	// Put the primitive into the primitives table
2061       if (pform_primitives[name]) {
2062 	    VLerror("UDP primitive already exists.");
2063 
2064       } else {
2065 	    PUdp*udp = new PUdp(name, pins.count());
2066 	    FILE_NAME(udp, file, lineno);
2067 
2068 	      // Detect sequential udp.
2069 	    udp->sequential = synchronous_flag;
2070 
2071 	      // Make the port list for the UDP
2072 	    for (unsigned idx = 0 ;  idx < pins.count() ;  idx += 1)
2073 		  udp->ports[idx] = pins[idx]->basename();
2074 
2075 	    assert(udp);
2076 	    assert(table);
2077 	    process_udp_table(udp, table, file, lineno);
2078 	    udp->initial  = init;
2079 
2080 	    pform_primitives[name] = udp;
2081       }
2082 
2083       delete parms;
2084       delete table;
2085       delete init_expr;
2086 }
2087 
2088 /*
2089  * This function attaches a range to a given name. The function is
2090  * only called by the parser within the scope of the net declaration,
2091  * and the name that I receive only has the tail component.
2092  */
pform_set_net_range(perm_string name,NetNet::Type net_type,const list<pform_range_t> * range,bool signed_flag,ivl_variable_type_t dt,PWSRType rt,std::list<named_pexpr_t> * attr)2093 static void pform_set_net_range(perm_string name,
2094 				NetNet::Type net_type,
2095 				const list<pform_range_t>*range,
2096 				bool signed_flag,
2097 				ivl_variable_type_t dt,
2098 				PWSRType rt,
2099 				std::list<named_pexpr_t>*attr)
2100 {
2101       PWire*cur = pform_get_wire_in_scope(name);
2102       if (cur == 0) {
2103 	    VLerror("error: name is not a valid net.");
2104 	    return;
2105       }
2106 
2107 	// If this is not implicit ("implicit" meaning we don't
2108 	// know what the type is yet) then set the type now.
2109       if (net_type != NetNet::IMPLICIT && net_type != NetNet::NONE) {
2110 	    bool rc = cur->set_wire_type(net_type);
2111 	    if (rc == false) {
2112 		  ostringstream msg;
2113 		  msg << name << " " << net_type
2114 		      << " definition conflicts with " << cur->get_wire_type()
2115 		      << " definition at " << cur->get_fileline()
2116 		      << ".";
2117 		  VLerror(msg.str().c_str());
2118 	    }
2119       }
2120 
2121       if (range == 0) {
2122 	      /* This is the special case that we really mean a
2123 		 scalar. Set a fake range. */
2124 	    cur->set_range_scalar(rt);
2125 
2126       } else {
2127 	    cur->set_range(*range, rt);
2128       }
2129       cur->set_signed(signed_flag);
2130 
2131       if (dt != IVL_VT_NO_TYPE)
2132 	    cur->set_data_type(dt);
2133 
2134       pform_bind_attributes(cur->attributes, attr, true);
2135 }
2136 
pform_set_net_range(list<perm_string> * names,list<pform_range_t> * range,bool signed_flag,ivl_variable_type_t dt,NetNet::Type net_type,std::list<named_pexpr_t> * attr)2137 static void pform_set_net_range(list<perm_string>*names,
2138 				list<pform_range_t>*range,
2139 				bool signed_flag,
2140 				ivl_variable_type_t dt,
2141 				NetNet::Type net_type,
2142 				std::list<named_pexpr_t>*attr)
2143 {
2144       for (list<perm_string>::iterator cur = names->begin()
2145 		 ; cur != names->end() ; ++ cur ) {
2146 	    perm_string txt = *cur;
2147 	    pform_set_net_range(txt, net_type, range, signed_flag, dt, SR_NET, attr);
2148       }
2149 
2150 }
2151 
2152 /*
2153  * This is invoked to make a named event. This is the declaration of
2154  * the event, and not necessarily the use of it.
2155  */
pform_make_event(perm_string name,const char * fn,unsigned ln)2156 static void pform_make_event(perm_string name, const char*fn, unsigned ln)
2157 {
2158       PEvent*event = new PEvent(name);
2159       FILE_NAME(event, fn, ln);
2160 
2161       add_local_symbol(lexical_scope, name, event);
2162       lexical_scope->events[name] = event;
2163 }
2164 
pform_make_events(list<perm_string> * names,const char * fn,unsigned ln)2165 void pform_make_events(list<perm_string>*names, const char*fn, unsigned ln)
2166 {
2167       list<perm_string>::iterator cur;
2168       for (cur = names->begin() ;  cur != names->end() ; ++ cur ) {
2169 	    perm_string txt = *cur;
2170 	    pform_make_event(txt, fn, ln);
2171       }
2172 
2173       delete names;
2174 }
2175 
2176 /*
2177  * pform_makegates is called when a list of gates (with the same type)
2178  * are ready to be instantiated. The function runs through the list of
2179  * gates and calls the pform_makegate function to make the individual gate.
2180  */
pform_makegate(PGBuiltin::Type type,struct str_pair_t str,list<PExpr * > * delay,const lgate & info,list<named_pexpr_t> * attr)2181 static void pform_makegate(PGBuiltin::Type type,
2182 			   struct str_pair_t str,
2183 			   list<PExpr*>* delay,
2184 			   const lgate&info,
2185 			   list<named_pexpr_t>*attr)
2186 {
2187       if (info.parms_by_name) {
2188 	    cerr << info.file << ":" << info.lineno << ": Gates do not "
2189 		  "have port names." << endl;
2190 	    error_count += 1;
2191 	    return;
2192       }
2193 
2194       if (info.parms) {
2195 	    for (list<PExpr*>::iterator cur = info.parms->begin()
2196 		       ; cur != info.parms->end() ; ++cur) {
2197 		  pform_declare_implicit_nets(*cur);
2198 	    }
2199       }
2200 
2201       perm_string dev_name = lex_strings.make(info.name);
2202       PGBuiltin*cur = new PGBuiltin(type, dev_name, info.parms, delay);
2203       if (info.range.first)
2204 	    cur->set_range(info.range.first, info.range.second);
2205 
2206 	// The pform_makegates() that calls me will take care of
2207 	// deleting the attr pointer, so tell the
2208 	// pform_bind_attributes function to keep the attr object.
2209       pform_bind_attributes(cur->attributes, attr, true);
2210 
2211       cur->strength0(str.str0);
2212       cur->strength1(str.str1);
2213       FILE_NAME(cur, info.file, info.lineno);
2214 
2215       if (pform_cur_generate) {
2216 	    if (dev_name != "") add_local_symbol(pform_cur_generate, dev_name, cur);
2217 	    pform_cur_generate->add_gate(cur);
2218       } else {
2219 	    if (dev_name != "") add_local_symbol(pform_cur_module.front(), dev_name, cur);
2220 	    pform_cur_module.front()->add_gate(cur);
2221       }
2222 }
2223 
pform_makegates(const struct vlltype & loc,PGBuiltin::Type type,struct str_pair_t str,list<PExpr * > * delay,svector<lgate> * gates,list<named_pexpr_t> * attr)2224 void pform_makegates(const struct vlltype&loc,
2225 		     PGBuiltin::Type type,
2226 		     struct str_pair_t str,
2227 		     list<PExpr*>*delay,
2228 		     svector<lgate>*gates,
2229 		     list<named_pexpr_t>*attr)
2230 {
2231       assert(! pform_cur_module.empty());
2232       if (pform_cur_module.front()->program_block) {
2233 	    cerr << loc << ": error: Gates and switches may not be instantiated in "
2234 		 << "program blocks." << endl;
2235 	    error_count += 1;
2236       }
2237       if (pform_cur_module.front()->is_interface) {
2238 	    cerr << loc << ": error: Gates and switches may not be instantiated in "
2239 		 << "interfaces." << endl;
2240 	    error_count += 1;
2241       }
2242 
2243       for (unsigned idx = 0 ;  idx < gates->count() ;  idx += 1) {
2244 	    pform_makegate(type, str, delay, (*gates)[idx], attr);
2245       }
2246 
2247       if (attr) delete attr;
2248       delete gates;
2249 }
2250 
2251 /*
2252  * A module is different from a gate in that there are different
2253  * constraints, and sometimes different syntax. The X_modgate
2254  * functions handle the instantiations of modules (and UDP objects) by
2255  * making PGModule objects.
2256  *
2257  * The first pform_make_modgate handles the case of a module
2258  * instantiated with ports passed by position. The "wires" is an
2259  * ordered array of port expressions.
2260  *
2261  * The second pform_make_modgate handles the case of a module
2262  * instantiated with ports passed by name. The "bind" argument is the
2263  * ports matched with names.
2264  */
pform_make_modgate(perm_string type,perm_string name,struct parmvalue_t * overrides,list<PExpr * > * wires,PExpr * msb,PExpr * lsb,const char * fn,unsigned ln,std::list<named_pexpr_t> * attr)2265 static void pform_make_modgate(perm_string type,
2266 			       perm_string name,
2267 			       struct parmvalue_t*overrides,
2268 			       list<PExpr*>*wires,
2269 			       PExpr*msb, PExpr*lsb,
2270 			       const char*fn, unsigned ln,
2271 			       std::list<named_pexpr_t>*attr)
2272 {
2273       for (list<PExpr*>::iterator idx = wires->begin()
2274 		 ; idx != wires->end() ; ++idx) {
2275 	    pform_declare_implicit_nets(*idx);
2276       }
2277 
2278       PGModule*cur = new PGModule(type, name, wires);
2279       FILE_NAME(cur, fn, ln);
2280       cur->set_range(msb,lsb);
2281 
2282       if (overrides && overrides->by_name) {
2283 	    unsigned cnt = overrides->by_name->size();
2284 	    named<PExpr*>*byname = new named<PExpr*>[cnt];
2285 
2286 	    list<named_pexpr_t>::iterator by_name_cur = overrides->by_name->begin();
2287 	    for (unsigned idx = 0 ;  idx < cnt ;  idx += 1, ++ by_name_cur) {
2288 		  byname[idx].name = by_name_cur->name;
2289 		  byname[idx].parm = by_name_cur->parm;
2290 	    }
2291 
2292 	    cur->set_parameters(byname, cnt);
2293 
2294       } else if (overrides && overrides->by_order) {
2295 	    cur->set_parameters(overrides->by_order);
2296       }
2297 
2298       if (pform_cur_generate) {
2299 	    if (name != "") add_local_symbol(pform_cur_generate, name, cur);
2300 	    pform_cur_generate->add_gate(cur);
2301       } else {
2302 	    if (name != "") add_local_symbol(pform_cur_module.front(), name, cur);
2303 	    pform_cur_module.front()->add_gate(cur);
2304       }
2305       pform_bind_attributes(cur->attributes, attr);
2306 }
2307 
pform_make_modgate(perm_string type,perm_string name,struct parmvalue_t * overrides,list<named_pexpr_t> * bind,PExpr * msb,PExpr * lsb,const char * fn,unsigned ln,std::list<named_pexpr_t> * attr)2308 static void pform_make_modgate(perm_string type,
2309 			       perm_string name,
2310 			       struct parmvalue_t*overrides,
2311 			       list<named_pexpr_t>*bind,
2312 			       PExpr*msb, PExpr*lsb,
2313 			       const char*fn, unsigned ln,
2314 			       std::list<named_pexpr_t>*attr)
2315 {
2316       unsigned npins = bind->size();
2317       named<PExpr*>*pins = new named<PExpr*>[npins];
2318       list<named_pexpr_t>::iterator bind_cur = bind->begin();
2319       for (unsigned idx = 0 ;  idx < npins ;  idx += 1,  ++bind_cur) {
2320 	    pins[idx].name = bind_cur->name;
2321 	    pins[idx].parm = bind_cur->parm;
2322             pform_declare_implicit_nets(bind_cur->parm);
2323       }
2324 
2325       PGModule*cur = new PGModule(type, name, pins, npins);
2326       FILE_NAME(cur, fn, ln);
2327       cur->set_range(msb,lsb);
2328 
2329       if (overrides && overrides->by_name) {
2330 	    unsigned cnt = overrides->by_name->size();
2331 	    named<PExpr*>*byname = new named<PExpr*>[cnt];
2332 
2333 	    list<named_pexpr_t>::iterator by_name_cur = overrides->by_name->begin();
2334 	    for (unsigned idx = 0 ;  idx < cnt ;  idx += 1,  ++by_name_cur) {
2335 		  byname[idx].name = by_name_cur->name;
2336 		  byname[idx].parm = by_name_cur->parm;
2337 	    }
2338 
2339 	    cur->set_parameters(byname, cnt);
2340 
2341       } else if (overrides && overrides->by_order) {
2342 
2343 	    cur->set_parameters(overrides->by_order);
2344       }
2345 
2346       if (pform_cur_generate) {
2347 	    add_local_symbol(pform_cur_generate, name, cur);
2348 	    pform_cur_generate->add_gate(cur);
2349       } else {
2350 	    add_local_symbol(pform_cur_module.front(), name, cur);
2351 	    pform_cur_module.front()->add_gate(cur);
2352       }
2353       pform_bind_attributes(cur->attributes, attr);
2354 }
2355 
pform_make_modgates(const struct vlltype & loc,perm_string type,struct parmvalue_t * overrides,svector<lgate> * gates,std::list<named_pexpr_t> * attr)2356 void pform_make_modgates(const struct vlltype&loc,
2357 			 perm_string type,
2358 			 struct parmvalue_t*overrides,
2359 			 svector<lgate>*gates,
2360 			 std::list<named_pexpr_t>*attr)
2361 {
2362 	// The grammer should not allow module gates to happen outside
2363 	// an active module. But if really bad input errors combine in
2364 	// an ugly way with error recovery, then catch this
2365 	// implausible situation and return an error.
2366       if (pform_cur_module.empty()) {
2367 	    cerr << loc << ": internal error: "
2368 		 << "Module instantiations outside module scope are not possible."
2369 		 << endl;
2370 	    error_count += 1;
2371 	    delete gates;
2372 	    return;
2373       }
2374       assert(! pform_cur_module.empty());
2375 
2376 	// Detect some more realistic errors.
2377 
2378       if (pform_cur_module.front()->program_block) {
2379 	    cerr << loc << ": error: Module instantiations are not allowed in "
2380 		 << "program blocks." << endl;
2381 	    error_count += 1;
2382       }
2383       if (pform_cur_module.front()->is_interface) {
2384 	    cerr << loc << ": error: Module instantiations are not allowed in "
2385 		 << "interfaces." << endl;
2386 	    error_count += 1;
2387       }
2388 
2389       for (unsigned idx = 0 ;  idx < gates->count() ;  idx += 1) {
2390 	    lgate cur = (*gates)[idx];
2391 	    perm_string cur_name = lex_strings.make(cur.name);
2392 
2393 	    if (cur.parms_by_name) {
2394 		  pform_make_modgate(type, cur_name, overrides,
2395 				     cur.parms_by_name,
2396 				     cur.range.first, cur.range.second,
2397 				     cur.file, cur.lineno, attr);
2398 
2399 	    } else if (cur.parms) {
2400 
2401 		    /* If there are no parameters, the parser will be
2402 		       tricked into thinking it is one empty
2403 		       parameter. This fixes that. */
2404 		  if ((cur.parms->size() == 1) && (cur.parms->front() == 0)) {
2405 			delete cur.parms;
2406 			cur.parms = new list<PExpr*>;
2407 		  }
2408 		  pform_make_modgate(type, cur_name, overrides,
2409 				     cur.parms,
2410 				     cur.range.first, cur.range.second,
2411 				     cur.file, cur.lineno, attr);
2412 
2413 	    } else {
2414 		  list<PExpr*>*wires = new list<PExpr*>;
2415 		  pform_make_modgate(type, cur_name, overrides,
2416 				     wires,
2417 				     cur.range.first, cur.range.second,
2418 				     cur.file, cur.lineno, attr);
2419 	    }
2420       }
2421 
2422       delete gates;
2423 }
2424 
pform_make_pgassign(PExpr * lval,PExpr * rval,list<PExpr * > * del,struct str_pair_t str)2425 static PGAssign* pform_make_pgassign(PExpr*lval, PExpr*rval,
2426 			      list<PExpr*>*del,
2427 			      struct str_pair_t str)
2428 {
2429         /* Implicit declaration of nets on the LHS of a continuous
2430            assignment was introduced in IEEE1364-2001. */
2431       if (generation_flag != GN_VER1995)
2432             pform_declare_implicit_nets(lval);
2433 
2434       list<PExpr*>*wires = new list<PExpr*>;
2435       wires->push_back(lval);
2436       wires->push_back(rval);
2437 
2438       PGAssign*cur;
2439 
2440       if (del == 0)
2441 	    cur = new PGAssign(wires);
2442       else
2443 	    cur = new PGAssign(wires, del);
2444 
2445       cur->strength0(str.str0);
2446       cur->strength1(str.str1);
2447 
2448       if (pform_cur_generate)
2449 	    pform_cur_generate->add_gate(cur);
2450       else
2451 	    pform_cur_module.front()->add_gate(cur);
2452 
2453       return cur;
2454 }
2455 
pform_make_pgassign_list(list<PExpr * > * alist,list<PExpr * > * del,struct str_pair_t str,const char * fn,unsigned lineno)2456 void pform_make_pgassign_list(list<PExpr*>*alist,
2457 			      list<PExpr*>*del,
2458 			      struct str_pair_t str,
2459 			      const char* fn,
2460 			      unsigned lineno)
2461 {
2462       assert(alist->size() % 2 == 0);
2463       while (! alist->empty()) {
2464 	    PExpr*lval = alist->front(); alist->pop_front();
2465 	    PExpr*rval = alist->front(); alist->pop_front();
2466 	    PGAssign*tmp = pform_make_pgassign(lval, rval, del, str);
2467 	    FILE_NAME(tmp, fn, lineno);
2468       }
2469 }
2470 
2471 /*
2472  * This function makes the initial assignment to a variable as given
2473  * in the source. It handles the case where a variable is assigned
2474  * where it is declared, e.g.
2475  *
2476  *    reg foo = <expr>;
2477  *
2478  * In Verilog-2001 this is only supported at the module level, and is
2479  * equivalent to the combination of statements:
2480  *
2481  *    reg foo;
2482  *    initial foo = <expr>;
2483  *
2484  * In SystemVerilog, variable initializations are allowed in any scope.
2485  * For static variables, initializations are performed before the start
2486  * of simulation. For automatic variables, initializations are performed
2487  * each time the enclosing block is entered. Here we store the variable
2488  * assignments in the current scope, and later elaboration creates an
2489  * initialization block that will be executed at the appropriate time.
2490  *
2491  * This syntax is not part of the IEEE1364-1995 standard, but is
2492  * approved by OVI as enhancement BTF-B14.
2493  */
pform_make_var_init(const struct vlltype & li,perm_string name,PExpr * expr)2494 void pform_make_var_init(const struct vlltype&li,
2495 			 perm_string name, PExpr*expr)
2496 {
2497       if (! pform_at_module_level() && !gn_system_verilog()) {
2498 	    VLerror(li, "error: variable declaration assignments are only "
2499                         "allowed at the module level.");
2500 	    delete expr;
2501 	    return;
2502       }
2503 
2504       PWire*cur = pform_get_wire_in_scope(name);
2505       if (cur == 0) {
2506 	    VLerror(li, "internal error: var_init to non-register?");
2507 	    delete expr;
2508 	    return;
2509       }
2510 
2511       PEIdent*lval = new PEIdent(name);
2512       FILE_NAME(lval, li);
2513       PAssign*ass = new PAssign(lval, expr, !gn_system_verilog());
2514       FILE_NAME(ass, li);
2515 
2516       lexical_scope->var_inits.push_back(ass);
2517 }
2518 
2519 /*
2520  * This function is used by the parser when I have port definition of
2521  * the form like this:
2522  *
2523  *     input wire signed [7:0] nm;
2524  *
2525  * The port_type, type, signed_flag and range are known all at once,
2526  * so we can create the PWire object all at once instead of piecemeal
2527  * as is done for the old method.
2528  */
pform_module_define_port(const struct vlltype & li,perm_string name,NetNet::PortType port_kind,NetNet::Type type,data_type_t * vtype,list<named_pexpr_t> * attr,bool keep_attr)2529 void pform_module_define_port(const struct vlltype&li,
2530 			      perm_string name,
2531 			      NetNet::PortType port_kind,
2532 			      NetNet::Type type,
2533 			      data_type_t*vtype,
2534 			      list<named_pexpr_t>*attr,
2535 			      bool keep_attr)
2536 {
2537       struct_type_t*struct_type = 0;
2538       ivl_variable_type_t data_type = IVL_VT_NO_TYPE;
2539       bool signed_flag = false;
2540 
2541       PWire*cur = pform_get_wire_in_scope(name);
2542       if (cur) {
2543 	    ostringstream msg;
2544 	    msg << name << " definition conflicts with "
2545 		<< "definition at " << cur->get_fileline()
2546 		<< ".";
2547 	    VLerror(msg.str().c_str());
2548 	    return;
2549       }
2550 
2551 	// Packed ranges
2552       list<pform_range_t>*prange = 0;
2553 	// Unpacked dimensions
2554       list<pform_range_t>*urange = 0;
2555 
2556 	// If this is an unpacked array, then split out the parts that
2557 	// we can send to the PWire object that we create.
2558       if (uarray_type_t*uarr_type = dynamic_cast<uarray_type_t*> (vtype)) {
2559 	    urange = uarr_type->dims.get();
2560 	    vtype = uarr_type->base_type;
2561       }
2562 
2563       if (vector_type_t*vec_type = dynamic_cast<vector_type_t*> (vtype)) {
2564 	    data_type = vec_type->base_type;
2565 	    signed_flag = vec_type->signed_flag;
2566 	    prange = vec_type->pdims.get();
2567 	    if (vec_type->reg_flag)
2568 		  type = NetNet::REG;
2569 
2570       } else if (atom2_type_t*atype = dynamic_cast<atom2_type_t*>(vtype)) {
2571 	    data_type = IVL_VT_BOOL;
2572 	    signed_flag = atype->signed_flag;
2573 	    prange = make_range_from_width(atype->type_code);
2574 
2575       } else if (real_type_t*rtype = dynamic_cast<real_type_t*>(vtype)) {
2576 	    data_type = IVL_VT_REAL;
2577 	    signed_flag = true;
2578 	    prange = 0;
2579 
2580 	    if (rtype->type_code != real_type_t::REAL) {
2581 		  VLerror(li, "sorry: Only real (not shortreal) supported here (%s:%d).",
2582 			  __FILE__, __LINE__);
2583 	    }
2584 
2585       } else if ((struct_type = dynamic_cast<struct_type_t*>(vtype))) {
2586 	    data_type = struct_type->figure_packed_base_type();
2587 	    signed_flag = false;
2588 	    prange = 0;
2589 
2590       } else if (enum_type_t*enum_type = dynamic_cast<enum_type_t*>(vtype)) {
2591 	    data_type = enum_type->base_type;
2592 	    signed_flag = enum_type->signed_flag;
2593 	    prange = enum_type->range.get();
2594 
2595       } else if (vtype) {
2596 	    VLerror(li, "sorry: Given type %s not supported here (%s:%d).",
2597 		    typeid(*vtype).name(), __FILE__, __LINE__);
2598       }
2599 
2600 
2601 	// The default type for all flavor of ports is LOGIC.
2602       if (data_type == IVL_VT_NO_TYPE)
2603 	    data_type = IVL_VT_LOGIC;
2604 
2605       cur = new PWire(name, type, port_kind, data_type);
2606       FILE_NAME(cur, li);
2607 
2608       cur->set_signed(signed_flag);
2609 
2610       if (struct_type) {
2611 	    cur->set_data_type(struct_type);
2612 
2613       } else if (prange == 0) {
2614 	    cur->set_range_scalar((type == NetNet::IMPLICIT) ? SR_PORT : SR_BOTH);
2615 
2616       } else {
2617 	    cur->set_range(*prange, (type == NetNet::IMPLICIT) ? SR_PORT : SR_BOTH);
2618       }
2619 
2620       if (urange) {
2621 	    cur->set_unpacked_idx(*urange);
2622       }
2623 
2624       pform_bind_attributes(cur->attributes, attr, keep_attr);
2625       pform_put_wire_in_scope(name, cur);
2626 }
2627 
pform_module_define_port(const struct vlltype & li,list<pform_port_t> * ports,NetNet::PortType port_kind,NetNet::Type type,data_type_t * vtype,list<named_pexpr_t> * attr)2628 void pform_module_define_port(const struct vlltype&li,
2629 			      list<pform_port_t>*ports,
2630 			      NetNet::PortType port_kind,
2631 			      NetNet::Type type,
2632 			      data_type_t*vtype,
2633 			      list<named_pexpr_t>*attr)
2634 {
2635       for (list<pform_port_t>::iterator cur = ports->begin()
2636 		 ; cur != ports->end() ; ++ cur ) {
2637 
2638 	    data_type_t*use_type = vtype;
2639 	    if (cur->udims)
2640 		  use_type = new uarray_type_t(vtype, cur->udims);
2641 
2642 	    pform_module_define_port(li, cur->name, port_kind, type, use_type,
2643 				     attr, true);
2644 	    if (cur->udims)
2645 		  delete use_type;
2646 
2647 	    if (cur->expr)
2648 		  pform_make_var_init(li, cur->name, cur->expr);
2649       }
2650 
2651       delete ports;
2652       delete attr;
2653 }
2654 
2655 /*
2656  * This function makes a single signal (a wire, a reg, etc) as
2657  * requested by the parser. The name is unscoped, so I attach the
2658  * current scope to it (with the scoped_name function) and I try to
2659  * resolve it with an existing PWire in the scope.
2660  *
2661  * The wire might already exist because of an implicit declaration in
2662  * a module port, i.e.:
2663  *
2664  *     module foo (bar...
2665  *
2666  *         reg bar;
2667  *
2668  * The output (or other port direction indicator) may or may not have
2669  * been seen already, so I do not do any checking with it yet. But I
2670  * do check to see if the name has already been declared, as this
2671  * function is called for every declaration.
2672  */
2673 
pform_get_or_make_wire(const vlltype & li,perm_string name,NetNet::Type type,NetNet::PortType ptype,ivl_variable_type_t dtype)2674 static PWire* pform_get_or_make_wire(const vlltype&li, perm_string name,
2675 			      NetNet::Type type, NetNet::PortType ptype,
2676 			      ivl_variable_type_t dtype)
2677 {
2678       PWire*cur = pform_get_wire_in_scope(name);
2679 
2680 	// If the wire already exists but isn't yet fully defined,
2681 	// carry on adding details.
2682       if (cur && (cur->get_data_type() == IVL_VT_NO_TYPE ||
2683                   cur->get_wire_type() == NetNet::IMPLICIT) ) {
2684 	      // If this is not implicit ("implicit" meaning we don't
2685 	      // know what the type is yet) then set the type now.
2686 	    if (type != NetNet::IMPLICIT) {
2687 		  bool rc = cur->set_wire_type(type);
2688 		  if (rc == false) {
2689 			ostringstream msg;
2690 			msg << name << " " << type
2691 			    << " definition conflicts with " << cur->get_wire_type()
2692 			    << " definition at " << cur->get_fileline()
2693 			    << ".";
2694 			VLerror(msg.str().c_str());
2695 		  }
2696 		  FILE_NAME(cur, li.text, li.first_line);
2697 	    }
2698 	    return cur;
2699       }
2700 
2701 	// If the wire already exists and is fully defined, this
2702 	// must be a redeclaration. Start again with a new wire.
2703 	// The error will be reported when we add the new wire
2704 	// to the scope. Do not delete the old wire - it will
2705 	// remain in the local symbol map.
2706 
2707       cur = new PWire(name, type, ptype, dtype);
2708       FILE_NAME(cur, li.text, li.first_line);
2709 
2710       pform_put_wire_in_scope(name, cur);
2711 
2712       return cur;
2713 }
2714 
2715 /*
2716  * this is the basic form of pform_makewire. This takes a single simple
2717  * name, port type, net type, data type, and attributes, and creates
2718  * the variable/net. Other forms of pform_makewire ultimately call
2719  * this one to create the wire and stash it.
2720  */
pform_makewire(const vlltype & li,perm_string name,NetNet::Type type,NetNet::PortType pt,ivl_variable_type_t dt,list<named_pexpr_t> * attr)2721 void pform_makewire(const vlltype&li, perm_string name,
2722 		    NetNet::Type type, NetNet::PortType pt,
2723 		    ivl_variable_type_t dt,
2724 		    list<named_pexpr_t>*attr)
2725 {
2726       PWire*cur = pform_get_or_make_wire(li, name, type, pt, dt);
2727 
2728       if (! cur) {
2729 	    cur = new PWire(name, type, pt, dt);
2730 	    FILE_NAME(cur, li.text, li.first_line);
2731       }
2732 
2733       bool flag;
2734       switch (dt) {
2735 	  case IVL_VT_REAL:
2736 	    flag = cur->set_data_type(dt);
2737 	    if (flag == false) {
2738 		  cerr << cur->get_fileline() << ": internal error: "
2739 		       << " wire data type handling mismatch. Cannot change "
2740 		       << cur->get_data_type()
2741 		       << " to " << dt << "." << endl;
2742 	    }
2743 	    ivl_assert(*cur, flag);
2744 	    cur->set_range_scalar(SR_NET);
2745 	    cur->set_signed(true);
2746 	    break;
2747 	  default:
2748 	    break;
2749       }
2750 
2751       if (attr) {
2752 	    for (list<named_pexpr_t>::iterator attr_cur = attr->begin()
2753 		       ; attr_cur != attr->end() ;  ++attr_cur) {
2754 		  cur->attributes[attr_cur->name] = attr_cur->parm;
2755 	    }
2756       }
2757 }
2758 
2759 /*
2760  * This form takes a list of names and some type information, and
2761  * generates a bunch of variables/nets. We use the basic
2762  * pform_makewire above.
2763  */
pform_makewire(const vlltype & li,list<pform_range_t> * range,bool signed_flag,list<perm_string> * names,NetNet::Type type,NetNet::PortType pt,ivl_variable_type_t dt,list<named_pexpr_t> * attr,PWSRType rt)2764 void pform_makewire(const vlltype&li,
2765 		    list<pform_range_t>*range,
2766 		    bool signed_flag,
2767 		    list<perm_string>*names,
2768 		    NetNet::Type type,
2769 		    NetNet::PortType pt,
2770 		    ivl_variable_type_t dt,
2771 		    list<named_pexpr_t>*attr,
2772 		    PWSRType rt)
2773 {
2774       for (list<perm_string>::iterator cur = names->begin()
2775 		 ; cur != names->end() ; ++ cur ) {
2776 	    perm_string txt = *cur;
2777 	    pform_makewire(li, txt, type, pt, dt, attr);
2778 	    /* This has already been done for real variables. */
2779 	    if (dt != IVL_VT_REAL) {
2780 		  pform_set_net_range(txt, type, range, signed_flag, dt, rt, 0);
2781 	    }
2782       }
2783 
2784       delete names;
2785       delete range;
2786       delete attr;
2787 }
2788 
2789 /*
2790  * This form makes nets with delays and continuous assignments.
2791  */
pform_makewire(const vlltype & li,list<PExpr * > * delay,str_pair_t str,net_decl_assign_t * decls,NetNet::Type type,data_type_t * data_type)2792 void pform_makewire(const vlltype&li,
2793 		    list<PExpr*>*delay,
2794 		    str_pair_t str,
2795 		    net_decl_assign_t*decls,
2796 		    NetNet::Type type,
2797 		    data_type_t*data_type)
2798 {
2799 	// The decls pointer is a circularly linked list.
2800       net_decl_assign_t*first = decls->next;
2801 
2802       list<perm_string>*names = new list<perm_string>;
2803 
2804 	// Go through the circularly linked list non-destructively.
2805       do {
2806 	    pform_makewire(li, first->name, type, NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, 0);
2807 	    names->push_back(first->name);
2808 	    first = first->next;
2809       } while (first != decls->next);
2810 
2811 	// The pform_set_data_type function will delete the names list.
2812       pform_set_data_type(li, data_type, names, type, 0);
2813 
2814 	// This time, go through the list, deleting cells as I'm done.
2815       first = decls->next;
2816       decls->next = 0;
2817       while (first) {
2818 	    net_decl_assign_t*next = first->next;
2819 	    PWire*cur = pform_get_wire_in_scope(first->name);
2820 	    if (cur != 0) {
2821 		  PEIdent*lval = new PEIdent(first->name);
2822 		  FILE_NAME(lval, li.text, li.first_line);
2823 		  PGAssign*ass = pform_make_pgassign(lval, first->expr,
2824 						     delay, str);
2825 		  FILE_NAME(ass, li.text, li.first_line);
2826 	    }
2827 
2828 	    delete first;
2829 	    first = next;
2830       }
2831 }
2832 
2833 /*
2834  * This should eventually replace the form above that takes a
2835  * net_decl_assign_t argument.
2836  */
pform_makewire(const struct vlltype & li,std::list<PExpr * > * delay,str_pair_t str,std::list<decl_assignment_t * > * assign_list,NetNet::Type type,data_type_t * data_type)2837 void pform_makewire(const struct vlltype&li,
2838 		    std::list<PExpr*>*delay,
2839 		    str_pair_t str,
2840 		    std::list<decl_assignment_t*>*assign_list,
2841 		    NetNet::Type type,
2842 		    data_type_t*data_type)
2843 {
2844       if (is_compilation_unit(lexical_scope) && !gn_system_verilog()) {
2845 	    VLerror(li, "error: variable declarations must be contained within a module.");
2846 	    return;
2847       }
2848 
2849       list<perm_string>*names = new list<perm_string>;
2850 
2851       for (list<decl_assignment_t*>::iterator cur = assign_list->begin()
2852 		 ; cur != assign_list->end() ; ++ cur) {
2853 	    decl_assignment_t* curp = *cur;
2854 	    pform_makewire(li, curp->name, type, NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, 0);
2855 	    pform_set_reg_idx(curp->name, &curp->index);
2856 	    names->push_back(curp->name);
2857       }
2858 
2859       pform_set_data_type(li, data_type, names, type, 0);
2860 
2861       while (! assign_list->empty()) {
2862 	    decl_assignment_t*first = assign_list->front();
2863 	    assign_list->pop_front();
2864             if (PExpr*expr = first->expr.release()) {
2865                   if (type == NetNet::REG || type == NetNet::IMPLICIT_REG) {
2866                         pform_make_var_init(li, first->name, expr);
2867                   } else {
2868 		        PEIdent*lval = new PEIdent(first->name);
2869 		        FILE_NAME(lval, li.text, li.first_line);
2870 		        PGAssign*ass = pform_make_pgassign(lval, expr, delay, str);
2871 		        FILE_NAME(ass, li.text, li.first_line);
2872                   }
2873             }
2874 	    delete first;
2875       }
2876 }
2877 
2878 /*
2879  * This function is called by the parser to create task ports. The
2880  * resulting wire (which should be a register) is put into a list to
2881  * be packed into the task parameter list.
2882  *
2883  * It is possible that the wire (er, register) was already created,
2884  * but we know that if the name matches it is a part of the current
2885  * task, so in that case I just assign direction to it.
2886  *
2887  * The following example demonstrates some of the issues:
2888  *
2889  *   task foo;
2890  *      input a;
2891  *      reg a, b;
2892  *      input b;
2893  *      [...]
2894  *   endtask
2895  *
2896  * This function is called when the parser matches the "input a" and
2897  * the "input b" statements. For ``a'', this function is called before
2898  * the wire is declared as a register, so I create the foo.a
2899  * wire. For ``b'', I will find that there is already a foo.b and I
2900  * just set the port direction. In either case, the ``reg a, b''
2901  * statement is caught by the block_item non-terminal and processed
2902  * there.
2903  *
2904  * Ports are implicitly type reg, because it must be possible for the
2905  * port to act as an l-value in a procedural assignment. It is obvious
2906  * for output and inout ports that the type is reg, because the task
2907  * only contains behavior (no structure) to a procedural assignment is
2908  * the *only* way to affect the output. It is less obvious for input
2909  * ports, but in practice an input port receives its value as if by a
2910  * procedural assignment from the calling behavior.
2911  *
2912  * This function also handles the input ports of function
2913  * definitions. Input ports to function definitions have the same
2914  * constraints as those of tasks, so this works fine. Functions have
2915  * no output or inout ports.
2916  */
pform_make_task_ports(const struct vlltype & loc,NetNet::PortType pt,ivl_variable_type_t vtype,bool signed_flag,list<pform_range_t> * range,list<perm_string> * names,bool isint)2917 vector<pform_tf_port_t>*pform_make_task_ports(const struct vlltype&loc,
2918 				     NetNet::PortType pt,
2919 				     ivl_variable_type_t vtype,
2920 				     bool signed_flag,
2921 				     list<pform_range_t>*range,
2922 				     list<perm_string>*names,
2923 				     bool isint)
2924 {
2925       assert(pt != NetNet::PIMPLICIT && pt != NetNet::NOT_A_PORT);
2926       assert(names);
2927       vector<pform_tf_port_t>*res = new vector<pform_tf_port_t>(0);
2928       for (list<perm_string>::iterator cur = names->begin()
2929 		 ; cur != names->end() ; ++ cur ) {
2930 
2931 	    perm_string name = *cur;
2932 
2933 	      /* Look for a preexisting wire. If it exists, set the
2934 		 port direction. If not, create it. */
2935 	    PWire*curw = pform_get_wire_in_scope(name);
2936 	    if (curw) {
2937 		  curw->set_port_type(pt);
2938 	    } else {
2939 		  curw = new PWire(name, NetNet::IMPLICIT_REG, pt, vtype);
2940 		  FILE_NAME(curw, loc);
2941 		  pform_put_wire_in_scope(name, curw);
2942 	    }
2943 
2944 	    curw->set_signed(signed_flag);
2945 		if (isint) {
2946 			bool flag = curw->set_wire_type(NetNet::INTEGER);
2947 			assert(flag);
2948 		}
2949 
2950 	      /* If there is a range involved, it needs to be set. */
2951 	    if (range) {
2952 		  curw->set_range(*range, SR_PORT);
2953 	    }
2954 
2955 	    res->push_back(pform_tf_port_t(curw));
2956       }
2957 
2958       delete range;
2959       return res;
2960 }
2961 
do_make_task_ports(const struct vlltype & loc,NetNet::PortType pt,ivl_variable_type_t var_type,data_type_t * data_type,list<perm_string> * names)2962 static vector<pform_tf_port_t>*do_make_task_ports(const struct vlltype&loc,
2963 					 NetNet::PortType pt,
2964 					 ivl_variable_type_t var_type,
2965 					 data_type_t*data_type,
2966 					 list<perm_string>*names)
2967 {
2968       assert(pt != NetNet::PIMPLICIT && pt != NetNet::NOT_A_PORT);
2969       assert(names);
2970       vector<pform_tf_port_t>*res = new vector<pform_tf_port_t>(0);
2971 
2972       for (list<perm_string>::iterator cur = names->begin()
2973 		 ; cur != names->end() ; ++cur) {
2974 	    perm_string name = *cur;
2975 	    PWire*curw = pform_get_wire_in_scope(name);
2976 	    if (curw) {
2977 		  curw->set_port_type(pt);
2978 	    } else {
2979 		  curw = new PWire(name, NetNet::IMPLICIT_REG, pt, var_type);
2980 		  FILE_NAME(curw, loc);
2981 		  curw->set_data_type(data_type);
2982 		  pform_put_wire_in_scope(name, curw);
2983 	    }
2984 
2985 	    res->push_back(pform_tf_port_t(curw));
2986       }
2987       return res;
2988 }
2989 
pform_make_task_ports(const struct vlltype & loc,NetNet::PortType pt,data_type_t * vtype,list<perm_string> * names)2990 vector<pform_tf_port_t>*pform_make_task_ports(const struct vlltype&loc,
2991 				      NetNet::PortType pt,
2992 				      data_type_t*vtype,
2993 				      list<perm_string>*names)
2994 {
2995       vector<pform_tf_port_t>*ret = NULL;
2996       std::list<pform_range_t>*unpacked_dims = NULL;
2997 
2998       if (uarray_type_t*uarray = dynamic_cast<uarray_type_t*> (vtype)) {
2999             unpacked_dims = uarray->dims.get();
3000             vtype = uarray->base_type;
3001       }
3002 
3003       if (atom2_type_t*atype = dynamic_cast<atom2_type_t*> (vtype)) {
3004 	    list<pform_range_t>*range_tmp = make_range_from_width(atype->type_code);
3005 	    ret = pform_make_task_ports(loc, pt, IVL_VT_BOOL,
3006 					 atype->signed_flag,
3007 					 range_tmp, names);
3008       }
3009 
3010       if (vector_type_t*vec_type = dynamic_cast<vector_type_t*> (vtype)) {
3011 	    ret = pform_make_task_ports(loc, pt, vec_type->base_type,
3012 					 vec_type->signed_flag,
3013 					 copy_range(vec_type->pdims.get()),
3014 					 names, vec_type->integer_flag);
3015       }
3016 
3017       if (/*real_type_t*real_type = */ dynamic_cast<real_type_t*> (vtype)) {
3018 	    ret = pform_make_task_ports(loc, pt, IVL_VT_REAL,
3019 					 true, 0, names);
3020       }
3021 
3022       if (dynamic_cast<string_type_t*> (vtype)) {
3023 	    ret = pform_make_task_ports(loc, pt, IVL_VT_STRING,
3024 					 false, 0, names);
3025       }
3026 
3027       if (class_type_t*class_type = dynamic_cast<class_type_t*> (vtype)) {
3028 	    ret = do_make_task_ports(loc, pt, IVL_VT_CLASS, class_type, names);
3029       }
3030 
3031       if (! ret) {
3032 	    ret = do_make_task_ports(loc, pt, IVL_VT_NO_TYPE, vtype, names);
3033       }
3034 
3035       if (unpacked_dims) {
3036 	    for (list<perm_string>::iterator cur = names->begin()
3037                     ; cur != names->end() ; ++ cur ) {
3038 		PWire*wire = pform_get_wire_in_scope(*cur);
3039 		wire->set_unpacked_idx(*unpacked_dims);
3040 	    }
3041       }
3042 
3043       delete names;
3044       return ret;
3045 }
3046 
3047 /*
3048  * The parser calls this in the rule that matches increment/decrement
3049  * statements. The rule that does the matching creates a PEUnary with
3050  * all the information we need, but here we convert that expression to
3051  * a compressed assignment statement.
3052  */
pform_compressed_assign_from_inc_dec(const struct vlltype & loc,PExpr * exp)3053 PAssign* pform_compressed_assign_from_inc_dec(const struct vlltype&loc, PExpr*exp)
3054 {
3055       PEUnary*expu = dynamic_cast<PEUnary*> (exp);
3056       ivl_assert(*exp, expu != 0);
3057 
3058       char use_op = 0;
3059       switch (expu->get_op()) {
3060 	  case 'i':
3061 	  case 'I':
3062 	    use_op = '+';
3063 	    break;
3064 	  case 'd':
3065 	  case 'D':
3066 	    use_op = '-';
3067 	    break;
3068 	  default:
3069 	    ivl_assert(*exp, 0);
3070 	    break;
3071       }
3072 
3073       PExpr*lval = expu->get_expr();
3074       PExpr*rval = new PENumber(new verinum((uint64_t)1, 1));
3075       FILE_NAME(rval, loc);
3076 
3077       PAssign*tmp = new PAssign(lval, use_op, rval);
3078       FILE_NAME(tmp, loc);
3079 
3080       delete exp;
3081       return tmp;
3082 }
3083 
pform_genvar_inc_dec(const struct vlltype & loc,const char * name,bool inc_flag)3084 PExpr* pform_genvar_inc_dec(const struct vlltype&loc, const char*name, bool inc_flag)
3085 {
3086       if (!gn_system_verilog()) {
3087 	    cerr << loc << ": error: Increment/decrement operators "
3088 		    "require SystemVerilog." << endl;
3089 	    error_count += 1;
3090       }
3091 
3092       PExpr*lval = new PEIdent(lex_strings.make(name));
3093       PExpr*rval = new PENumber(new verinum((uint64_t)1, 1));
3094       FILE_NAME(lval, loc);
3095       FILE_NAME(rval, loc);
3096 
3097       PEBinary*tmp = new PEBinary(inc_flag ? '+' : '-', lval, rval);
3098       FILE_NAME(tmp, loc);
3099 
3100       return tmp;
3101 }
3102 
pform_set_attrib(perm_string name,perm_string key,char * value)3103 void pform_set_attrib(perm_string name, perm_string key, char*value)
3104 {
3105       if (PWire*cur = lexical_scope->wires_find(name)) {
3106 	    cur->attributes[key] = new PEString(value);
3107 
3108       } else if (PGate*curg = pform_cur_module.front()->get_gate(name)) {
3109 	    curg->attributes[key] = new PEString(value);
3110 
3111       } else {
3112 	    delete[] value;
3113 	    VLerror("Unable to match name for setting attribute.");
3114 
3115       }
3116 }
3117 
3118 /*
3119  * Set the attribute of a TYPE. This is different from an object in
3120  * that this applies to every instantiation of the given type.
3121  */
pform_set_type_attrib(perm_string name,const string & key,char * value)3122 void pform_set_type_attrib(perm_string name, const string&key,
3123 			   char*value)
3124 {
3125       map<perm_string,PUdp*>::const_iterator udp = pform_primitives.find(name);
3126       if (udp == pform_primitives.end()) {
3127 	    VLerror("type name is not (yet) defined.");
3128 	    delete[] value;
3129 	    return;
3130       }
3131 
3132       (*udp).second ->attributes[key] = new PEString(value);
3133 }
3134 
3135 /*
3136  * This function attaches a memory index range to an existing
3137  * register. (The named wire must be a register.
3138  */
pform_set_reg_idx(perm_string name,list<pform_range_t> * indices)3139 void pform_set_reg_idx(perm_string name, list<pform_range_t>*indices)
3140 {
3141       PWire*cur = lexical_scope->wires_find(name);
3142       if (cur == 0) {
3143 	    VLerror("internal error: name is not a valid memory for index.");
3144 	    return;
3145       }
3146 
3147       if (indices && !indices->empty())
3148 	    cur->set_unpacked_idx(*indices);
3149 }
3150 
pform_parameter_value_range(bool exclude_flag,bool low_open,PExpr * low_expr,bool hig_open,PExpr * hig_expr)3151 LexicalScope::range_t* pform_parameter_value_range(bool exclude_flag,
3152 					     bool low_open, PExpr*low_expr,
3153 					     bool hig_open, PExpr*hig_expr)
3154 {
3155 	// Detect +-inf and make the the *_open flags false to force
3156 	// the range interpretation as inf.
3157       if (low_expr == 0) low_open = false;
3158       if (hig_expr == 0) hig_open = false;
3159 
3160       LexicalScope::range_t*tmp = new LexicalScope::range_t;
3161       tmp->exclude_flag = exclude_flag;
3162       tmp->low_open_flag = low_open;
3163       tmp->low_expr = low_expr;
3164       tmp->high_open_flag = hig_open;
3165       tmp->high_expr = hig_expr;
3166       tmp->next = 0;
3167       return tmp;
3168 }
3169 
pform_set_parameter(const struct vlltype & loc,perm_string name,ivl_variable_type_t type,bool signed_flag,list<pform_range_t> * range,PExpr * expr,LexicalScope::range_t * value_range)3170 void pform_set_parameter(const struct vlltype&loc,
3171 			 perm_string name, ivl_variable_type_t type,
3172 			 bool signed_flag, list<pform_range_t>*range, PExpr*expr,
3173 			 LexicalScope::range_t*value_range)
3174 {
3175       LexicalScope*scope = lexical_scope;
3176       if (is_compilation_unit(scope) && !gn_system_verilog()) {
3177 	    VLerror(loc, "error: parameter declarations must be contained within a module.");
3178 	    return;
3179       }
3180       if (scope == pform_cur_generate) {
3181             VLerror("parameter declarations are not permitted in generate blocks");
3182             return;
3183       }
3184 
3185       assert(expr);
3186       Module::param_expr_t*parm = new Module::param_expr_t();
3187       FILE_NAME(parm, loc);
3188 
3189       add_local_symbol(scope, name, parm);
3190       scope->parameters[name] = parm;
3191 
3192       parm->expr = expr;
3193 
3194       parm->type = type;
3195       if (range) {
3196 	    assert(range->size() == 1);
3197 	    pform_range_t&rng = range->front();
3198 	    assert(rng.first);
3199 	    assert(rng.second);
3200 	    parm->msb = rng.first;
3201 	    parm->lsb = rng.second;
3202       } else {
3203 	    parm->msb = 0;
3204 	    parm->lsb = 0;
3205       }
3206       parm->signed_flag = signed_flag;
3207       parm->range = value_range;
3208 
3209 	// Only a Module keeps the position of the parameter.
3210       if ((dynamic_cast<Module*>(scope)) && (scope == pform_cur_module.front()))
3211             pform_cur_module.front()->param_names.push_back(name);
3212 }
3213 
pform_set_localparam(const struct vlltype & loc,perm_string name,ivl_variable_type_t type,bool signed_flag,list<pform_range_t> * range,PExpr * expr)3214 void pform_set_localparam(const struct vlltype&loc,
3215 			  perm_string name, ivl_variable_type_t type,
3216 			  bool signed_flag, list<pform_range_t>*range, PExpr*expr)
3217 {
3218       LexicalScope*scope = lexical_scope;
3219       if (is_compilation_unit(scope) && !gn_system_verilog()) {
3220 	    VLerror(loc, "error: localparam declarations must be contained within a module.");
3221 	    return;
3222       }
3223 
3224       assert(expr);
3225       Module::param_expr_t*parm = new Module::param_expr_t();
3226       FILE_NAME(parm, loc);
3227 
3228       add_local_symbol(scope, name, parm);
3229       scope->localparams[name] = parm;
3230 
3231       parm->expr = expr;
3232 
3233       parm->type = type;
3234       if (range) {
3235 	    assert(range->size() == 1);
3236 	    pform_range_t&rng = range->front();
3237 	    assert(rng.first);
3238 	    assert(rng.second);
3239 	    parm->msb = rng.first;
3240 	    parm->lsb = rng.second;
3241       } else {
3242 	    parm->msb  = 0;
3243 	    parm->lsb  = 0;
3244       }
3245       parm->signed_flag = signed_flag;
3246       parm->range = 0;
3247 }
3248 
pform_set_specparam(const struct vlltype & loc,perm_string name,list<pform_range_t> * range,PExpr * expr)3249 void pform_set_specparam(const struct vlltype&loc, perm_string name,
3250 			 list<pform_range_t>*range, PExpr*expr)
3251 {
3252       assert(! pform_cur_module.empty());
3253       Module*scope = pform_cur_module.front();
3254       assert(scope == lexical_scope);
3255 
3256       assert(expr);
3257       Module::param_expr_t*parm = new Module::param_expr_t();
3258       FILE_NAME(parm, loc);
3259 
3260       add_local_symbol(scope, name, parm);
3261       pform_cur_module.front()->specparams[name] = parm;
3262 
3263       parm->expr = expr;
3264 
3265       if (range) {
3266 	    assert(range->size() == 1);
3267 	    pform_range_t&rng = range->front();
3268 	    assert(rng.first);
3269 	    assert(rng.second);
3270 	    parm->type = IVL_VT_LOGIC;
3271 	    parm->msb = rng.first;
3272 	    parm->lsb = rng.second;
3273       } else {
3274 	    parm->type = IVL_VT_NO_TYPE;
3275 	    parm->msb  = 0;
3276 	    parm->lsb  = 0;
3277       }
3278       parm->signed_flag = false;
3279       parm->range = 0;
3280 }
3281 
pform_set_defparam(const pform_name_t & name,PExpr * expr)3282 void pform_set_defparam(const pform_name_t&name, PExpr*expr)
3283 {
3284       assert(expr);
3285       if (pform_cur_generate)
3286             pform_cur_generate->defparms.push_back(make_pair(name,expr));
3287       else
3288             pform_cur_module.front()->defparms.push_back(make_pair(name,expr));
3289 }
3290 
pform_set_param_from_type(const struct vlltype & loc,const data_type_t * data_type,const char * name,list<pform_range_t> * & param_range,bool & param_signed,ivl_variable_type_t & param_type)3291 void pform_set_param_from_type(const struct vlltype&loc,
3292                                const data_type_t *data_type,
3293                                const char *name,
3294                                list<pform_range_t> *&param_range,
3295                                bool &param_signed,
3296                                ivl_variable_type_t &param_type)
3297 {
3298       if (const vector_type_t *vec = dynamic_cast<const vector_type_t*> (data_type)) {
3299 	    param_range = vec->pdims.get();
3300 	    param_signed = vec->signed_flag;
3301 	    param_type = vec->base_type;
3302 	    return;
3303       }
3304 
3305       param_range = 0;
3306       param_signed = false;
3307       param_type = IVL_VT_NO_TYPE;
3308       cerr << loc.get_fileline() << ": sorry: cannot currently create a "
3309               "parameter of type '" << name << "' which was defined at: "
3310            << data_type->get_fileline() <<  "." << endl;
3311       error_count += 1;
3312 }
3313 /*
3314  * Specify paths.
3315  */
pform_make_specify_path(const struct vlltype & li,list<perm_string> * src,char pol,bool full_flag,list<perm_string> * dst)3316 extern PSpecPath* pform_make_specify_path(const struct vlltype&li,
3317 					  list<perm_string>*src, char pol,
3318 					  bool full_flag, list<perm_string>*dst)
3319 {
3320       PSpecPath*path = new PSpecPath(src->size(), dst->size(), pol, full_flag);
3321       FILE_NAME(path, li.text, li.first_line);
3322 
3323       unsigned idx;
3324       list<perm_string>::const_iterator cur;
3325 
3326       idx = 0;
3327       for (idx = 0, cur = src->begin() ;  cur != src->end() ;  ++ idx, ++ cur) {
3328 	    path->src[idx] = *cur;
3329       }
3330       assert(idx == path->src.size());
3331       delete src;
3332 
3333       for (idx = 0, cur = dst->begin() ;  cur != dst->end() ;  ++ idx, ++ cur) {
3334 	    path->dst[idx] = *cur;
3335       }
3336       assert(idx == path->dst.size());
3337       delete dst;
3338 
3339       return path;
3340 }
3341 
pform_make_specify_edge_path(const struct vlltype & li,int edge_flag,list<perm_string> * src,char pol,bool full_flag,list<perm_string> * dst,PExpr * data_source_expression)3342 extern PSpecPath*pform_make_specify_edge_path(const struct vlltype&li,
3343 					 int edge_flag, /*posedge==true */
3344 					 list<perm_string>*src, char pol,
3345 					 bool full_flag, list<perm_string>*dst,
3346 					 PExpr*data_source_expression)
3347 {
3348       PSpecPath*tmp = pform_make_specify_path(li, src, pol, full_flag, dst);
3349       tmp->edge = edge_flag;
3350       tmp->data_source_expression = data_source_expression;
3351       return tmp;
3352 }
3353 
pform_assign_path_delay(PSpecPath * path,list<PExpr * > * del)3354 extern PSpecPath* pform_assign_path_delay(PSpecPath*path, list<PExpr*>*del)
3355 {
3356       if (path == 0)
3357 	    return 0;
3358 
3359       assert(path->delays.empty());
3360 
3361       path->delays.resize(del->size());
3362       for (unsigned idx = 0 ;  idx < path->delays.size() ;  idx += 1) {
3363 	    path->delays[idx] = del->front();
3364 	    del->pop_front();
3365       }
3366 
3367       delete del;
3368 
3369       return path;
3370 }
3371 
3372 
pform_module_specify_path(PSpecPath * obj)3373 extern void pform_module_specify_path(PSpecPath*obj)
3374 {
3375       if (obj == 0)
3376 	    return;
3377       pform_cur_module.front()->specify_paths.push_back(obj);
3378 }
3379 
3380 
pform_set_port_type(perm_string name,NetNet::PortType pt,const char * file,unsigned lineno)3381 static void pform_set_port_type(perm_string name, NetNet::PortType pt,
3382 				const char*file, unsigned lineno)
3383 {
3384       PWire*cur = pform_get_wire_in_scope(name);
3385       if (cur == 0) {
3386 	    cur = new PWire(name, NetNet::IMPLICIT, NetNet::PIMPLICIT, IVL_VT_NO_TYPE);
3387 	    FILE_NAME(cur, file, lineno);
3388 	    pform_put_wire_in_scope(name, cur);
3389       }
3390 
3391       switch (cur->get_port_type()) {
3392 	  case NetNet::PIMPLICIT:
3393 	    if (! cur->set_port_type(pt))
3394 		  VLerror("error setting port direction.");
3395 	    break;
3396 
3397 	  case NetNet::NOT_A_PORT:
3398 	    cerr << file << ":" << lineno << ": error: "
3399 		 << "port " << name << " is not in the port list."
3400 		 << endl;
3401 	    error_count += 1;
3402 	    break;
3403 
3404 	  default:
3405 	    cerr << file << ":" << lineno << ": error: "
3406 		 << "port " << name << " already has a port declaration."
3407 		 << endl;
3408 	    error_count += 1;
3409 	    break;
3410       }
3411 
3412 }
3413 
pform_set_port_type(const struct vlltype & li,list<pform_port_t> * ports,NetNet::PortType pt,data_type_t * dt,list<named_pexpr_t> * attr)3414 void pform_set_port_type(const struct vlltype&li,
3415 			 list<pform_port_t>*ports,
3416 			 NetNet::PortType pt,
3417 			 data_type_t*dt,
3418 			 list<named_pexpr_t>*attr)
3419 {
3420       assert(pt != NetNet::PIMPLICIT && pt != NetNet::NOT_A_PORT);
3421 
3422       list<pform_range_t>*range = 0;
3423       bool signed_flag = false;
3424       if (vector_type_t*vt = dynamic_cast<vector_type_t*> (dt)) {
3425 	    assert(vt->implicit_flag);
3426 	    range = vt->pdims.get();
3427 	    signed_flag = vt->signed_flag;
3428       } else {
3429 	    assert(dt == 0);
3430       }
3431 
3432       bool have_init_expr = false;
3433       for (list<pform_port_t>::iterator cur = ports->begin()
3434 		 ; cur != ports->end() ; ++ cur ) {
3435 
3436 	    pform_set_port_type(cur->name, pt, li.text, li.first_line);
3437 	    pform_set_net_range(cur->name, NetNet::NONE, range, signed_flag,
3438 				IVL_VT_NO_TYPE, SR_PORT, attr);
3439 	    if (cur->udims) {
3440 		  cerr << li.text << ":" << li.first_line << ": warning: "
3441 		       << "Array dimensions in incomplete port declarations "
3442 		       << "are currently ignored." << endl;
3443 		  cerr << li.text << ":" << li.first_line << ":        : "
3444 		       << "The dimensions specified in the net or variable "
3445 		       << "declaration will be used." << endl;
3446 		  delete cur->udims;
3447 	    }
3448 	    if (cur->expr) {
3449 		  have_init_expr = true;
3450 		  delete cur->expr;
3451 	    }
3452       }
3453       if (have_init_expr) {
3454 	    cerr << li.text << ":" << li.first_line << ": error: "
3455 		 << "Incomplete port declarations cannot be initialized."
3456 		 << endl;
3457 	    error_count += 1;
3458       }
3459 
3460       delete ports;
3461       delete dt;
3462       delete attr;
3463 }
3464 
pform_set_integer_2atom(const struct vlltype & li,uint64_t width,bool signed_flag,perm_string name,NetNet::Type net_type,list<named_pexpr_t> * attr)3465 static void pform_set_integer_2atom(const struct vlltype&li, uint64_t width, bool signed_flag, perm_string name, NetNet::Type net_type, list<named_pexpr_t>*attr)
3466 {
3467       PWire*cur = pform_get_make_wire_in_scope(li, name, net_type, NetNet::NOT_A_PORT, IVL_VT_BOOL);
3468       assert(cur);
3469 
3470       cur->set_signed(signed_flag);
3471 
3472       pform_range_t rng;
3473       rng.first = new PENumber(new verinum(width-1, integer_width));
3474       rng.second = new PENumber(new verinum((uint64_t)0, integer_width));
3475       list<pform_range_t>rlist;
3476       rlist.push_back(rng);
3477       cur->set_range(rlist, SR_NET);
3478       pform_bind_attributes(cur->attributes, attr, true);
3479 }
3480 
pform_set_integer_2atom(const struct vlltype & li,uint64_t width,bool signed_flag,list<perm_string> * names,NetNet::Type net_type,list<named_pexpr_t> * attr)3481 static void pform_set_integer_2atom(const struct vlltype&li, uint64_t width, bool signed_flag, list<perm_string>*names, NetNet::Type net_type, list<named_pexpr_t>*attr)
3482 {
3483       for (list<perm_string>::iterator cur = names->begin()
3484 		 ; cur != names->end() ; ++ cur ) {
3485 	    perm_string txt = *cur;
3486 	    pform_set_integer_2atom(li, width, signed_flag, txt, net_type, attr);
3487       }
3488 }
3489 
pform_set2_data_type(const struct vlltype & li,T * data_type,perm_string name,NetNet::Type net_type,list<named_pexpr_t> * attr)3490 template <class T> static void pform_set2_data_type(const struct vlltype&li, T*data_type, perm_string name, NetNet::Type net_type, list<named_pexpr_t>*attr)
3491 {
3492       ivl_variable_type_t base_type = data_type->figure_packed_base_type();
3493       if (base_type == IVL_VT_NO_TYPE) {
3494 	    VLerror(li, "Compound type is not PACKED in this context.");
3495       }
3496 
3497       PWire*net = pform_get_make_wire_in_scope(li, name, net_type, NetNet::NOT_A_PORT, base_type);
3498       assert(net);
3499       pform_bind_attributes(net->attributes, attr, true);
3500 }
3501 
pform_set2_data_type(const struct vlltype & li,T * data_type,list<perm_string> * names,NetNet::Type net_type,list<named_pexpr_t> * attr)3502 template <class T> static void pform_set2_data_type(const struct vlltype&li, T*data_type, list<perm_string>*names, NetNet::Type net_type, list<named_pexpr_t>*attr)
3503 {
3504       for (list<perm_string>::iterator cur = names->begin()
3505 		 ; cur != names->end() ; ++ cur) {
3506 	    pform_set2_data_type(li, data_type, *cur, net_type, attr);
3507       }
3508 }
3509 
pform_set_enum(const struct vlltype & li,enum_type_t * enum_type,perm_string name,NetNet::Type net_type,std::list<named_pexpr_t> * attr)3510 static void pform_set_enum(const struct vlltype&li, enum_type_t*enum_type,
3511 			   perm_string name, NetNet::Type net_type,
3512 			   std::list<named_pexpr_t>*attr)
3513 {
3514       PWire*cur = pform_get_make_wire_in_scope(li, name, net_type, NetNet::NOT_A_PORT, enum_type->base_type);
3515       assert(cur);
3516 
3517       cur->set_signed(enum_type->signed_flag);
3518 
3519       assert(enum_type->range.get() != 0);
3520       assert(enum_type->range->size() == 1);
3521 	//XXXXcur->set_range(*enum_type->range, SR_NET);
3522 	// If this is an integer enumeration switch the wire to an integer.
3523       if (enum_type->integer_flag) {
3524 	    bool res = cur->set_wire_type(NetNet::INTEGER);
3525 	    assert(res);
3526       }
3527       pform_bind_attributes(cur->attributes, attr, true);
3528 }
3529 
pform_set_enum(const struct vlltype & li,enum_type_t * enum_type,list<perm_string> * names,NetNet::Type net_type,std::list<named_pexpr_t> * attr)3530 static void pform_set_enum(const struct vlltype&li, enum_type_t*enum_type,
3531 			   list<perm_string>*names, NetNet::Type net_type,
3532 			   std::list<named_pexpr_t>*attr)
3533 {
3534 	// By definition, the base type can only be IVL_VT_LOGIC or
3535 	// IVL_VT_BOOL.
3536       assert(enum_type->base_type==IVL_VT_LOGIC || enum_type->base_type==IVL_VT_BOOL);
3537 
3538       assert(enum_type->range.get() != 0);
3539       assert(enum_type->range->size() == 1);
3540 
3541 	// Add the file and line information to the enumeration type.
3542       FILE_NAME(&(enum_type->li), li);
3543 
3544 	// If this is an anonymous enumeration, attach it to the current scope.
3545       if (enum_type->name.nil())
3546 	    pform_put_enum_type_in_scope(enum_type);
3547 
3548 	// Now apply the checked enumeration type to the variables
3549 	// that are being declared with this type.
3550       for (list<perm_string>::iterator cur = names->begin()
3551 		 ; cur != names->end() ; ++ cur) {
3552 	    perm_string txt = *cur;
3553 	    pform_set_enum(li, enum_type, txt, net_type, attr);
3554       }
3555 
3556 }
3557 
3558 /*
3559  * This function detects the derived class for the given type and
3560  * dispatches the type to the proper subtype function.
3561  */
pform_set_data_type(const struct vlltype & li,data_type_t * data_type,list<perm_string> * names,NetNet::Type net_type,list<named_pexpr_t> * attr)3562 void pform_set_data_type(const struct vlltype&li, data_type_t*data_type, list<perm_string>*names, NetNet::Type net_type, list<named_pexpr_t>*attr)
3563 {
3564       if (data_type == 0) {
3565 	    VLerror(li, "internal error: data_type==0.");
3566 	    assert(0);
3567       }
3568 
3569       uarray_type_t*uarray_type = dynamic_cast<uarray_type_t*> (data_type);
3570       if (uarray_type)
3571             data_type = uarray_type->base_type;
3572 
3573       if (atom2_type_t*atom2_type = dynamic_cast<atom2_type_t*> (data_type)) {
3574 	    pform_set_integer_2atom(li, atom2_type->type_code, atom2_type->signed_flag, names, net_type, attr);
3575       }
3576 
3577       else if (struct_type_t*struct_type = dynamic_cast<struct_type_t*> (data_type)) {
3578 	    pform_set_struct_type(li, struct_type, names, net_type, attr);
3579       }
3580 
3581       else if (enum_type_t*enum_type = dynamic_cast<enum_type_t*> (data_type)) {
3582 	    pform_set_enum(li, enum_type, names, net_type, attr);
3583       }
3584 
3585       else if (vector_type_t*vec_type = dynamic_cast<vector_type_t*> (data_type)) {
3586 	    if (net_type==NetNet::REG && vec_type->integer_flag)
3587 		  net_type=NetNet::INTEGER;
3588 
3589 	    pform_set_net_range(names, vec_type->pdims.get(),
3590 				vec_type->signed_flag,
3591 				vec_type->base_type, net_type, attr);
3592       }
3593 
3594       else if (/*real_type_t*real_type =*/ dynamic_cast<real_type_t*> (data_type)) {
3595 	    pform_set_net_range(names, 0, true, IVL_VT_REAL, net_type, attr);
3596       }
3597 
3598       else if (class_type_t*class_type = dynamic_cast<class_type_t*> (data_type)) {
3599 	    pform_set_class_type(li, class_type, names, net_type, attr);
3600       }
3601 
3602       else if (parray_type_t*array_type = dynamic_cast<parray_type_t*> (data_type)) {
3603 	    pform_set2_data_type(li, array_type, names, net_type, attr);
3604       }
3605 
3606       else if (string_type_t*string_type = dynamic_cast<string_type_t*> (data_type)) {
3607 	    pform_set_string_type(li, string_type, names, net_type, attr);
3608 
3609       } else {
3610 	    VLerror(li, "internal error: Unexpected data_type.");
3611 	    assert(0);
3612       }
3613 
3614       for (list<perm_string>::iterator cur = names->begin()
3615 	      ; cur != names->end() ; ++ cur ) {
3616 	    PWire*wire = pform_get_wire_in_scope(*cur);
3617 	    if (uarray_type) {
3618 		  wire->set_unpacked_idx(*uarray_type->dims.get());
3619 		  wire->set_uarray_type(uarray_type);
3620 	    }
3621 	    wire->set_data_type(data_type);
3622       }
3623 
3624       delete names;
3625 }
3626 
pform_make_udp_input_ports(list<perm_string> * names)3627 vector<PWire*>* pform_make_udp_input_ports(list<perm_string>*names)
3628 {
3629       vector<PWire*>*out = new vector<PWire*>(names->size());
3630 
3631       unsigned idx = 0;
3632       for (list<perm_string>::iterator cur = names->begin()
3633 		 ; cur != names->end() ; ++ cur ) {
3634 	    perm_string txt = *cur;
3635 	    PWire*pp = new PWire(txt,
3636 				 NetNet::IMPLICIT,
3637 				 NetNet::PINPUT,
3638 				 IVL_VT_LOGIC);
3639 	    (*out)[idx] = pp;
3640 	    idx += 1;
3641       }
3642 
3643       delete names;
3644       return out;
3645 }
3646 
pform_make_behavior(ivl_process_type_t type,Statement * st,list<named_pexpr_t> * attr)3647 PProcess* pform_make_behavior(ivl_process_type_t type, Statement*st,
3648 			      list<named_pexpr_t>*attr)
3649 {
3650 	// Add an implicit @* around the statement for the always_comb and
3651 	// always_latch statements.
3652       if ((type == IVL_PR_ALWAYS_COMB) || (type == IVL_PR_ALWAYS_LATCH)) {
3653 	    PEventStatement *tmp = new PEventStatement(true);
3654 	    tmp->set_file(st->get_file());
3655 	    tmp->set_lineno(st->get_lineno());
3656 	    tmp->set_statement(st);
3657 	    st = tmp;
3658       }
3659 
3660       PProcess*pp = new PProcess(type, st);
3661 
3662 	// If we are in a part of the code where the meta-comment
3663 	// synthesis translate_off is in effect, then implicitly add
3664 	// the ivl_synthesis_off attribute to any behavioral code that
3665 	// we run into.
3666       if (pform_mc_translate_flag == false) {
3667 	    if (attr == 0) attr = new list<named_pexpr_t>;
3668 	    named_pexpr_t tmp;
3669 	    tmp.name = perm_string::literal("ivl_synthesis_off");
3670 	    tmp.parm = 0;
3671 	    attr->push_back(tmp);
3672       }
3673 
3674       pform_bind_attributes(pp->attributes, attr);
3675 
3676       pform_put_behavior_in_scope(pp);
3677 
3678       ivl_assert(*st, ! pform_cur_module.empty());
3679       if (pform_cur_module.front()->program_block &&
3680           ((type == IVL_PR_ALWAYS) || (type == IVL_PR_ALWAYS_COMB) ||
3681            (type == IVL_PR_ALWAYS_FF) || (type == IVL_PR_ALWAYS_LATCH))) {
3682 	    cerr << st->get_fileline() << ": error: Always statements are not allowed"
3683 		 << " in program blocks." << endl;
3684 	    error_count += 1;
3685       }
3686 
3687       return pp;
3688 }
3689 
pform_start_modport_item(const struct vlltype & loc,const char * name)3690 void pform_start_modport_item(const struct vlltype&loc, const char*name)
3691 {
3692       Module*scope = pform_cur_module.front();
3693       ivl_assert(loc, scope && scope->is_interface);
3694       ivl_assert(loc, pform_cur_modport == 0);
3695 
3696       perm_string use_name = lex_strings.make(name);
3697       pform_cur_modport = new PModport(use_name);
3698       FILE_NAME(pform_cur_modport, loc);
3699 
3700       add_local_symbol(scope, use_name, pform_cur_modport);
3701       scope->modports[use_name] = pform_cur_modport;
3702 
3703       delete[] name;
3704 }
3705 
pform_end_modport_item(const struct vlltype & loc)3706 void pform_end_modport_item(const struct vlltype&loc)
3707 {
3708       ivl_assert(loc, pform_cur_modport);
3709       pform_cur_modport = 0;
3710 }
3711 
pform_add_modport_port(const struct vlltype & loc,NetNet::PortType port_type,perm_string name,PExpr * expr)3712 void pform_add_modport_port(const struct vlltype&loc,
3713                             NetNet::PortType port_type,
3714                             perm_string name, PExpr*expr)
3715 {
3716       ivl_assert(loc, pform_cur_modport);
3717 
3718       if (pform_cur_modport->simple_ports.find(name)
3719 	  != pform_cur_modport->simple_ports.end()) {
3720 	    cerr << loc << ": error: duplicate declaration of port '"
3721 		 << name << "' in modport list '"
3722 		 << pform_cur_modport->name() << "'." << endl;
3723 	    error_count += 1;
3724       }
3725       pform_cur_modport->simple_ports[name] = make_pair(port_type, expr);
3726 }
3727 
3728 
3729 FILE*vl_input = 0;
3730 extern void reset_lexor();
3731 
pform_parse(const char * path)3732 int pform_parse(const char*path)
3733 {
3734       vl_file = path;
3735       if (strcmp(path, "-") == 0) {
3736 	    vl_input = stdin;
3737       } else if (ivlpp_string) {
3738 	    char*cmdline = (char*)malloc(strlen(ivlpp_string) +
3739 					        strlen(path) + 4);
3740 	    strcpy(cmdline, ivlpp_string);
3741 	    strcat(cmdline, " \"");
3742 	    strcat(cmdline, path);
3743 	    strcat(cmdline, "\"");
3744 
3745 	    if (verbose_flag)
3746 		  cerr << "Executing: " << cmdline << endl<< flush;
3747 
3748 	    vl_input = popen(cmdline, "r");
3749 	    if (vl_input == 0) {
3750 		  cerr << "Unable to preprocess " << path << "." << endl;
3751 		  return 1;
3752 	    }
3753 
3754 	    if (verbose_flag)
3755 		  cerr << "...parsing output from preprocessor..." << endl << flush;
3756 
3757 	    free(cmdline);
3758       } else {
3759 	    vl_input = fopen(path, "r");
3760 	    if (vl_input == 0) {
3761 		  cerr << "Unable to open " << path << "." << endl;
3762 		  return 1;
3763 	    }
3764       }
3765 
3766       if (pform_units.empty() || separate_compilation) {
3767 	    char unit_name[20];
3768 	    static unsigned nunits = 0;
3769 	    if (separate_compilation)
3770 		  sprintf(unit_name, "$unit#%u", ++nunits);
3771 	    else
3772 		  sprintf(unit_name, "$unit");
3773 
3774 	    PPackage*unit = new PPackage(lex_strings.make(unit_name), 0);
3775 	    unit->default_lifetime = LexicalScope::STATIC;
3776 	    unit->set_file(filename_strings.make(path));
3777 	    unit->set_lineno(1);
3778 	    pform_units.push_back(unit);
3779 
3780             pform_cur_module.clear();
3781             pform_cur_generate = 0;
3782             pform_cur_modport = 0;
3783 
3784 	    pform_set_timescale(def_ts_units, def_ts_prec, 0, 0);
3785 
3786 	    allow_timeunit_decl = true;
3787 	    allow_timeprec_decl = true;
3788 
3789 	    lexical_scope = unit;
3790       }
3791       reset_lexor();
3792       error_count = 0;
3793       warn_count = 0;
3794       int rc = VLparse();
3795 
3796       if (vl_input != stdin) {
3797 	    if (ivlpp_string)
3798 		  pclose(vl_input);
3799 	    else
3800 		  fclose(vl_input);
3801       }
3802 
3803       if (rc) {
3804 	    cerr << "I give up." << endl;
3805 	    error_count += 1;
3806       }
3807 
3808       destroy_lexor();
3809       return error_count;
3810 }
3811