1 /*
2  * Copyright (c) 2000-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 # include  "compiler.h"
23 # include  "netmisc.h"
24 # include  <cstring>
25 # include  <iostream>
26 # include  <cstdlib>
27 # include  <cstdio>
28 
29 /*
30  * Elaboration happens in two passes, generally. The first scans the
31  * pform to generate the NetScope tree and attach it to the Design
32  * object. The methods in this source file implement the elaboration
33  * of the scopes.
34  */
35 
36 # include  "Module.h"
37 # include  "PClass.h"
38 # include  "PExpr.h"
39 # include  "PEvent.h"
40 # include  "PClass.h"
41 # include  "PGate.h"
42 # include  "PGenerate.h"
43 # include  "PPackage.h"
44 # include  "PTask.h"
45 # include  "PWire.h"
46 # include  "Statement.h"
47 # include  "AStatement.h"
48 # include  "netlist.h"
49 # include  "netclass.h"
50 # include  "netenum.h"
51 # include  "parse_api.h"
52 # include  "util.h"
53 # include  <typeinfo>
54 # include  <cassert>
55 # include  "ivl_assert.h"
56 
57 
set_scope_timescale(Design * des,NetScope * scope,PScope * pscope)58 void set_scope_timescale(Design*des, NetScope*scope, PScope*pscope)
59 {
60       scope->time_unit(pscope->time_unit);
61       scope->time_precision(pscope->time_precision);
62       scope->time_from_timescale(pscope->has_explicit_timescale());
63       des->set_precision(pscope->time_precision);
64 }
65 
66 typedef map<perm_string,LexicalScope::param_expr_t*>::const_iterator mparm_it_t;
67 
collect_parm_item_(Design * des,NetScope * scope,perm_string name,const LexicalScope::param_expr_t & cur,bool is_annotatable,bool local_flag)68 static void collect_parm_item_(Design*des, NetScope*scope, perm_string name,
69 			       const LexicalScope::param_expr_t&cur,
70                                bool is_annotatable,
71                                bool local_flag)
72 {
73       NetScope::range_t*range_list = 0;
74       for (LexicalScope::range_t*range = cur.range ; range ; range = range->next) {
75 	    NetScope::range_t*tmp = new NetScope::range_t;
76 	    tmp->exclude_flag = range->exclude_flag;
77 	    tmp->low_open_flag = range->low_open_flag;
78 	    tmp->high_open_flag = range->high_open_flag;
79 
80 	    if (range->low_expr) {
81 		  tmp->low_expr = elab_and_eval(des, scope, range->low_expr, -1);
82 		  ivl_assert(*range->low_expr, tmp->low_expr);
83 	    } else {
84 		  tmp->low_expr = 0;
85 	    }
86 
87 	    if (range->high_expr && range->high_expr==range->low_expr) {
88 		    // Detect the special case of a "point"
89 		    // range. These are called out by setting the high
90 		    // and low expression ranges to the same
91 		    // expression. The exclude_flags should be false
92 		    // in this case
93 		  ivl_assert(*range->high_expr, tmp->low_open_flag==false && tmp->high_open_flag==false);
94 		  tmp->high_expr = tmp->low_expr;
95 
96 	    } else if (range->high_expr) {
97 		  tmp->high_expr = elab_and_eval(des, scope, range->high_expr, -1);
98 		  ivl_assert(*range->high_expr, tmp->high_expr);
99 	    } else {
100 		  tmp->high_expr = 0;
101 	    }
102 
103 	    tmp->next = range_list;
104 	    range_list = tmp;
105       }
106 
107 
108       scope->set_parameter(name, is_annotatable, cur.expr, cur.type, cur.msb,
109 			   cur.lsb, cur.signed_flag, local_flag, range_list, cur);
110 }
111 
collect_scope_parameters_(Design * des,NetScope * scope,const map<perm_string,LexicalScope::param_expr_t * > & parameters)112 static void collect_scope_parameters_(Design*des, NetScope*scope,
113       const map<perm_string,LexicalScope::param_expr_t*>&parameters)
114 {
115       for (mparm_it_t cur = parameters.begin()
116 		 ; cur != parameters.end() ;  ++ cur ) {
117 
118 	    collect_parm_item_(des, scope, cur->first, *(cur->second), false, false);
119       }
120 }
121 
collect_scope_localparams_(Design * des,NetScope * scope,const map<perm_string,LexicalScope::param_expr_t * > & localparams)122 static void collect_scope_localparams_(Design*des, NetScope*scope,
123       const map<perm_string,LexicalScope::param_expr_t*>&localparams)
124 {
125       for (mparm_it_t cur = localparams.begin()
126 		 ; cur != localparams.end() ;  ++ cur ) {
127 
128 	    collect_parm_item_(des, scope, cur->first, *(cur->second), false, true);
129       }
130 }
131 
collect_scope_specparams_(Design * des,NetScope * scope,const map<perm_string,LexicalScope::param_expr_t * > & specparams)132 static void collect_scope_specparams_(Design*des, NetScope*scope,
133       const map<perm_string,LexicalScope::param_expr_t*>&specparams)
134 {
135       for (mparm_it_t cur = specparams.begin()
136 		 ; cur != specparams.end() ;  ++ cur ) {
137 
138 	    collect_parm_item_(des, scope, cur->first, *(cur->second), true, false);
139       }
140 }
141 
142 /*
143  * Elaborate the enumeration into the given scope.
144  */
elaborate_scope_enumeration(Design * des,NetScope * scope,enum_type_t * enum_type)145 static void elaborate_scope_enumeration(Design*des, NetScope*scope,
146 					enum_type_t*enum_type)
147 {
148       bool rc_flag;
149       assert(enum_type->range->size() == 1);
150       pform_range_t&range = enum_type->range->front();
151       NetExpr*msb_ex = elab_and_eval(des, scope, range.first, -1);
152       NetExpr*lsb_ex = elab_and_eval(des, scope, range.second, -1);
153 
154       long msb = 0;
155       rc_flag = eval_as_long(msb, msb_ex);
156       assert(rc_flag);
157       long lsb = 0;
158       rc_flag = eval_as_long(lsb, lsb_ex);
159       assert(rc_flag);
160 
161       netenum_t*use_enum = new netenum_t(enum_type->base_type,
162 					 enum_type->signed_flag,
163 					 enum_type->integer_flag, msb, lsb,
164 					 enum_type->names->size(),
165 					 enum_type);
166 
167       use_enum->set_line(enum_type->li);
168       scope->add_enumeration_set(enum_type, use_enum);
169 
170       size_t name_idx = 0;
171 	// Find the enumeration width.
172       long raw_width = use_enum->packed_width();
173       assert(raw_width > 0);
174       unsigned enum_width = (unsigned)raw_width;
175 	// Define the default start value and the increment value to be the
176 	// correct type for this enumeration.
177       verinum cur_value ((uint64_t)0, enum_width);
178       cur_value.has_sign(enum_type->signed_flag);
179       verinum one_value ((uint64_t)1, enum_width);
180       one_value.has_sign(enum_type->signed_flag);
181 	// Find the maximum allowed enumeration value.
182       verinum max_value (0);
183       if (enum_type->signed_flag) {
184 	    max_value = pow(verinum(2), verinum(enum_width-1)) - one_value;
185       } else {
186 	    max_value = pow(verinum(2), verinum(enum_width)) - one_value;
187       }
188       max_value.has_sign(enum_type->signed_flag);
189 	// Variable to indicate when a defined value wraps.
190       bool implicit_wrapped = false;
191 	// Process the enumeration definition.
192       for (list<named_pexpr_t>::const_iterator cur = enum_type->names->begin()
193 		 ; cur != enum_type->names->end() ;  ++ cur, name_idx += 1) {
194 	      // Check to see if the enumeration name has a value given.
195 	    if (cur->parm) {
196 		    // There is an explicit value. elaborate/evaluate
197 		    // the value and assign it to the enumeration name.
198 		  NetExpr*val = elab_and_eval(des, scope, cur->parm, -1);
199 		  NetEConst*val_const = dynamic_cast<NetEConst*> (val);
200 		  if (val_const == 0) {
201 			cerr << use_enum->get_fileline()
202 			     << ": error: Enumeration expression for "
203 			     << cur->name <<" is not an integer constant."
204 			     << endl;
205 			des->errors += 1;
206 			continue;
207 		  }
208 		  cur_value = val_const->value();
209 		    // Clear the implicit wrapped flag if a parameter is given.
210 		  implicit_wrapped = false;
211 
212 		    // A 2-state value can not have a constant with X/Z bits.
213 		  if (enum_type->base_type==IVL_VT_BOOL &&
214 		      ! cur_value.is_defined()) {
215 			cerr << use_enum->get_fileline()
216 			     << ": error: Enumeration name " << cur->name
217 			     << " can not have an undefined value." << endl;
218 			des->errors += 1;
219 		  }
220 		    // If this is a literal constant and it has a defined
221 		    // width then the width must match the enumeration width.
222 		  if (PENumber *tmp = dynamic_cast<PENumber*>(cur->parm)) {
223 			if (tmp->value().has_len() &&
224 			    (tmp->value().len() != enum_width)) {
225 			      cerr << use_enum->get_fileline()
226 			           << ": error: Enumeration name " << cur->name
227 			           << " has an incorrectly sized constant."
228 			           << endl;
229 			      des->errors += 1;
230 			}
231 		  }
232 
233 		    // If we are padding/truncating a negative value for an
234 		    // unsigned enumeration that is an error or if the new
235 		    // value does not have a defined width.
236 		  if (((cur_value.len() != enum_width) ||
237 		       ! cur_value.has_len()) &&
238 		      ! enum_type->signed_flag && cur_value.is_negative()) {
239 			cerr << use_enum->get_fileline()
240 			     << ": error: Enumeration name " << cur->name
241 			     << " has a negative value." << endl;
242 			des->errors += 1;
243 		  }
244 
245 		    // Narrower values need to be padded to the width of the
246 		    // enumeration and defined to have the specified width.
247 		  if (cur_value.len() < enum_width) {
248 			cur_value = pad_to_width(cur_value, enum_width);
249 		  }
250 
251 		    // Some wider values can be truncated.
252 		  if (cur_value.len() > enum_width) {
253 			unsigned check_width = enum_width - 1;
254 			  // Check that the upper bits match the MSB
255 			for (unsigned idx = enum_width;
256 			     idx < cur_value.len();
257 			     idx += 1) {
258 			      if (cur_value[idx] != cur_value[check_width]) {
259 				      // If this is an unsigned enumeration
260 				      // then zero padding is okay.
261 				    if (! enum_type->signed_flag &&
262 				        (idx == enum_width) &&
263 				        (cur_value[idx] == verinum::V0)) {
264 					  check_width += 1;
265 					  continue;
266 				    }
267 				    if (cur_value.is_defined()) {
268 					  cerr << use_enum->get_fileline()
269 					       << ": error: Enumeration name "
270 					       << cur->name
271 					       << " has a value that is too "
272 					       << ((cur_value > max_value) ?
273 					           "large" : "small")
274 					       << " " << cur_value << "."
275 					       << endl;
276 				    } else {
277 					  cerr << use_enum->get_fileline()
278 					       << ": error: Enumeration name "
279 					       << cur->name
280 					       << " has trimmed bits that do "
281 					       << "not match the enumeration "
282 					       << "MSB: " << cur_value << "."
283 					       << endl;
284 				    }
285 				    des->errors += 1;
286 				    break;
287 			      }
288 			}
289 			  // If this is an unsigned value then make sure
290 			  // The upper bits are not 1.
291 			if (! cur_value.has_sign() &&
292 			    (cur_value[enum_width] == verinum::V1)) {
293 			      cerr << use_enum->get_fileline()
294 			           << ": error: Enumeration name "
295 			           << cur->name
296 			           << " has a value that is too large: "
297 			           << cur_value << "." << endl;
298 			      des->errors += 1;
299 			      break;
300 			}
301 			cur_value = verinum(cur_value, enum_width);
302 		  }
303 
304 		    // At this point the value has the correct size and needs
305 		    // to have the correct sign attribute set.
306 		  cur_value.has_len(true);
307 		  cur_value.has_sign(enum_type->signed_flag);
308 
309 	    } else if (! cur_value.is_defined()) {
310 		  cerr << use_enum->get_fileline()
311 		       << ": error: Enumeration name " << cur->name
312 		       << " has an undefined inferred value." << endl;
313 		  des->errors += 1;
314 		  continue;
315 	    }
316 
317 	      // Check to see if an implicitly wrapped value is used.
318 	    if (implicit_wrapped) {
319 		  cerr << use_enum->get_fileline()
320 		       << ": error: Enumeration name " << cur->name
321 		       << " has an inferred value that overflowed." << endl;
322 		  des->errors += 1;
323 	    }
324 
325 	    // The enumeration value must be unique.
326 	    perm_string dup_name = use_enum->find_value(cur_value);
327 	    if (dup_name) {
328 		  cerr << use_enum->get_fileline()
329 		       << ": error: Enumeration name "
330 		       << cur->name << " and " << dup_name
331 		       << " have the same value: " << cur_value << endl;
332 		  des->errors += 1;
333 	    }
334 
335 	    rc_flag = use_enum->insert_name(name_idx, cur->name, cur_value);
336 	    rc_flag &= scope->add_enumeration_name(use_enum, cur->name);
337 
338 	    if (! rc_flag) {
339 		  cerr << use_enum->get_fileline()
340 		       << ": error: Duplicate enumeration name "
341 		       << cur->name << endl;
342 		  des->errors += 1;
343 	    }
344 
345 	      // In case the next name has an implicit value,
346 	      // increment the current value by one.
347 	    if (cur_value.is_defined()) {
348 		  if (cur_value == max_value) implicit_wrapped = true;
349 		  cur_value = cur_value + one_value;
350 	    }
351       }
352 
353       use_enum->insert_name_close();
354 }
355 
elaborate_scope_enumerations(Design * des,NetScope * scope,const set<enum_type_t * > & enum_types)356 static void elaborate_scope_enumerations(Design*des, NetScope*scope,
357 					 const set<enum_type_t*>&enum_types)
358 {
359       for (set<enum_type_t*>::const_iterator cur = enum_types.begin()
360 		 ; cur != enum_types.end() ; ++ cur) {
361 	    enum_type_t*curp = *cur;
362 	    elaborate_scope_enumeration(des, scope, curp);
363       }
364 }
365 
366 /*
367  * If the pclass includes an implicit and explicit constructor, then
368  * merge the implicit constructor into the explicit constructor as
369  * statements in the beginning.
370  *
371  * This is not necessary for proper functionality, it is an
372  * optimization, so we can easily give up if it doesn't seem like it
373  * will obviously work.
374  */
blend_class_constructors(PClass * pclass)375 static void blend_class_constructors(PClass*pclass)
376 {
377       perm_string new1 = perm_string::literal("new");
378       perm_string new2 = perm_string::literal("new@");
379 
380       PFunction*use_new;
381       PFunction*use_new2;
382 
383 	// Locate the explicit constructor.
384       map<perm_string,PFunction*>::iterator iter_new = pclass->funcs.find(new1);
385       if (iter_new == pclass->funcs.end())
386 	    use_new = 0;
387       else
388 	    use_new = iter_new->second;
389 
390 	// Locate the implicit constructor.
391       map<perm_string,PFunction*>::iterator iter_new2 = pclass->funcs.find(new2);
392       if (iter_new2 == pclass->funcs.end())
393 	    use_new2 = 0;
394       else
395 	    use_new2 = iter_new2->second;
396 
397 	// If there are no constructors, then we are done.
398       if (use_new==0 && use_new2==0)
399 	    return;
400 
401 	// While we're here, look for a super.new() call. If we find
402 	// it, strip it out of the constructor and set it aside for
403 	// when we actually call the chained constructor.
404       PChainConstructor*chain_new = use_new? use_new->extract_chain_constructor() : 0;
405 
406 	// If we do not have an explicit constructor chain, but there
407 	// is a parent class, then create an implicit chain.
408       if (chain_new==0 && pclass->type->base_type!=0) {
409 	    chain_new = new PChainConstructor(pclass->type->base_args);
410 	    chain_new->set_line(*pclass);
411       }
412 
413 	// If there are both an implicit and explicit constructor,
414 	// then blend the implicit constructor into the explicit
415 	// constructor. This eases the task for the elaborator later.
416       if (use_new && use_new2) {
417 	      // These constructors must be methods of the same class.
418 	    ivl_assert(*use_new, use_new->method_of() == use_new2->method_of());
419 
420 	    Statement*def_new = use_new->get_statement();
421 	    Statement*def_new2 = use_new2->get_statement();
422 
423 	      // It is possible, i.e. recovering from a parse error,
424 	      // for the statement from the constructor to be
425 	      // missing. In that case, create an empty one.
426 	    if (def_new==0) {
427 		  def_new = new PBlock(PBlock::BL_SEQ);
428 		  use_new->set_statement(def_new);
429 	    }
430 
431 	    if (def_new2) use_new->push_statement_front(def_new2);
432 
433 	      // Now the implicit initializations are all built into
434 	      // the constructor. Delete the "new@" constructor.
435 	    pclass->funcs.erase(iter_new2);
436 	    delete use_new2;
437 	    use_new2 = 0;
438       }
439 
440       if (chain_new) {
441 	    if (use_new2) {
442 		  use_new2->push_statement_front(chain_new);
443 	    } else {
444 		  use_new->push_statement_front(chain_new);
445 	    }
446 	    chain_new = 0;
447       }
448 }
449 
elaborate_scope_class(Design * des,NetScope * scope,PClass * pclass)450 static void elaborate_scope_class(Design*des, NetScope*scope, PClass*pclass)
451 {
452       class_type_t*use_type = pclass->type;
453 
454       if (debug_scopes) {
455 	    cerr << pclass->get_fileline() <<": elaborate_scope_class: "
456 		 << "Elaborate scope class " << pclass->pscope_name()
457 		 << " within scope " << scope_path(scope)
458 		 << endl;
459       }
460 
461       class_type_t*base_class = dynamic_cast<class_type_t*> (use_type->base_type);
462       if (use_type->base_type && !base_class) {
463 	    cerr << pclass->get_fileline() << ": error: "
464 		 << "Base type of " << use_type->name
465 		 << " is not a class." << endl;
466 	    des->errors += 1;
467       }
468 
469       netclass_t*use_base_class = 0;
470       if (base_class) {
471 	    use_base_class = scope->find_class(base_class->name);
472 	    if (use_base_class == 0) {
473 		  cerr << pclass->get_fileline() << ": error: "
474 		       << "Base class " << base_class->name
475 		       << " not found." << endl;
476 		  des->errors += 1;
477 	    }
478       }
479 
480       netclass_t*use_class = new netclass_t(use_type->name, use_base_class);
481 
482       ivl_assert(*pclass, use_type->save_elaborated_type == 0);
483       use_type->save_elaborated_type = use_class;
484 
485       NetScope*class_scope = new NetScope(scope, hname_t(pclass->pscope_name()),
486 					  NetScope::CLASS, scope->unit());
487       class_scope->set_line(pclass);
488       class_scope->set_class_def(use_class);
489       use_class->set_class_scope(class_scope);
490       use_class->set_definition_scope(scope);
491       set_scope_timescale(des, class_scope, pclass);
492 
493       class_scope->add_typedefs(&pclass->typedefs);
494 
495 	// Elaborate enum types declared in the class. We need these
496 	// now because enumeration constants can be used during scope
497 	// elaboration.
498       if (debug_scopes) {
499 	    cerr << pclass->get_fileline() << ": elaborate_scope_class: "
500 		 << "Elaborate " << pclass->enum_sets.size() << " enumerations"
501 		 << " in class " << scope_path(class_scope)
502 		 << ", scope=" << scope_path(scope) << "."
503 		 << endl;
504       }
505       elaborate_scope_enumerations(des, class_scope, pclass->enum_sets);
506 
507 	// Collect the properties, elaborate them, and add them to the
508 	// elaborated class definition.
509       for (map<perm_string, class_type_t::prop_info_t>::iterator cur = use_type->properties.begin()
510 		 ; cur != use_type->properties.end() ; ++ cur) {
511 
512 	    ivl_type_s*tmp = cur->second.type->elaborate_type(des, class_scope);
513 	    ivl_assert(*pclass, tmp);
514 	    if (debug_scopes) {
515 		  cerr << pclass->get_fileline() << ": elaborate_scope_class: "
516 		       << "  Property " << cur->first
517 		       << " type=" << *tmp << endl;
518 	    }
519 	    use_class->set_property(cur->first, cur->second.qual, tmp);
520 
521       }
522 
523       for (map<perm_string,PTask*>::iterator cur = pclass->tasks.begin()
524 		 ; cur != pclass->tasks.end() ; ++cur) {
525 
526 	    hname_t use_name (cur->first);
527 	    NetScope*method_scope = new NetScope(class_scope, use_name, NetScope::TASK);
528 	      // Task methods are always automatic...
529 	    method_scope->is_auto(true);
530 	    method_scope->set_line(cur->second);
531 	    method_scope->add_imports(&cur->second->explicit_imports);
532 
533 	    if (debug_scopes) {
534 		  cerr << cur->second->get_fileline() << ": elaborate_scope_class: "
535 		       << "Elaborate method (task) scope "
536 		       << scope_path(method_scope) << endl;
537 	    }
538 
539 	    cur->second->elaborate_scope(des, method_scope);
540       }
541 
542       for (map<perm_string,PFunction*>::iterator cur = pclass->funcs.begin()
543 		 ; cur != pclass->funcs.end() ; ++cur) {
544 
545 	    hname_t use_name (cur->first);
546 	    NetScope*method_scope = new NetScope(class_scope, use_name, NetScope::FUNC);
547 	      // Function methods are always automatic...
548 	    method_scope->is_auto(true);
549 	    method_scope->set_line(cur->second);
550 	    method_scope->add_imports(&cur->second->explicit_imports);
551 
552 	    if (debug_scopes) {
553 		  cerr << cur->second->get_fileline() << ": elaborate_scope_class: "
554 		       << "Elaborate method (function) scope "
555 		       << scope_path(method_scope) << endl;
556 	    }
557 
558 	    cur->second->elaborate_scope(des, method_scope);
559       }
560 
561       scope->add_class(use_class);
562 }
563 
elaborate_scope_classes(Design * des,NetScope * scope,const vector<PClass * > & classes)564 static void elaborate_scope_classes(Design*des, NetScope*scope,
565 				    const vector<PClass*>&classes)
566 {
567       for (size_t idx = 0 ; idx < classes.size() ; idx += 1) {
568 	    blend_class_constructors(classes[idx]);
569 	    elaborate_scope_class(des, scope, classes[idx]);
570       }
571 }
572 
replace_scope_parameters_(NetScope * scope,const LineInfo & loc,const Module::replace_t & replacements)573 static void replace_scope_parameters_(NetScope*scope, const LineInfo&loc,
574 			              const Module::replace_t&replacements)
575 {
576       for (Module::replace_t::const_iterator cur = replacements.begin()
577 		 ; cur != replacements.end() ;  ++ cur ) {
578 
579 	    PExpr*val = (*cur).second;
580 	    if (val == 0) {
581 		  cerr << loc.get_fileline() << ": internal error: "
582 		       << "Missing expression in parameter replacement for "
583 		       << (*cur).first << endl;;
584 	    }
585 	    assert(val);
586 	    if (debug_scopes) {
587 		  cerr << loc.get_fileline() << ": debug: "
588 		       << "Replace " << (*cur).first
589 		       << " with expression " << *val
590 		       << " from " << val->get_fileline() << "." << endl;
591 		  cerr << loc.get_fileline() << ":      : "
592 		       << "Type=" << val->expr_type() << endl;
593 	    }
594 	    bool flag = scope->replace_parameter((*cur).first, val,
595                                                  scope->parent());
596 	    if (! flag) {
597 		  cerr << val->get_fileline() << ": warning: parameter "
598 		       << (*cur).first << " not found in "
599 		       << scope_path(scope) << "." << endl;
600 	    }
601       }
602 }
603 
elaborate_scope_events_(Design * des,NetScope * scope,const map<perm_string,PEvent * > & events)604 static void elaborate_scope_events_(Design*des, NetScope*scope,
605                                     const map<perm_string,PEvent*>&events)
606 {
607       for (map<perm_string,PEvent*>::const_iterator et = events.begin()
608 		 ; et != events.end() ;  ++ et ) {
609 
610 	    (*et).second->elaborate_scope(des, scope);
611       }
612 }
613 
elaborate_scope_task(Design * des,NetScope * scope,PTask * task)614 static void elaborate_scope_task(Design*des, NetScope*scope, PTask*task)
615 {
616       hname_t use_name( task->pscope_name() );
617 
618       NetScope*task_scope = new NetScope(scope, use_name, NetScope::TASK);
619       task_scope->is_auto(task->is_auto());
620       task_scope->set_line(task);
621       task_scope->add_imports(&task->explicit_imports);
622 
623       if (debug_scopes) {
624 	    cerr << task->get_fileline() << ": elaborate_scope_task: "
625 		 << "Elaborate task scope " << scope_path(task_scope) << endl;
626       }
627 
628       task->elaborate_scope(des, task_scope);
629 }
630 
elaborate_scope_tasks(Design * des,NetScope * scope,const map<perm_string,PTask * > & tasks)631 static void elaborate_scope_tasks(Design*des, NetScope*scope,
632 				  const map<perm_string,PTask*>&tasks)
633 {
634       typedef map<perm_string,PTask*>::const_iterator tasks_it_t;
635 
636       for (tasks_it_t cur = tasks.begin()
637 		 ; cur != tasks.end() ;  ++ cur ) {
638 
639 	    elaborate_scope_task(des, scope, cur->second);
640       }
641 
642 }
643 
elaborate_scope_func(Design * des,NetScope * scope,PFunction * task)644 static void elaborate_scope_func(Design*des, NetScope*scope, PFunction*task)
645 {
646       hname_t use_name( task->pscope_name() );
647 
648       NetScope*task_scope = new NetScope(scope, use_name, NetScope::FUNC);
649       task_scope->is_auto(task->is_auto());
650       task_scope->set_line(task);
651       task_scope->add_imports(&task->explicit_imports);
652 
653       if (debug_scopes) {
654 	    cerr << task->get_fileline() << ": elaborate_scope_func: "
655 		 << "Elaborate task scope " << scope_path(task_scope) << endl;
656       }
657 
658       task->elaborate_scope(des, task_scope);
659 }
660 
elaborate_scope_funcs(Design * des,NetScope * scope,const map<perm_string,PFunction * > & funcs)661 static void elaborate_scope_funcs(Design*des, NetScope*scope,
662 				  const map<perm_string,PFunction*>&funcs)
663 {
664       typedef map<perm_string,PFunction*>::const_iterator funcs_it_t;
665 
666       for (funcs_it_t cur = funcs.begin()
667 		 ; cur != funcs.end() ;  ++ cur ) {
668 
669 	    elaborate_scope_func(des, scope, cur->second);
670       }
671 
672 }
673 
674 class generate_schemes_work_item_t : public elaborator_work_item_t {
675     public:
generate_schemes_work_item_t(Design * des__,NetScope * scope,Module * mod)676       generate_schemes_work_item_t(Design*des__, NetScope*scope, Module*mod)
677       : elaborator_work_item_t(des__), scope_(scope), mod_(mod)
678       { }
679 
elaborate_runrun()680       void elaborate_runrun()
681       {
682 	    if (debug_scopes)
683 		  cerr << mod_->get_fileline() << ": debug: "
684 		       << "Processing generate schemes for "
685 		       << scope_path(scope_) << endl;
686 
687 	      // Generate schemes can create new scopes in the form of
688 	      // generated code. Scan the generate schemes, and *generate*
689 	      // new scopes, which is slightly different from simple
690 	      // elaboration.
691 	    typedef list<PGenerate*>::const_iterator generate_it_t;
692 	    for (generate_it_t cur = mod_->generate_schemes.begin()
693 		       ; cur != mod_->generate_schemes.end() ; ++ cur ) {
694 		  (*cur) -> generate_scope(des, scope_);
695 	    }
696       }
697 
698     private:
699 	// The scope_ is the scope that contains the generate scheme
700 	// we are to work on. the mod_ is the Module definition for
701 	// that scope, and contains the parsed generate schemes.
702       NetScope*scope_;
703       Module*mod_;
704 };
705 
elaborate_scope(Design * des,NetScope * scope)706 bool PPackage::elaborate_scope(Design*des, NetScope*scope)
707 {
708       if (debug_scopes) {
709 	    cerr << get_fileline() << ": PPackage::elaborate_scope: "
710 		 << "Elaborate package " << scope_path(scope) << "." << endl;
711       }
712 
713       scope->add_typedefs(&typedefs);
714 
715       collect_scope_parameters_(des, scope, parameters);
716       collect_scope_localparams_(des, scope, localparams);
717 
718       if (debug_scopes) {
719 	    cerr << get_fileline() << ": PPackage::elaborate_scope: "
720 		 << "Elaborate " << enum_sets.size() << " enumerations"
721 		 << " in package scope " << scope_path(scope) << "."
722 		 << endl;
723       }
724       elaborate_scope_enumerations(des, scope, enum_sets);
725 
726       elaborate_scope_classes(des, scope, classes_lexical);
727       elaborate_scope_funcs(des, scope, funcs);
728       elaborate_scope_tasks(des, scope, tasks);
729       elaborate_scope_events_(des, scope, events);
730       return true;
731 }
732 
elaborate_scope(Design * des,NetScope * scope,const replace_t & replacements)733 bool Module::elaborate_scope(Design*des, NetScope*scope,
734 			     const replace_t&replacements)
735 {
736       if (debug_scopes) {
737 	    cerr << get_fileline() << ": Module::elaborate_scope: "
738 		 << "Elaborate " << scope_path(scope) << "." << endl;
739       }
740 
741       scope->add_typedefs(&typedefs);
742 
743 	// Add the genvars to the scope.
744       typedef map<perm_string,LineInfo*>::const_iterator genvar_it_t;
745       for (genvar_it_t cur = genvars.begin(); cur != genvars.end(); ++ cur ) {
746 	    scope->add_genvar((*cur).first, (*cur).second);
747       }
748 
749 	// Scan the parameters in the module, and store the information
750 	// needed to evaluate the parameter expressions. The expressions
751 	// will be evaluated later, once all parameter overrides for this
752 	// module have been done.
753 
754       collect_scope_parameters_(des, scope, parameters);
755 
756       collect_scope_localparams_(des, scope, localparams);
757 
758       collect_scope_specparams_(des, scope, specparams);
759 
760 	// Run parameter replacements that were collected from the
761 	// containing scope and meant for me.
762 
763       replace_scope_parameters_(scope, *this, replacements);
764 
765       if (debug_scopes) {
766 	    cerr << get_fileline() << ": Module::elaborate_scope: "
767 		 << "Elaborate " << enum_sets.size() << " enumerations"
768 		 << " in scope " << scope_path(scope) << "."
769 		 << endl;
770       }
771       elaborate_scope_enumerations(des, scope, enum_sets);
772 
773       assert(classes.size() == classes_lexical.size());
774       elaborate_scope_classes(des, scope, classes_lexical);
775 
776 	// Run through the defparams for this module and save the result
777 	// in a table for later final override.
778 
779       typedef list<Module::named_expr_t>::const_iterator defparms_iter_t;
780       for (defparms_iter_t cur = defparms.begin()
781 		 ; cur != defparms.end() ; ++ cur ) {
782 	    scope->defparams.push_back(make_pair(cur->first, cur->second));
783       }
784 
785 	// Evaluate the attributes. Evaluate them in the scope of the
786 	// module that the attribute is attached to. Is this correct?
787       unsigned nattr;
788       attrib_list_t*attr = evaluate_attributes(attributes, nattr, des, scope);
789 
790       for (unsigned idx = 0 ;  idx < nattr ;  idx += 1)
791 	    scope->attribute(attr[idx].key, attr[idx].val);
792 
793       delete[]attr;
794 
795 	// Generate schemes need to have their scopes elaborated, but
796 	// we can not do that until defparams are run, so push it off
797 	// into an elaborate work item.
798       if (debug_scopes)
799 	    cerr << get_fileline() << ": debug: "
800 		 << "Schedule generates within " << scope_path(scope)
801 		 << " for elaboration after defparams." << endl;
802 
803       des->elaboration_work_list.push_back(new generate_schemes_work_item_t(des, scope, this));
804 
805 	// Tasks introduce new scopes, so scan the tasks in this
806 	// module. Create a scope for the task and pass that to the
807 	// elaborate_scope method of the PTask for detailed
808 	// processing.
809 
810       elaborate_scope_tasks(des, scope, tasks);
811 
812 
813 	// Functions are very similar to tasks, at least from the
814 	// perspective of scopes. So handle them exactly the same
815 	// way.
816 
817       elaborate_scope_funcs(des, scope, funcs);
818 
819 	// Look for implicit modules and implicit gates for them.
820 
821       for (map<perm_string,Module*>::iterator cur = nested_modules.begin()
822 		 ; cur != nested_modules.end() ; ++cur) {
823 	      // Skip modules that must be explicitly instantiated.
824 	    if (cur->second->port_count() > 0)
825 		  continue;
826 
827 	    PGModule*nested_gate = new PGModule(cur->second, cur->second->mod_name());
828 	    nested_gate->set_line(*cur->second);
829 	    gates_.push_back(nested_gate);
830       }
831 
832 	// Gates include modules, which might introduce new scopes, so
833 	// scan all of them to create those scopes.
834 
835       typedef list<PGate*>::const_iterator gates_it_t;
836       for (gates_it_t cur = gates_.begin()
837 		 ; cur != gates_.end() ; ++ cur ) {
838 
839 	    (*cur) -> elaborate_scope(des, scope);
840       }
841 
842 
843 	// initial and always blocks may contain begin-end and
844 	// fork-join blocks that can introduce scopes. Therefore, I
845 	// get to scan processes here.
846 
847       typedef list<PProcess*>::const_iterator proc_it_t;
848 
849       for (proc_it_t cur = behaviors.begin()
850 		 ; cur != behaviors.end() ; ++ cur ) {
851 
852 	    (*cur) -> statement() -> elaborate_scope(des, scope);
853       }
854 
855 	// Scan through all the named events in this scope. We do not
856 	// need anything more than the current scope to do this
857 	// elaboration, so do it now. This allows for normal
858 	// elaboration to reference these events.
859 
860       elaborate_scope_events_(des, scope, events);
861 
862       scope->is_cell(is_cell);
863 
864       return des->errors == 0;
865 }
866 
generate_scope(Design * des,NetScope * container)867 bool PGenerate::generate_scope(Design*des, NetScope*container)
868 {
869       switch (scheme_type) {
870 	  case GS_LOOP:
871 	    return generate_scope_loop_(des, container);
872 
873 	  case GS_CONDIT:
874 	    return generate_scope_condit_(des, container, false);
875 
876 	  case GS_ELSE:
877 	    return generate_scope_condit_(des, container, true);
878 
879 	  case GS_CASE:
880 	    return generate_scope_case_(des, container);
881 
882 	  case GS_NBLOCK:
883 	    return generate_scope_nblock_(des, container);
884 
885 	  case GS_CASE_ITEM:
886 	    cerr << get_fileline() << ": internal error: "
887 		 << "Case item outside of a case generate scheme?" << endl;
888 	    return false;
889 
890 	  default:
891 	    cerr << get_fileline() << ": sorry: Generate of this sort"
892 		 << " is not supported yet!" << endl;
893 	    return false;
894       }
895 }
896 
897 /*
898  * This is the elaborate scope method for a generate loop.
899  */
generate_scope_loop_(Design * des,NetScope * container)900 bool PGenerate::generate_scope_loop_(Design*des, NetScope*container)
901 {
902       if (!local_index) {
903 	      // Check that the loop_index variable was declared in a
904 	      // genvar statement.
905 	    NetScope*cscope = container;
906 	    while (cscope && !cscope->find_genvar(loop_index))
907 		  cscope = cscope->parent();
908 	    if (!cscope) {
909 		  cerr << get_fileline() << ": error: genvar is missing for "
910 			  "generate \"loop\" variable '" << loop_index << "'."
911 		       << endl;
912 		  des->errors += 1;
913 		  return false;
914 	    }
915       }
916 
917 	// We're going to need a genvar...
918       int genvar;
919 
920 	// The initial value for the genvar does not need (nor can it
921 	// use) the genvar itself, so we can evaluate this expression
922 	// the same way any other parameter value is evaluated.
923       NetExpr*init_ex = elab_and_eval(des, container, loop_init, -1, true);
924       NetEConst*init = dynamic_cast<NetEConst*> (init_ex);
925       if (init == 0) {
926 	    cerr << get_fileline() << ": error: Cannot evaluate genvar"
927 		 << " init expression: " << *loop_init << endl;
928 	    des->errors += 1;
929 	    return false;
930       }
931 
932       genvar = init->value().as_long();
933       delete init_ex;
934 
935       if (debug_scopes)
936 	    cerr << get_fileline() << ": debug: genvar init = " << genvar << endl;
937       container->genvar_tmp = loop_index;
938       container->genvar_tmp_val = genvar;
939       NetExpr*test_ex = elab_and_eval(des, container, loop_test, -1, true);
940       NetEConst*test = dynamic_cast<NetEConst*>(test_ex);
941       if (test == 0) {
942 	    cerr << get_fileline() << ": error: Cannot evaluate genvar"
943 		 << " conditional expression: " << *loop_test << endl;
944 	    des->errors += 1;
945 	    return false;
946       }
947       while (test->value().as_long()) {
948 
949 	      // The actual name of the scope includes the genvar so
950 	      // that each instance has a unique name in the
951 	      // container. The format of using [] is part of the
952 	      // Verilog standard.
953 	    hname_t use_name (scope_name, genvar);
954 
955 	    if (debug_scopes)
956 		  cerr << get_fileline() << ": debug: "
957 		       << "Create generated scope " << use_name << endl;
958 
959 	    NetScope*scope = new NetScope(container, use_name,
960 					  NetScope::GENBLOCK);
961 	    scope->set_line(get_file(), get_lineno());
962 	    scope->add_imports(&explicit_imports);
963 
964 	      // Set in the scope a localparam for the value of the
965 	      // genvar within this instance of the generate
966 	      // block. Code within this scope thus has access to the
967 	      // genvar as a constant.
968 	    {
969 		  verinum genvar_verinum(genvar);
970 		  genvar_verinum.has_sign(true);
971 		  NetEConstParam*gp = new NetEConstParam(scope,
972 							 loop_index,
973 							 genvar_verinum);
974 		    // The file and line information should really come
975 		    // from the genvar statement, not the for loop.
976 		  scope->set_parameter(loop_index, gp, *this);
977 		  if (debug_scopes)
978 			cerr << get_fileline() << ": debug: "
979 			     << "Create implicit localparam "
980 			     << loop_index << " = " << genvar_verinum << endl;
981 	    }
982 
983 	    elaborate_subscope_(des, scope);
984 
985 	      // Calculate the step for the loop variable.
986 	    NetExpr*step_ex = elab_and_eval(des, container, loop_step, -1, true);
987 	    NetEConst*step = dynamic_cast<NetEConst*>(step_ex);
988 	    if (step == 0) {
989 		  cerr << get_fileline() << ": error: Cannot evaluate genvar"
990 		       << " step expression: " << *loop_step << endl;
991 		  des->errors += 1;
992 		  return false;
993 	    }
994 	    if (debug_scopes)
995 		  cerr << get_fileline() << ": debug: genvar step from "
996 		       << genvar << " to " << step->value().as_long() << endl;
997 
998 	    genvar = step->value().as_long();
999 	    container->genvar_tmp_val = genvar;
1000 	    delete step;
1001 	    delete test_ex;
1002 	    test_ex = elab_and_eval(des, container, loop_test, -1, true);
1003 	    test = dynamic_cast<NetEConst*>(test_ex);
1004 	    assert(test);
1005       }
1006 
1007 	// Clear the genvar_tmp field in the scope to reflect that the
1008 	// genvar is no longer valid for evaluating expressions.
1009       container->genvar_tmp = perm_string();
1010 
1011       return true;
1012 }
1013 
generate_scope_condit_(Design * des,NetScope * container,bool else_flag)1014 bool PGenerate::generate_scope_condit_(Design*des, NetScope*container, bool else_flag)
1015 {
1016       NetExpr*test_ex = elab_and_eval(des, container, loop_test, -1, true);
1017       NetEConst*test = dynamic_cast<NetEConst*> (test_ex);
1018       if (test == 0) {
1019 	    cerr << get_fileline() << ": error: Cannot evaluate genvar"
1020 		 << " conditional expression: " << *loop_test << endl;
1021 	    des->errors += 1;
1022 	    return false;
1023       }
1024 
1025 	// If the condition evaluates as false, then do not create the
1026 	// scope.
1027       if ( (test->value().as_long() == 0 && !else_flag)
1028 	|| (test->value().as_long() != 0 &&  else_flag) ) {
1029 	    if (debug_scopes)
1030 		  cerr << get_fileline() << ": debug: Generate condition "
1031 		       << (else_flag? "(else)" : "(if)")
1032 		       << " value=" << test->value() << ": skip generation"
1033 		       << endl;
1034 	    delete test_ex;
1035 	    return true;
1036       }
1037 
1038       hname_t use_name (scope_name);
1039       if (debug_scopes)
1040 	    cerr << get_fileline() << ": debug: Generate condition "
1041 		 << (else_flag? "(else)" : "(if)")
1042 		 << " value=" << test->value() << ": Generate scope="
1043 		 << use_name << endl;
1044 
1045       probe_for_direct_nesting_();
1046       if (direct_nested_) {
1047 	    if (debug_scopes)
1048 		  cerr << get_fileline() << ": debug: Generate condition "
1049 		       << (else_flag? "(else)" : "(if)")
1050 		       << " detected direct nesting." << endl;
1051 	    elaborate_subscope_direct_(des, container);
1052 	    return true;
1053       }
1054 
1055 	// If this is not directly nested, then generate a scope
1056 	// for myself. That is what I will pass to the subscope.
1057       NetScope*scope = new NetScope(container, use_name, NetScope::GENBLOCK);
1058       scope->set_line(get_file(), get_lineno());
1059       scope->add_imports(&explicit_imports);
1060 
1061       elaborate_subscope_(des, scope);
1062 
1063       return true;
1064 }
1065 
generate_scope_case_(Design * des,NetScope * container)1066 bool PGenerate::generate_scope_case_(Design*des, NetScope*container)
1067 {
1068       NetExpr*case_value_ex = elab_and_eval(des, container, loop_test, -1, true);
1069       NetEConst*case_value_co = dynamic_cast<NetEConst*>(case_value_ex);
1070       if (case_value_co == 0) {
1071 	    cerr << get_fileline() << ": error: Cannot evaluate genvar case"
1072 		 << " expression: " << *loop_test << endl;
1073 	    des->errors += 1;
1074 	    return false;
1075       }
1076 
1077       if (debug_scopes)
1078 	    cerr << get_fileline() << ": debug: Generate case "
1079 		 << "switch value=" << case_value_co->value() << endl;
1080 
1081       PGenerate*default_item = 0;
1082 
1083       typedef list<PGenerate*>::const_iterator generator_it_t;
1084       generator_it_t cur = generate_schemes.begin();
1085       while (cur != generate_schemes.end()) {
1086 	    PGenerate*item = *cur;
1087 	    assert( item->scheme_type == PGenerate::GS_CASE_ITEM );
1088 
1089 	      // Detect that the item is a default.
1090 	    if (item->item_test.size() == 0) {
1091 		  default_item = item;
1092 		  ++ cur;
1093 		  continue;
1094 	    }
1095 
1096 	    bool match_flag = false;
1097 	    for (unsigned idx = 0 ; idx < item->item_test.size() && !match_flag ; idx +=1 ) {
1098 		  NetExpr*item_value_ex = elab_and_eval(des, container,
1099                                                         item->item_test[idx],
1100                                                         -1, true);
1101 		  NetEConst*item_value_co = dynamic_cast<NetEConst*>(item_value_ex);
1102 		  if (item_value_co == 0) {
1103 			cerr << get_fileline() << ": error: Cannot evaluate "
1104 			     << " genvar case item expression: "
1105 			     << *item->item_test[idx] << endl;
1106 			des->errors += 1;
1107 			return false;
1108 		  }
1109 
1110 		  if (debug_scopes)
1111 			cerr << get_fileline() << ": debug: Generate case "
1112 			     << "item value=" << item_value_co->value() << endl;
1113 
1114 		  if (case_value_co->value() == item_value_co->value())
1115 			match_flag = true;
1116 		  delete item_value_co;
1117 	    }
1118 
1119 	      // If we stumble on the item that matches, then break out now.
1120 	    if (match_flag)
1121 		  break;
1122 
1123 	    ++ cur;
1124       }
1125 
1126       delete case_value_co;
1127       case_value_co = 0;
1128 
1129       PGenerate*item = (cur == generate_schemes.end())? default_item : *cur;
1130       if (item == 0) {
1131 	    cerr << get_fileline() << ": debug: "
1132 		 << "No generate items found" << endl;
1133 	    return true;
1134       }
1135 
1136       if (debug_scopes)
1137 	    cerr << get_fileline() << ": debug: "
1138 		 << "Generate case matches item at "
1139 		 << item->get_fileline() << endl;
1140 
1141 	// The name of the scope to generate, whatever that item is.
1142       hname_t use_name (item->scope_name);
1143 
1144       item->probe_for_direct_nesting_();
1145       if (item->direct_nested_) {
1146 	    if (debug_scopes)
1147 		  cerr << get_fileline() << ": debug: Generate case item " << scope_name
1148 		       << " detected direct nesting." << endl;
1149 	    item->elaborate_subscope_direct_(des, container);
1150 	    return true;
1151       }
1152 
1153       if (debug_scopes) {
1154 	    cerr << get_fileline() << ": PGenerate::generate_scope_case_: "
1155 		 << "Generate subscope " << use_name
1156 		 << " and elaborate." << endl;
1157       }
1158 
1159       NetScope*scope = new NetScope(container, use_name,
1160 				    NetScope::GENBLOCK);
1161       scope->set_line(get_file(), get_lineno());
1162       scope->add_imports(&explicit_imports);
1163 
1164       item->elaborate_subscope_(des, scope);
1165 
1166       return true;
1167 }
1168 
generate_scope_nblock_(Design * des,NetScope * container)1169 bool PGenerate::generate_scope_nblock_(Design*des, NetScope*container)
1170 {
1171       hname_t use_name (scope_name);
1172       if (debug_scopes)
1173 	    cerr << get_fileline() << ": debug: Generate named block "
1174 		 << ": Generate scope=" << use_name << endl;
1175 
1176       NetScope*scope = new NetScope(container, use_name,
1177 				    NetScope::GENBLOCK);
1178       scope->set_line(get_file(), get_lineno());
1179       scope->add_imports(&explicit_imports);
1180 
1181       elaborate_subscope_(des, scope);
1182 
1183       return true;
1184 }
1185 
elaborate_subscope_direct_(Design * des,NetScope * scope)1186 void PGenerate::elaborate_subscope_direct_(Design*des, NetScope*scope)
1187 {
1188       typedef list<PGenerate*>::const_iterator generate_it_t;
1189       for (generate_it_t cur = generate_schemes.begin()
1190 		 ; cur != generate_schemes.end() ; ++ cur ) {
1191 	    PGenerate*curp = *cur;
1192 	    if (debug_scopes) {
1193 		  cerr << get_fileline() << ": elaborate_subscope_direct_: "
1194 		       << "Elaborate direct subscope " << curp->scope_name
1195 		       << " within scope " << scope_name << endl;
1196 	    }
1197 	    curp -> generate_scope(des, scope);
1198       }
1199 }
1200 
elaborate_subscope_(Design * des,NetScope * scope)1201 void PGenerate::elaborate_subscope_(Design*des, NetScope*scope)
1202 {
1203       scope->add_typedefs(&typedefs);
1204 
1205 	// Add the genvars to this scope.
1206       typedef map<perm_string,LineInfo*>::const_iterator genvar_it_t;
1207       for (genvar_it_t cur = genvars.begin(); cur != genvars.end(); ++ cur ) {
1208 	    scope->add_genvar((*cur).first, (*cur).second);
1209       }
1210 
1211 	// Scan the localparams in this scope, and store the information
1212         // needed to evaluate the parameter expressions. The expressions
1213 	// will be evaluated later, once all parameter overrides for this
1214 	// module have been done.
1215       collect_scope_localparams_(des, scope, localparams);
1216 
1217 	// Run through the defparams for this scope and save the result
1218 	// in a table for later final override.
1219 
1220       typedef list<PGenerate::named_expr_t>::const_iterator defparms_iter_t;
1221       for (defparms_iter_t cur = defparms.begin()
1222 		 ; cur != defparms.end() ; ++ cur ) {
1223 	    scope->defparams.push_back(make_pair(cur->first, cur->second));
1224       }
1225 
1226 	// Scan the generated scope for nested generate schemes,
1227 	// and *generate* new scopes, which is slightly different
1228 	// from simple elaboration.
1229 
1230       typedef list<PGenerate*>::const_iterator generate_it_t;
1231       for (generate_it_t cur = generate_schemes.begin()
1232 		 ; cur != generate_schemes.end() ; ++ cur ) {
1233 	    (*cur) -> generate_scope(des, scope);
1234       }
1235 
1236         // Scan through all the task and function declarations in this
1237         // scope.
1238       elaborate_scope_tasks(des, scope, tasks);
1239       elaborate_scope_funcs(des, scope, funcs);
1240 
1241 	// Scan the generated scope for gates that may create
1242 	// their own scopes.
1243       typedef list<PGate*>::const_iterator pgate_list_it_t;
1244       for (pgate_list_it_t cur = gates.begin()
1245 		 ; cur != gates.end() ; ++ cur ) {
1246 	    (*cur) ->elaborate_scope(des, scope);
1247       }
1248 
1249       typedef list<PProcess*>::const_iterator proc_it_t;
1250       for (proc_it_t cur = behaviors.begin()
1251 		 ; cur != behaviors.end() ; ++ cur ) {
1252 	    (*cur) -> statement() -> elaborate_scope(des, scope);
1253       }
1254 
1255 	// Scan through all the named events in this scope.
1256       elaborate_scope_events_(des, scope, events);
1257 
1258       if (debug_scopes)
1259 	    cerr << get_fileline() << ": debug: Generated scope " << scope_path(scope)
1260 		 << " for generate block " << scope_name << endl;
1261 
1262 	// Save the scope that we created, for future use.
1263       scope_list_.push_back(scope);
1264 }
1265 
1266 class delayed_elaborate_scope_mod_instances : public elaborator_work_item_t {
1267 
1268     public:
delayed_elaborate_scope_mod_instances(Design * des__,const PGModule * obj,Module * mod,NetScope * sc)1269       delayed_elaborate_scope_mod_instances(Design*des__,
1270 					    const PGModule*obj,
1271 					    Module*mod,
1272 					    NetScope*sc)
1273       : elaborator_work_item_t(des__), obj_(obj), mod_(mod), sc_(sc)
1274       { }
~delayed_elaborate_scope_mod_instances()1275       ~delayed_elaborate_scope_mod_instances() { }
1276 
1277       virtual void elaborate_runrun();
1278 
1279     private:
1280       const PGModule*obj_;
1281       Module*mod_;
1282       NetScope*sc_;
1283 };
1284 
elaborate_runrun()1285 void delayed_elaborate_scope_mod_instances::elaborate_runrun()
1286 {
1287       if (debug_scopes)
1288 	    cerr << obj_->get_fileline() << ": debug: "
1289 		 << "Resume scope elaboration of instances of "
1290 		 << mod_->mod_name() << "." << endl;
1291 
1292       obj_->elaborate_scope_mod_instances_(des, mod_, sc_);
1293 }
1294 
1295 /*
1296  * Here we handle the elaborate scope of a module instance. The caller
1297  * has already figured out that this "gate" is a module, and has found
1298  * the module definition. The "sc" argument is the scope that will
1299  * contain this instance.
1300  */
elaborate_scope_mod_(Design * des,Module * mod,NetScope * sc) const1301 void PGModule::elaborate_scope_mod_(Design*des, Module*mod, NetScope*sc) const
1302 {
1303       if (get_name() == "") {
1304 	    cerr << get_fileline() << ": error: Instantiation of module "
1305 		 << mod->mod_name() << " requires an instance name." << endl;
1306 	    des->errors += 1;
1307 	    return;
1308       }
1309 
1310 	// Missing module instance names have already been rejected.
1311       assert(get_name() != "");
1312 
1313 	// check for recursive instantiation by scanning the current
1314 	// scope and its parents. Look for a module instantiation of
1315 	// the same module, but farther up in the scope.
1316       unsigned rl_count = 0;
1317       bool in_genblk = false;
1318       for (NetScope*scn = sc ;  scn ;  scn = scn->parent()) {
1319 	      // We need to know if we are inside a generate block to allow
1320 	      // recursive instances.
1321 	    if (scn->type() == NetScope::GENBLOCK) {
1322 		  in_genblk = true;
1323 		  continue;
1324 	    }
1325 
1326 	    if (scn->type() != NetScope::MODULE) continue;
1327 
1328 	    if (strcmp(mod->mod_name(), scn->module_name()) != 0) continue;
1329 
1330 	      // We allow nested scopes if they are inside a generate block,
1331 	      // but only to a certain nesting depth.
1332 	    if (in_genblk) {
1333 		  rl_count += 1;
1334 		  if (rl_count > recursive_mod_limit) {
1335 			cerr << get_fileline() << ": error: instance "
1336 			     << scope_path(sc) << "." << get_name()
1337 			     << " of module " << mod->mod_name()
1338 			     << " is nested too deep." << endl;
1339 			cerr << get_fileline() << ":      : check for "
1340 			        "proper recursion termination or increase the "
1341 			        "limit (" << recursive_mod_limit
1342 			     << ") with the -pRECURSIVE_MOD_LIMIT flag."
1343 			     << endl;
1344 			des->errors += 1;
1345 			return;
1346 		  }
1347 		  continue;
1348 	    }
1349 
1350 	    cerr << get_fileline() << ": error: You can not instantiate "
1351 		 << "module " << mod->mod_name() << " within itself." << endl;
1352 	    cerr << get_fileline() << ":      : The offending instance is "
1353 		 << get_name() << " within " << scope_path(scn) << "." << endl;
1354 	    des->errors += 1;
1355 	    return;
1356       }
1357 
1358       if (msb_ || lsb_) {
1359 	      // If there are expressions to evaluate in order to know
1360 	      // the actual number of instances that will be
1361 	      // instantiated, then we have to delay further scope
1362 	      // elaboration until after defparams (above me) are
1363 	      // run. Do that by appending a work item to the
1364 	      // elaboration work list.
1365 	    if (debug_scopes)
1366 		  cerr << get_fileline() << ": debug: delay elaborate_scope"
1367 		       << " of array of " << get_name()
1368 		       << " in scope " << scope_path(sc) << "." << endl;
1369 
1370 	    elaborator_work_item_t*tmp
1371 		  = new delayed_elaborate_scope_mod_instances(des, this, mod, sc);
1372 	    des->elaboration_work_list.push_back(tmp);
1373 
1374       } else {
1375 	      // If there are no expressions that need to be evaluated
1376 	      // to elaborate the scope of this next instances, then
1377 	      // get right to it.
1378 	    elaborate_scope_mod_instances_(des, mod, sc);
1379       }
1380 }
1381 
1382 /*
1383  * This method is called to process a module instantiation after basic
1384  * sanity testing is already complete.
1385  */
elaborate_scope_mod_instances_(Design * des,Module * mod,NetScope * sc) const1386 void PGModule::elaborate_scope_mod_instances_(Design*des, Module*mod, NetScope*sc) const
1387 {
1388       NetExpr*mse = msb_ ? elab_and_eval(des, sc, msb_, -1, true) : 0;
1389       NetExpr*lse = lsb_ ? elab_and_eval(des, sc, lsb_, -1, true) : 0;
1390       NetEConst*msb = dynamic_cast<NetEConst*> (mse);
1391       NetEConst*lsb = dynamic_cast<NetEConst*> (lse);
1392 
1393       assert( (msb == 0) || (lsb != 0) );
1394 
1395       long instance_low  = 0;
1396       long instance_high = 0;
1397       long instance_count  = 1;
1398       bool instance_array = false;
1399 
1400       if (msb) {
1401 	    instance_array = true;
1402 	    instance_high = msb->value().as_long();
1403 	    instance_low  = lsb->value().as_long();
1404 	    if (instance_high > instance_low)
1405 		  instance_count = instance_high - instance_low + 1;
1406 	    else
1407 		  instance_count = instance_low - instance_high + 1;
1408 
1409 	    delete mse;
1410 	    delete lse;
1411       }
1412 
1413       NetScope::scope_vec_t instances (instance_count);
1414       if (debug_scopes) {
1415 	    cerr << get_fileline() << ": debug: Create " << instance_count
1416 		 << " instances of " << get_name()
1417 		 << "." << endl;
1418       }
1419 
1420 	    struct attrib_list_t*attrib_list;
1421 	    unsigned attrib_list_n = 0;
1422 	    attrib_list = evaluate_attributes(attributes, attrib_list_n, des, sc);
1423 
1424 	// Run through the module instances, and make scopes out of
1425 	// them. Also do parameter overrides that are done on the
1426 	// instantiation line.
1427       for (int idx = 0 ;  idx < instance_count ;  idx += 1) {
1428 
1429 	    hname_t use_name (get_name());
1430 
1431 	    if (instance_array) {
1432 		  int instance_idx = idx;
1433 		  if (instance_low < instance_high)
1434 			instance_idx = instance_low + idx;
1435 		  else
1436 			instance_idx = instance_low - idx;
1437 
1438 		  use_name = hname_t(get_name(), instance_idx);
1439 	    }
1440 
1441 	    if (debug_scopes) {
1442 		  cerr << get_fileline() << ": debug: Module instance " << use_name
1443 		       << " becomes child of " << scope_path(sc)
1444 		       << "." << endl;
1445 	    }
1446 
1447 	      // Create the new scope as a MODULE with my name. Note
1448 	      // that if this is a nested module, mark it thus so that
1449 	      // scope searches will continue into the parent scope.
1450 	    NetScope*my_scope = new NetScope(sc, use_name, NetScope::MODULE, 0,
1451 					     bound_type_? true : false,
1452 					     mod->program_block,
1453 					     mod->is_interface);
1454 	    my_scope->set_line(get_file(), mod->get_file(),
1455 	                       get_lineno(), mod->get_lineno());
1456 	    my_scope->set_module_name(mod->mod_name());
1457 	    my_scope->add_imports(&mod->explicit_imports);
1458 
1459 	    for (unsigned adx = 0 ;  adx < attrib_list_n ;  adx += 1)
1460 	      my_scope->attribute(attrib_list[adx].key, attrib_list[adx].val);
1461 
1462 	    instances[idx] = my_scope;
1463 
1464 	    set_scope_timescale(des, my_scope, mod);
1465 
1466 	      // Look for module parameter replacements. The "replace" map
1467 	      // maps parameter name to replacement expression that is
1468 	      // passed. It is built up by the ordered overrides or named
1469 	      // overrides.
1470 
1471 	    Module::replace_t replace;
1472 
1473 	      // Positional parameter overrides are matched to parameter
1474 	      // names by using the param_names list of parameter
1475 	      // names. This is an ordered list of names so the first name
1476 	      // is parameter 0, the second parameter 1, and so on.
1477 
1478 	    if (overrides_) {
1479 		  assert(parms_ == 0);
1480 		  list<perm_string>::const_iterator cur
1481 			= mod->param_names.begin();
1482 		  list<PExpr*>::const_iterator jdx = overrides_->begin();
1483 		  for (;;) {
1484 			if (jdx == overrides_->end())
1485 			      break;
1486 			if (cur == mod->param_names.end())
1487 			      break;
1488 
1489 		          // No expression means that the parameter is not
1490 		          // replaced at all.
1491 			if (*jdx)
1492 			      replace[*cur] = *jdx;
1493 
1494 			++ jdx;
1495 			++ cur;
1496 		  }
1497 	    }
1498 
1499 	      // Named parameter overrides carry a name with each override
1500 	      // so the mapping into the replace list is much easier.
1501 	    if (parms_) {
1502 		  assert(overrides_ == 0);
1503 		  for (unsigned jdx = 0 ;  jdx < nparms_ ;  jdx += 1) {
1504 		          // No expression means that the parameter is not
1505 		          // replaced.
1506 			if (parms_[jdx].parm)
1507 			      replace[parms_[jdx].name] = parms_[jdx].parm;
1508 		  }
1509 
1510 	    }
1511 
1512 	      // This call actually arranges for the description of the
1513 	      // module type to process this instance and handle parameters
1514 	      // and sub-scopes that might occur. Parameters are also
1515 	      // created in that scope, as they exist. (I'll override them
1516 	      // later.)
1517 	    mod->elaborate_scope(des, my_scope, replace);
1518 
1519       }
1520 	    delete[]attrib_list;
1521 
1522 	/* Stash the instance array of scopes into the parent
1523 	   scope. Later elaboration passes will use this vector to
1524 	   further elaborate the array.
1525 
1526 	   Note that the array is ordered from LSB to MSB. We will use
1527 	   that fact in the main elaborate to connect things in the
1528 	   correct order. */
1529       sc->instance_arrays[get_name()] = instances;
1530 }
1531 
1532 /*
1533  * The isn't really able to create new scopes, but it does create the
1534  * event name in the current scope, so can be done during the
1535  * elaborate_scope scan. Note that the name_ of the PEvent object has
1536  * no hierarchy, but neither does the NetEvent, until it is stored in
1537  * the NetScope object.
1538  */
elaborate_scope(Design *,NetScope * scope) const1539 void PEvent::elaborate_scope(Design*, NetScope*scope) const
1540 {
1541       NetEvent*ev = new NetEvent(name_);
1542       ev->set_line(*this);
1543       scope->add_event(ev);
1544 }
1545 
elaborate_scope(Design * des,NetScope * scope) const1546 void PFunction::elaborate_scope(Design*des, NetScope*scope) const
1547 {
1548       assert(scope->type() == NetScope::FUNC);
1549 
1550         // Save a reference to the pform representation of the function
1551         // in case we need to perform early elaboration.
1552       scope->set_func_pform(this);
1553 
1554         // Assume the function is a constant function until we
1555         // find otherwise.
1556       scope->is_const_func(true);
1557 
1558       scope->add_typedefs(&typedefs);
1559 
1560 	// Scan the parameters in the function, and store the information
1561         // needed to evaluate the parameter expressions.
1562 
1563       collect_scope_parameters_(des, scope, parameters);
1564 
1565       collect_scope_localparams_(des, scope, localparams);
1566 
1567 	// Scan through all the named events in this scope.
1568       elaborate_scope_events_(des, scope, events);
1569 
1570       if (statement_)
1571 	    statement_->elaborate_scope(des, scope);
1572 }
1573 
elaborate_scope(Design * des,NetScope * scope) const1574 void PTask::elaborate_scope(Design*des, NetScope*scope) const
1575 {
1576       assert(scope->type() == NetScope::TASK);
1577 
1578       scope->add_typedefs(&typedefs);
1579 
1580 	// Scan the parameters in the task, and store the information
1581         // needed to evaluate the parameter expressions.
1582 
1583       collect_scope_parameters_(des, scope, parameters);
1584 
1585       collect_scope_localparams_(des, scope, localparams);
1586 
1587 	// Scan through all the named events in this scope.
1588       elaborate_scope_events_(des, scope, events);
1589 
1590       if (statement_)
1591 	    statement_->elaborate_scope(des, scope);
1592 }
1593 
1594 
1595 /*
1596  * The base statement does not have sub-statements and does not
1597  * introduce any scope, so this is a no-op.
1598  */
elaborate_scope(Design *,NetScope *) const1599 void Statement::elaborate_scope(Design*, NetScope*) const
1600 {
1601 }
1602 
1603 /*
1604  * When I get a behavioral block, check to see if it has a name. If it
1605  * does, then create a new scope for the statements within it,
1606  * otherwise use the current scope. Use the selected scope to scan the
1607  * statements that I contain.
1608  */
elaborate_scope(Design * des,NetScope * scope) const1609 void PBlock::elaborate_scope(Design*des, NetScope*scope) const
1610 {
1611       NetScope*my_scope = scope;
1612 
1613       if (pscope_name() != 0) {
1614 	    hname_t use_name(pscope_name());
1615 	    if (debug_scopes)
1616 		  cerr << get_fileline() << ": debug: "
1617 		       << "Elaborate block scope " << use_name
1618 		       << " within " << scope_path(scope) << endl;
1619 
1620 	      // The scope type is begin-end or fork-join. The
1621 	      // sub-types of fork-join are not interesting to the scope.
1622 	    my_scope = new NetScope(scope, use_name, bl_type_!=BL_SEQ
1623 				    ? NetScope::FORK_JOIN
1624 				    : NetScope::BEGIN_END);
1625 	    my_scope->set_line(get_file(), get_lineno());
1626             my_scope->is_auto(scope->is_auto());
1627 	    my_scope->add_imports(&explicit_imports);
1628 	    my_scope->add_typedefs(&typedefs);
1629 
1630 	      // Scan the parameters in the scope, and store the information
1631 	      // needed to evaluate the parameter expressions.
1632 
1633             collect_scope_parameters_(des, my_scope, parameters);
1634 
1635             collect_scope_localparams_(des, my_scope, localparams);
1636 
1637               // Scan through all the named events in this scope.
1638             elaborate_scope_events_(des, my_scope, events);
1639       }
1640 
1641       for (unsigned idx = 0 ;  idx < list_.size() ;  idx += 1)
1642 	    list_[idx] -> elaborate_scope(des, my_scope);
1643 }
1644 
1645 /*
1646  * The case statement itself does not introduce scope, but contains
1647  * other statements that may be named blocks. So scan the case items
1648  * with the elaborate_scope method.
1649  */
elaborate_scope(Design * des,NetScope * scope) const1650 void PCase::elaborate_scope(Design*des, NetScope*scope) const
1651 {
1652       assert(items_);
1653       for (unsigned idx = 0 ;  idx < (*items_).count() ;  idx += 1) {
1654 	    assert( (*items_)[idx] );
1655 
1656 	    if (Statement*sp = (*items_)[idx]->stat)
1657 		  sp -> elaborate_scope(des, scope);
1658       }
1659 }
1660 
1661 /*
1662  * The conditional statement (if-else) does not introduce scope, but
1663  * the statements of the clauses may, so elaborate_scope the contained
1664  * statements.
1665  */
elaborate_scope(Design * des,NetScope * scope) const1666 void PCondit::elaborate_scope(Design*des, NetScope*scope) const
1667 {
1668       if (if_)
1669 	    if_ -> elaborate_scope(des, scope);
1670 
1671       if (else_)
1672 	    else_ -> elaborate_scope(des, scope);
1673 }
1674 
1675 /*
1676  * Statements that contain a further statement but do not
1677  * intrinsically add a scope need to elaborate_scope the contained
1678  * statement.
1679  */
elaborate_scope(Design * des,NetScope * scope) const1680 void PDelayStatement::elaborate_scope(Design*des, NetScope*scope) const
1681 {
1682       if (statement_)
1683 	    statement_ -> elaborate_scope(des, scope);
1684 }
1685 
1686 /*
1687  * Statements that contain a further statement but do not
1688  * intrinsically add a scope need to elaborate_scope the contained
1689  * statement.
1690  */
elaborate_scope(Design * des,NetScope * scope) const1691 void PDoWhile::elaborate_scope(Design*des, NetScope*scope) const
1692 {
1693       if (statement_)
1694 	    statement_ -> elaborate_scope(des, scope);
1695 }
1696 
1697 /*
1698  * Statements that contain a further statement but do not
1699  * intrinsically add a scope need to elaborate_scope the contained
1700  * statement.
1701  */
elaborate_scope(Design * des,NetScope * scope) const1702 void PEventStatement::elaborate_scope(Design*des, NetScope*scope) const
1703 {
1704       if (statement_)
1705 	    statement_ -> elaborate_scope(des, scope);
1706 }
1707 
1708 /*
1709  * The standard says that we create an implicit scope for foreach
1710  * loops, but that is just to hold the index variables, and we'll
1711  * handle them by creating unique names. So just jump into the
1712  * contained statement for scope elaboration.
1713  */
elaborate_scope(Design * des,NetScope * scope) const1714 void PForeach::elaborate_scope(Design*des, NetScope*scope) const
1715 {
1716       if (statement_)
1717 	    statement_ -> elaborate_scope(des, scope);
1718 }
1719 
1720 /*
1721  * Statements that contain a further statement but do not
1722  * intrinsically add a scope need to elaborate_scope the contained
1723  * statement.
1724  */
elaborate_scope(Design * des,NetScope * scope) const1725 void PForever::elaborate_scope(Design*des, NetScope*scope) const
1726 {
1727       if (statement_)
1728 	    statement_ -> elaborate_scope(des, scope);
1729 }
1730 
1731 /*
1732  * Statements that contain a further statement but do not
1733  * intrinsically add a scope need to elaborate_scope the contained
1734  * statement.
1735  */
elaborate_scope(Design * des,NetScope * scope) const1736 void PForStatement::elaborate_scope(Design*des, NetScope*scope) const
1737 {
1738       if (statement_)
1739 	    statement_ -> elaborate_scope(des, scope);
1740 }
1741 
1742 /*
1743  * Statements that contain a further statement but do not
1744  * intrinsically add a scope need to elaborate_scope the contained
1745  * statement.
1746  */
elaborate_scope(Design * des,NetScope * scope) const1747 void PRepeat::elaborate_scope(Design*des, NetScope*scope) const
1748 {
1749       if (statement_)
1750 	    statement_ -> elaborate_scope(des, scope);
1751 }
1752 
1753 /*
1754  * Statements that contain a further statement but do not
1755  * intrinsically add a scope need to elaborate_scope the contained
1756  * statement.
1757  */
elaborate_scope(Design * des,NetScope * scope) const1758 void PWhile::elaborate_scope(Design*des, NetScope*scope) const
1759 {
1760       if (statement_)
1761 	    statement_ -> elaborate_scope(des, scope);
1762 }
1763