1 // gogo.cc -- Go frontend parsed representation.
2 
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6 
7 #include "go-system.h"
8 
9 #include <fstream>
10 
11 #include "filenames.h"
12 
13 #include "go-c.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
16 #include "go-dump.h"
17 #include "go-optimize.h"
18 #include "lex.h"
19 #include "types.h"
20 #include "statements.h"
21 #include "expressions.h"
22 #include "runtime.h"
23 #include "import.h"
24 #include "export.h"
25 #include "backend.h"
26 #include "gogo.h"
27 
28 // Class Gogo.
29 
Gogo(Backend * backend,Linemap * linemap,int,int pointer_size)30 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
31   : backend_(backend),
32     linemap_(linemap),
33     package_(NULL),
34     functions_(),
35     globals_(new Bindings(NULL)),
36     file_block_names_(),
37     imports_(),
38     imported_unsafe_(false),
39     current_file_imported_unsafe_(false),
40     packages_(),
41     init_functions_(),
42     var_deps_(),
43     need_init_fn_(false),
44     init_fn_name_(),
45     imported_init_fns_(),
46     pkgpath_(),
47     pkgpath_symbol_(),
48     prefix_(),
49     pkgpath_set_(false),
50     pkgpath_from_option_(false),
51     prefix_from_option_(false),
52     relative_import_path_(),
53     c_header_(),
54     check_divide_by_zero_(true),
55     check_divide_overflow_(true),
56     compiling_runtime_(false),
57     debug_escape_level_(0),
58     debug_optimization_(false),
59     nil_check_size_threshold_(4096),
60     verify_types_(),
61     interface_types_(),
62     specific_type_functions_(),
63     specific_type_functions_are_written_(false),
64     named_types_are_converted_(false),
65     analysis_sets_(),
66     gc_roots_(),
67     type_descriptors_(),
68     imported_inlinable_functions_(),
69     imported_inline_functions_()
70 {
71   const Location loc = Linemap::predeclared_location();
72 
73   Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
74 						   RUNTIME_TYPE_KIND_UINT8);
75   this->add_named_type(uint8_type);
76   this->add_named_type(Type::make_integer_type("uint16", true,  16,
77 					       RUNTIME_TYPE_KIND_UINT16));
78   this->add_named_type(Type::make_integer_type("uint32", true,  32,
79 					       RUNTIME_TYPE_KIND_UINT32));
80   this->add_named_type(Type::make_integer_type("uint64", true,  64,
81 					       RUNTIME_TYPE_KIND_UINT64));
82 
83   this->add_named_type(Type::make_integer_type("int8",  false,   8,
84 					       RUNTIME_TYPE_KIND_INT8));
85   this->add_named_type(Type::make_integer_type("int16", false,  16,
86 					       RUNTIME_TYPE_KIND_INT16));
87   Named_type* int32_type = Type::make_integer_type("int32", false,  32,
88 						   RUNTIME_TYPE_KIND_INT32);
89   this->add_named_type(int32_type);
90   this->add_named_type(Type::make_integer_type("int64", false,  64,
91 					       RUNTIME_TYPE_KIND_INT64));
92 
93   this->add_named_type(Type::make_float_type("float32", 32,
94 					     RUNTIME_TYPE_KIND_FLOAT32));
95   this->add_named_type(Type::make_float_type("float64", 64,
96 					     RUNTIME_TYPE_KIND_FLOAT64));
97 
98   this->add_named_type(Type::make_complex_type("complex64", 64,
99 					       RUNTIME_TYPE_KIND_COMPLEX64));
100   this->add_named_type(Type::make_complex_type("complex128", 128,
101 					       RUNTIME_TYPE_KIND_COMPLEX128));
102 
103   int int_type_size = pointer_size;
104   if (int_type_size < 32)
105     int_type_size = 32;
106   this->add_named_type(Type::make_integer_type("uint", true,
107 					       int_type_size,
108 					       RUNTIME_TYPE_KIND_UINT));
109   Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
110 						 RUNTIME_TYPE_KIND_INT);
111   this->add_named_type(int_type);
112 
113   this->add_named_type(Type::make_integer_type("uintptr", true,
114 					       pointer_size,
115 					       RUNTIME_TYPE_KIND_UINTPTR));
116 
117   // "byte" is an alias for "uint8".
118   uint8_type->integer_type()->set_is_byte();
119   Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
120 						    loc);
121   byte_type->type_value()->set_is_alias();
122   this->add_named_type(byte_type->type_value());
123 
124   // "rune" is an alias for "int32".
125   int32_type->integer_type()->set_is_rune();
126   Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
127 						    loc);
128   rune_type->type_value()->set_is_alias();
129   this->add_named_type(rune_type->type_value());
130 
131   this->add_named_type(Type::make_named_bool_type());
132 
133   this->add_named_type(Type::make_named_string_type());
134 
135   // "error" is interface { Error() string }.
136   {
137     Typed_identifier_list *methods = new Typed_identifier_list;
138     Typed_identifier_list *results = new Typed_identifier_list;
139     results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
140     Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
141     methods->push_back(Typed_identifier("Error", method_type, loc));
142     Interface_type *error_iface = Type::make_interface_type(methods, loc);
143     error_iface->finalize_methods();
144     Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
145     this->add_named_type(error_type);
146   }
147 
148   this->globals_->add_constant(Typed_identifier("true",
149 						Type::make_boolean_type(),
150 						loc),
151 			       NULL,
152 			       Expression::make_boolean(true, loc),
153 			       0);
154   this->globals_->add_constant(Typed_identifier("false",
155 						Type::make_boolean_type(),
156 						loc),
157 			       NULL,
158 			       Expression::make_boolean(false, loc),
159 			       0);
160 
161   this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
162 						loc),
163 			       NULL,
164 			       Expression::make_nil(loc),
165 			       0);
166 
167   Type* abstract_int_type = Type::make_abstract_integer_type();
168   this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
169 						loc),
170 			       NULL,
171 			       Expression::make_iota(),
172 			       0);
173 
174   Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
175   new_type->set_is_varargs();
176   new_type->set_is_builtin();
177   this->globals_->add_function_declaration("new", NULL, new_type, loc);
178 
179   Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
180   make_type->set_is_varargs();
181   make_type->set_is_builtin();
182   this->globals_->add_function_declaration("make", NULL, make_type, loc);
183 
184   Typed_identifier_list* len_result = new Typed_identifier_list();
185   len_result->push_back(Typed_identifier("", int_type, loc));
186   Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
187 						     loc);
188   len_type->set_is_builtin();
189   this->globals_->add_function_declaration("len", NULL, len_type, loc);
190 
191   Typed_identifier_list* cap_result = new Typed_identifier_list();
192   cap_result->push_back(Typed_identifier("", int_type, loc));
193   Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
194 						     loc);
195   cap_type->set_is_builtin();
196   this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
197 
198   Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
199   print_type->set_is_varargs();
200   print_type->set_is_builtin();
201   this->globals_->add_function_declaration("print", NULL, print_type, loc);
202 
203   print_type = Type::make_function_type(NULL, NULL, NULL, loc);
204   print_type->set_is_varargs();
205   print_type->set_is_builtin();
206   this->globals_->add_function_declaration("println", NULL, print_type, loc);
207 
208   Type *empty = Type::make_empty_interface_type(loc);
209   Typed_identifier_list* panic_parms = new Typed_identifier_list();
210   panic_parms->push_back(Typed_identifier("e", empty, loc));
211   Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
212 						       NULL, loc);
213   panic_type->set_is_builtin();
214   this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
215 
216   Typed_identifier_list* recover_result = new Typed_identifier_list();
217   recover_result->push_back(Typed_identifier("", empty, loc));
218   Function_type* recover_type = Type::make_function_type(NULL, NULL,
219 							 recover_result,
220 							 loc);
221   recover_type->set_is_builtin();
222   this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
223 
224   Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
225   close_type->set_is_varargs();
226   close_type->set_is_builtin();
227   this->globals_->add_function_declaration("close", NULL, close_type, loc);
228 
229   Typed_identifier_list* copy_result = new Typed_identifier_list();
230   copy_result->push_back(Typed_identifier("", int_type, loc));
231   Function_type* copy_type = Type::make_function_type(NULL, NULL,
232 						      copy_result, loc);
233   copy_type->set_is_varargs();
234   copy_type->set_is_builtin();
235   this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
236 
237   Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
238   append_type->set_is_varargs();
239   append_type->set_is_builtin();
240   this->globals_->add_function_declaration("append", NULL, append_type, loc);
241 
242   Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
243   complex_type->set_is_varargs();
244   complex_type->set_is_builtin();
245   this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
246 
247   Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
248   real_type->set_is_varargs();
249   real_type->set_is_builtin();
250   this->globals_->add_function_declaration("real", NULL, real_type, loc);
251 
252   Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
253   imag_type->set_is_varargs();
254   imag_type->set_is_builtin();
255   this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
256 
257   Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
258   delete_type->set_is_varargs();
259   delete_type->set_is_builtin();
260   this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
261 }
262 
263 std::string
pkgpath_for_symbol(const std::string & pkgpath)264 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
265 {
266   go_assert(!pkgpath.empty());
267   return go_encode_id(pkgpath);
268 }
269 
270 // Return a hash code for a string, given a starting hash.
271 
272 unsigned int
hash_string(const std::string & s,unsigned int h)273 Gogo::hash_string(const std::string& s, unsigned int h)
274 {
275   const char* p = s.data();
276   size_t len = s.length();
277   for (; len > 0; --len)
278     {
279       h ^= *p++;
280       h*= 16777619;
281     }
282   return h;
283 }
284 
285 // Get the package path to use for type reflection data.  This should
286 // ideally be unique across the entire link.
287 
288 const std::string&
pkgpath() const289 Gogo::pkgpath() const
290 {
291   go_assert(this->pkgpath_set_);
292   return this->pkgpath_;
293 }
294 
295 // Set the package path from the -fgo-pkgpath command line option.
296 
297 void
set_pkgpath(const std::string & arg)298 Gogo::set_pkgpath(const std::string& arg)
299 {
300   go_assert(!this->pkgpath_set_);
301   this->pkgpath_ = go_mangle_pkgpath(arg);
302   this->pkgpath_set_ = true;
303   this->pkgpath_from_option_ = true;
304 }
305 
306 // Get the package path to use for symbol names.
307 
308 const std::string&
pkgpath_symbol() const309 Gogo::pkgpath_symbol() const
310 {
311   go_assert(this->pkgpath_set_);
312   return this->pkgpath_symbol_;
313 }
314 
315 // Set the unique prefix to use to determine the package path, from
316 // the -fgo-prefix command line option.
317 
318 void
set_prefix(const std::string & arg)319 Gogo::set_prefix(const std::string& arg)
320 {
321   go_assert(!this->prefix_from_option_);
322   this->prefix_ = arg;
323   this->prefix_from_option_ = true;
324 }
325 
326 // Given a name which may or may not have been hidden, append the
327 // appropriate version of the name to the result string. Take care
328 // to avoid creating a sequence that will be rejected by go_encode_id
329 // (avoid ..u, ..U, ..z).
330 void
append_possibly_hidden_name(std::string * result,const std::string & name)331 Gogo::append_possibly_hidden_name(std::string *result, const std::string& name)
332 {
333   // FIXME: This adds in pkgpath twice for hidden symbols, which is
334   // less than ideal.
335   if (!Gogo::is_hidden_name(name))
336     (*result) += name;
337   else
338     {
339       std::string n = ".";
340       std::string pkgpath = Gogo::hidden_name_pkgpath(name);
341       char lastR = result->at(result->length() - 1);
342       char firstP = pkgpath.at(0);
343       if (lastR == '.' && (firstP == 'u' || firstP == 'U' || firstP == 'z'))
344         n = "_.";
345       n.append(pkgpath);
346       n.append(1, '.');
347       n.append(Gogo::unpack_hidden_name(name));
348       (*result) += n;
349     }
350 }
351 
352 // Munge name for use in an error message.
353 
354 std::string
message_name(const std::string & name)355 Gogo::message_name(const std::string& name)
356 {
357   return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
358 }
359 
360 // Get the package name.
361 
362 const std::string&
package_name() const363 Gogo::package_name() const
364 {
365   go_assert(this->package_ != NULL);
366   return this->package_->package_name();
367 }
368 
369 // Set the package name.
370 
371 void
set_package_name(const std::string & package_name,Location location)372 Gogo::set_package_name(const std::string& package_name,
373 		       Location location)
374 {
375   if (this->package_ != NULL)
376     {
377       if (this->package_->package_name() != package_name)
378 	go_error_at(location, "expected package %<%s%>",
379 		    Gogo::message_name(this->package_->package_name()).c_str());
380       return;
381     }
382 
383   // Now that we know the name of the package we are compiling, set
384   // the package path to use for reflect.Type.PkgPath and global
385   // symbol names.
386   if (this->pkgpath_set_)
387     this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
388   else
389     {
390       if (!this->prefix_from_option_ && package_name == "main")
391 	{
392 	  this->pkgpath_ = package_name;
393 	  this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name);
394 	}
395       else
396 	{
397 	  if (!this->prefix_from_option_)
398 	    this->prefix_ = "go";
399 	  this->pkgpath_ = (go_mangle_pkgpath(this->prefix_) + '.'
400 			    + package_name);
401 	  this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.'
402 				   + Gogo::pkgpath_for_symbol(package_name));
403 	}
404       this->pkgpath_set_ = true;
405     }
406 
407   this->package_ = this->register_package(this->pkgpath_,
408 					  this->pkgpath_symbol_, location);
409   this->package_->set_package_name(package_name, location);
410 
411   if (this->is_main_package())
412     {
413       // Declare "main" as a function which takes no parameters and
414       // returns no value.
415       Location uloc = Linemap::unknown_location();
416       this->declare_function(Gogo::pack_hidden_name("main", false),
417 			     Type::make_function_type (NULL, NULL, NULL, uloc),
418 			     uloc);
419     }
420 }
421 
422 // Return whether this is the "main" package.  This is not true if
423 // -fgo-pkgpath or -fgo-prefix was used.
424 
425 bool
is_main_package() const426 Gogo::is_main_package() const
427 {
428   return (this->package_name() == "main"
429 	  && !this->pkgpath_from_option_
430 	  && !this->prefix_from_option_);
431 }
432 
433 // Import a package.
434 
435 void
import_package(const std::string & filename,const std::string & local_name,bool is_local_name_exported,bool must_exist,Location location)436 Gogo::import_package(const std::string& filename,
437 		     const std::string& local_name,
438 		     bool is_local_name_exported,
439 		     bool must_exist,
440 		     Location location)
441 {
442   if (filename.empty())
443     {
444       go_error_at(location, "import path is empty");
445       return;
446     }
447 
448   const char *pf = filename.data();
449   const char *pend = pf + filename.length();
450   while (pf < pend)
451     {
452       unsigned int c;
453       int adv = Lex::fetch_char(pf, &c);
454       if (adv == 0)
455 	{
456 	  go_error_at(location, "import path contains invalid UTF-8 sequence");
457 	  return;
458 	}
459       if (c == '\0')
460 	{
461 	  go_error_at(location, "import path contains NUL");
462 	  return;
463 	}
464       if (c < 0x20 || c == 0x7f)
465 	{
466 	  go_error_at(location, "import path contains control character");
467 	  return;
468 	}
469       if (c == '\\')
470 	{
471 	  go_error_at(location, "import path contains backslash; use slash");
472 	  return;
473 	}
474       if (Lex::is_unicode_space(c))
475 	{
476 	  go_error_at(location, "import path contains space character");
477 	  return;
478 	}
479       if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
480 	{
481 	  go_error_at(location,
482                       "import path contains invalid character '%c'", c);
483 	  return;
484 	}
485       pf += adv;
486     }
487 
488   if (IS_ABSOLUTE_PATH(filename.c_str()))
489     {
490       go_error_at(location, "import path cannot be absolute path");
491       return;
492     }
493 
494   if (local_name == "init")
495     go_error_at(location, "cannot import package as init");
496 
497   if (filename == "unsafe")
498     {
499       this->import_unsafe(local_name, is_local_name_exported, location);
500       this->current_file_imported_unsafe_ = true;
501       return;
502     }
503 
504   Imports::const_iterator p = this->imports_.find(filename);
505   if (p != this->imports_.end())
506     {
507       Package* package = p->second;
508       package->set_location(location);
509       std::string ln = local_name;
510       bool is_ln_exported = is_local_name_exported;
511       if (ln.empty())
512 	{
513 	  ln = package->package_name();
514 	  go_assert(!ln.empty());
515 	  is_ln_exported = Lex::is_exported_name(ln);
516 	}
517       if (ln == "_")
518         ;
519       else if (ln == ".")
520 	{
521 	  Bindings* bindings = package->bindings();
522 	  for (Bindings::const_declarations_iterator pd =
523 		 bindings->begin_declarations();
524 	       pd != bindings->end_declarations();
525 	       ++pd)
526 	    this->add_dot_import_object(pd->second);
527           std::string dot_alias = "." + package->package_name();
528           package->add_alias(dot_alias, location);
529 	}
530       else
531 	{
532           package->add_alias(ln, location);
533 	  ln = this->pack_hidden_name(ln, is_ln_exported);
534 	  this->package_->bindings()->add_package(ln, package);
535 	}
536       return;
537     }
538 
539   Import::Stream* stream = Import::open_package(filename, location,
540 						this->relative_import_path_);
541   if (stream == NULL)
542     {
543       if (must_exist)
544 	go_error_at(location, "import file %qs not found", filename.c_str());
545       return;
546     }
547 
548   Import* imp = new Import(stream, location);
549   imp->register_builtin_types(this);
550   Package* package = imp->import(this, local_name, is_local_name_exported);
551   if (package != NULL)
552     {
553       if (package->pkgpath() == this->pkgpath())
554 	go_error_at(location,
555 		    ("imported package uses same package path as package "
556 		     "being compiled (see %<-fgo-pkgpath%> option)"));
557 
558       this->imports_.insert(std::make_pair(filename, package));
559     }
560 
561   imp->clear_stream();
562   delete stream;
563 
564   // FIXME: we never delete imp; we may need it for inlinable functions.
565 }
566 
567 Import_init *
lookup_init(const std::string & init_name)568 Gogo::lookup_init(const std::string& init_name)
569 {
570   Import_init tmp("", init_name, -1);
571   Import_init_set::iterator it = this->imported_init_fns_.find(&tmp);
572   return (it != this->imported_init_fns_.end()) ? *it : NULL;
573 }
574 
575 // Add an import control function for an imported package to the list.
576 
577 void
add_import_init_fn(const std::string & package_name,const std::string & init_name,int prio)578 Gogo::add_import_init_fn(const std::string& package_name,
579 			 const std::string& init_name, int prio)
580 {
581   for (Import_init_set::iterator p =
582 	 this->imported_init_fns_.begin();
583        p != this->imported_init_fns_.end();
584        ++p)
585     {
586       Import_init *ii = (*p);
587       if (ii->init_name() == init_name)
588 	{
589 	  // If a test of package P1, built as part of package P1,
590 	  // imports package P2, and P2 imports P1 (perhaps
591 	  // indirectly), then we will see the same import name with
592 	  // different import priorities.  That is OK, so don't give
593 	  // an error about it.
594 	  if (ii->package_name() != package_name)
595 	    {
596 	      go_error_at(Linemap::unknown_location(),
597 		       "duplicate package initialization name %qs",
598 		       Gogo::message_name(init_name).c_str());
599 	      go_inform(Linemap::unknown_location(), "used by package %qs",
600 			Gogo::message_name(ii->package_name()).c_str());
601 	      go_inform(Linemap::unknown_location(), " and by package %qs",
602 			Gogo::message_name(package_name).c_str());
603 	    }
604           ii->set_priority(prio);
605           return;
606 	}
607     }
608 
609   Import_init* nii = new Import_init(package_name, init_name, prio);
610   this->imported_init_fns_.insert(nii);
611 }
612 
613 // Return whether we are at the global binding level.
614 
615 bool
in_global_scope() const616 Gogo::in_global_scope() const
617 {
618   return this->functions_.empty();
619 }
620 
621 // Return the current binding contour.
622 
623 Bindings*
current_bindings()624 Gogo::current_bindings()
625 {
626   if (!this->functions_.empty())
627     return this->functions_.back().blocks.back()->bindings();
628   else if (this->package_ != NULL)
629     return this->package_->bindings();
630   else
631     return this->globals_;
632 }
633 
634 const Bindings*
current_bindings() const635 Gogo::current_bindings() const
636 {
637   if (!this->functions_.empty())
638     return this->functions_.back().blocks.back()->bindings();
639   else if (this->package_ != NULL)
640     return this->package_->bindings();
641   else
642     return this->globals_;
643 }
644 
645 void
update_init_priority(Import_init * ii,std::set<const Import_init * > * visited)646 Gogo::update_init_priority(Import_init* ii,
647                            std::set<const Import_init *>* visited)
648 {
649   visited->insert(ii);
650   int succ_prior = -1;
651 
652   for (std::set<std::string>::const_iterator pci =
653            ii->precursors().begin();
654        pci != ii->precursors().end();
655        ++pci)
656     {
657       Import_init* succ = this->lookup_init(*pci);
658       if (visited->find(succ) == visited->end())
659         update_init_priority(succ, visited);
660       succ_prior = std::max(succ_prior, succ->priority());
661     }
662   if (ii->priority() <= succ_prior)
663     ii->set_priority(succ_prior + 1);
664 }
665 
666 void
recompute_init_priorities()667 Gogo::recompute_init_priorities()
668 {
669   std::set<Import_init *> nonroots;
670 
671   for (Import_init_set::const_iterator p =
672            this->imported_init_fns_.begin();
673        p != this->imported_init_fns_.end();
674        ++p)
675     {
676       const Import_init *ii = *p;
677       for (std::set<std::string>::const_iterator pci =
678                ii->precursors().begin();
679            pci != ii->precursors().end();
680            ++pci)
681         {
682           Import_init* ii_init = this->lookup_init(*pci);
683           nonroots.insert(ii_init);
684         }
685     }
686 
687   // Recursively update priorities starting at roots.
688   std::set<const Import_init*> visited;
689   for (Import_init_set::iterator p =
690            this->imported_init_fns_.begin();
691        p != this->imported_init_fns_.end();
692        ++p)
693     {
694       Import_init* ii = *p;
695       if (nonroots.find(ii) != nonroots.end())
696         continue;
697       update_init_priority(ii, &visited);
698     }
699 }
700 
701 // Add statements to INIT_STMTS which run the initialization
702 // functions for imported packages.  This is only used for the "main"
703 // package.
704 
705 void
init_imports(std::vector<Bstatement * > & init_stmts,Bfunction * bfunction)706 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction)
707 {
708   go_assert(this->is_main_package());
709 
710   if (this->imported_init_fns_.empty())
711     return;
712 
713   Location unknown_loc = Linemap::unknown_location();
714   Function_type* func_type =
715       Type::make_function_type(NULL, NULL, NULL, unknown_loc);
716   Btype* fntype = func_type->get_backend_fntype(this);
717 
718   // Recompute init priorities based on a walk of the init graph.
719   recompute_init_priorities();
720 
721   // We must call them in increasing priority order.
722   std::vector<const Import_init*> v;
723   for (Import_init_set::const_iterator p =
724 	 this->imported_init_fns_.begin();
725        p != this->imported_init_fns_.end();
726        ++p)
727     {
728       // Don't include dummy inits. They are not real functions.
729       if ((*p)->is_dummy())
730         continue;
731       if ((*p)->priority() < 0)
732 	go_error_at(Linemap::unknown_location(),
733 		    "internal error: failed to set init priority for %s",
734 		    (*p)->package_name().c_str());
735       v.push_back(*p);
736     }
737   std::sort(v.begin(), v.end(), priority_compare);
738 
739   // We build calls to the init functions, which take no arguments.
740   std::vector<Bexpression*> empty_args;
741   for (std::vector<const Import_init*>::const_iterator p = v.begin();
742        p != v.end();
743        ++p)
744     {
745       const Import_init* ii = *p;
746       std::string user_name = ii->package_name() + ".init";
747       const std::string& init_name(ii->init_name());
748       const unsigned int flags =
749 	(Backend::function_is_visible
750 	 | Backend::function_is_declaration
751 	 | Backend::function_is_inlinable);
752       Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
753 						   flags, unknown_loc);
754       Bexpression* pfunc_code =
755           this->backend()->function_code_expression(pfunc, unknown_loc);
756       Bexpression* pfunc_call =
757           this->backend()->call_expression(bfunction, pfunc_code, empty_args,
758                                            NULL, unknown_loc);
759       init_stmts.push_back(this->backend()->expression_statement(bfunction,
760                                                                  pfunc_call));
761     }
762 }
763 
764 // Register global variables with the garbage collector.  We need to
765 // register all variables which can hold a pointer value.  They become
766 // roots during the mark phase.  We build a struct that is easy to
767 // hook into a list of roots.
768 
769 // type gcRoot struct {
770 // 	decl    unsafe.Pointer // Pointer to variable.
771 //	size    uintptr        // Total size of variable.
772 // 	ptrdata uintptr        // Length of variable's gcdata.
773 // 	gcdata  *byte          // Pointer mask.
774 // }
775 //
776 // type gcRootList struct {
777 // 	next  *gcRootList
778 // 	count int
779 // 	roots [...]gcRoot
780 // }
781 
782 // The last entry in the roots array has a NULL decl field.
783 
784 void
register_gc_vars(const std::vector<Named_object * > & var_gc,std::vector<Bstatement * > & init_stmts,Bfunction * init_bfn)785 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
786 		       std::vector<Bstatement*>& init_stmts,
787                        Bfunction* init_bfn)
788 {
789   if (var_gc.empty() && this->gc_roots_.empty())
790     return;
791 
792   Type* pvt = Type::make_pointer_type(Type::make_void_type());
793   Type* uintptr_type = Type::lookup_integer_type("uintptr");
794   Type* byte_type = this->lookup_global("byte")->type_value();
795   Type* pointer_byte_type = Type::make_pointer_type(byte_type);
796   Struct_type* root_type =
797     Type::make_builtin_struct_type(4,
798 				   "decl", pvt,
799 				   "size", uintptr_type,
800 				   "ptrdata", uintptr_type,
801 				   "gcdata", pointer_byte_type);
802 
803   Location builtin_loc = Linemap::predeclared_location();
804   unsigned long roots_len = var_gc.size() + this->gc_roots_.size();
805   Expression* length = Expression::make_integer_ul(roots_len, NULL,
806                                                    builtin_loc);
807   Array_type* root_array_type = Type::make_array_type(root_type, length);
808   root_array_type->set_is_array_incomparable();
809 
810   Type* int_type = Type::lookup_integer_type("int");
811   Struct_type* root_list_type =
812       Type::make_builtin_struct_type(3,
813                                      "next", pvt,
814 				     "count", int_type,
815                                      "roots", root_array_type);
816 
817   // Build an initializer for the roots array.
818 
819   Expression_list* roots_init = new Expression_list();
820 
821   for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
822        p != var_gc.end();
823        ++p)
824     {
825       Expression_list* init = new Expression_list();
826 
827       Location no_loc = (*p)->location();
828       Expression* decl = Expression::make_var_reference(*p, no_loc);
829       Expression* decl_addr =
830           Expression::make_unary(OPERATOR_AND, decl, no_loc);
831       decl_addr->unary_expression()->set_does_not_escape();
832       decl_addr = Expression::make_cast(pvt, decl_addr, no_loc);
833       init->push_back(decl_addr);
834 
835       Expression* size =
836 	Expression::make_type_info(decl->type(),
837 				   Expression::TYPE_INFO_SIZE);
838       init->push_back(size);
839 
840       Expression* ptrdata =
841 	Expression::make_type_info(decl->type(),
842 				   Expression::TYPE_INFO_BACKEND_PTRDATA);
843       init->push_back(ptrdata);
844 
845       Expression* gcdata = Expression::make_ptrmask_symbol(decl->type());
846       init->push_back(gcdata);
847 
848       Expression* root_ctor =
849           Expression::make_struct_composite_literal(root_type, init, no_loc);
850       roots_init->push_back(root_ctor);
851     }
852 
853   for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin();
854        p != this->gc_roots_.end();
855        ++p)
856     {
857       Expression_list *init = new Expression_list();
858 
859       Expression* expr = *p;
860       Location eloc = expr->location();
861       init->push_back(Expression::make_cast(pvt, expr, eloc));
862 
863       Type* type = expr->type()->points_to();
864       go_assert(type != NULL);
865 
866       Expression* size =
867 	Expression::make_type_info(type,
868 				   Expression::TYPE_INFO_SIZE);
869       init->push_back(size);
870 
871       Expression* ptrdata =
872 	Expression::make_type_info(type,
873 				   Expression::TYPE_INFO_BACKEND_PTRDATA);
874       init->push_back(ptrdata);
875 
876       Expression* gcdata = Expression::make_ptrmask_symbol(type);
877       init->push_back(gcdata);
878 
879       Expression* root_ctor =
880 	Expression::make_struct_composite_literal(root_type, init, eloc);
881       roots_init->push_back(root_ctor);
882     }
883 
884   // Build a constructor for the struct.
885 
886   Expression_list* root_list_init = new Expression_list();
887   root_list_init->push_back(Expression::make_nil(builtin_loc));
888   root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type,
889 							builtin_loc));
890 
891   Expression* roots_ctor =
892       Expression::make_array_composite_literal(root_array_type, roots_init,
893                                                builtin_loc);
894   root_list_init->push_back(roots_ctor);
895 
896   Expression* root_list_ctor =
897       Expression::make_struct_composite_literal(root_list_type, root_list_init,
898                                                 builtin_loc);
899 
900   Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
901                                                  builtin_loc);
902   root_addr->unary_expression()->set_is_gc_root();
903   Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
904                                                   builtin_loc, 1, root_addr);
905 
906   Translate_context context(this, NULL, NULL, NULL);
907   Bexpression* bcall = register_roots->get_backend(&context);
908   init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall));
909 }
910 
911 // Build the list of type descriptors defined in this package. This is to help
912 // the reflect package to find compiler-generated types.
913 
914 // type typeDescriptorList struct {
915 // 	 count int
916 // 	 types [...]unsafe.Pointer
917 // }
918 
919 static Struct_type*
type_descriptor_list_type(unsigned long len)920 type_descriptor_list_type(unsigned long len)
921 {
922   Location builtin_loc = Linemap::predeclared_location();
923   Type* int_type = Type::lookup_integer_type("int");
924   Type* ptr_type = Type::make_pointer_type(Type::make_void_type());
925   // Avoid creating zero-length type.
926   unsigned long nelems = (len != 0 ? len : 1);
927   Expression* len_expr = Expression::make_integer_ul(nelems, NULL,
928                                                      builtin_loc);
929   Array_type* array_type = Type::make_array_type(ptr_type, len_expr);
930   array_type->set_is_array_incomparable();
931   Struct_type* list_type =
932     Type::make_builtin_struct_type(2, "count", int_type,
933                                    "types", array_type);
934   return list_type;
935 }
936 
937 void
build_type_descriptor_list()938 Gogo::build_type_descriptor_list()
939 {
940   // Create the list type
941   Location builtin_loc = Linemap::predeclared_location();
942   unsigned long len = this->type_descriptors_.size();
943   Struct_type* list_type = type_descriptor_list_type(len);
944   Btype* bt = list_type->get_backend(this);
945   Btype* bat = list_type->field(1)->type()->get_backend(this);
946 
947   // Create the variable
948   std::string name = this->type_descriptor_list_symbol(this->pkgpath_symbol());
949   Bvariable* bv = this->backend()->implicit_variable(name, name, bt,
950                                                      false, true, false,
951                                                      0);
952 
953   // Build the initializer
954   std::vector<unsigned long> indexes;
955   std::vector<Bexpression*> vals;
956   std::vector<Type*>::iterator p = this->type_descriptors_.begin();
957   for (unsigned long i = 0; i < len; ++i, ++p)
958     {
959       Bexpression* bexpr = (*p)->type_descriptor_pointer(this,
960                                                          builtin_loc);
961       indexes.push_back(i);
962       vals.push_back(bexpr);
963     }
964   Bexpression* barray =
965     this->backend()->array_constructor_expression(bat, indexes, vals,
966                                                   builtin_loc);
967 
968   Translate_context context(this, NULL, NULL, NULL);
969   std::vector<Bexpression*> fields;
970   Expression* len_expr = Expression::make_integer_ul(len, NULL,
971                                                      builtin_loc);
972   fields.push_back(len_expr->get_backend(&context));
973   fields.push_back(barray);
974   Bexpression* binit =
975     this->backend()->constructor_expression(bt, fields, builtin_loc);
976 
977   this->backend()->implicit_variable_set_init(bv, name, bt, false,
978                                               true, false, binit);
979 }
980 
981 // Register the type descriptors with the runtime.  This is to help
982 // the reflect package to find compiler-generated types.
983 
984 void
register_type_descriptors(std::vector<Bstatement * > & init_stmts,Bfunction * init_bfn)985 Gogo::register_type_descriptors(std::vector<Bstatement*>& init_stmts,
986                                 Bfunction* init_bfn)
987 {
988   // Create the list type
989   Location builtin_loc = Linemap::predeclared_location();
990   Struct_type* list_type = type_descriptor_list_type(1);
991   Btype* bt = list_type->get_backend(this);
992 
993   // Collect type lists from transitive imports.
994   std::vector<std::string> list_names;
995   for (Import_init_set::iterator it = this->imported_init_fns_.begin();
996        it != this->imported_init_fns_.end();
997        ++it)
998     {
999       std::string pkgpath =
1000         this->pkgpath_from_init_fn_name((*it)->init_name());
1001       list_names.push_back(this->type_descriptor_list_symbol(pkgpath));
1002     }
1003   // Add the main package itself.
1004   list_names.push_back(this->type_descriptor_list_symbol("main"));
1005 
1006   // Build a list of lists.
1007   std::vector<unsigned long> indexes;
1008   std::vector<Bexpression*> vals;
1009   unsigned long i = 0;
1010   for (std::vector<std::string>::iterator p = list_names.begin();
1011        p != list_names.end();
1012        ++p)
1013     {
1014       Bvariable* bv =
1015         this->backend()->implicit_variable_reference(*p, *p, bt);
1016       Bexpression* bexpr = this->backend()->var_expression(bv, builtin_loc);
1017       bexpr = this->backend()->address_expression(bexpr, builtin_loc);
1018 
1019       indexes.push_back(i);
1020       vals.push_back(bexpr);
1021       i++;
1022     }
1023   Expression* len_expr = Expression::make_integer_ul(i, NULL, builtin_loc);
1024   Type* list_ptr_type = Type::make_pointer_type(list_type);
1025   Type* list_array_type = Type::make_array_type(list_ptr_type, len_expr);
1026   Btype* bat = list_array_type->get_backend(this);
1027   Bexpression* barray =
1028     this->backend()->array_constructor_expression(bat, indexes, vals,
1029                                                   builtin_loc);
1030 
1031   // Create a variable holding the list.
1032   std::string name = this->typelists_symbol();
1033   Bvariable* bv = this->backend()->implicit_variable(name, name, bat,
1034                                                      true, true, false,
1035                                                      0);
1036   this->backend()->implicit_variable_set_init(bv, name, bat, true, true,
1037                                               false, barray);
1038 
1039   // Build the call in main package's init function.
1040   Translate_context context(this, NULL, NULL, NULL);
1041   Bexpression* bexpr = this->backend()->var_expression(bv, builtin_loc);
1042   bexpr = this->backend()->address_expression(bexpr, builtin_loc);
1043   Type* array_ptr_type = Type::make_pointer_type(list_array_type);
1044   Expression* expr = Expression::make_backend(bexpr, array_ptr_type,
1045                                               builtin_loc);
1046   expr = Runtime::make_call(Runtime::REGISTER_TYPE_DESCRIPTORS,
1047                             builtin_loc, 2, len_expr->copy(), expr);
1048   Bexpression* bcall = expr->get_backend(&context);
1049   init_stmts.push_back(this->backend()->expression_statement(init_bfn,
1050                                                              bcall));
1051 }
1052 
1053 // Build the decl for the initialization function.
1054 
1055 Named_object*
initialization_function_decl()1056 Gogo::initialization_function_decl()
1057 {
1058   std::string name = this->get_init_fn_name();
1059   Location loc = this->package_->location();
1060 
1061   Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
1062   Function* initfn = new Function(fntype, NULL, NULL, loc);
1063   return Named_object::make_function(name, NULL, initfn);
1064 }
1065 
1066 // Create the magic initialization function.  CODE_STMT is the
1067 // code that it needs to run.
1068 
1069 Named_object*
create_initialization_function(Named_object * initfn,Bstatement * code_stmt)1070 Gogo::create_initialization_function(Named_object* initfn,
1071 				     Bstatement* code_stmt)
1072 {
1073   // Make sure that we thought we needed an initialization function,
1074   // as otherwise we will not have reported it in the export data.
1075   go_assert(this->is_main_package() || this->need_init_fn_);
1076 
1077   if (initfn == NULL)
1078     initfn = this->initialization_function_decl();
1079 
1080   // Bind the initialization function code to a block.
1081   Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
1082   Location pkg_loc = this->package_->location();
1083   std::vector<Bvariable*> vars;
1084   this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
1085 
1086   if (!this->backend()->function_set_body(fndecl, code_stmt))
1087     {
1088       go_assert(saw_errors());
1089       return NULL;
1090     }
1091   return initfn;
1092 }
1093 
1094 // Given an expression, collect all the global variables defined in
1095 // this package that it references.
1096 
1097 class Find_vars : public Traverse
1098 {
1099  private:
1100   // The list of variables we accumulate.
1101   typedef Unordered_set(Named_object*) Vars;
1102 
1103   // A hash table we use to avoid looping.  The index is a
1104   // Named_object* or a Temporary_statement*.  We only look through
1105   // objects defined in this package.
1106   typedef Unordered_set(const void*) Seen_objects;
1107 
1108  public:
Find_vars()1109   Find_vars()
1110     : Traverse(traverse_expressions),
1111       vars_(), seen_objects_()
1112   { }
1113 
1114   // An iterator through the variables found, after the traversal.
1115   typedef Vars::const_iterator const_iterator;
1116 
1117   const_iterator
begin() const1118   begin() const
1119   { return this->vars_.begin(); }
1120 
1121   const_iterator
end() const1122   end() const
1123   { return this->vars_.end(); }
1124 
1125   int
1126   expression(Expression**);
1127 
1128  private:
1129   // Accumulated variables.
1130   Vars vars_;
1131   // Objects we have already seen.
1132   Seen_objects seen_objects_;
1133 };
1134 
1135 // Collect global variables referenced by EXPR.  Look through function
1136 // calls and variable initializations.
1137 
1138 int
expression(Expression ** pexpr)1139 Find_vars::expression(Expression** pexpr)
1140 {
1141   Expression* e = *pexpr;
1142 
1143   Var_expression* ve = e->var_expression();
1144   if (ve != NULL)
1145     {
1146       Named_object* v = ve->named_object();
1147       if (!v->is_variable() || v->package() != NULL)
1148 	{
1149 	  // This is a result parameter or a variable defined in a
1150 	  // different package.  Either way we don't care about it.
1151 	  return TRAVERSE_CONTINUE;
1152 	}
1153 
1154       std::pair<Seen_objects::iterator, bool> ins =
1155 	this->seen_objects_.insert(v);
1156       if (!ins.second)
1157 	{
1158 	  // We've seen this variable before.
1159 	  return TRAVERSE_CONTINUE;
1160 	}
1161 
1162       if (v->var_value()->is_global())
1163 	this->vars_.insert(v);
1164 
1165       Expression* init = v->var_value()->init();
1166       if (init != NULL)
1167 	{
1168 	  if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1169 	    return TRAVERSE_EXIT;
1170 	}
1171     }
1172 
1173   // We traverse the code of any function or bound method we see.  Note that
1174   // this means that we will traverse the code of a function or bound method
1175   // whose address is taken even if it is not called.
1176   Func_expression* fe = e->func_expression();
1177   Bound_method_expression* bme = e->bound_method_expression();
1178   if (fe != NULL || bme != NULL)
1179     {
1180       const Named_object* f = fe != NULL ? fe->named_object() : bme->function();
1181       if (f->is_function() && f->package() == NULL)
1182 	{
1183 	  std::pair<Seen_objects::iterator, bool> ins =
1184 	    this->seen_objects_.insert(f);
1185 	  if (ins.second)
1186 	    {
1187 	      // This is the first time we have seen this name.
1188 	      if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
1189 		return TRAVERSE_EXIT;
1190 	    }
1191 	}
1192     }
1193 
1194   Temporary_reference_expression* tre = e->temporary_reference_expression();
1195   if (tre != NULL)
1196     {
1197       Temporary_statement* ts = tre->statement();
1198       Expression* init = ts->init();
1199       if (init != NULL)
1200 	{
1201 	  std::pair<Seen_objects::iterator, bool> ins =
1202 	    this->seen_objects_.insert(ts);
1203 	  if (ins.second)
1204 	    {
1205 	      // This is the first time we have seen this temporary
1206 	      // statement.
1207 	      if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1208 		return TRAVERSE_EXIT;
1209 	    }
1210 	}
1211     }
1212 
1213   return TRAVERSE_CONTINUE;
1214 }
1215 
1216 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1217 
1218 static bool
expression_requires(Expression * expr,Block * preinit,Named_object * dep,Named_object * var)1219 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1220 		    Named_object* var)
1221 {
1222   Find_vars find_vars;
1223   if (expr != NULL)
1224     Expression::traverse(&expr, &find_vars);
1225   if (preinit != NULL)
1226     preinit->traverse(&find_vars);
1227   if (dep != NULL)
1228     {
1229       Expression* init = dep->var_value()->init();
1230       if (init != NULL)
1231 	Expression::traverse(&init, &find_vars);
1232       if (dep->var_value()->has_pre_init())
1233 	dep->var_value()->preinit()->traverse(&find_vars);
1234     }
1235 
1236   for (Find_vars::const_iterator p = find_vars.begin();
1237        p != find_vars.end();
1238        ++p)
1239     {
1240       if (*p == var)
1241 	return true;
1242     }
1243   return false;
1244 }
1245 
1246 // Sort variable initializations.  If the initialization expression
1247 // for variable A refers directly or indirectly to the initialization
1248 // expression for variable B, then we must initialize B before A.
1249 
1250 class Var_init
1251 {
1252  public:
Var_init()1253   Var_init()
1254     : var_(NULL), init_(NULL), refs_(NULL), dep_count_(0)
1255   { }
1256 
Var_init(Named_object * var,Bstatement * init)1257   Var_init(Named_object* var, Bstatement* init)
1258     : var_(var), init_(init), refs_(NULL), dep_count_(0)
1259   { }
1260 
1261   // Return the variable.
1262   Named_object*
var() const1263   var() const
1264   { return this->var_; }
1265 
1266   // Return the initialization expression.
1267   Bstatement*
init() const1268   init() const
1269   { return this->init_; }
1270 
1271   // Add a reference.
1272   void
1273   add_ref(Named_object* var);
1274 
1275   // The variables which this variable's initializers refer to.
1276   const std::vector<Named_object*>*
refs()1277   refs()
1278   { return this->refs_; }
1279 
1280   // Clear the references, if any.
1281   void
1282   clear_refs();
1283 
1284   // Return the number of remaining dependencies.
1285   size_t
dep_count() const1286   dep_count() const
1287   { return this->dep_count_; }
1288 
1289   // Increment the number of dependencies.
1290   void
add_dependency()1291   add_dependency()
1292   { ++this->dep_count_; }
1293 
1294   // Decrement the number of dependencies.
1295   void
remove_dependency()1296   remove_dependency()
1297   { --this->dep_count_; }
1298 
1299  private:
1300   // The variable being initialized.
1301   Named_object* var_;
1302   // The backend initialization statement.
1303   Bstatement* init_;
1304   // Variables this refers to.
1305   std::vector<Named_object*>* refs_;
1306   // The number of initializations this is dependent on.  A variable
1307   // initialization should not be emitted if any of its dependencies
1308   // have not yet been resolved.
1309   size_t dep_count_;
1310 };
1311 
1312 // Add a reference.
1313 
1314 void
add_ref(Named_object * var)1315 Var_init::add_ref(Named_object* var)
1316 {
1317   if (this->refs_ == NULL)
1318     this->refs_ = new std::vector<Named_object*>;
1319   this->refs_->push_back(var);
1320 }
1321 
1322 // Clear the references, if any.
1323 
1324 void
clear_refs()1325 Var_init::clear_refs()
1326 {
1327   if (this->refs_ != NULL)
1328     {
1329       delete this->refs_;
1330       this->refs_ = NULL;
1331     }
1332 }
1333 
1334 // For comparing Var_init keys in a map.
1335 
1336 inline bool
operator <(const Var_init & v1,const Var_init & v2)1337 operator<(const Var_init& v1, const Var_init& v2)
1338 { return v1.var()->name() < v2.var()->name(); }
1339 
1340 typedef std::list<Var_init> Var_inits;
1341 
1342 // Sort the variable initializations.  The rule we follow is that we
1343 // emit them in the order they appear in the array, except that if the
1344 // initialization expression for a variable V1 depends upon another
1345 // variable V2 then we initialize V1 after V2.
1346 
1347 static void
sort_var_inits(Gogo * gogo,Var_inits * var_inits)1348 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1349 {
1350   if (var_inits->empty())
1351     return;
1352 
1353   std::map<Named_object*, Var_init*> var_to_init;
1354 
1355   // A mapping from a variable initialization to a set of
1356   // variable initializations that depend on it.
1357   typedef std::map<Var_init, std::set<Var_init*> > Init_deps;
1358   Init_deps init_deps;
1359   bool init_loop = false;
1360 
1361   // Compute all variable references.
1362   for (Var_inits::iterator pvar = var_inits->begin();
1363        pvar != var_inits->end();
1364        ++pvar)
1365     {
1366       Named_object* var = pvar->var();
1367       var_to_init[var] = &*pvar;
1368 
1369       Find_vars find_vars;
1370       Expression* init = var->var_value()->init();
1371       if (init != NULL)
1372 	Expression::traverse(&init, &find_vars);
1373       if (var->var_value()->has_pre_init())
1374 	var->var_value()->preinit()->traverse(&find_vars);
1375       Named_object* dep = gogo->var_depends_on(var->var_value());
1376       if (dep != NULL)
1377 	{
1378 	  Expression* dinit = dep->var_value()->init();
1379 	  if (dinit != NULL)
1380 	    Expression::traverse(&dinit, &find_vars);
1381 	  if (dep->var_value()->has_pre_init())
1382 	    dep->var_value()->preinit()->traverse(&find_vars);
1383 	}
1384       for (Find_vars::const_iterator p = find_vars.begin();
1385 	   p != find_vars.end();
1386 	   ++p)
1387 	pvar->add_ref(*p);
1388     }
1389 
1390   // Add dependencies to init_deps, and check for cycles.
1391   for (Var_inits::iterator pvar = var_inits->begin();
1392        pvar != var_inits->end();
1393        ++pvar)
1394     {
1395       Named_object* var = pvar->var();
1396 
1397       const std::vector<Named_object*>* refs = pvar->refs();
1398       if (refs == NULL)
1399 	continue;
1400       for (std::vector<Named_object*>::const_iterator pdep = refs->begin();
1401 	   pdep != refs->end();
1402 	   ++pdep)
1403 	{
1404 	  Named_object* dep = *pdep;
1405 	  if (var == dep)
1406 	    {
1407 	      // This is a reference from a variable to itself, which
1408 	      // may indicate a loop.  We only report an error if
1409 	      // there is an initializer and there is no dependency.
1410 	      // When there is no initializer, it means that the
1411 	      // preinitializer sets the variable, which will appear
1412 	      // to be a loop here.
1413 	      if (var->var_value()->init() != NULL
1414 		  && gogo->var_depends_on(var->var_value()) == NULL)
1415 		go_error_at(var->location(),
1416 			    ("initialization expression for %qs "
1417 			     "depends upon itself"),
1418 			    var->message_name().c_str());
1419 
1420 	      continue;
1421 	    }
1422 
1423 	  Var_init* dep_init = var_to_init[dep];
1424 	  if (dep_init == NULL)
1425 	    {
1426 	      // This is a dependency on some variable that doesn't
1427 	      // have an initializer, so for purposes of
1428 	      // initialization ordering this is irrelevant.
1429 	      continue;
1430 	    }
1431 
1432 	  init_deps[*dep_init].insert(&(*pvar));
1433 	  pvar->add_dependency();
1434 
1435 	  // Check for cycles.
1436 	  const std::vector<Named_object*>* deprefs = dep_init->refs();
1437 	  if (deprefs == NULL)
1438 	    continue;
1439 	  for (std::vector<Named_object*>::const_iterator pdepdep =
1440 		 deprefs->begin();
1441 	       pdepdep != deprefs->end();
1442 	       ++pdepdep)
1443 	    {
1444 	      if (*pdepdep == var)
1445 		{
1446 		  go_error_at(var->location(),
1447 			      ("initialization expressions for %qs and "
1448 			       "%qs depend upon each other"),
1449 			      var->message_name().c_str(),
1450 			      dep->message_name().c_str());
1451 		  go_inform(dep->location(), "%qs defined here",
1452 			    dep->message_name().c_str());
1453 		  init_loop = true;
1454 		  break;
1455 		}
1456 	    }
1457 	}
1458     }
1459 
1460   var_to_init.clear();
1461   for (Var_inits::iterator pvar = var_inits->begin();
1462        pvar != var_inits->end();
1463        ++pvar)
1464     pvar->clear_refs();
1465 
1466   // If there are no dependencies then the declaration order is sorted.
1467   if (!init_deps.empty() && !init_loop)
1468     {
1469       // Otherwise, sort variable initializations by emitting all variables with
1470       // no dependencies in declaration order. VAR_INITS is already in
1471       // declaration order.
1472       Var_inits ready;
1473       while (!var_inits->empty())
1474 	{
1475 	  Var_inits::iterator v1;;
1476 	  for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1)
1477 	    {
1478 	      if (v1->dep_count() == 0)
1479 		break;
1480 	    }
1481 	  go_assert(v1 != var_inits->end());
1482 
1483 	  // V1 either has no dependencies or its dependencies have already
1484 	  // been emitted, add it to READY next.  When V1 is emitted, remove
1485 	  // a dependency from each V that depends on V1.
1486 	  ready.splice(ready.end(), *var_inits, v1);
1487 
1488 	  Init_deps::iterator p1 = init_deps.find(*v1);
1489 	  if (p1 != init_deps.end())
1490 	    {
1491 	      std::set<Var_init*> resolved = p1->second;
1492 	      for (std::set<Var_init*>::iterator pv = resolved.begin();
1493 		   pv != resolved.end();
1494 		   ++pv)
1495 		(*pv)->remove_dependency();
1496 	      init_deps.erase(p1);
1497 	    }
1498 	}
1499       var_inits->swap(ready);
1500       go_assert(init_deps.empty());
1501     }
1502 }
1503 
1504 // Give an error if the initialization expression for VAR depends on
1505 // itself.  We only check if INIT is not NULL and there is no
1506 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1507 // which we will interpret as a loop.
1508 
1509 void
check_self_dep(Named_object * var)1510 Gogo::check_self_dep(Named_object* var)
1511 {
1512   Expression* init = var->var_value()->init();
1513   Block* preinit = var->var_value()->preinit();
1514   Named_object* dep = this->var_depends_on(var->var_value());
1515   if (init != NULL
1516       && dep == NULL
1517       && expression_requires(init, preinit, NULL, var))
1518     go_error_at(var->location(),
1519 		"initialization expression for %qs depends upon itself",
1520 		var->message_name().c_str());
1521 }
1522 
1523 // Write out the global definitions.
1524 
1525 void
write_globals()1526 Gogo::write_globals()
1527 {
1528   this->build_interface_method_tables();
1529 
1530   Bindings* bindings = this->current_bindings();
1531 
1532   for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1533        p != bindings->end_declarations();
1534        ++p)
1535     {
1536       // If any function declarations needed a descriptor, make sure
1537       // we build it.
1538       Named_object* no = p->second;
1539       if (no->is_function_declaration())
1540 	no->func_declaration_value()->build_backend_descriptor(this);
1541     }
1542 
1543   // Lists of globally declared types, variables, constants, and functions
1544   // that must be defined.
1545   std::vector<Btype*> type_decls;
1546   std::vector<Bvariable*> var_decls;
1547   std::vector<Bexpression*> const_decls;
1548   std::vector<Bfunction*> func_decls;
1549 
1550   // The init function declaration and associated Bfunction, if necessary.
1551   Named_object* init_fndecl = NULL;
1552   Bfunction* init_bfn = NULL;
1553 
1554   std::vector<Bstatement*> init_stmts;
1555   std::vector<Bstatement*> var_init_stmts;
1556 
1557   if (this->is_main_package())
1558     {
1559       init_fndecl = this->initialization_function_decl();
1560       init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl);
1561     }
1562 
1563   // A list of variable initializations.
1564   Var_inits var_inits;
1565 
1566   // A list of variables which need to be registered with the garbage
1567   // collector.
1568   size_t count_definitions = bindings->size_definitions();
1569   std::vector<Named_object*> var_gc;
1570   var_gc.reserve(count_definitions);
1571 
1572   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1573        p != bindings->end_definitions();
1574        ++p)
1575     {
1576       Named_object* no = *p;
1577       go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1578 
1579       // There is nothing to do for a package.
1580       if (no->is_package())
1581         continue;
1582 
1583       // There is nothing to do for an object which was imported from
1584       // a different package into the global scope.
1585       if (no->package() != NULL)
1586         continue;
1587 
1588       // Skip blank named functions and constants.
1589       if ((no->is_function() && no->func_value()->is_sink())
1590 	  || (no->is_const() && no->const_value()->is_sink()))
1591         continue;
1592 
1593       // There is nothing useful we can output for constants which
1594       // have ideal or non-integral type.
1595       if (no->is_const())
1596         {
1597           Type* type = no->const_value()->type();
1598           if (type == NULL)
1599             type = no->const_value()->expr()->type();
1600           if (type->is_abstract() || !type->is_numeric_type())
1601             continue;
1602         }
1603 
1604       if (!no->is_variable())
1605         no->get_backend(this, const_decls, type_decls, func_decls);
1606       else
1607 	{
1608           Variable* var = no->var_value();
1609 	  Bvariable* bvar = no->get_backend_variable(this, NULL);
1610           var_decls.push_back(bvar);
1611 
1612 	  // Check for a sink variable, which may be used to run an
1613 	  // initializer purely for its side effects.
1614 	  bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1615 
1616           Bstatement* var_init_stmt = NULL;
1617 	  if (!var->has_pre_init())
1618 	    {
1619               // If the backend representation of the variable initializer is
1620               // constant, we can just set the initial value using
1621               // global_var_set_init instead of during the init() function.
1622               // The initializer is constant if it is the zero-value of the
1623               // variable's type or if the initial value is an immutable value
1624               // that is not copied to the heap.
1625               bool is_static_initializer = false;
1626               if (var->init() == NULL)
1627                 is_static_initializer = true;
1628               else
1629                 {
1630                   Type* var_type = var->type();
1631                   Expression* init = var->init();
1632                   Expression* init_cast =
1633                       Expression::make_cast(var_type, init, var->location());
1634                   is_static_initializer = init_cast->is_static_initializer();
1635                 }
1636 
1637 	      // Non-constant variable initializations might need to create
1638 	      // temporary variables, which will need the initialization
1639 	      // function as context.
1640 	      Named_object* var_init_fn;
1641 	      if (is_static_initializer)
1642 		var_init_fn = NULL;
1643 	      else
1644 		{
1645 		  if (init_fndecl == NULL)
1646                     {
1647                       init_fndecl = this->initialization_function_decl();
1648                       Function* func = init_fndecl->func_value();
1649                       init_bfn = func->get_or_make_decl(this, init_fndecl);
1650                     }
1651 		  var_init_fn = init_fndecl;
1652 		}
1653               Bexpression* var_binit = var->get_init(this, var_init_fn);
1654 
1655               if (var_binit == NULL)
1656 		;
1657 	      else if (is_static_initializer)
1658 		{
1659 		  if (expression_requires(var->init(), NULL,
1660 					  this->var_depends_on(var), no))
1661 		    go_error_at(no->location(),
1662 				"initialization expression for %qs depends "
1663 				"upon itself",
1664 				no->message_name().c_str());
1665 		  this->backend()->global_variable_set_init(bvar, var_binit);
1666 		}
1667 	      else if (is_sink)
1668 	        var_init_stmt =
1669                     this->backend()->expression_statement(init_bfn, var_binit);
1670 	      else
1671                 {
1672                   Location loc = var->location();
1673                   Bexpression* var_expr =
1674                       this->backend()->var_expression(bvar, loc);
1675                   var_init_stmt =
1676                       this->backend()->assignment_statement(init_bfn, var_expr,
1677                                                             var_binit, loc);
1678                 }
1679 	    }
1680 	  else
1681 	    {
1682 	      // We are going to create temporary variables which
1683 	      // means that we need an fndecl.
1684               if (init_fndecl == NULL)
1685 		init_fndecl = this->initialization_function_decl();
1686 
1687 	      Bvariable* var_decl = is_sink ? NULL : bvar;
1688 	      var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1689 	    }
1690 
1691 	  if (var_init_stmt != NULL)
1692 	    {
1693 	      if (var->init() == NULL && !var->has_pre_init())
1694                 var_init_stmts.push_back(var_init_stmt);
1695 	      else
1696                 var_inits.push_back(Var_init(no, var_init_stmt));
1697 	    }
1698 	  else if (this->var_depends_on(var) != NULL)
1699 	    {
1700 	      // This variable is initialized from something that is
1701 	      // not in its init or preinit.  This variable needs to
1702 	      // participate in dependency analysis sorting, in case
1703 	      // some other variable depends on this one.
1704               Btype* btype = no->var_value()->type()->get_backend(this);
1705               Bexpression* zero = this->backend()->zero_expression(btype);
1706               Bstatement* zero_stmt =
1707                   this->backend()->expression_statement(init_bfn, zero);
1708 	      var_inits.push_back(Var_init(no, zero_stmt));
1709 	    }
1710 
1711 	  // Collect a list of all global variables with pointers,
1712 	  // to register them for the garbage collector.
1713 	  if (!is_sink && var->type()->has_pointer())
1714 	    {
1715 	      // Avoid putting runtime.gcRoots itself on the list.
1716 	      if (this->compiling_runtime()
1717 		  && this->package_name() == "runtime"
1718 		  && (Gogo::unpack_hidden_name(no->name()) == "gcRoots"
1719                    || Gogo::unpack_hidden_name(no->name()) == "gcRootsIndex"))
1720 		;
1721 	      else
1722 		var_gc.push_back(no);
1723 	    }
1724 	}
1725     }
1726 
1727   // Output inline functions, which are in different packages.
1728   for (std::vector<Named_object*>::const_iterator p =
1729 	 this->imported_inline_functions_.begin();
1730        p != this->imported_inline_functions_.end();
1731        ++p)
1732     (*p)->get_backend(this, const_decls, type_decls, func_decls);
1733 
1734   // Build the list of type descriptors.
1735   this->build_type_descriptor_list();
1736 
1737   if (this->is_main_package())
1738     {
1739       // Register the type descriptor lists, so that at run time
1740       // the reflect package can find compiler-created types, and
1741       // deduplicate if the same type is created with reflection.
1742       // This needs to be done before calling any package's init
1743       // function, as it may create type through reflection.
1744       this->register_type_descriptors(init_stmts, init_bfn);
1745 
1746       // Initialize imported packages.
1747       this->init_imports(init_stmts, init_bfn);
1748     }
1749 
1750   // Register global variables with the garbage collector.
1751   this->register_gc_vars(var_gc, init_stmts, init_bfn);
1752 
1753   // Simple variable initializations, after all variables are
1754   // registered.
1755   init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1756 
1757   // Complete variable initializations, first sorting them into a
1758   // workable order.
1759   if (!var_inits.empty())
1760     {
1761       sort_var_inits(this, &var_inits);
1762       for (Var_inits::const_iterator p = var_inits.begin();
1763            p != var_inits.end();
1764            ++p)
1765         init_stmts.push_back(p->init());
1766     }
1767 
1768   // After all the variables are initialized, call the init
1769   // functions if there are any.  Init functions take no arguments, so
1770   // we pass in EMPTY_ARGS to call them.
1771   std::vector<Bexpression*> empty_args;
1772   for (std::vector<Named_object*>::const_iterator p =
1773            this->init_functions_.begin();
1774        p != this->init_functions_.end();
1775        ++p)
1776     {
1777       Location func_loc = (*p)->location();
1778       Function* func = (*p)->func_value();
1779       Bfunction* initfn = func->get_or_make_decl(this, *p);
1780       Bexpression* func_code =
1781           this->backend()->function_code_expression(initfn, func_loc);
1782       Bexpression* call = this->backend()->call_expression(init_bfn, func_code,
1783                                                            empty_args,
1784 							   NULL, func_loc);
1785       Bstatement* ist = this->backend()->expression_statement(init_bfn, call);
1786       init_stmts.push_back(ist);
1787     }
1788 
1789   // Set up a magic function to do all the initialization actions.
1790   // This will be called if this package is imported.
1791   Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1792   if (this->need_init_fn_ || this->is_main_package())
1793     {
1794       init_fndecl =
1795 	this->create_initialization_function(init_fndecl, init_fncode);
1796       if (init_fndecl != NULL)
1797 	func_decls.push_back(init_fndecl->func_value()->get_decl());
1798     }
1799 
1800   // We should not have seen any new bindings created during the conversion.
1801   go_assert(count_definitions == this->current_bindings()->size_definitions());
1802 
1803   // Define all globally declared values.
1804   if (!saw_errors())
1805     this->backend()->write_global_definitions(type_decls, const_decls,
1806 					      func_decls, var_decls);
1807 }
1808 
1809 // Return the current block.
1810 
1811 Block*
current_block()1812 Gogo::current_block()
1813 {
1814   if (this->functions_.empty())
1815     return NULL;
1816   else
1817     return this->functions_.back().blocks.back();
1818 }
1819 
1820 // Look up a name in the current binding contour.  If PFUNCTION is not
1821 // NULL, set it to the function in which the name is defined, or NULL
1822 // if the name is defined in global scope.
1823 
1824 Named_object*
lookup(const std::string & name,Named_object ** pfunction) const1825 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1826 {
1827   if (pfunction != NULL)
1828     *pfunction = NULL;
1829 
1830   if (Gogo::is_sink_name(name))
1831     return Named_object::make_sink();
1832 
1833   for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1834        p != this->functions_.rend();
1835        ++p)
1836     {
1837       Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1838       if (ret != NULL)
1839 	{
1840 	  if (pfunction != NULL)
1841 	    *pfunction = p->function;
1842 	  return ret;
1843 	}
1844     }
1845 
1846   if (this->package_ != NULL)
1847     {
1848       Named_object* ret = this->package_->bindings()->lookup(name);
1849       if (ret != NULL)
1850 	{
1851 	  if (ret->package() != NULL)
1852             {
1853               std::string dot_alias = "." + ret->package()->package_name();
1854               ret->package()->note_usage(dot_alias);
1855             }
1856 	  return ret;
1857 	}
1858     }
1859 
1860   // We do not look in the global namespace.  If we did, the global
1861   // namespace would effectively hide names which were defined in
1862   // package scope which we have not yet seen.  Instead,
1863   // define_global_names is called after parsing is over to connect
1864   // undefined names at package scope with names defined at global
1865   // scope.
1866 
1867   return NULL;
1868 }
1869 
1870 // Look up a name in the current block, without searching enclosing
1871 // blocks.
1872 
1873 Named_object*
lookup_in_block(const std::string & name) const1874 Gogo::lookup_in_block(const std::string& name) const
1875 {
1876   go_assert(!this->functions_.empty());
1877   go_assert(!this->functions_.back().blocks.empty());
1878   return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1879 }
1880 
1881 // Look up a name in the global namespace.
1882 
1883 Named_object*
lookup_global(const char * name) const1884 Gogo::lookup_global(const char* name) const
1885 {
1886   return this->globals_->lookup(name);
1887 }
1888 
1889 // Add an imported package.
1890 
1891 Package*
add_imported_package(const std::string & real_name,const std::string & alias_arg,bool is_alias_exported,const std::string & pkgpath,const std::string & pkgpath_symbol,Location location,bool * padd_to_globals)1892 Gogo::add_imported_package(const std::string& real_name,
1893 			   const std::string& alias_arg,
1894 			   bool is_alias_exported,
1895 			   const std::string& pkgpath,
1896 			   const std::string& pkgpath_symbol,
1897 			   Location location,
1898 			   bool* padd_to_globals)
1899 {
1900   Package* ret = this->register_package(pkgpath, pkgpath_symbol, location);
1901   ret->set_package_name(real_name, location);
1902 
1903   *padd_to_globals = false;
1904 
1905   if (alias_arg == "_")
1906     ;
1907   else if (alias_arg == ".")
1908     {
1909       *padd_to_globals = true;
1910       std::string dot_alias = "." + real_name;
1911       ret->add_alias(dot_alias, location);
1912     }
1913   else
1914     {
1915       std::string alias = alias_arg;
1916       if (alias.empty())
1917 	{
1918 	  alias = real_name;
1919 	  is_alias_exported = Lex::is_exported_name(alias);
1920 	}
1921       ret->add_alias(alias, location);
1922       alias = this->pack_hidden_name(alias, is_alias_exported);
1923       Named_object* no = this->package_->bindings()->add_package(alias, ret);
1924       if (!no->is_package())
1925 	return NULL;
1926     }
1927 
1928   return ret;
1929 }
1930 
1931 // Register a package.  This package may or may not be imported.  This
1932 // returns the Package structure for the package, creating if it
1933 // necessary.  LOCATION is the location of the import statement that
1934 // led us to see this package.  PKGPATH_SYMBOL is the symbol to use
1935 // for names in the package; it may be the empty string, in which case
1936 // we either get it later or make a guess when we need it.
1937 
1938 Package*
register_package(const std::string & pkgpath,const std::string & pkgpath_symbol,Location location)1939 Gogo::register_package(const std::string& pkgpath,
1940 		       const std::string& pkgpath_symbol, Location location)
1941 {
1942   Package* package = NULL;
1943   std::pair<Packages::iterator, bool> ins =
1944     this->packages_.insert(std::make_pair(pkgpath, package));
1945   if (!ins.second)
1946     {
1947       // We have seen this package name before.
1948       package = ins.first->second;
1949       go_assert(package != NULL && package->pkgpath() == pkgpath);
1950       if (!pkgpath_symbol.empty())
1951 	package->set_pkgpath_symbol(pkgpath_symbol);
1952       if (Linemap::is_unknown_location(package->location()))
1953 	package->set_location(location);
1954     }
1955   else
1956     {
1957       // First time we have seen this package name.
1958       package = new Package(pkgpath, pkgpath_symbol, location);
1959       go_assert(ins.first->second == NULL);
1960       ins.first->second = package;
1961     }
1962 
1963   return package;
1964 }
1965 
1966 // Return the pkgpath symbol for a package, given the pkgpath.
1967 
1968 std::string
pkgpath_symbol_for_package(const std::string & pkgpath)1969 Gogo::pkgpath_symbol_for_package(const std::string& pkgpath)
1970 {
1971   Packages::iterator p = this->packages_.find(pkgpath);
1972   go_assert(p != this->packages_.end());
1973   return p->second->pkgpath_symbol();
1974 }
1975 
1976 // Start compiling a function.
1977 
1978 Named_object*
start_function(const std::string & name,Function_type * type,bool add_method_to_type,Location location)1979 Gogo::start_function(const std::string& name, Function_type* type,
1980 		     bool add_method_to_type, Location location)
1981 {
1982   bool at_top_level = this->functions_.empty();
1983 
1984   Block* block = new Block(NULL, location);
1985 
1986   Named_object* enclosing = (at_top_level
1987 			 ? NULL
1988 			 : this->functions_.back().function);
1989 
1990   Function* function = new Function(type, enclosing, block, location);
1991 
1992   if (type->is_method())
1993     {
1994       const Typed_identifier* receiver = type->receiver();
1995       Variable* this_param = new Variable(receiver->type(), NULL, false,
1996 					  true, true, location);
1997       std::string rname = receiver->name();
1998       unsigned rcounter = 0;
1999 
2000       // We need to give a nameless receiver parameter a synthesized name to
2001       // avoid having it clash with some other nameless param. FIXME.
2002       Gogo::rename_if_empty(&rname, "r", &rcounter);
2003 
2004       block->bindings()->add_variable(rname, NULL, this_param);
2005     }
2006 
2007   const Typed_identifier_list* parameters = type->parameters();
2008   bool is_varargs = type->is_varargs();
2009   unsigned pcounter = 0;
2010   if (parameters != NULL)
2011     {
2012       for (Typed_identifier_list::const_iterator p = parameters->begin();
2013 	   p != parameters->end();
2014 	   ++p)
2015 	{
2016 	  Variable* param = new Variable(p->type(), NULL, false, true, false,
2017 					 p->location());
2018 	  if (is_varargs && p + 1 == parameters->end())
2019 	    param->set_is_varargs_parameter();
2020 
2021 	  std::string pname = p->name();
2022 
2023           // We need to give each nameless parameter a non-empty name to avoid
2024           // having it clash with some other nameless param. FIXME.
2025           Gogo::rename_if_empty(&pname, "p", &pcounter);
2026 
2027 	  block->bindings()->add_variable(pname, NULL, param);
2028 	}
2029     }
2030 
2031   function->create_result_variables(this);
2032 
2033   const std::string* pname;
2034   std::string nested_name;
2035   bool is_init = false;
2036   if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
2037     {
2038       if ((type->parameters() != NULL && !type->parameters()->empty())
2039 	  || (type->results() != NULL && !type->results()->empty()))
2040 	go_error_at(location,
2041 		    "func init must have no arguments and no return values");
2042       // There can be multiple "init" functions, so give them each a
2043       // different name.
2044       nested_name = this->init_function_name();
2045       pname = &nested_name;
2046       is_init = true;
2047     }
2048   else if (!name.empty())
2049     pname = &name;
2050   else
2051     {
2052       // Invent a name for a nested function.
2053       nested_name = this->nested_function_name(enclosing);
2054       pname = &nested_name;
2055     }
2056 
2057   Named_object* ret;
2058   if (Gogo::is_sink_name(*pname))
2059     {
2060       std::string sname(this->sink_function_name());
2061       ret = Named_object::make_function(sname, NULL, function);
2062       ret->func_value()->set_is_sink();
2063 
2064       if (!type->is_method())
2065 	ret = this->package_->bindings()->add_named_object(ret);
2066       else if (add_method_to_type)
2067 	{
2068 	  // We should report errors even for sink methods.
2069 	  Type* rtype = type->receiver()->type();
2070 	  // Avoid points_to and deref to avoid getting an error if
2071 	  // the type is not yet defined.
2072 	  if (rtype->classification() == Type::TYPE_POINTER)
2073 	    rtype = rtype->points_to();
2074 	  while (rtype->named_type() != NULL
2075 		 && rtype->named_type()->is_alias())
2076 	    rtype = rtype->named_type()->real_type()->forwarded();
2077 	  if (rtype->is_error_type())
2078 	    ;
2079 	  else if (rtype->named_type() != NULL)
2080 	    {
2081 	      if (rtype->named_type()->named_object()->package() != NULL)
2082 		go_error_at(type->receiver()->location(),
2083 			    "may not define methods on non-local type");
2084 	    }
2085 	  else if (rtype->forward_declaration_type() != NULL)
2086 	    {
2087 	      // Go ahead and add the method in case we need to report
2088 	      // an error when we see the definition.
2089 	      rtype->forward_declaration_type()->add_existing_method(ret);
2090 	    }
2091 	  else
2092 	    go_error_at(type->receiver()->location(),
2093 			("invalid receiver type "
2094 			 "(receiver must be a named type)"));
2095 	}
2096     }
2097   else if (!type->is_method())
2098     {
2099       ret = this->package_->bindings()->add_function(*pname, NULL, function);
2100       if (!ret->is_function() || ret->func_value() != function)
2101 	{
2102 	  // Redefinition error.  Invent a name to avoid knockon
2103 	  // errors.
2104 	  std::string rname(this->redefined_function_name());
2105 	  ret = this->package_->bindings()->add_function(rname, NULL, function);
2106 	}
2107     }
2108   else
2109     {
2110       if (!add_method_to_type)
2111 	ret = Named_object::make_function(name, NULL, function);
2112       else
2113 	{
2114 	  go_assert(at_top_level);
2115 	  Type* rtype = type->receiver()->type();
2116 
2117 	  while (rtype->named_type() != NULL
2118 		 && rtype->named_type()->is_alias())
2119 	    rtype = rtype->named_type()->real_type()->forwarded();
2120 
2121 	  // We want to look through the pointer created by the
2122 	  // parser, without getting an error if the type is not yet
2123 	  // defined.
2124 	  if (rtype->classification() == Type::TYPE_POINTER)
2125 	    rtype = rtype->points_to();
2126 
2127 	  while (rtype->named_type() != NULL
2128 		 && rtype->named_type()->is_alias())
2129 	    rtype = rtype->named_type()->real_type()->forwarded();
2130 
2131 	  if (rtype->is_error_type())
2132 	    ret = Named_object::make_function(name, NULL, function);
2133 	  else if (rtype->named_type() != NULL)
2134 	    {
2135 	      if (rtype->named_type()->named_object()->package() != NULL)
2136 		{
2137 		  go_error_at(type->receiver()->location(),
2138 			      "may not define methods on non-local type");
2139 		  ret = Named_object::make_function(name, NULL, function);
2140 		}
2141 	      else
2142 		{
2143 		  ret = rtype->named_type()->add_method(name, function);
2144 		  if (!ret->is_function())
2145 		    {
2146 		      // Redefinition error.
2147 		      ret = Named_object::make_function(name, NULL, function);
2148 		    }
2149 		}
2150 	    }
2151 	  else if (rtype->forward_declaration_type() != NULL)
2152 	    {
2153 	      Named_object* type_no =
2154 		rtype->forward_declaration_type()->named_object();
2155 	      if (type_no->is_unknown())
2156 		{
2157 		  // If we are seeing methods it really must be a
2158 		  // type.  Declare it as such.  An alternative would
2159 		  // be to support lists of methods for unknown
2160 		  // expressions.  Either way the error messages if
2161 		  // this is not a type are going to get confusing.
2162 		  Named_object* declared =
2163 		    this->declare_package_type(type_no->name(),
2164 					       type_no->location());
2165 		  go_assert(declared
2166 			     == type_no->unknown_value()->real_named_object());
2167 		}
2168 	      ret = rtype->forward_declaration_type()->add_method(name,
2169 								  function);
2170 	    }
2171 	  else
2172             {
2173 	      go_error_at(type->receiver()->location(),
2174 			  ("invalid receiver type (receiver must "
2175 			   "be a named type)"));
2176               ret = Named_object::make_function(name, NULL, function);
2177             }
2178 	}
2179       this->package_->bindings()->add_method(ret);
2180     }
2181 
2182   this->functions_.resize(this->functions_.size() + 1);
2183   Open_function& of(this->functions_.back());
2184   of.function = ret;
2185   of.blocks.push_back(block);
2186 
2187   if (is_init)
2188     {
2189       this->init_functions_.push_back(ret);
2190       this->need_init_fn_ = true;
2191     }
2192 
2193   return ret;
2194 }
2195 
2196 // Finish compiling a function.
2197 
2198 void
finish_function(Location location)2199 Gogo::finish_function(Location location)
2200 {
2201   this->finish_block(location);
2202   go_assert(this->functions_.back().blocks.empty());
2203   this->functions_.pop_back();
2204 }
2205 
2206 // Return the current function.
2207 
2208 Named_object*
current_function() const2209 Gogo::current_function() const
2210 {
2211   go_assert(!this->functions_.empty());
2212   return this->functions_.back().function;
2213 }
2214 
2215 // Start a new block.
2216 
2217 void
start_block(Location location)2218 Gogo::start_block(Location location)
2219 {
2220   go_assert(!this->functions_.empty());
2221   Block* block = new Block(this->current_block(), location);
2222   this->functions_.back().blocks.push_back(block);
2223 }
2224 
2225 // Finish a block.
2226 
2227 Block*
finish_block(Location location)2228 Gogo::finish_block(Location location)
2229 {
2230   go_assert(!this->functions_.empty());
2231   go_assert(!this->functions_.back().blocks.empty());
2232   Block* block = this->functions_.back().blocks.back();
2233   this->functions_.back().blocks.pop_back();
2234   block->set_end_location(location);
2235   return block;
2236 }
2237 
2238 // Add an erroneous name.
2239 
2240 Named_object*
add_erroneous_name(const std::string & name)2241 Gogo::add_erroneous_name(const std::string& name)
2242 {
2243   return this->package_->bindings()->add_erroneous_name(name);
2244 }
2245 
2246 // Add an unknown name.
2247 
2248 Named_object*
add_unknown_name(const std::string & name,Location location)2249 Gogo::add_unknown_name(const std::string& name, Location location)
2250 {
2251   return this->package_->bindings()->add_unknown_name(name, location);
2252 }
2253 
2254 // Declare a function.
2255 
2256 Named_object*
declare_function(const std::string & name,Function_type * type,Location location)2257 Gogo::declare_function(const std::string& name, Function_type* type,
2258 		       Location location)
2259 {
2260   if (!type->is_method())
2261     return this->current_bindings()->add_function_declaration(name, NULL, type,
2262 							      location);
2263   else
2264     {
2265       // We don't bother to add this to the list of global
2266       // declarations.
2267       Type* rtype = type->receiver()->type();
2268 
2269       while (rtype->named_type() != NULL
2270 	  && rtype->named_type()->is_alias())
2271 	rtype = rtype->named_type()->real_type()->forwarded();
2272 
2273       // We want to look through the pointer created by the
2274       // parser, without getting an error if the type is not yet
2275       // defined.
2276       if (rtype->classification() == Type::TYPE_POINTER)
2277 	rtype = rtype->points_to();
2278 
2279       while (rtype->named_type() != NULL
2280 	  && rtype->named_type()->is_alias())
2281 	rtype = rtype->named_type()->real_type()->forwarded();
2282 
2283       if (rtype->is_error_type())
2284 	return NULL;
2285       else if (rtype->named_type() != NULL)
2286 	return rtype->named_type()->add_method_declaration(name, NULL, type,
2287 							   location);
2288       else if (rtype->forward_declaration_type() != NULL)
2289 	{
2290 	  Forward_declaration_type* ftype = rtype->forward_declaration_type();
2291 	  return ftype->add_method_declaration(name, NULL, type, location);
2292 	}
2293       else
2294         {
2295 	  go_error_at(type->receiver()->location(),
2296 		      "invalid receiver type (receiver must be a named type)");
2297           return Named_object::make_erroneous_name(name);
2298         }
2299     }
2300 }
2301 
2302 // Add a label definition.
2303 
2304 Label*
add_label_definition(const std::string & label_name,Location location)2305 Gogo::add_label_definition(const std::string& label_name,
2306 			   Location location)
2307 {
2308   go_assert(!this->functions_.empty());
2309   Function* func = this->functions_.back().function->func_value();
2310   Label* label = func->add_label_definition(this, label_name, location);
2311   this->add_statement(Statement::make_label_statement(label, location));
2312   return label;
2313 }
2314 
2315 // Add a label reference.
2316 
2317 Label*
add_label_reference(const std::string & label_name,Location location,bool issue_goto_errors)2318 Gogo::add_label_reference(const std::string& label_name,
2319 			  Location location, bool issue_goto_errors)
2320 {
2321   go_assert(!this->functions_.empty());
2322   Function* func = this->functions_.back().function->func_value();
2323   return func->add_label_reference(this, label_name, location,
2324 				   issue_goto_errors);
2325 }
2326 
2327 // Return the current binding state.
2328 
2329 Bindings_snapshot*
bindings_snapshot(Location location)2330 Gogo::bindings_snapshot(Location location)
2331 {
2332   return new Bindings_snapshot(this->current_block(), location);
2333 }
2334 
2335 // Add a statement.
2336 
2337 void
add_statement(Statement * statement)2338 Gogo::add_statement(Statement* statement)
2339 {
2340   go_assert(!this->functions_.empty()
2341 	     && !this->functions_.back().blocks.empty());
2342   this->functions_.back().blocks.back()->add_statement(statement);
2343 }
2344 
2345 // Add a block.
2346 
2347 void
add_block(Block * block,Location location)2348 Gogo::add_block(Block* block, Location location)
2349 {
2350   go_assert(!this->functions_.empty()
2351 	     && !this->functions_.back().blocks.empty());
2352   Statement* statement = Statement::make_block_statement(block, location);
2353   this->functions_.back().blocks.back()->add_statement(statement);
2354 }
2355 
2356 // Add a constant.
2357 
2358 Named_object*
add_constant(const Typed_identifier & tid,Expression * expr,int iota_value)2359 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
2360 		   int iota_value)
2361 {
2362   return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
2363 }
2364 
2365 // Add a type.
2366 
2367 void
add_type(const std::string & name,Type * type,Location location)2368 Gogo::add_type(const std::string& name, Type* type, Location location)
2369 {
2370   Named_object* no = this->current_bindings()->add_type(name, NULL, type,
2371 							location);
2372   if (!this->in_global_scope() && no->is_type())
2373     {
2374       Named_object* f = this->functions_.back().function;
2375       unsigned int index;
2376       if (f->is_function())
2377 	index = f->func_value()->new_local_type_index();
2378       else
2379 	index = 0;
2380       no->type_value()->set_in_function(f, index);
2381     }
2382 }
2383 
2384 // Add a named type.
2385 
2386 void
add_named_type(Named_type * type)2387 Gogo::add_named_type(Named_type* type)
2388 {
2389   go_assert(this->in_global_scope());
2390   this->current_bindings()->add_named_type(type);
2391 }
2392 
2393 // Declare a type.
2394 
2395 Named_object*
declare_type(const std::string & name,Location location)2396 Gogo::declare_type(const std::string& name, Location location)
2397 {
2398   Bindings* bindings = this->current_bindings();
2399   Named_object* no = bindings->add_type_declaration(name, NULL, location);
2400   if (!this->in_global_scope() && no->is_type_declaration())
2401     {
2402       Named_object* f = this->functions_.back().function;
2403       unsigned int index;
2404       if (f->is_function())
2405 	index = f->func_value()->new_local_type_index();
2406       else
2407 	index = 0;
2408       no->type_declaration_value()->set_in_function(f, index);
2409     }
2410   return no;
2411 }
2412 
2413 // Declare a type at the package level.
2414 
2415 Named_object*
declare_package_type(const std::string & name,Location location)2416 Gogo::declare_package_type(const std::string& name, Location location)
2417 {
2418   return this->package_->bindings()->add_type_declaration(name, NULL, location);
2419 }
2420 
2421 // Declare a function at the package level.
2422 
2423 Named_object*
declare_package_function(const std::string & name,Function_type * type,Location location)2424 Gogo::declare_package_function(const std::string& name, Function_type* type,
2425 			       Location location)
2426 {
2427   return this->package_->bindings()->add_function_declaration(name, NULL, type,
2428 							      location);
2429 }
2430 
2431 // Add a function declaration to the list of functions we may want to
2432 // inline.
2433 
2434 void
add_imported_inlinable_function(Named_object * no)2435 Gogo::add_imported_inlinable_function(Named_object* no)
2436 {
2437   go_assert(no->is_function_declaration());
2438   Function_declaration* fd = no->func_declaration_value();
2439   if (fd->is_on_inlinable_list())
2440     return;
2441   this->imported_inlinable_functions_.push_back(no);
2442   fd->set_is_on_inlinable_list();
2443 }
2444 
2445 // Define a type which was already declared.
2446 
2447 void
define_type(Named_object * no,Named_type * type)2448 Gogo::define_type(Named_object* no, Named_type* type)
2449 {
2450   this->current_bindings()->define_type(no, type);
2451 }
2452 
2453 // Add a variable.
2454 
2455 Named_object*
add_variable(const std::string & name,Variable * variable)2456 Gogo::add_variable(const std::string& name, Variable* variable)
2457 {
2458   Named_object* no = this->current_bindings()->add_variable(name, NULL,
2459 							    variable);
2460 
2461   // In a function the middle-end wants to see a DECL_EXPR node.
2462   if (no != NULL
2463       && no->is_variable()
2464       && !no->var_value()->is_parameter()
2465       && !this->functions_.empty())
2466     this->add_statement(Statement::make_variable_declaration(no));
2467 
2468   return no;
2469 }
2470 
2471 void
rename_if_empty(std::string * pname,const char * tag,unsigned * count)2472 Gogo::rename_if_empty(std::string* pname, const char* tag, unsigned* count)
2473 {
2474   if (pname->empty() || Gogo::is_sink_name(*pname))
2475     {
2476       char buf[50];
2477       go_assert(strlen(tag) < 10);
2478       snprintf(buf, sizeof buf, "%s.%u", tag, *count);
2479       ++(*count);
2480       *pname = buf;
2481     }
2482 }
2483 
2484 
2485 // Add a sink--a reference to the blank identifier _.
2486 
2487 Named_object*
add_sink()2488 Gogo::add_sink()
2489 {
2490   return Named_object::make_sink();
2491 }
2492 
2493 // Add a named object for a dot import.
2494 
2495 void
add_dot_import_object(Named_object * no)2496 Gogo::add_dot_import_object(Named_object* no)
2497 {
2498   // If the name already exists, then it was defined in some file seen
2499   // earlier.  If the earlier name is just a declaration, don't add
2500   // this name, because that will cause the previous declaration to
2501   // merge to this imported name, which should not happen.  Just add
2502   // this name to the list of file block names to get appropriate
2503   // errors if we see a later definition.
2504   Named_object* e = this->package_->bindings()->lookup(no->name());
2505   if (e != NULL && e->package() == NULL)
2506     {
2507       if (e->is_unknown())
2508 	e = e->resolve();
2509       if (e->package() == NULL
2510 	  && (e->is_type_declaration()
2511 	      || e->is_function_declaration()
2512 	      || e->is_unknown()))
2513 	{
2514 	  this->add_file_block_name(no->name(), no->location());
2515 	  return;
2516 	}
2517     }
2518 
2519   this->current_bindings()->add_named_object(no);
2520 }
2521 
2522 // Add a linkname.  This implements the go:linkname compiler directive.
2523 // We only support this for functions and function declarations.
2524 
2525 void
add_linkname(const std::string & go_name,bool is_exported,const std::string & ext_name,Location loc)2526 Gogo::add_linkname(const std::string& go_name, bool is_exported,
2527 		   const std::string& ext_name, Location loc)
2528 {
2529   Named_object* no =
2530     this->package_->bindings()->lookup(this->pack_hidden_name(go_name,
2531 							      is_exported));
2532   if (no == NULL)
2533     go_error_at(loc, "%s is not defined", go_name.c_str());
2534   else if (no->is_function())
2535     {
2536       if (ext_name.empty())
2537 	no->func_value()->set_is_exported_by_linkname();
2538       else
2539 	no->func_value()->set_asm_name(ext_name);
2540     }
2541   else if (no->is_function_declaration())
2542     {
2543       if (ext_name.empty())
2544 	go_error_at(loc,
2545 		    ("%<//go:linkname%> missing external name "
2546 		     "for declaration of %s"),
2547 		    go_name.c_str());
2548       else
2549 	no->func_declaration_value()->set_asm_name(ext_name);
2550     }
2551   else
2552     go_error_at(loc,
2553 		("%s is not a function; "
2554 		 "%<//go:linkname%> is only supported for functions"),
2555 		go_name.c_str());
2556 }
2557 
2558 // Mark all local variables used.  This is used when some types of
2559 // parse error occur.
2560 
2561 void
mark_locals_used()2562 Gogo::mark_locals_used()
2563 {
2564   for (Open_functions::iterator pf = this->functions_.begin();
2565        pf != this->functions_.end();
2566        ++pf)
2567     {
2568       for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2569 	   pb != pf->blocks.end();
2570 	   ++pb)
2571 	(*pb)->bindings()->mark_locals_used();
2572     }
2573 }
2574 
2575 // Record that we've seen an interface type.
2576 
2577 void
record_interface_type(Interface_type * itype)2578 Gogo::record_interface_type(Interface_type* itype)
2579 {
2580   this->interface_types_.push_back(itype);
2581 }
2582 
2583 // Define the global names.  We do this only after parsing all the
2584 // input files, because the program might define the global names
2585 // itself.
2586 
2587 void
define_global_names()2588 Gogo::define_global_names()
2589 {
2590   if (this->is_main_package())
2591     {
2592       // Every Go program has to import the runtime package, so that
2593       // it is properly initialized.  We can't use
2594       // predeclared_location here as it will cause runtime functions
2595       // to appear to be builtin functions.
2596       this->import_package("runtime", "_", false, false,
2597 			   this->package_->location());
2598     }
2599 
2600   for (Bindings::const_declarations_iterator p =
2601 	 this->globals_->begin_declarations();
2602        p != this->globals_->end_declarations();
2603        ++p)
2604     {
2605       Named_object* global_no = p->second;
2606       std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2607       Named_object* no = this->package_->bindings()->lookup(name);
2608       if (no == NULL)
2609 	continue;
2610       no = no->resolve();
2611       if (no->is_type_declaration())
2612 	{
2613 	  if (global_no->is_type())
2614 	    {
2615 	      if (no->type_declaration_value()->has_methods())
2616 		{
2617 		  for (std::vector<Named_object*>::const_iterator pm =
2618 			 no->type_declaration_value()->methods()->begin();
2619 		       pm != no->type_declaration_value()->methods()->end();
2620 		       pm++)
2621 		    go_error_at((*pm)->location(),
2622 				"may not define methods on non-local type");
2623 		}
2624 	      no->set_type_value(global_no->type_value());
2625 	    }
2626 	  else
2627 	    {
2628 	      go_error_at(no->location(), "expected type");
2629 	      Type* errtype = Type::make_error_type();
2630 	      Named_object* err =
2631                 Named_object::make_type("erroneous_type", NULL, errtype,
2632                                         Linemap::predeclared_location());
2633 	      no->set_type_value(err->type_value());
2634 	    }
2635 	}
2636       else if (no->is_unknown())
2637 	no->unknown_value()->set_real_named_object(global_no);
2638     }
2639 
2640   // Give an error if any name is defined in both the package block
2641   // and the file block.  For example, this can happen if one file
2642   // imports "fmt" and another file defines a global variable fmt.
2643   for (Bindings::const_declarations_iterator p =
2644 	 this->package_->bindings()->begin_declarations();
2645        p != this->package_->bindings()->end_declarations();
2646        ++p)
2647     {
2648       if (p->second->is_unknown()
2649 	  && p->second->unknown_value()->real_named_object() == NULL)
2650 	{
2651 	  // No point in warning about an undefined name, as we will
2652 	  // get other errors later anyhow.
2653 	  continue;
2654 	}
2655       File_block_names::const_iterator pf =
2656 	this->file_block_names_.find(p->second->name());
2657       if (pf != this->file_block_names_.end())
2658 	{
2659 	  std::string n = p->second->message_name();
2660 	  go_error_at(p->second->location(),
2661 		      "%qs defined as both imported name and global name",
2662 		      n.c_str());
2663 	  go_inform(pf->second, "%qs imported here", n.c_str());
2664 	}
2665 
2666       // No package scope identifier may be named "init".
2667       if (!p->second->is_function()
2668 	  && Gogo::unpack_hidden_name(p->second->name()) == "init")
2669 	{
2670 	  go_error_at(p->second->location(),
2671 		      "cannot declare init - must be func");
2672 	}
2673     }
2674 }
2675 
2676 // Clear out names in file scope.
2677 
2678 void
clear_file_scope()2679 Gogo::clear_file_scope()
2680 {
2681   this->package_->bindings()->clear_file_scope(this);
2682 
2683   // Warn about packages which were imported but not used.
2684   bool quiet = saw_errors();
2685   for (Packages::iterator p = this->packages_.begin();
2686        p != this->packages_.end();
2687        ++p)
2688     {
2689       Package* package = p->second;
2690       if (package != this->package_ && !quiet)
2691         {
2692           for (Package::Aliases::const_iterator p1 = package->aliases().begin();
2693                p1 != package->aliases().end();
2694                ++p1)
2695             {
2696               if (!p1->second->used())
2697                 {
2698                   // Give a more refined error message if the alias name is known.
2699                   std::string pkg_name = package->package_name();
2700                   if (p1->first != pkg_name && p1->first[0] != '.')
2701                     {
2702 		      go_error_at(p1->second->location(),
2703 				  "imported and not used: %s as %s",
2704 				  Gogo::message_name(pkg_name).c_str(),
2705 				  Gogo::message_name(p1->first).c_str());
2706                     }
2707                   else
2708 		    go_error_at(p1->second->location(),
2709 				"imported and not used: %s",
2710 				Gogo::message_name(pkg_name).c_str());
2711                 }
2712             }
2713         }
2714       package->clear_used();
2715     }
2716 
2717   this->current_file_imported_unsafe_ = false;
2718 }
2719 
2720 // Queue up a type-specific hash function for later writing.  These
2721 // are written out in write_specific_type_functions, called after the
2722 // parse tree is lowered.
2723 
2724 void
queue_hash_function(Type * type,int64_t size,const std::string & hash_name,Function_type * hash_fntype)2725 Gogo::queue_hash_function(Type* type, int64_t size,
2726 			  const std::string& hash_name,
2727 			  Function_type* hash_fntype)
2728 {
2729   go_assert(!this->specific_type_functions_are_written_);
2730   go_assert(!this->in_global_scope());
2731   Specific_type_function::Specific_type_function_kind kind =
2732     Specific_type_function::SPECIFIC_HASH;
2733   Specific_type_function* tsf = new Specific_type_function(type, NULL, size,
2734 							   kind, hash_name,
2735 							   hash_fntype);
2736   this->specific_type_functions_.push_back(tsf);
2737 }
2738 
2739 // Queue up a type-specific equal function for later writing.  These
2740 // are written out in write_specific_type_functions, called after the
2741 // parse tree is lowered.
2742 
2743 void
queue_equal_function(Type * type,Named_type * name,int64_t size,const std::string & equal_name,Function_type * equal_fntype)2744 Gogo::queue_equal_function(Type* type, Named_type* name, int64_t size,
2745 			   const std::string& equal_name,
2746 			   Function_type* equal_fntype)
2747 {
2748   go_assert(!this->specific_type_functions_are_written_);
2749   go_assert(!this->in_global_scope());
2750   Specific_type_function::Specific_type_function_kind kind =
2751     Specific_type_function::SPECIFIC_EQUAL;
2752   Specific_type_function* tsf = new Specific_type_function(type, name, size,
2753 							   kind, equal_name,
2754 							   equal_fntype);
2755   this->specific_type_functions_.push_back(tsf);
2756 }
2757 
2758 // Look for types which need specific hash or equality functions.
2759 
2760 class Specific_type_functions : public Traverse
2761 {
2762  public:
Specific_type_functions(Gogo * gogo)2763   Specific_type_functions(Gogo* gogo)
2764     : Traverse(traverse_types),
2765       gogo_(gogo)
2766   { }
2767 
2768   int
2769   type(Type*);
2770 
2771  private:
2772   Gogo* gogo_;
2773 };
2774 
2775 int
type(Type * t)2776 Specific_type_functions::type(Type* t)
2777 {
2778   switch (t->classification())
2779     {
2780     case Type::TYPE_NAMED:
2781       {
2782 	Named_type* nt = t->named_type();
2783 	if (nt->is_alias())
2784 	  return TRAVERSE_CONTINUE;
2785 	if (t->needs_specific_type_functions(this->gogo_))
2786 	  t->equal_function(this->gogo_, nt, NULL);
2787 
2788 	// If this is a struct type, we don't want to make functions
2789 	// for the unnamed struct.
2790 	Type* rt = nt->real_type();
2791 	if (rt->struct_type() == NULL)
2792 	  {
2793 	    if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2794 	      return TRAVERSE_EXIT;
2795 	  }
2796 	else
2797 	  {
2798 	    // If this type is defined in another package, then we don't
2799 	    // need to worry about the unexported fields.
2800 	    bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2801 	    const Struct_field_list* fields = rt->struct_type()->fields();
2802 	    for (Struct_field_list::const_iterator p = fields->begin();
2803 		 p != fields->end();
2804 		 ++p)
2805 	      {
2806 		if (is_defined_elsewhere
2807 		    && Gogo::is_hidden_name(p->field_name()))
2808 		  continue;
2809 		if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2810 		  return TRAVERSE_EXIT;
2811 	      }
2812 	  }
2813 
2814 	return TRAVERSE_SKIP_COMPONENTS;
2815       }
2816 
2817     case Type::TYPE_STRUCT:
2818     case Type::TYPE_ARRAY:
2819       if (t->needs_specific_type_functions(this->gogo_))
2820 	t->equal_function(this->gogo_, NULL, NULL);
2821       break;
2822 
2823     case Type::TYPE_MAP:
2824       {
2825 	Type* key_type = t->map_type()->key_type();
2826 	if (key_type->needs_specific_type_functions(this->gogo_))
2827 	  key_type->hash_function(this->gogo_, NULL);
2828       }
2829       break;
2830 
2831     default:
2832       break;
2833     }
2834 
2835   return TRAVERSE_CONTINUE;
2836 }
2837 
2838 // Write out type specific functions.
2839 
2840 void
write_specific_type_functions()2841 Gogo::write_specific_type_functions()
2842 {
2843   Specific_type_functions stf(this);
2844   this->traverse(&stf);
2845 
2846   while (!this->specific_type_functions_.empty())
2847     {
2848       Specific_type_function* tsf = this->specific_type_functions_.back();
2849       this->specific_type_functions_.pop_back();
2850       if (tsf->kind == Specific_type_function::SPECIFIC_HASH)
2851 	tsf->type->write_hash_function(this, tsf->size, tsf->fnname,
2852 				       tsf->fntype);
2853       else
2854 	tsf->type->write_equal_function(this, tsf->name, tsf->size,
2855 					tsf->fnname, tsf->fntype);
2856       delete tsf;
2857     }
2858   this->specific_type_functions_are_written_ = true;
2859 }
2860 
2861 // Traverse the tree.
2862 
2863 void
traverse(Traverse * traverse)2864 Gogo::traverse(Traverse* traverse)
2865 {
2866   // Traverse the current package first for consistency.  The other
2867   // packages will only contain imported types, constants, and
2868   // declarations.
2869   if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2870     return;
2871   for (Packages::const_iterator p = this->packages_.begin();
2872        p != this->packages_.end();
2873        ++p)
2874     {
2875       if (p->second != this->package_)
2876 	{
2877 	  if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2878 	    break;
2879 	}
2880     }
2881 }
2882 
2883 // Add a type to verify.  This is used for types of sink variables, in
2884 // order to give appropriate error messages.
2885 
2886 void
add_type_to_verify(Type * type)2887 Gogo::add_type_to_verify(Type* type)
2888 {
2889   this->verify_types_.push_back(type);
2890 }
2891 
2892 // Traversal class used to verify types.
2893 
2894 class Verify_types : public Traverse
2895 {
2896  public:
Verify_types()2897   Verify_types()
2898     : Traverse(traverse_types)
2899   { }
2900 
2901   int
2902   type(Type*);
2903 };
2904 
2905 // Verify that a type is correct.
2906 
2907 int
type(Type * t)2908 Verify_types::type(Type* t)
2909 {
2910   if (!t->verify())
2911     return TRAVERSE_SKIP_COMPONENTS;
2912   return TRAVERSE_CONTINUE;
2913 }
2914 
2915 // Verify that all types are correct.
2916 
2917 void
verify_types()2918 Gogo::verify_types()
2919 {
2920   Verify_types traverse;
2921   this->traverse(&traverse);
2922 
2923   for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2924        p != this->verify_types_.end();
2925        ++p)
2926     (*p)->verify();
2927   this->verify_types_.clear();
2928 }
2929 
2930 // Traversal class used to lower parse tree.
2931 
2932 class Lower_parse_tree : public Traverse
2933 {
2934  public:
Lower_parse_tree(Gogo * gogo,Named_object * function)2935   Lower_parse_tree(Gogo* gogo, Named_object* function)
2936     : Traverse(traverse_variables
2937 	       | traverse_constants
2938 	       | traverse_functions
2939 	       | traverse_statements
2940 	       | traverse_expressions),
2941       gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2942   { }
2943 
2944   void
set_inserter(const Statement_inserter * inserter)2945   set_inserter(const Statement_inserter* inserter)
2946   { this->inserter_ = *inserter; }
2947 
2948   int
2949   variable(Named_object*);
2950 
2951   int
2952   constant(Named_object*, bool);
2953 
2954   int
2955   function(Named_object*);
2956 
2957   int
2958   statement(Block*, size_t* pindex, Statement*);
2959 
2960   int
2961   expression(Expression**);
2962 
2963  private:
2964   // General IR.
2965   Gogo* gogo_;
2966   // The function we are traversing.
2967   Named_object* function_;
2968   // Value to use for the predeclared constant iota.
2969   int iota_value_;
2970   // Current statement inserter for use by expressions.
2971   Statement_inserter inserter_;
2972 };
2973 
2974 // Lower variables.
2975 
2976 int
variable(Named_object * no)2977 Lower_parse_tree::variable(Named_object* no)
2978 {
2979   if (!no->is_variable())
2980     return TRAVERSE_CONTINUE;
2981 
2982   if (no->is_variable() && no->var_value()->is_global())
2983     {
2984       // Global variables can have loops in their initialization
2985       // expressions.  This is handled in lower_init_expression.
2986       no->var_value()->lower_init_expression(this->gogo_, this->function_,
2987 					     &this->inserter_);
2988       return TRAVERSE_CONTINUE;
2989     }
2990 
2991   // This is a local variable.  We are going to return
2992   // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2993   // initialization expression when we reach the variable declaration
2994   // statement.  However, that means that we need to traverse the type
2995   // ourselves.
2996   if (no->var_value()->has_type())
2997     {
2998       Type* type = no->var_value()->type();
2999       if (type != NULL)
3000 	{
3001 	  if (Type::traverse(type, this) == TRAVERSE_EXIT)
3002 	    return TRAVERSE_EXIT;
3003 	}
3004     }
3005   go_assert(!no->var_value()->has_pre_init());
3006 
3007   return TRAVERSE_SKIP_COMPONENTS;
3008 }
3009 
3010 // Lower constants.  We handle constants specially so that we can set
3011 // the right value for the predeclared constant iota.  This works in
3012 // conjunction with the way we lower Const_expression objects.
3013 
3014 int
constant(Named_object * no,bool)3015 Lower_parse_tree::constant(Named_object* no, bool)
3016 {
3017   Named_constant* nc = no->const_value();
3018 
3019   // Don't get into trouble if the constant's initializer expression
3020   // refers to the constant itself.
3021   if (nc->lowering())
3022     return TRAVERSE_CONTINUE;
3023   nc->set_lowering();
3024 
3025   go_assert(this->iota_value_ == -1);
3026   this->iota_value_ = nc->iota_value();
3027   nc->traverse_expression(this);
3028   this->iota_value_ = -1;
3029 
3030   nc->clear_lowering();
3031 
3032   // We will traverse the expression a second time, but that will be
3033   // fast.
3034 
3035   return TRAVERSE_CONTINUE;
3036 }
3037 
3038 // Lower the body of a function, and set the closure type.  Record the
3039 // function while lowering it, so that we can pass it down when
3040 // lowering an expression.
3041 
3042 int
function(Named_object * no)3043 Lower_parse_tree::function(Named_object* no)
3044 {
3045   no->func_value()->set_closure_type();
3046 
3047   go_assert(this->function_ == NULL);
3048   this->function_ = no;
3049   int t = no->func_value()->traverse(this);
3050   this->function_ = NULL;
3051 
3052   if (t == TRAVERSE_EXIT)
3053     return t;
3054   return TRAVERSE_SKIP_COMPONENTS;
3055 }
3056 
3057 // Lower statement parse trees.
3058 
3059 int
statement(Block * block,size_t * pindex,Statement * sorig)3060 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
3061 {
3062   // Because we explicitly traverse the statement's contents
3063   // ourselves, we want to skip block statements here.  There is
3064   // nothing to lower in a block statement.
3065   if (sorig->is_block_statement())
3066     return TRAVERSE_CONTINUE;
3067 
3068   Statement_inserter hold_inserter(this->inserter_);
3069   this->inserter_ = Statement_inserter(block, pindex);
3070 
3071   // Lower the expressions first.
3072   int t = sorig->traverse_contents(this);
3073   if (t == TRAVERSE_EXIT)
3074     {
3075       this->inserter_ = hold_inserter;
3076       return t;
3077     }
3078 
3079   // Keep lowering until nothing changes.
3080   Statement* s = sorig;
3081   while (true)
3082     {
3083       Statement* snew = s->lower(this->gogo_, this->function_, block,
3084 				 &this->inserter_);
3085       if (snew == s)
3086 	break;
3087       s = snew;
3088       t = s->traverse_contents(this);
3089       if (t == TRAVERSE_EXIT)
3090 	{
3091 	  this->inserter_ = hold_inserter;
3092 	  return t;
3093 	}
3094     }
3095 
3096   if (s != sorig)
3097     block->replace_statement(*pindex, s);
3098 
3099   this->inserter_ = hold_inserter;
3100   return TRAVERSE_SKIP_COMPONENTS;
3101 }
3102 
3103 // Lower expression parse trees.
3104 
3105 int
expression(Expression ** pexpr)3106 Lower_parse_tree::expression(Expression** pexpr)
3107 {
3108   // We have to lower all subexpressions first, so that we can get
3109   // their type if necessary.  This is awkward, because we don't have
3110   // a postorder traversal pass.
3111   if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3112     return TRAVERSE_EXIT;
3113   // Keep lowering until nothing changes.
3114   while (true)
3115     {
3116       Expression* e = *pexpr;
3117       Expression* enew = e->lower(this->gogo_, this->function_,
3118 				  &this->inserter_, this->iota_value_);
3119       if (enew == e)
3120 	break;
3121       if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
3122 	return TRAVERSE_EXIT;
3123       *pexpr = enew;
3124     }
3125 
3126   // Lower the type of this expression before the parent looks at it,
3127   // in case the type contains an array that has expressions in its
3128   // length.  Skip an Unknown_expression, as at this point that means
3129   // a composite literal key that does not have a type.
3130   if ((*pexpr)->unknown_expression() == NULL)
3131     Type::traverse((*pexpr)->type(), this);
3132 
3133   return TRAVERSE_SKIP_COMPONENTS;
3134 }
3135 
3136 // Lower the parse tree.  This is called after the parse is complete,
3137 // when all names should be resolved.
3138 
3139 void
lower_parse_tree()3140 Gogo::lower_parse_tree()
3141 {
3142   Lower_parse_tree lower_parse_tree(this, NULL);
3143   this->traverse(&lower_parse_tree);
3144 
3145   // If we found any functions defined in other packages that are
3146   // inlinables, import their bodies and turn them into functions.
3147   //
3148   // Note that as we import inlinable functions we may find more
3149   // inlinable functions, so don't use an iterator.
3150   for (size_t i = 0; i < this->imported_inlinable_functions_.size(); i++)
3151     {
3152       Named_object* no = this->imported_inlinable_functions_[i];
3153       no->func_declaration_value()->import_function_body(this, no);
3154     }
3155 
3156   // There might be type definitions that involve expressions such as the
3157   // array length.  Make sure to lower these expressions as well.  Otherwise,
3158   // errors hidden within a type can introduce unexpected errors into later
3159   // passes.
3160   for (std::vector<Type*>::iterator p = this->verify_types_.begin();
3161        p != this->verify_types_.end();
3162        ++p)
3163     Type::traverse(*p, &lower_parse_tree);
3164 }
3165 
3166 // Lower a block.
3167 
3168 void
lower_block(Named_object * function,Block * block)3169 Gogo::lower_block(Named_object* function, Block* block)
3170 {
3171   Lower_parse_tree lower_parse_tree(this, function);
3172   block->traverse(&lower_parse_tree);
3173 }
3174 
3175 // Lower an expression.  INSERTER may be NULL, in which case the
3176 // expression had better not need to create any temporaries.
3177 
3178 void
lower_expression(Named_object * function,Statement_inserter * inserter,Expression ** pexpr)3179 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
3180 		       Expression** pexpr)
3181 {
3182   Lower_parse_tree lower_parse_tree(this, function);
3183   if (inserter != NULL)
3184     lower_parse_tree.set_inserter(inserter);
3185   lower_parse_tree.expression(pexpr);
3186 }
3187 
3188 // Lower a constant.  This is called when lowering a reference to a
3189 // constant.  We have to make sure that the constant has already been
3190 // lowered.
3191 
3192 void
lower_constant(Named_object * no)3193 Gogo::lower_constant(Named_object* no)
3194 {
3195   go_assert(no->is_const());
3196   Lower_parse_tree lower(this, NULL);
3197   lower.constant(no, false);
3198 }
3199 
3200 // Make implicit type conversions explicit.  Currently only does for
3201 // interface conversions, so the escape analysis can see them and
3202 // optimize.
3203 
3204 class Add_conversions : public Traverse
3205 {
3206  public:
Add_conversions()3207   Add_conversions()
3208     : Traverse(traverse_statements
3209                | traverse_expressions)
3210   { }
3211 
3212   int
3213   statement(Block*, size_t* pindex, Statement*);
3214 
3215   int
3216   expression(Expression**);
3217 };
3218 
3219 // Add explicit conversions in a statement.
3220 
3221 int
statement(Block *,size_t *,Statement * sorig)3222 Add_conversions::statement(Block*, size_t*, Statement* sorig)
3223 {
3224   sorig->add_conversions();
3225   return TRAVERSE_CONTINUE;
3226 }
3227 
3228 // Add explicit conversions in an expression.
3229 
3230 int
expression(Expression ** pexpr)3231 Add_conversions::expression(Expression** pexpr)
3232 {
3233   (*pexpr)->add_conversions();
3234   return TRAVERSE_CONTINUE;
3235 }
3236 
3237 void
add_conversions()3238 Gogo::add_conversions()
3239 {
3240   Add_conversions add_conversions;
3241   this->traverse(&add_conversions);
3242 }
3243 
3244 void
add_conversions_in_block(Block * b)3245 Gogo::add_conversions_in_block(Block *b)
3246 {
3247   Add_conversions add_conversions;
3248   b->traverse(&add_conversions);
3249 }
3250 
3251 // Traversal class for simple deadcode elimination.
3252 
3253 class Remove_deadcode : public Traverse
3254 {
3255  public:
Remove_deadcode()3256   Remove_deadcode()
3257     : Traverse(traverse_statements
3258                | traverse_expressions)
3259   { }
3260 
3261   int
3262   statement(Block*, size_t* pindex, Statement*);
3263 
3264   int
3265   expression(Expression**);
3266 };
3267 
3268 // Remove deadcode in a statement.
3269 
3270 int
statement(Block * block,size_t * pindex,Statement * sorig)3271 Remove_deadcode::statement(Block* block, size_t* pindex, Statement* sorig)
3272 {
3273   Location loc = sorig->location();
3274   If_statement* ifs = sorig->if_statement();
3275   if (ifs != NULL)
3276     {
3277       // Remove the dead branch of an if statement.
3278       bool bval;
3279       if (ifs->condition()->boolean_constant_value(&bval))
3280         {
3281           Statement* s;
3282           if (bval)
3283             s = Statement::make_block_statement(ifs->then_block(),
3284                                                 loc);
3285           else
3286             if (ifs->else_block() != NULL)
3287               s = Statement::make_block_statement(ifs->else_block(),
3288                                                   loc);
3289             else
3290               // Make a dummy statement.
3291               s = Statement::make_statement(Expression::make_boolean(false, loc),
3292                                             true);
3293 
3294           block->replace_statement(*pindex, s);
3295         }
3296     }
3297   return TRAVERSE_CONTINUE;
3298 }
3299 
3300 // Remove deadcode in an expression.
3301 
3302 int
expression(Expression ** pexpr)3303 Remove_deadcode::expression(Expression** pexpr)
3304 {
3305   // Discard the right arm of a shortcut expression of constant value.
3306   Binary_expression* be = (*pexpr)->binary_expression();
3307   bool bval;
3308   if (be != NULL
3309       && be->boolean_constant_value(&bval)
3310       && (be->op() == OPERATOR_ANDAND
3311           || be->op() == OPERATOR_OROR))
3312     *pexpr = Expression::make_boolean(bval, be->location());
3313   return TRAVERSE_CONTINUE;
3314 }
3315 
3316 // Remove deadcode.
3317 
3318 void
remove_deadcode()3319 Gogo::remove_deadcode()
3320 {
3321   Remove_deadcode remove_deadcode;
3322   this->traverse(&remove_deadcode);
3323 }
3324 
3325 // Traverse the tree to create function descriptors as needed.
3326 
3327 class Create_function_descriptors : public Traverse
3328 {
3329  public:
Create_function_descriptors(Gogo * gogo)3330   Create_function_descriptors(Gogo* gogo)
3331     : Traverse(traverse_functions | traverse_expressions),
3332       gogo_(gogo)
3333   { }
3334 
3335   int
3336   function(Named_object*);
3337 
3338   int
3339   expression(Expression**);
3340 
3341  private:
3342   Gogo* gogo_;
3343 };
3344 
3345 // Create a descriptor for every top-level exported function.
3346 
3347 int
function(Named_object * no)3348 Create_function_descriptors::function(Named_object* no)
3349 {
3350   if (no->is_function()
3351       && no->func_value()->enclosing() == NULL
3352       && !no->func_value()->is_method()
3353       && !Gogo::is_hidden_name(no->name())
3354       && !Gogo::is_thunk(no))
3355     no->func_value()->descriptor(this->gogo_, no);
3356 
3357   return TRAVERSE_CONTINUE;
3358 }
3359 
3360 // If we see a function referenced in any way other than calling it,
3361 // create a descriptor for it.
3362 
3363 int
expression(Expression ** pexpr)3364 Create_function_descriptors::expression(Expression** pexpr)
3365 {
3366   Expression* expr = *pexpr;
3367 
3368   Func_expression* fe = expr->func_expression();
3369   if (fe != NULL)
3370     {
3371       // We would not get here for a call to this function, so this is
3372       // a reference to a function other than calling it.  We need a
3373       // descriptor.
3374       if (fe->closure() != NULL)
3375 	return TRAVERSE_CONTINUE;
3376       Named_object* no = fe->named_object();
3377       if (no->is_function() && !no->func_value()->is_method())
3378 	no->func_value()->descriptor(this->gogo_, no);
3379       else if (no->is_function_declaration()
3380 	       && !no->func_declaration_value()->type()->is_method()
3381 	       && !Linemap::is_predeclared_location(no->location()))
3382 	no->func_declaration_value()->descriptor(this->gogo_, no);
3383       return TRAVERSE_CONTINUE;
3384     }
3385 
3386   Bound_method_expression* bme = expr->bound_method_expression();
3387   if (bme != NULL)
3388     {
3389       // We would not get here for a call to this method, so this is a
3390       // method value.  We need to create a thunk.
3391       Bound_method_expression::create_thunk(this->gogo_, bme->method(),
3392 					    bme->function());
3393       return TRAVERSE_CONTINUE;
3394     }
3395 
3396   Interface_field_reference_expression* ifre =
3397     expr->interface_field_reference_expression();
3398   if (ifre != NULL)
3399     {
3400       // We would not get here for a call to this interface method, so
3401       // this is a method value.  We need to create a thunk.
3402       Interface_type* type = ifre->expr()->type()->interface_type();
3403       if (type != NULL)
3404 	Interface_field_reference_expression::create_thunk(this->gogo_, type,
3405 							   ifre->name());
3406       return TRAVERSE_CONTINUE;
3407     }
3408 
3409   Call_expression* ce = expr->call_expression();
3410   if (ce != NULL)
3411     {
3412       Expression* fn = ce->fn();
3413       if (fn->func_expression() != NULL
3414 	  || fn->bound_method_expression() != NULL
3415 	  || fn->interface_field_reference_expression() != NULL)
3416 	{
3417 	  // Traverse the arguments but not the function.
3418 	  Expression_list* args = ce->args();
3419 	  if (args != NULL)
3420 	    {
3421 	      if (args->traverse(this) == TRAVERSE_EXIT)
3422 		return TRAVERSE_EXIT;
3423 	    }
3424 	  return TRAVERSE_SKIP_COMPONENTS;
3425 	}
3426     }
3427 
3428   return TRAVERSE_CONTINUE;
3429 }
3430 
3431 // Create function descriptors as needed.  We need a function
3432 // descriptor for all exported functions and for all functions that
3433 // are referenced without being called.
3434 
3435 void
create_function_descriptors()3436 Gogo::create_function_descriptors()
3437 {
3438   // Create a function descriptor for any exported function that is
3439   // declared in this package.  This is so that we have a descriptor
3440   // for functions written in assembly.  Gather the descriptors first
3441   // so that we don't add declarations while looping over them.
3442   std::vector<Named_object*> fndecls;
3443   Bindings* b = this->package_->bindings();
3444   for (Bindings::const_declarations_iterator p = b->begin_declarations();
3445        p != b->end_declarations();
3446        ++p)
3447     {
3448       Named_object* no = p->second;
3449       if (no->is_function_declaration()
3450 	  && !no->func_declaration_value()->type()->is_method()
3451 	  && !Linemap::is_predeclared_location(no->location())
3452 	  && !Gogo::is_hidden_name(no->name()))
3453 	fndecls.push_back(no);
3454     }
3455   for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
3456        p != fndecls.end();
3457        ++p)
3458     (*p)->func_declaration_value()->descriptor(this, *p);
3459   fndecls.clear();
3460 
3461   Create_function_descriptors cfd(this);
3462   this->traverse(&cfd);
3463 }
3464 
3465 // Finalize the methods of an interface type.
3466 
3467 int
type(Type * t)3468 Finalize_methods::type(Type* t)
3469 {
3470   // Check the classification so that we don't finalize the methods
3471   // twice for a named interface type.
3472   switch (t->classification())
3473     {
3474     case Type::TYPE_INTERFACE:
3475       t->interface_type()->finalize_methods();
3476       break;
3477 
3478     case Type::TYPE_NAMED:
3479       {
3480 	Named_type* nt = t->named_type();
3481 	Type* rt = nt->real_type();
3482 	if (rt->classification() != Type::TYPE_STRUCT)
3483 	  {
3484 	    // Finalize the methods of the real type first.
3485 	    if (Type::traverse(rt, this) == TRAVERSE_EXIT)
3486 	      return TRAVERSE_EXIT;
3487 
3488 	    // Finalize the methods of this type.
3489 	    nt->finalize_methods(this->gogo_);
3490 	  }
3491 	else
3492 	  {
3493 	    // We don't want to finalize the methods of a named struct
3494 	    // type, as the methods should be attached to the named
3495 	    // type, not the struct type.  We just want to finalize
3496 	    // the field types.
3497 	    //
3498 	    // It is possible that a field type refers indirectly to
3499 	    // this type, such as via a field with function type with
3500 	    // an argument or result whose type is this type.  To
3501 	    // avoid the cycle, first finalize the methods of any
3502 	    // embedded types, which are the only types we need to
3503 	    // know to finalize the methods of this type.
3504 	    const Struct_field_list* fields = rt->struct_type()->fields();
3505 	    if (fields != NULL)
3506 	      {
3507 		for (Struct_field_list::const_iterator pf = fields->begin();
3508 		     pf != fields->end();
3509 		     ++pf)
3510 		  {
3511 		    if (pf->is_anonymous())
3512 		      {
3513 			if (Type::traverse(pf->type(), this) == TRAVERSE_EXIT)
3514 			  return TRAVERSE_EXIT;
3515 		      }
3516 		  }
3517 	      }
3518 
3519 	    // Finalize the methods of this type.
3520 	    nt->finalize_methods(this->gogo_);
3521 
3522 	    // Finalize all the struct fields.
3523 	    if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3524 	      return TRAVERSE_EXIT;
3525 	  }
3526 
3527 	// If this type is defined in a different package, then finalize the
3528 	// types of all the methods, since we won't see them otherwise.
3529 	if (nt->named_object()->package() != NULL && nt->has_any_methods())
3530 	  {
3531 	    const Methods* methods = nt->methods();
3532 	    for (Methods::const_iterator p = methods->begin();
3533 		 p != methods->end();
3534 		 ++p)
3535 	      {
3536 		if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3537 		  return TRAVERSE_EXIT;
3538 	      }
3539 	  }
3540 
3541 	// Finalize the types of all methods that are declared but not
3542 	// defined, since we won't see the declarations otherwise.
3543 	if (nt->named_object()->package() == NULL
3544 	    && nt->local_methods() != NULL)
3545 	  {
3546 	    const Bindings* methods = nt->local_methods();
3547 	    for (Bindings::const_declarations_iterator p =
3548 		   methods->begin_declarations();
3549 		 p != methods->end_declarations();
3550 		 p++)
3551 	      {
3552 		if (p->second->is_function_declaration())
3553 		  {
3554 		    Type* mt = p->second->func_declaration_value()->type();
3555 		    if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3556 		      return TRAVERSE_EXIT;
3557 		  }
3558 	      }
3559 	  }
3560 
3561 	return TRAVERSE_SKIP_COMPONENTS;
3562       }
3563 
3564     case Type::TYPE_STRUCT:
3565       // Traverse the field types first in case there is an embedded
3566       // field with methods that the struct should inherit.
3567       if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3568           return TRAVERSE_EXIT;
3569       t->struct_type()->finalize_methods(this->gogo_);
3570       return TRAVERSE_SKIP_COMPONENTS;
3571 
3572     default:
3573       break;
3574     }
3575 
3576   return TRAVERSE_CONTINUE;
3577 }
3578 
3579 // Finalize method lists and build stub methods for types.
3580 
3581 void
finalize_methods()3582 Gogo::finalize_methods()
3583 {
3584   Finalize_methods finalize(this);
3585   this->traverse(&finalize);
3586 }
3587 
3588 // Finalize the method list for a type.  This is called when a type is
3589 // parsed for an inlined function body, which happens after the
3590 // finalize_methods pass.
3591 
3592 void
finalize_methods_for_type(Type * type)3593 Gogo::finalize_methods_for_type(Type* type)
3594 {
3595   Finalize_methods finalize(this);
3596   Type::traverse(type, &finalize);
3597 }
3598 
3599 // Set types for unspecified variables and constants.
3600 
3601 void
determine_types()3602 Gogo::determine_types()
3603 {
3604   Bindings* bindings = this->current_bindings();
3605   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3606        p != bindings->end_definitions();
3607        ++p)
3608     {
3609       if ((*p)->is_function())
3610 	(*p)->func_value()->determine_types();
3611       else if ((*p)->is_variable())
3612 	(*p)->var_value()->determine_type();
3613       else if ((*p)->is_const())
3614 	(*p)->const_value()->determine_type();
3615 
3616       // See if a variable requires us to build an initialization
3617       // function.  We know that we will see all global variables
3618       // here.
3619       if (!this->need_init_fn_ && (*p)->is_variable())
3620 	{
3621 	  Variable* variable = (*p)->var_value();
3622 
3623 	  // If this is a global variable which requires runtime
3624 	  // initialization, we need an initialization function.
3625 	  if (!variable->is_global())
3626 	    ;
3627 	  else if (variable->init() == NULL)
3628 	    ;
3629 	  else if (variable->type()->interface_type() != NULL)
3630 	    this->need_init_fn_ = true;
3631 	  else if (variable->init()->is_constant())
3632 	    ;
3633 	  else if (!variable->init()->is_composite_literal())
3634 	    this->need_init_fn_ = true;
3635 	  else if (variable->init()->is_nonconstant_composite_literal())
3636 	    this->need_init_fn_ = true;
3637 
3638 	  // If this is a global variable which holds a pointer value,
3639 	  // then we need an initialization function to register it as a
3640 	  // GC root.
3641 	  if (variable->is_global() && variable->type()->has_pointer())
3642 	    this->need_init_fn_ = true;
3643 	}
3644     }
3645 
3646   // Determine the types of constants in packages.
3647   for (Packages::const_iterator p = this->packages_.begin();
3648        p != this->packages_.end();
3649        ++p)
3650     p->second->determine_types();
3651 }
3652 
3653 // Traversal class used for type checking.
3654 
3655 class Check_types_traverse : public Traverse
3656 {
3657  public:
Check_types_traverse(Gogo * gogo)3658   Check_types_traverse(Gogo* gogo)
3659     : Traverse(traverse_variables
3660 	       | traverse_constants
3661 	       | traverse_functions
3662 	       | traverse_statements
3663 	       | traverse_expressions),
3664       gogo_(gogo)
3665   { }
3666 
3667   int
3668   variable(Named_object*);
3669 
3670   int
3671   constant(Named_object*, bool);
3672 
3673   int
3674   function(Named_object*);
3675 
3676   int
3677   statement(Block*, size_t* pindex, Statement*);
3678 
3679   int
3680   expression(Expression**);
3681 
3682  private:
3683   // General IR.
3684   Gogo* gogo_;
3685 };
3686 
3687 // Check that a variable initializer has the right type.
3688 
3689 int
variable(Named_object * named_object)3690 Check_types_traverse::variable(Named_object* named_object)
3691 {
3692   if (named_object->is_variable())
3693     {
3694       Variable* var = named_object->var_value();
3695 
3696       // Give error if variable type is not defined.
3697       var->type()->base();
3698 
3699       Expression* init = var->init();
3700       std::string reason;
3701       if (init != NULL
3702 	  && !Type::are_assignable(var->type(), init->type(), &reason))
3703 	{
3704 	  if (reason.empty())
3705 	    go_error_at(var->location(), "incompatible type in initialization");
3706 	  else
3707 	    go_error_at(var->location(),
3708 			"incompatible type in initialization (%s)",
3709 			reason.c_str());
3710           init = Expression::make_error(named_object->location());
3711 	  var->clear_init();
3712 	}
3713       else if (init != NULL
3714                && init->func_expression() != NULL)
3715         {
3716           Named_object* no = init->func_expression()->named_object();
3717           Function_type* fntype;
3718           if (no->is_function())
3719             fntype = no->func_value()->type();
3720           else if (no->is_function_declaration())
3721             fntype = no->func_declaration_value()->type();
3722           else
3723             go_unreachable();
3724 
3725           // Builtin functions cannot be used as function values for variable
3726           // initialization.
3727           if (fntype->is_builtin())
3728             {
3729 	      go_error_at(init->location(),
3730 			  "invalid use of special built-in function %qs; "
3731 			  "must be called",
3732 			  no->message_name().c_str());
3733             }
3734         }
3735       if (!var->is_used()
3736           && !var->is_global()
3737           && !var->is_parameter()
3738           && !var->is_receiver()
3739           && !var->type()->is_error()
3740           && (init == NULL || !init->is_error_expression())
3741           && !Lex::is_invalid_identifier(named_object->name()))
3742 	go_error_at(var->location(), "%qs declared and not used",
3743 		    named_object->message_name().c_str());
3744     }
3745   return TRAVERSE_CONTINUE;
3746 }
3747 
3748 // Check that a constant initializer has the right type.
3749 
3750 int
constant(Named_object * named_object,bool)3751 Check_types_traverse::constant(Named_object* named_object, bool)
3752 {
3753   Named_constant* constant = named_object->const_value();
3754   Type* ctype = constant->type();
3755   if (ctype->integer_type() == NULL
3756       && ctype->float_type() == NULL
3757       && ctype->complex_type() == NULL
3758       && !ctype->is_boolean_type()
3759       && !ctype->is_string_type())
3760     {
3761       if (ctype->is_nil_type())
3762 	go_error_at(constant->location(), "const initializer cannot be nil");
3763       else if (!ctype->is_error())
3764 	go_error_at(constant->location(), "invalid constant type");
3765       constant->set_error();
3766     }
3767   else if (!constant->expr()->is_constant())
3768     {
3769       go_error_at(constant->expr()->location(), "expression is not constant");
3770       constant->set_error();
3771     }
3772   else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3773 				 NULL))
3774     {
3775       go_error_at(constant->location(),
3776                   "initialization expression has wrong type");
3777       constant->set_error();
3778     }
3779   return TRAVERSE_CONTINUE;
3780 }
3781 
3782 // There are no types to check in a function, but this is where we
3783 // issue warnings about labels which are defined but not referenced.
3784 
3785 int
function(Named_object * no)3786 Check_types_traverse::function(Named_object* no)
3787 {
3788   no->func_value()->check_labels();
3789   return TRAVERSE_CONTINUE;
3790 }
3791 
3792 // Check that types are valid in a statement.
3793 
3794 int
statement(Block *,size_t *,Statement * s)3795 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3796 {
3797   s->check_types(this->gogo_);
3798   return TRAVERSE_CONTINUE;
3799 }
3800 
3801 // Check that types are valid in an expression.
3802 
3803 int
expression(Expression ** expr)3804 Check_types_traverse::expression(Expression** expr)
3805 {
3806   (*expr)->check_types(this->gogo_);
3807   return TRAVERSE_CONTINUE;
3808 }
3809 
3810 // Check that types are valid.
3811 
3812 void
check_types()3813 Gogo::check_types()
3814 {
3815   Check_types_traverse traverse(this);
3816   this->traverse(&traverse);
3817 
3818   Bindings* bindings = this->current_bindings();
3819   for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3820        p != bindings->end_declarations();
3821        ++p)
3822     {
3823       // Also check the types in a function declaration's signature.
3824       Named_object* no = p->second;
3825       if (no->is_function_declaration())
3826         no->func_declaration_value()->check_types();
3827     }
3828 }
3829 
3830 // Check the types in a single block.
3831 
3832 void
check_types_in_block(Block * block)3833 Gogo::check_types_in_block(Block* block)
3834 {
3835   Check_types_traverse traverse(this);
3836   block->traverse(&traverse);
3837 }
3838 
3839 // A traversal class which finds all the expressions which must be
3840 // evaluated in order within a statement or larger expression.  This
3841 // is used to implement the rules about order of evaluation.
3842 
3843 class Find_eval_ordering : public Traverse
3844 {
3845  private:
3846   typedef std::vector<Expression**> Expression_pointers;
3847 
3848  public:
Find_eval_ordering()3849   Find_eval_ordering()
3850     : Traverse(traverse_blocks
3851 	       | traverse_statements
3852 	       | traverse_expressions),
3853       exprs_()
3854   { }
3855 
3856   size_t
size() const3857   size() const
3858   { return this->exprs_.size(); }
3859 
3860   typedef Expression_pointers::const_iterator const_iterator;
3861 
3862   const_iterator
begin() const3863   begin() const
3864   { return this->exprs_.begin(); }
3865 
3866   const_iterator
end() const3867   end() const
3868   { return this->exprs_.end(); }
3869 
3870  protected:
3871   int
block(Block *)3872   block(Block*)
3873   { return TRAVERSE_SKIP_COMPONENTS; }
3874 
3875   int
statement(Block *,size_t *,Statement *)3876   statement(Block*, size_t*, Statement*)
3877   { return TRAVERSE_SKIP_COMPONENTS; }
3878 
3879   int
3880   expression(Expression**);
3881 
3882  private:
3883   // A list of pointers to expressions with side-effects.
3884   Expression_pointers exprs_;
3885 };
3886 
3887 // If an expression must be evaluated in order, put it on the list.
3888 
3889 int
expression(Expression ** expression_pointer)3890 Find_eval_ordering::expression(Expression** expression_pointer)
3891 {
3892   Binary_expression* binexp = (*expression_pointer)->binary_expression();
3893   if (binexp != NULL
3894       && (binexp->op() == OPERATOR_ANDAND || binexp->op() == OPERATOR_OROR))
3895     {
3896       // Shortcut expressions may potentially have side effects which need
3897       // to be ordered, so add them to the list.
3898       // We don't order its subexpressions here since they may be evaluated
3899       // conditionally. This is handled in remove_shortcuts.
3900       this->exprs_.push_back(expression_pointer);
3901       return TRAVERSE_SKIP_COMPONENTS;
3902     }
3903 
3904   // We have to look at subexpressions before this one.
3905   if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3906     return TRAVERSE_EXIT;
3907   if ((*expression_pointer)->must_eval_in_order())
3908     this->exprs_.push_back(expression_pointer);
3909   return TRAVERSE_SKIP_COMPONENTS;
3910 }
3911 
3912 // A traversal class for ordering evaluations.
3913 
3914 class Order_eval : public Traverse
3915 {
3916  public:
Order_eval(Gogo * gogo)3917   Order_eval(Gogo* gogo)
3918     : Traverse(traverse_variables
3919 	       | traverse_statements),
3920       gogo_(gogo)
3921   { }
3922 
3923   int
3924   variable(Named_object*);
3925 
3926   int
3927   statement(Block*, size_t*, Statement*);
3928 
3929  private:
3930   // The IR.
3931   Gogo* gogo_;
3932 };
3933 
3934 // Implement the order of evaluation rules for a statement.
3935 
3936 int
statement(Block * block,size_t * pindex,Statement * stmt)3937 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3938 {
3939   // FIXME: This approach doesn't work for switch statements, because
3940   // we add the new statements before the whole switch when we need to
3941   // instead add them just before the switch expression.  The right
3942   // fix is probably to lower switch statements with nonconstant cases
3943   // to a series of conditionals.
3944   if (stmt->switch_statement() != NULL)
3945     return TRAVERSE_CONTINUE;
3946 
3947   Find_eval_ordering find_eval_ordering;
3948 
3949   // If S is a variable declaration, then ordinary traversal won't do
3950   // anything.  We want to explicitly traverse the initialization
3951   // expression if there is one.
3952   Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3953   Expression* init = NULL;
3954   Expression* orig_init = NULL;
3955   if (vds == NULL)
3956     stmt->traverse_contents(&find_eval_ordering);
3957   else
3958     {
3959       init = vds->var()->var_value()->init();
3960       if (init == NULL)
3961 	return TRAVERSE_CONTINUE;
3962       orig_init = init;
3963 
3964       // It might seem that this could be
3965       // init->traverse_subexpressions.  Unfortunately that can fail
3966       // in a case like
3967       //   var err os.Error
3968       //   newvar, err := call(arg())
3969       // Here newvar will have an init of call result 0 of
3970       // call(arg()).  If we only traverse subexpressions, we will
3971       // only find arg(), and we won't bother to move anything out.
3972       // Then we get to the assignment to err, we will traverse the
3973       // whole statement, and this time we will find both call() and
3974       // arg(), and so we will move them out.  This will cause them to
3975       // be put into temporary variables before the assignment to err
3976       // but after the declaration of newvar.  To avoid that problem,
3977       // we traverse the entire expression here.
3978       Expression::traverse(&init, &find_eval_ordering);
3979     }
3980 
3981   size_t c = find_eval_ordering.size();
3982   if (c == 0)
3983     return TRAVERSE_CONTINUE;
3984 
3985   // If there is only one expression with a side-effect, we can
3986   // usually leave it in place.
3987   if (c == 1)
3988     {
3989       switch (stmt->classification())
3990 	{
3991 	case Statement::STATEMENT_ASSIGNMENT:
3992 	  // For an assignment statement, we need to evaluate an
3993 	  // expression on the right hand side before we evaluate any
3994 	  // index expression on the left hand side, so for that case
3995 	  // we always move the expression.  Otherwise we mishandle
3996 	  // m[0] = len(m) where m is a map.
3997 	  break;
3998 
3999 	case Statement::STATEMENT_EXPRESSION:
4000 	  {
4001 	    // If this is a call statement that doesn't return any
4002 	    // values, it will not have been counted as a value to
4003 	    // move.  We need to move any subexpressions in case they
4004 	    // are themselves call statements that require passing a
4005 	    // closure.
4006 	    Expression* expr = stmt->expression_statement()->expr();
4007 	    if (expr->call_expression() != NULL
4008 		&& expr->call_expression()->result_count() == 0)
4009 	      break;
4010 	    return TRAVERSE_CONTINUE;
4011 	  }
4012 
4013 	default:
4014 	  // We can leave the expression in place.
4015 	  return TRAVERSE_CONTINUE;
4016 	}
4017     }
4018 
4019   bool is_thunk = stmt->thunk_statement() != NULL;
4020   Expression_statement* es = stmt->expression_statement();
4021   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
4022        p != find_eval_ordering.end();
4023        ++p)
4024     {
4025       Expression** pexpr = *p;
4026 
4027       // The last expression in a thunk will be the call passed to go
4028       // or defer, which we must not evaluate early.
4029       if (is_thunk && p + 1 == find_eval_ordering.end())
4030 	break;
4031 
4032       Location loc = (*pexpr)->location();
4033       Statement* s;
4034       if ((*pexpr)->call_expression() == NULL
4035 	  || (*pexpr)->call_expression()->result_count() < 2)
4036 	{
4037 	  Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
4038 							      loc);
4039 	  s = ts;
4040 	  *pexpr = Expression::make_temporary_reference(ts, loc);
4041 	}
4042       else
4043 	{
4044 	  // A call expression which returns multiple results needs to
4045 	  // be handled specially.  We can't create a temporary
4046 	  // because there is no type to give it.  Any actual uses of
4047 	  // the values will be done via Call_result_expressions.
4048           //
4049           // Since a given call expression can be shared by multiple
4050           // Call_result_expressions, avoid hoisting the call the
4051           // second time we see it here. In addition, don't try to
4052           // hoist the top-level multi-return call in the statement,
4053           // since doing this would result a tree with more than one copy
4054           // of the call.
4055           if (this->remember_expression(*pexpr))
4056             s = NULL;
4057           else if (es != NULL && *pexpr == es->expr())
4058             s = NULL;
4059           else
4060             s = Statement::make_statement(*pexpr, true);
4061         }
4062 
4063       if (s != NULL)
4064         {
4065           block->insert_statement_before(*pindex, s);
4066           ++*pindex;
4067         }
4068     }
4069 
4070   if (init != orig_init)
4071     vds->var()->var_value()->set_init(init);
4072 
4073   return TRAVERSE_CONTINUE;
4074 }
4075 
4076 // Implement the order of evaluation rules for the initializer of a
4077 // global variable.
4078 
4079 int
variable(Named_object * no)4080 Order_eval::variable(Named_object* no)
4081 {
4082   if (no->is_result_variable())
4083     return TRAVERSE_CONTINUE;
4084   Variable* var = no->var_value();
4085   Expression* init = var->init();
4086   if (!var->is_global() || init == NULL)
4087     return TRAVERSE_CONTINUE;
4088 
4089   Find_eval_ordering find_eval_ordering;
4090   Expression::traverse(&init, &find_eval_ordering);
4091 
4092   if (find_eval_ordering.size() <= 1)
4093     {
4094       // If there is only one expression with a side-effect, we can
4095       // leave it in place.
4096       return TRAVERSE_SKIP_COMPONENTS;
4097     }
4098 
4099   Expression* orig_init = init;
4100 
4101   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
4102        p != find_eval_ordering.end();
4103        ++p)
4104     {
4105       Expression** pexpr = *p;
4106       Location loc = (*pexpr)->location();
4107       Statement* s;
4108       if ((*pexpr)->call_expression() == NULL
4109 	  || (*pexpr)->call_expression()->result_count() < 2)
4110 	{
4111 	  Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
4112 							      loc);
4113 	  s = ts;
4114 	  *pexpr = Expression::make_temporary_reference(ts, loc);
4115 	}
4116       else
4117 	{
4118 	  // A call expression which returns multiple results needs to
4119 	  // be handled specially.
4120 	  s = Statement::make_statement(*pexpr, true);
4121 	}
4122       var->add_preinit_statement(this->gogo_, s);
4123     }
4124 
4125   if (init != orig_init)
4126     var->set_init(init);
4127 
4128   return TRAVERSE_SKIP_COMPONENTS;
4129 }
4130 
4131 // Use temporary variables to implement the order of evaluation rules.
4132 
4133 void
order_evaluations()4134 Gogo::order_evaluations()
4135 {
4136   Order_eval order_eval(this);
4137   this->traverse(&order_eval);
4138 }
4139 
4140 // Order evaluations in a block.
4141 
4142 void
order_block(Block * block)4143 Gogo::order_block(Block* block)
4144 {
4145   Order_eval order_eval(this);
4146   block->traverse(&order_eval);
4147 }
4148 
4149 // A traversal class used to find a single shortcut operator within an
4150 // expression.
4151 
4152 class Find_shortcut : public Traverse
4153 {
4154  public:
Find_shortcut()4155   Find_shortcut()
4156     : Traverse(traverse_blocks
4157 	       | traverse_statements
4158 	       | traverse_expressions),
4159       found_(NULL)
4160   { }
4161 
4162   // A pointer to the expression which was found, or NULL if none was
4163   // found.
4164   Expression**
found() const4165   found() const
4166   { return this->found_; }
4167 
4168  protected:
4169   int
block(Block *)4170   block(Block*)
4171   { return TRAVERSE_SKIP_COMPONENTS; }
4172 
4173   int
statement(Block *,size_t *,Statement *)4174   statement(Block*, size_t*, Statement*)
4175   { return TRAVERSE_SKIP_COMPONENTS; }
4176 
4177   int
4178   expression(Expression**);
4179 
4180  private:
4181   Expression** found_;
4182 };
4183 
4184 // Find a shortcut expression.
4185 
4186 int
expression(Expression ** pexpr)4187 Find_shortcut::expression(Expression** pexpr)
4188 {
4189   Expression* expr = *pexpr;
4190   Binary_expression* be = expr->binary_expression();
4191   if (be == NULL)
4192     return TRAVERSE_CONTINUE;
4193   Operator op = be->op();
4194   if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
4195     return TRAVERSE_CONTINUE;
4196   go_assert(this->found_ == NULL);
4197   this->found_ = pexpr;
4198   return TRAVERSE_EXIT;
4199 }
4200 
4201 // A traversal class used to turn shortcut operators into explicit if
4202 // statements.
4203 
4204 class Shortcuts : public Traverse
4205 {
4206  public:
Shortcuts(Gogo * gogo)4207   Shortcuts(Gogo* gogo)
4208     : Traverse(traverse_variables
4209 	       | traverse_statements),
4210       gogo_(gogo)
4211   { }
4212 
4213  protected:
4214   int
4215   variable(Named_object*);
4216 
4217   int
4218   statement(Block*, size_t*, Statement*);
4219 
4220  private:
4221   // Convert a shortcut operator.
4222   Statement*
4223   convert_shortcut(Block* enclosing, Expression** pshortcut);
4224 
4225   // The IR.
4226   Gogo* gogo_;
4227 };
4228 
4229 // Remove shortcut operators in a single statement.
4230 
4231 int
statement(Block * block,size_t * pindex,Statement * s)4232 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
4233 {
4234   // FIXME: This approach doesn't work for switch statements, because
4235   // we add the new statements before the whole switch when we need to
4236   // instead add them just before the switch expression.  The right
4237   // fix is probably to lower switch statements with nonconstant cases
4238   // to a series of conditionals.
4239   if (s->switch_statement() != NULL)
4240     return TRAVERSE_CONTINUE;
4241 
4242   while (true)
4243     {
4244       Find_shortcut find_shortcut;
4245 
4246       // If S is a variable declaration, then ordinary traversal won't
4247       // do anything.  We want to explicitly traverse the
4248       // initialization expression if there is one.
4249       Variable_declaration_statement* vds = s->variable_declaration_statement();
4250       Expression* init = NULL;
4251       if (vds == NULL)
4252 	s->traverse_contents(&find_shortcut);
4253       else
4254 	{
4255 	  init = vds->var()->var_value()->init();
4256 	  if (init == NULL)
4257 	    return TRAVERSE_CONTINUE;
4258 	  init->traverse(&init, &find_shortcut);
4259 	}
4260       Expression** pshortcut = find_shortcut.found();
4261       if (pshortcut == NULL)
4262 	return TRAVERSE_CONTINUE;
4263 
4264       Statement* snew = this->convert_shortcut(block, pshortcut);
4265       block->insert_statement_before(*pindex, snew);
4266       ++*pindex;
4267 
4268       if (pshortcut == &init)
4269 	vds->var()->var_value()->set_init(init);
4270     }
4271 }
4272 
4273 // Remove shortcut operators in the initializer of a global variable.
4274 
4275 int
variable(Named_object * no)4276 Shortcuts::variable(Named_object* no)
4277 {
4278   if (no->is_result_variable())
4279     return TRAVERSE_CONTINUE;
4280   Variable* var = no->var_value();
4281   Expression* init = var->init();
4282   if (!var->is_global() || init == NULL)
4283     return TRAVERSE_CONTINUE;
4284 
4285   while (true)
4286     {
4287       Find_shortcut find_shortcut;
4288       init->traverse(&init, &find_shortcut);
4289       Expression** pshortcut = find_shortcut.found();
4290       if (pshortcut == NULL)
4291 	return TRAVERSE_CONTINUE;
4292 
4293       Statement* snew = this->convert_shortcut(NULL, pshortcut);
4294       var->add_preinit_statement(this->gogo_, snew);
4295       if (pshortcut == &init)
4296 	var->set_init(init);
4297     }
4298 }
4299 
4300 // Given an expression which uses a shortcut operator, return a
4301 // statement which implements it, and update *PSHORTCUT accordingly.
4302 
4303 Statement*
convert_shortcut(Block * enclosing,Expression ** pshortcut)4304 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
4305 {
4306   Binary_expression* shortcut = (*pshortcut)->binary_expression();
4307   Expression* left = shortcut->left();
4308   Expression* right = shortcut->right();
4309   Location loc = shortcut->location();
4310 
4311   Block* retblock = new Block(enclosing, loc);
4312   retblock->set_end_location(loc);
4313 
4314   Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
4315 						      left, loc);
4316   retblock->add_statement(ts);
4317 
4318   Block* block = new Block(retblock, loc);
4319   block->set_end_location(loc);
4320   Expression* tmpref = Expression::make_temporary_reference(ts, loc);
4321   Statement* assign = Statement::make_assignment(tmpref, right, loc);
4322   block->add_statement(assign);
4323 
4324   Expression* cond = Expression::make_temporary_reference(ts, loc);
4325   if (shortcut->binary_expression()->op() == OPERATOR_OROR)
4326     cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
4327 
4328   Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
4329 							 loc);
4330   retblock->add_statement(if_statement);
4331 
4332   *pshortcut = Expression::make_temporary_reference(ts, loc);
4333 
4334   delete shortcut;
4335 
4336   // Now convert any shortcut operators in LEFT and RIGHT.
4337   // LEFT and RIGHT were skipped in the top level
4338   // Gogo::order_evaluations. We need to order their
4339   // components first.
4340   Order_eval order_eval(this->gogo_);
4341   retblock->traverse(&order_eval);
4342   Shortcuts shortcuts(this->gogo_);
4343   retblock->traverse(&shortcuts);
4344 
4345   return Statement::make_block_statement(retblock, loc);
4346 }
4347 
4348 // Turn shortcut operators into explicit if statements.  Doing this
4349 // considerably simplifies the order of evaluation rules.
4350 
4351 void
remove_shortcuts()4352 Gogo::remove_shortcuts()
4353 {
4354   Shortcuts shortcuts(this);
4355   this->traverse(&shortcuts);
4356 }
4357 
4358 // Turn shortcut operators into explicit if statements in a block.
4359 
4360 void
remove_shortcuts_in_block(Block * block)4361 Gogo::remove_shortcuts_in_block(Block* block)
4362 {
4363   Shortcuts shortcuts(this);
4364   block->traverse(&shortcuts);
4365 }
4366 
4367 // Traversal to flatten parse tree after order of evaluation rules are applied.
4368 
4369 class Flatten : public Traverse
4370 {
4371  public:
Flatten(Gogo * gogo,Named_object * function)4372   Flatten(Gogo* gogo, Named_object* function)
4373     : Traverse(traverse_variables
4374 	       | traverse_functions
4375 	       | traverse_statements
4376 	       | traverse_expressions),
4377       gogo_(gogo), function_(function), inserter_()
4378   { }
4379 
4380   void
set_inserter(const Statement_inserter * inserter)4381   set_inserter(const Statement_inserter* inserter)
4382   { this->inserter_ = *inserter; }
4383 
4384   int
4385   variable(Named_object*);
4386 
4387   int
4388   function(Named_object*);
4389 
4390   int
4391   statement(Block*, size_t* pindex, Statement*);
4392 
4393   int
4394   expression(Expression**);
4395 
4396  private:
4397   // General IR.
4398   Gogo* gogo_;
4399   // The function we are traversing.
4400   Named_object* function_;
4401   // Current statement inserter for use by expressions.
4402   Statement_inserter inserter_;
4403 };
4404 
4405 // Flatten variables.
4406 
4407 int
variable(Named_object * no)4408 Flatten::variable(Named_object* no)
4409 {
4410   if (!no->is_variable())
4411     return TRAVERSE_CONTINUE;
4412 
4413   if (no->is_variable() && no->var_value()->is_global())
4414     {
4415       // Global variables can have loops in their initialization
4416       // expressions.  This is handled in flatten_init_expression.
4417       no->var_value()->flatten_init_expression(this->gogo_, this->function_,
4418                                                &this->inserter_);
4419       return TRAVERSE_CONTINUE;
4420     }
4421 
4422   if (!no->var_value()->is_parameter()
4423       && !no->var_value()->is_receiver()
4424       && !no->var_value()->is_closure()
4425       && no->var_value()->is_non_escaping_address_taken()
4426       && !no->var_value()->is_in_heap()
4427       && no->var_value()->toplevel_decl() == NULL)
4428     {
4429       // Local variable that has address taken but not escape.
4430       // It needs to be live beyond its lexical scope. So we
4431       // create a top-level declaration for it.
4432       // No need to do it if it is already in the top level.
4433       Block* top_block = function_->func_value()->block();
4434       if (top_block->bindings()->lookup_local(no->name()) != no)
4435         {
4436           Variable* var = no->var_value();
4437           Temporary_statement* ts =
4438             Statement::make_temporary(var->type(), NULL, var->location());
4439           ts->set_is_address_taken();
4440           top_block->add_statement_at_front(ts);
4441           var->set_toplevel_decl(ts);
4442         }
4443     }
4444 
4445   go_assert(!no->var_value()->has_pre_init());
4446 
4447   return TRAVERSE_SKIP_COMPONENTS;
4448 }
4449 
4450 // Flatten the body of a function.  Record the function while flattening it,
4451 // so that we can pass it down when flattening an expression.
4452 
4453 int
function(Named_object * no)4454 Flatten::function(Named_object* no)
4455 {
4456   go_assert(this->function_ == NULL);
4457   this->function_ = no;
4458   int t = no->func_value()->traverse(this);
4459   this->function_ = NULL;
4460 
4461   if (t == TRAVERSE_EXIT)
4462     return t;
4463   return TRAVERSE_SKIP_COMPONENTS;
4464 }
4465 
4466 // Flatten statement parse trees.
4467 
4468 int
statement(Block * block,size_t * pindex,Statement * sorig)4469 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
4470 {
4471   // Because we explicitly traverse the statement's contents
4472   // ourselves, we want to skip block statements here.  There is
4473   // nothing to flatten in a block statement.
4474   if (sorig->is_block_statement())
4475     return TRAVERSE_CONTINUE;
4476 
4477   Statement_inserter hold_inserter(this->inserter_);
4478   this->inserter_ = Statement_inserter(block, pindex);
4479 
4480   // Flatten the expressions first.
4481   int t = sorig->traverse_contents(this);
4482   if (t == TRAVERSE_EXIT)
4483     {
4484       this->inserter_ = hold_inserter;
4485       return t;
4486     }
4487 
4488   // Keep flattening until nothing changes.
4489   Statement* s = sorig;
4490   while (true)
4491     {
4492       Statement* snew = s->flatten(this->gogo_, this->function_, block,
4493                                    &this->inserter_);
4494       if (snew == s)
4495 	break;
4496       s = snew;
4497       t = s->traverse_contents(this);
4498       if (t == TRAVERSE_EXIT)
4499 	{
4500 	  this->inserter_ = hold_inserter;
4501 	  return t;
4502 	}
4503     }
4504 
4505   if (s != sorig)
4506     block->replace_statement(*pindex, s);
4507 
4508   this->inserter_ = hold_inserter;
4509   return TRAVERSE_SKIP_COMPONENTS;
4510 }
4511 
4512 // Flatten expression parse trees.
4513 
4514 int
expression(Expression ** pexpr)4515 Flatten::expression(Expression** pexpr)
4516 {
4517   // Keep flattening until nothing changes.
4518   while (true)
4519     {
4520       Expression* e = *pexpr;
4521       if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
4522         return TRAVERSE_EXIT;
4523 
4524       Expression* enew = e->flatten(this->gogo_, this->function_,
4525                                     &this->inserter_);
4526       if (enew == e)
4527 	break;
4528       *pexpr = enew;
4529     }
4530   return TRAVERSE_SKIP_COMPONENTS;
4531 }
4532 
4533 // Flatten a block.
4534 
4535 void
flatten_block(Named_object * function,Block * block)4536 Gogo::flatten_block(Named_object* function, Block* block)
4537 {
4538   Flatten flatten(this, function);
4539   block->traverse(&flatten);
4540 }
4541 
4542 // Flatten an expression.  INSERTER may be NULL, in which case the
4543 // expression had better not need to create any temporaries.
4544 
4545 void
flatten_expression(Named_object * function,Statement_inserter * inserter,Expression ** pexpr)4546 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
4547                          Expression** pexpr)
4548 {
4549   Flatten flatten(this, function);
4550   if (inserter != NULL)
4551     flatten.set_inserter(inserter);
4552   flatten.expression(pexpr);
4553 }
4554 
4555 void
flatten()4556 Gogo::flatten()
4557 {
4558   Flatten flatten(this, NULL);
4559   this->traverse(&flatten);
4560 }
4561 
4562 // Traversal to convert calls to the predeclared recover function to
4563 // pass in an argument indicating whether it can recover from a panic
4564 // or not.
4565 
4566 class Convert_recover : public Traverse
4567 {
4568  public:
Convert_recover(Named_object * arg)4569   Convert_recover(Named_object* arg)
4570     : Traverse(traverse_expressions),
4571       arg_(arg)
4572   { }
4573 
4574  protected:
4575   int
4576   expression(Expression**);
4577 
4578  private:
4579   // The argument to pass to the function.
4580   Named_object* arg_;
4581 };
4582 
4583 // Convert calls to recover.
4584 
4585 int
expression(Expression ** pp)4586 Convert_recover::expression(Expression** pp)
4587 {
4588   Call_expression* ce = (*pp)->call_expression();
4589   if (ce != NULL && ce->is_recover_call())
4590     ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4591 						       ce->location()));
4592   return TRAVERSE_CONTINUE;
4593 }
4594 
4595 // Traversal for build_recover_thunks.
4596 
4597 class Build_recover_thunks : public Traverse
4598 {
4599  public:
Build_recover_thunks(Gogo * gogo)4600   Build_recover_thunks(Gogo* gogo)
4601     : Traverse(traverse_functions),
4602       gogo_(gogo)
4603   { }
4604 
4605   int
4606   function(Named_object*);
4607 
4608  private:
4609   Expression*
4610   can_recover_arg(Location);
4611 
4612   // General IR.
4613   Gogo* gogo_;
4614 };
4615 
4616 // If this function calls recover, turn it into a thunk.
4617 
4618 int
function(Named_object * orig_no)4619 Build_recover_thunks::function(Named_object* orig_no)
4620 {
4621   Function* orig_func = orig_no->func_value();
4622   if (!orig_func->calls_recover()
4623       || orig_func->is_recover_thunk()
4624       || orig_func->has_recover_thunk())
4625     return TRAVERSE_CONTINUE;
4626 
4627   Gogo* gogo = this->gogo_;
4628   Location location = orig_func->location();
4629 
4630   static int count;
4631   char buf[50];
4632 
4633   Function_type* orig_fntype = orig_func->type();
4634   Typed_identifier_list* new_params = new Typed_identifier_list();
4635   std::string receiver_name;
4636   if (orig_fntype->is_method())
4637     {
4638       const Typed_identifier* receiver = orig_fntype->receiver();
4639       snprintf(buf, sizeof buf, "rt.%u", count);
4640       ++count;
4641       receiver_name = buf;
4642       new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4643 					     receiver->location()));
4644     }
4645   const Typed_identifier_list* orig_params = orig_fntype->parameters();
4646   if (orig_params != NULL && !orig_params->empty())
4647     {
4648       for (Typed_identifier_list::const_iterator p = orig_params->begin();
4649 	   p != orig_params->end();
4650 	   ++p)
4651 	{
4652 	  snprintf(buf, sizeof buf, "pt.%u", count);
4653 	  ++count;
4654 	  new_params->push_back(Typed_identifier(buf, p->type(),
4655 						 p->location()));
4656 	}
4657     }
4658   snprintf(buf, sizeof buf, "pr.%u", count);
4659   ++count;
4660   std::string can_recover_name = buf;
4661   new_params->push_back(Typed_identifier(can_recover_name,
4662 					 Type::lookup_bool_type(),
4663 					 orig_fntype->location()));
4664 
4665   const Typed_identifier_list* orig_results = orig_fntype->results();
4666   Typed_identifier_list* new_results;
4667   if (orig_results == NULL || orig_results->empty())
4668     new_results = NULL;
4669   else
4670     {
4671       new_results = new Typed_identifier_list();
4672       for (Typed_identifier_list::const_iterator p = orig_results->begin();
4673 	   p != orig_results->end();
4674 	   ++p)
4675 	new_results->push_back(Typed_identifier("", p->type(), p->location()));
4676     }
4677 
4678   Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4679 						       new_results,
4680 						       orig_fntype->location());
4681   if (orig_fntype->is_varargs())
4682     new_fntype->set_is_varargs();
4683 
4684   Type* rtype = NULL;
4685   if (orig_fntype->is_method())
4686     rtype = orig_fntype->receiver()->type();
4687   std::string name(gogo->recover_thunk_name(orig_no->name(), rtype));
4688   Named_object *new_no = gogo->start_function(name, new_fntype, false,
4689 					      location);
4690   Function *new_func = new_no->func_value();
4691   if (orig_func->enclosing() != NULL)
4692     new_func->set_enclosing(orig_func->enclosing());
4693 
4694   // We build the code for the original function attached to the new
4695   // function, and then swap the original and new function bodies.
4696   // This means that existing references to the original function will
4697   // then refer to the new function.  That makes this code a little
4698   // confusing, in that the reference to NEW_NO really refers to the
4699   // other function, not the one we are building.
4700 
4701   Expression* closure = NULL;
4702   if (orig_func->needs_closure())
4703     {
4704       // For the new function we are creating, declare a new parameter
4705       // variable NEW_CLOSURE_NO and set it to be the closure variable
4706       // of the function.  This will be set to the closure value
4707       // passed in by the caller.  Then pass a reference to this
4708       // variable as the closure value when calling the original
4709       // function.  In other words, simply pass the closure value
4710       // through the thunk we are creating.
4711       Named_object* orig_closure_no = orig_func->closure_var();
4712       Variable* orig_closure_var = orig_closure_no->var_value();
4713       Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4714 				       false, false, location);
4715       new_var->set_is_closure();
4716       snprintf(buf, sizeof buf, "closure.%u", count);
4717       ++count;
4718       Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4719 								 new_var);
4720       new_func->set_closure_var(new_closure_no);
4721       closure = Expression::make_var_reference(new_closure_no, location);
4722     }
4723 
4724   Expression* fn = Expression::make_func_reference(new_no, closure, location);
4725 
4726   Expression_list* args = new Expression_list();
4727   if (new_params != NULL)
4728     {
4729       // Note that we skip the last parameter, which is the boolean
4730       // indicating whether recover can succed.
4731       for (Typed_identifier_list::const_iterator p = new_params->begin();
4732 	   p + 1 != new_params->end();
4733 	   ++p)
4734 	{
4735 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
4736 	  go_assert(p_no != NULL
4737 		     && p_no->is_variable()
4738 		     && p_no->var_value()->is_parameter());
4739 	  args->push_back(Expression::make_var_reference(p_no, location));
4740 	}
4741     }
4742   args->push_back(this->can_recover_arg(location));
4743 
4744   gogo->start_block(location);
4745 
4746   Call_expression* call = Expression::make_call(fn, args, false, location);
4747 
4748   // Any varargs call has already been lowered.
4749   call->set_varargs_are_lowered();
4750 
4751   Statement* s = Statement::make_return_from_call(call, location);
4752   s->determine_types();
4753   gogo->add_statement(s);
4754 
4755   Block* b = gogo->finish_block(location);
4756 
4757   gogo->add_block(b, location);
4758 
4759   // Lower the call in case it returns multiple results.
4760   gogo->lower_block(new_no, b);
4761 
4762   gogo->finish_function(location);
4763 
4764   // Swap the function bodies and types.
4765   new_func->swap_for_recover(orig_func);
4766   orig_func->set_is_recover_thunk();
4767   new_func->set_calls_recover();
4768   new_func->set_has_recover_thunk();
4769 
4770   Bindings* orig_bindings = orig_func->block()->bindings();
4771   Bindings* new_bindings = new_func->block()->bindings();
4772   if (orig_fntype->is_method())
4773     {
4774       // We changed the receiver to be a regular parameter.  We have
4775       // to update the binding accordingly in both functions.
4776       Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4777       go_assert(orig_rec_no != NULL
4778 		 && orig_rec_no->is_variable()
4779 		 && !orig_rec_no->var_value()->is_receiver());
4780       orig_rec_no->var_value()->set_is_receiver();
4781 
4782       std::string new_receiver_name(orig_fntype->receiver()->name());
4783       if (new_receiver_name.empty())
4784 	{
4785 	  // Find the receiver.  It was named "r.NNN" in
4786 	  // Gogo::start_function.
4787 	  for (Bindings::const_definitions_iterator p =
4788 		 new_bindings->begin_definitions();
4789 	       p != new_bindings->end_definitions();
4790 	       ++p)
4791 	    {
4792 	      const std::string& pname((*p)->name());
4793 	      if (pname[0] == 'r' && pname[1] == '.')
4794 		{
4795 		  new_receiver_name = pname;
4796 		  break;
4797 		}
4798 	    }
4799 	  go_assert(!new_receiver_name.empty());
4800 	}
4801       Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4802       if (new_rec_no == NULL)
4803 	go_assert(saw_errors());
4804       else
4805 	{
4806 	  go_assert(new_rec_no->is_variable()
4807 		     && new_rec_no->var_value()->is_receiver());
4808 	  new_rec_no->var_value()->set_is_not_receiver();
4809 	}
4810     }
4811 
4812   // Because we flipped blocks but not types, the can_recover
4813   // parameter appears in the (now) old bindings as a parameter.
4814   // Change it to a local variable, whereupon it will be discarded.
4815   Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4816   go_assert(can_recover_no != NULL
4817 	     && can_recover_no->is_variable()
4818 	     && can_recover_no->var_value()->is_parameter());
4819   orig_bindings->remove_binding(can_recover_no);
4820 
4821   // Add the can_recover argument to the (now) new bindings, and
4822   // attach it to any recover statements.
4823   Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4824 					   false, true, false, location);
4825   can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4826 					      can_recover_var);
4827   Convert_recover convert_recover(can_recover_no);
4828   new_func->traverse(&convert_recover);
4829 
4830   // Update the function pointers in any named results.
4831   new_func->update_result_variables();
4832   orig_func->update_result_variables();
4833 
4834   return TRAVERSE_CONTINUE;
4835 }
4836 
4837 // Return the expression to pass for the .can_recover parameter to the
4838 // new function.  This indicates whether a call to recover may return
4839 // non-nil.  The expression is runtime.canrecover(__builtin_return_address()).
4840 
4841 Expression*
can_recover_arg(Location location)4842 Build_recover_thunks::can_recover_arg(Location location)
4843 {
4844   Type* uintptr_type = Type::lookup_integer_type("uintptr");
4845   static Named_object* can_recover;
4846   if (can_recover == NULL)
4847     {
4848       const Location bloc = Linemap::predeclared_location();
4849       Typed_identifier_list* param_types = new Typed_identifier_list();
4850       param_types->push_back(Typed_identifier("a", uintptr_type, bloc));
4851       Type* boolean_type = Type::lookup_bool_type();
4852       Typed_identifier_list* results = new Typed_identifier_list();
4853       results->push_back(Typed_identifier("", boolean_type, bloc));
4854       Function_type* fntype = Type::make_function_type(NULL, param_types,
4855 						       results, bloc);
4856       can_recover =
4857 	Named_object::make_function_declaration("runtime_canrecover",
4858 						NULL, fntype, bloc);
4859       can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4860     }
4861 
4862   Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4863   Expression* call = Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS,
4864                                         location, 1, zexpr);
4865   call = Expression::make_unsafe_cast(uintptr_type, call, location);
4866 
4867   Expression_list* args = new Expression_list();
4868   args->push_back(call);
4869 
4870   Expression* fn = Expression::make_func_reference(can_recover, NULL, location);
4871   return Expression::make_call(fn, args, false, location);
4872 }
4873 
4874 // Build thunks for functions which call recover.  We build a new
4875 // function with an extra parameter, which is whether a call to
4876 // recover can succeed.  We then move the body of this function to
4877 // that one.  We then turn this function into a thunk which calls the
4878 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4879 // The function will be marked as not splitting the stack.  This will
4880 // cooperate with the implementation of defer to make recover do the
4881 // right thing.
4882 
4883 void
build_recover_thunks()4884 Gogo::build_recover_thunks()
4885 {
4886   Build_recover_thunks build_recover_thunks(this);
4887   this->traverse(&build_recover_thunks);
4888 }
4889 
4890 // Look for named types to see whether we need to create an interface
4891 // method table.
4892 
4893 class Build_method_tables : public Traverse
4894 {
4895  public:
Build_method_tables(Gogo * gogo,const std::vector<Interface_type * > & interfaces)4896   Build_method_tables(Gogo* gogo,
4897 		      const std::vector<Interface_type*>& interfaces)
4898     : Traverse(traverse_types),
4899       gogo_(gogo), interfaces_(interfaces)
4900   { }
4901 
4902   int
4903   type(Type*);
4904 
4905  private:
4906   // The IR.
4907   Gogo* gogo_;
4908   // A list of locally defined interfaces which have hidden methods.
4909   const std::vector<Interface_type*>& interfaces_;
4910 };
4911 
4912 // Build all required interface method tables for types.  We need to
4913 // ensure that we have an interface method table for every interface
4914 // which has a hidden method, for every named type which implements
4915 // that interface.  Normally we can just build interface method tables
4916 // as we need them.  However, in some cases we can require an
4917 // interface method table for an interface defined in a different
4918 // package for a type defined in that package.  If that interface and
4919 // type both use a hidden method, that is OK.  However, we will not be
4920 // able to build that interface method table when we need it, because
4921 // the type's hidden method will be static.  So we have to build it
4922 // here, and just refer it from other packages as needed.
4923 
4924 void
build_interface_method_tables()4925 Gogo::build_interface_method_tables()
4926 {
4927   if (saw_errors())
4928     return;
4929 
4930   std::vector<Interface_type*> hidden_interfaces;
4931   hidden_interfaces.reserve(this->interface_types_.size());
4932   for (std::vector<Interface_type*>::const_iterator pi =
4933 	 this->interface_types_.begin();
4934        pi != this->interface_types_.end();
4935        ++pi)
4936     {
4937       const Typed_identifier_list* methods = (*pi)->methods();
4938       if (methods == NULL)
4939 	continue;
4940       for (Typed_identifier_list::const_iterator pm = methods->begin();
4941 	   pm != methods->end();
4942 	   ++pm)
4943 	{
4944 	  if (Gogo::is_hidden_name(pm->name()))
4945 	    {
4946 	      hidden_interfaces.push_back(*pi);
4947 	      break;
4948 	    }
4949 	}
4950     }
4951 
4952   if (!hidden_interfaces.empty())
4953     {
4954       // Now traverse the tree looking for all named types.
4955       Build_method_tables bmt(this, hidden_interfaces);
4956       this->traverse(&bmt);
4957     }
4958 
4959   // We no longer need the list of interfaces.
4960 
4961   this->interface_types_.clear();
4962 }
4963 
4964 // This is called for each type.  For a named type, for each of the
4965 // interfaces with hidden methods that it implements, create the
4966 // method table.
4967 
4968 int
type(Type * type)4969 Build_method_tables::type(Type* type)
4970 {
4971   Named_type* nt = type->named_type();
4972   Struct_type* st = type->struct_type();
4973   if (nt != NULL || st != NULL)
4974     {
4975       Translate_context context(this->gogo_, NULL, NULL, NULL);
4976       for (std::vector<Interface_type*>::const_iterator p =
4977 	     this->interfaces_.begin();
4978 	   p != this->interfaces_.end();
4979 	   ++p)
4980 	{
4981 	  // We ask whether a pointer to the named type implements the
4982 	  // interface, because a pointer can implement more methods
4983 	  // than a value.
4984 	  if (nt != NULL)
4985 	    {
4986 	      if ((*p)->implements_interface(Type::make_pointer_type(nt),
4987 					     NULL))
4988 		{
4989 		  nt->interface_method_table(*p, false)->get_backend(&context);
4990                   nt->interface_method_table(*p, true)->get_backend(&context);
4991 		}
4992 	    }
4993 	  else
4994 	    {
4995 	      if ((*p)->implements_interface(Type::make_pointer_type(st),
4996 					     NULL))
4997 		{
4998 		  st->interface_method_table(*p, false)->get_backend(&context);
4999 		  st->interface_method_table(*p, true)->get_backend(&context);
5000 		}
5001 	    }
5002 	}
5003     }
5004   return TRAVERSE_CONTINUE;
5005 }
5006 
5007 // Return an expression which allocates memory to hold values of type TYPE.
5008 
5009 Expression*
allocate_memory(Type * type,Location location)5010 Gogo::allocate_memory(Type* type, Location location)
5011 {
5012   Expression* td = Expression::make_type_descriptor(type, location);
5013   return Runtime::make_call(Runtime::NEW, location, 1, td);
5014 }
5015 
5016 // Traversal class used to check for return statements.
5017 
5018 class Check_return_statements_traverse : public Traverse
5019 {
5020  public:
Check_return_statements_traverse()5021   Check_return_statements_traverse()
5022     : Traverse(traverse_functions)
5023   { }
5024 
5025   int
5026   function(Named_object*);
5027 };
5028 
5029 // Check that a function has a return statement if it needs one.
5030 
5031 int
function(Named_object * no)5032 Check_return_statements_traverse::function(Named_object* no)
5033 {
5034   Function* func = no->func_value();
5035   const Function_type* fntype = func->type();
5036   const Typed_identifier_list* results = fntype->results();
5037 
5038   // We only need a return statement if there is a return value.
5039   if (results == NULL || results->empty())
5040     return TRAVERSE_CONTINUE;
5041 
5042   if (func->block()->may_fall_through())
5043     go_error_at(func->block()->end_location(),
5044 		"missing return at end of function");
5045 
5046   return TRAVERSE_CONTINUE;
5047 }
5048 
5049 // Check return statements.
5050 
5051 void
check_return_statements()5052 Gogo::check_return_statements()
5053 {
5054   Check_return_statements_traverse traverse;
5055   this->traverse(&traverse);
5056 }
5057 
5058 // Traversal class to decide whether a function body is less than the
5059 // inlining budget.  This adjusts *available as it goes, and stops the
5060 // traversal if it goes negative.
5061 
5062 class Inline_within_budget : public Traverse
5063 {
5064  public:
Inline_within_budget(int * available)5065   Inline_within_budget(int* available)
5066     : Traverse(traverse_statements
5067 	       | traverse_expressions),
5068       available_(available)
5069   { }
5070 
5071   int
5072   statement(Block*, size_t*, Statement*);
5073 
5074   int
5075   expression(Expression**);
5076 
5077  private:
5078   // Pointer to remaining budget.
5079   int* available_;
5080 };
5081 
5082 // Adjust the budget for the inlining cost of a statement.
5083 
5084 int
statement(Block *,size_t *,Statement * s)5085 Inline_within_budget::statement(Block*, size_t*, Statement* s)
5086 {
5087   if (*this->available_ < 0)
5088     return TRAVERSE_EXIT;
5089   *this->available_ -= s->inlining_cost();
5090   return TRAVERSE_CONTINUE;
5091 }
5092 
5093 // Adjust the budget for the inlining cost of an expression.
5094 
5095 int
expression(Expression ** pexpr)5096 Inline_within_budget::expression(Expression** pexpr)
5097 {
5098   if (*this->available_ < 0)
5099     return TRAVERSE_EXIT;
5100   *this->available_ -= (*pexpr)->inlining_cost();
5101   return TRAVERSE_CONTINUE;
5102 }
5103 
5104 // Traversal class to find functions whose body should be exported for
5105 // inlining by other packages.
5106 
5107 class Mark_inline_candidates : public Traverse
5108 {
5109  public:
Mark_inline_candidates(Unordered_set (Named_object *)* marked)5110   Mark_inline_candidates(Unordered_set(Named_object*)* marked)
5111     : Traverse(traverse_functions
5112 	       | traverse_types),
5113       marked_functions_(marked)
5114   { }
5115 
5116   int
5117   function(Named_object*);
5118 
5119   int
5120   type(Type*);
5121 
5122  private:
5123   // We traverse the function body trying to determine how expensive
5124   // it is for inlining.  We start with a budget, and decrease that
5125   // budget for each statement and expression.  If the budget goes
5126   // negative, we do not export the function body.  The value of this
5127   // budget is a heuristic.  In the usual GCC spirit, we could
5128   // consider setting this via a command line option.
5129   const int budget_heuristic = 80;
5130 
5131   // Set of named objects that are marked as inline candidates.
5132   Unordered_set(Named_object*)* marked_functions_;
5133 };
5134 
5135 // Mark a function if it is an inline candidate.
5136 
5137 int
function(Named_object * no)5138 Mark_inline_candidates::function(Named_object* no)
5139 {
5140   Function* func = no->func_value();
5141   if ((func->pragmas() & GOPRAGMA_NOINLINE) != 0)
5142     return TRAVERSE_CONTINUE;
5143   int budget = budget_heuristic;
5144   Inline_within_budget iwb(&budget);
5145   func->block()->traverse(&iwb);
5146   if (budget >= 0)
5147     {
5148       func->set_export_for_inlining();
5149       this->marked_functions_->insert(no);
5150     }
5151   return TRAVERSE_CONTINUE;
5152 }
5153 
5154 // Mark methods if they are inline candidates.
5155 
5156 int
type(Type * t)5157 Mark_inline_candidates::type(Type* t)
5158 {
5159   Named_type* nt = t->named_type();
5160   if (nt == NULL || nt->is_alias())
5161     return TRAVERSE_CONTINUE;
5162   const Bindings* methods = nt->local_methods();
5163   if (methods == NULL)
5164     return TRAVERSE_CONTINUE;
5165   for (Bindings::const_definitions_iterator p = methods->begin_definitions();
5166        p != methods->end_definitions();
5167        ++p)
5168     {
5169       Named_object* no = *p;
5170       go_assert(no->is_function());
5171       Function *func = no->func_value();
5172       if ((func->pragmas() & GOPRAGMA_NOINLINE) != 0)
5173         continue;
5174       int budget = budget_heuristic;
5175       Inline_within_budget iwb(&budget);
5176       func->block()->traverse(&iwb);
5177       if (budget >= 0)
5178         {
5179           func->set_export_for_inlining();
5180           this->marked_functions_->insert(no);
5181         }
5182     }
5183   return TRAVERSE_CONTINUE;
5184 }
5185 
5186 // Export identifiers as requested.
5187 
5188 void
do_exports()5189 Gogo::do_exports()
5190 {
5191   if (saw_errors())
5192     return;
5193 
5194   // Mark any functions whose body should be exported for inlining by
5195   // other packages.
5196   Unordered_set(Named_object*) marked_functions;
5197   Mark_inline_candidates mic(&marked_functions);
5198   this->traverse(&mic);
5199 
5200   // For now we always stream to a section.  Later we may want to
5201   // support streaming to a separate file.
5202   Stream_to_section stream(this->backend());
5203 
5204   // Write out either the prefix or pkgpath depending on how we were
5205   // invoked.
5206   std::string prefix;
5207   std::string pkgpath;
5208   if (this->pkgpath_from_option_)
5209     pkgpath = this->pkgpath_;
5210   else if (this->prefix_from_option_)
5211     prefix = this->prefix_;
5212   else if (this->is_main_package())
5213     pkgpath = "main";
5214   else
5215     prefix = "go";
5216 
5217   std::string init_fn_name;
5218   if (this->is_main_package())
5219     init_fn_name = "";
5220   else if (this->need_init_fn_)
5221     init_fn_name = this->get_init_fn_name();
5222   else
5223     init_fn_name = this->dummy_init_fn_name();
5224 
5225   Export exp(&stream);
5226   exp.register_builtin_types(this);
5227   exp.export_globals(this->package_name(),
5228 		     prefix,
5229 		     pkgpath,
5230 		     this->packages_,
5231 		     this->imports_,
5232 		     init_fn_name,
5233 		     this->imported_init_fns_,
5234 		     this->package_->bindings(),
5235                      &marked_functions);
5236 
5237   if (!this->c_header_.empty() && !saw_errors())
5238     this->write_c_header();
5239 }
5240 
5241 // Write the top level named struct types in C format to a C header
5242 // file.  This is used when building the runtime package, to share
5243 // struct definitions between C and Go.
5244 
5245 void
write_c_header()5246 Gogo::write_c_header()
5247 {
5248   std::ofstream out;
5249   out.open(this->c_header_.c_str());
5250   if (out.fail())
5251     {
5252       go_error_at(Linemap::unknown_location(),
5253 		  "cannot open %s: %m", this->c_header_.c_str());
5254       return;
5255     }
5256 
5257   std::list<Named_object*> types;
5258   Bindings* top = this->package_->bindings();
5259   for (Bindings::const_definitions_iterator p = top->begin_definitions();
5260        p != top->end_definitions();
5261        ++p)
5262     {
5263       Named_object* no = *p;
5264 
5265       // Skip names that start with underscore followed by something
5266       // other than an uppercase letter, as when compiling the runtime
5267       // package they are mostly types defined by mkrsysinfo.sh based
5268       // on the C system header files.  We don't need to translate
5269       // types to C and back to Go.  But do accept the special cases
5270       // _defer, _panic, and _type.
5271       std::string name = Gogo::unpack_hidden_name(no->name());
5272       if (name[0] == '_'
5273 	  && (name[1] < 'A' || name[1] > 'Z')
5274 	  && (name != "_defer" && name != "_panic" && name != "_type"))
5275 	continue;
5276 
5277       if (no->is_type() && no->type_value()->struct_type() != NULL)
5278 	types.push_back(no);
5279       if (no->is_const()
5280 	  && no->const_value()->type()->integer_type() != NULL
5281 	  && !no->const_value()->is_sink())
5282 	{
5283 	  Numeric_constant nc;
5284 	  unsigned long val;
5285 	  if (no->const_value()->expr()->numeric_constant_value(&nc)
5286 	      && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
5287 	    {
5288 	      out << "#define " << no->message_name() << ' ' << val
5289 		  << std::endl;
5290 	    }
5291 	}
5292     }
5293 
5294   std::vector<const Named_object*> written;
5295   int loop = 0;
5296   while (!types.empty())
5297     {
5298       Named_object* no = types.front();
5299       types.pop_front();
5300 
5301       std::vector<const Named_object*> requires;
5302       std::vector<const Named_object*> declare;
5303       if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
5304 								  &declare))
5305 	continue;
5306 
5307       bool ok = true;
5308       for (std::vector<const Named_object*>::const_iterator pr
5309 	     = requires.begin();
5310 	   pr != requires.end() && ok;
5311 	   ++pr)
5312 	{
5313 	  for (std::list<Named_object*>::const_iterator pt = types.begin();
5314 	       pt != types.end() && ok;
5315 	       ++pt)
5316 	    if (*pr == *pt)
5317 	      ok = false;
5318 	}
5319       if (!ok)
5320 	{
5321 	  ++loop;
5322 	  if (loop > 10000)
5323 	    {
5324 	      // This should be impossible since the code parsed and
5325 	      // type checked.
5326 	      go_unreachable();
5327 	    }
5328 
5329 	  types.push_back(no);
5330 	  continue;
5331 	}
5332 
5333       for (std::vector<const Named_object*>::const_iterator pd
5334 	     = declare.begin();
5335 	   pd != declare.end();
5336 	   ++pd)
5337 	{
5338 	  if (*pd == no)
5339 	    continue;
5340 
5341 	  std::vector<const Named_object*> drequires;
5342 	  std::vector<const Named_object*> ddeclare;
5343 	  if (!(*pd)->type_value()->struct_type()->
5344 	      can_write_to_c_header(&drequires, &ddeclare))
5345 	    continue;
5346 
5347 	  bool done = false;
5348 	  for (std::vector<const Named_object*>::const_iterator pw
5349 		 = written.begin();
5350 	       pw != written.end();
5351 	       ++pw)
5352 	    {
5353 	      if (*pw == *pd)
5354 		{
5355 		  done = true;
5356 		  break;
5357 		}
5358 	    }
5359 	  if (!done)
5360 	    {
5361 	      out << std::endl;
5362 	      out << "struct " << (*pd)->message_name() << ";" << std::endl;
5363 	      written.push_back(*pd);
5364 	    }
5365 	}
5366 
5367       out << std::endl;
5368       out << "struct " << no->message_name() << " {" << std::endl;
5369       no->type_value()->struct_type()->write_to_c_header(out);
5370       out << "};" << std::endl;
5371       written.push_back(no);
5372     }
5373 
5374   out.close();
5375   if (out.fail())
5376     go_error_at(Linemap::unknown_location(),
5377 		"error writing to %s: %m", this->c_header_.c_str());
5378 }
5379 
5380 // Find the blocks in order to convert named types defined in blocks.
5381 
5382 class Convert_named_types : public Traverse
5383 {
5384  public:
Convert_named_types(Gogo * gogo)5385   Convert_named_types(Gogo* gogo)
5386     : Traverse(traverse_blocks),
5387       gogo_(gogo)
5388   { }
5389 
5390  protected:
5391   int
5392   block(Block* block);
5393 
5394  private:
5395   Gogo* gogo_;
5396 };
5397 
5398 int
block(Block * block)5399 Convert_named_types::block(Block* block)
5400 {
5401   this->gogo_->convert_named_types_in_bindings(block->bindings());
5402   return TRAVERSE_CONTINUE;
5403 }
5404 
5405 // Convert all named types to the backend representation.  Since named
5406 // types can refer to other types, this needs to be done in the right
5407 // sequence, which is handled by Named_type::convert.  Here we arrange
5408 // to call that for each named type.
5409 
5410 void
convert_named_types()5411 Gogo::convert_named_types()
5412 {
5413   this->convert_named_types_in_bindings(this->globals_);
5414   for (Packages::iterator p = this->packages_.begin();
5415        p != this->packages_.end();
5416        ++p)
5417     {
5418       Package* package = p->second;
5419       this->convert_named_types_in_bindings(package->bindings());
5420     }
5421 
5422   Convert_named_types cnt(this);
5423   this->traverse(&cnt);
5424 
5425   // Make all the builtin named types used for type descriptors, and
5426   // then convert them.  They will only be written out if they are
5427   // needed.
5428   Type::make_type_descriptor_type();
5429   Type::make_type_descriptor_ptr_type();
5430   Function_type::make_function_type_descriptor_type();
5431   Pointer_type::make_pointer_type_descriptor_type();
5432   Struct_type::make_struct_type_descriptor_type();
5433   Array_type::make_array_type_descriptor_type();
5434   Array_type::make_slice_type_descriptor_type();
5435   Map_type::make_map_type_descriptor_type();
5436   Channel_type::make_chan_type_descriptor_type();
5437   Interface_type::make_interface_type_descriptor_type();
5438   Expression::make_func_descriptor_type();
5439   Type::convert_builtin_named_types(this);
5440 
5441   Runtime::convert_types(this);
5442 
5443   this->named_types_are_converted_ = true;
5444 
5445   Type::finish_pointer_types(this);
5446 }
5447 
5448 // Convert all names types in a set of bindings.
5449 
5450 void
convert_named_types_in_bindings(Bindings * bindings)5451 Gogo::convert_named_types_in_bindings(Bindings* bindings)
5452 {
5453   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5454        p != bindings->end_definitions();
5455        ++p)
5456     {
5457       if ((*p)->is_type())
5458 	(*p)->type_value()->convert(this);
5459     }
5460 }
5461 
5462 void
debug_go_gogo(Gogo * gogo)5463 debug_go_gogo(Gogo* gogo)
5464 {
5465   if (gogo != NULL)
5466     gogo->debug_dump();
5467 }
5468 
5469 void
debug_dump()5470 Gogo::debug_dump()
5471 {
5472   std::cerr << "Packages:\n";
5473   for (Packages::const_iterator p = this->packages_.begin();
5474        p != this->packages_.end();
5475        ++p)
5476     {
5477       const char *tag = "  ";
5478       if (p->second == this->package_)
5479         tag = "* ";
5480       std::cerr << tag << "'" << p->first << "' "
5481                 << p->second->pkgpath() << " " << ((void*)p->second) << "\n";
5482     }
5483 }
5484 
5485 // Class Function.
5486 
Function(Function_type * type,Named_object * enclosing,Block * block,Location location)5487 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
5488 		   Location location)
5489   : type_(type), enclosing_(enclosing), results_(NULL),
5490     closure_var_(NULL), block_(block), location_(location), labels_(),
5491     local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
5492     pragmas_(0), nested_functions_(0), is_sink_(false),
5493     results_are_named_(false), is_unnamed_type_stub_method_(false),
5494     calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5495     calls_defer_retaddr_(false), is_type_specific_function_(false),
5496     in_unique_section_(false), export_for_inlining_(false),
5497     is_inline_only_(false), is_referenced_by_inline_(false),
5498     is_exported_by_linkname_(false)
5499 {
5500 }
5501 
5502 // Create the named result variables.
5503 
5504 void
create_result_variables(Gogo * gogo)5505 Function::create_result_variables(Gogo* gogo)
5506 {
5507   const Typed_identifier_list* results = this->type_->results();
5508   if (results == NULL || results->empty())
5509     return;
5510 
5511   if (!results->front().name().empty())
5512     this->results_are_named_ = true;
5513 
5514   this->results_ = new Results();
5515   this->results_->reserve(results->size());
5516 
5517   Block* block = this->block_;
5518   int index = 0;
5519   for (Typed_identifier_list::const_iterator p = results->begin();
5520        p != results->end();
5521        ++p, ++index)
5522     {
5523       std::string name = p->name();
5524       if (name.empty() || Gogo::is_sink_name(name))
5525 	{
5526 	  static int result_counter;
5527 	  char buf[100];
5528 	  snprintf(buf, sizeof buf, "$ret%d", result_counter);
5529 	  ++result_counter;
5530 	  name = gogo->pack_hidden_name(buf, false);
5531 	}
5532       Result_variable* result = new Result_variable(p->type(), this, index,
5533 						    p->location());
5534       Named_object* no = block->bindings()->add_result_variable(name, result);
5535       if (no->is_result_variable())
5536 	this->results_->push_back(no);
5537       else
5538 	{
5539 	  static int dummy_result_count;
5540 	  char buf[100];
5541 	  snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
5542 	  ++dummy_result_count;
5543 	  name = gogo->pack_hidden_name(buf, false);
5544 	  no = block->bindings()->add_result_variable(name, result);
5545 	  go_assert(no->is_result_variable());
5546 	  this->results_->push_back(no);
5547 	}
5548     }
5549 }
5550 
5551 // Update the named result variables when cloning a function which
5552 // calls recover.
5553 
5554 void
update_result_variables()5555 Function::update_result_variables()
5556 {
5557   if (this->results_ == NULL)
5558     return;
5559 
5560   for (Results::iterator p = this->results_->begin();
5561        p != this->results_->end();
5562        ++p)
5563     (*p)->result_var_value()->set_function(this);
5564 }
5565 
5566 // Whether this method should not be included in the type descriptor.
5567 
5568 bool
nointerface() const5569 Function::nointerface() const
5570 {
5571   go_assert(this->is_method());
5572   return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
5573 }
5574 
5575 // Record that this method should not be included in the type
5576 // descriptor.
5577 
5578 void
set_nointerface()5579 Function::set_nointerface()
5580 {
5581   this->pragmas_ |= GOPRAGMA_NOINTERFACE;
5582 }
5583 
5584 // Return the closure variable, creating it if necessary.
5585 
5586 Named_object*
closure_var()5587 Function::closure_var()
5588 {
5589   if (this->closure_var_ == NULL)
5590     {
5591       go_assert(this->descriptor_ == NULL);
5592       // We don't know the type of the variable yet.  We add fields as
5593       // we find them.
5594       Location loc = this->type_->location();
5595       Struct_field_list* sfl = new Struct_field_list;
5596       Struct_type* struct_type = Type::make_struct_type(sfl, loc);
5597       struct_type->set_is_struct_incomparable();
5598       Variable* var = new Variable(Type::make_pointer_type(struct_type),
5599 				   NULL, false, false, false, loc);
5600       var->set_is_used();
5601       var->set_is_closure();
5602       this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
5603       // Note that the new variable is not in any binding contour.
5604     }
5605   return this->closure_var_;
5606 }
5607 
5608 // Set the type of the closure variable.
5609 
5610 void
set_closure_type()5611 Function::set_closure_type()
5612 {
5613   if (this->closure_var_ == NULL)
5614     return;
5615   Named_object* closure = this->closure_var_;
5616   Struct_type* st = closure->var_value()->type()->deref()->struct_type();
5617 
5618   // The first field of a closure is always a pointer to the function
5619   // code.
5620   Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
5621   st->push_field(Struct_field(Typed_identifier(".f", voidptr_type,
5622 					       this->location_)));
5623 
5624   unsigned int index = 1;
5625   for (Closure_fields::const_iterator p = this->closure_fields_.begin();
5626        p != this->closure_fields_.end();
5627        ++p, ++index)
5628     {
5629       Named_object* no = p->first;
5630       char buf[20];
5631       snprintf(buf, sizeof buf, "%u", index);
5632       std::string n = no->name() + buf;
5633       Type* var_type;
5634       if (no->is_variable())
5635 	var_type = no->var_value()->type();
5636       else
5637 	var_type = no->result_var_value()->type();
5638       Type* field_type = Type::make_pointer_type(var_type);
5639       st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
5640     }
5641 }
5642 
5643 // Return whether this function is a method.
5644 
5645 bool
is_method() const5646 Function::is_method() const
5647 {
5648   return this->type_->is_method();
5649 }
5650 
5651 // Add a label definition.
5652 
5653 Label*
add_label_definition(Gogo * gogo,const std::string & label_name,Location location)5654 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
5655 			       Location location)
5656 {
5657   Label* lnull = NULL;
5658   std::pair<Labels::iterator, bool> ins =
5659     this->labels_.insert(std::make_pair(label_name, lnull));
5660   Label* label;
5661   if (label_name == "_")
5662     {
5663       label = Label::create_dummy_label();
5664       if (ins.second)
5665 	ins.first->second = label;
5666     }
5667   else if (ins.second)
5668     {
5669       // This is a new label.
5670       label = new Label(label_name);
5671       ins.first->second = label;
5672     }
5673   else
5674     {
5675       // The label was already in the hash table.
5676       label = ins.first->second;
5677       if (label->is_defined())
5678 	{
5679 	  go_error_at(location, "label %qs already defined",
5680 		      Gogo::message_name(label_name).c_str());
5681 	  go_inform(label->location(), "previous definition of %qs was here",
5682 		    Gogo::message_name(label_name).c_str());
5683 	  return new Label(label_name);
5684 	}
5685     }
5686 
5687   label->define(location, gogo->bindings_snapshot(location));
5688 
5689   // Issue any errors appropriate for any previous goto's to this
5690   // label.
5691   const std::vector<Bindings_snapshot*>& refs(label->refs());
5692   for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
5693        p != refs.end();
5694        ++p)
5695     (*p)->check_goto_to(gogo->current_block());
5696   label->clear_refs();
5697 
5698   return label;
5699 }
5700 
5701 // Add a reference to a label.
5702 
5703 Label*
add_label_reference(Gogo * gogo,const std::string & label_name,Location location,bool issue_goto_errors)5704 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5705 			      Location location, bool issue_goto_errors)
5706 {
5707   Label* lnull = NULL;
5708   std::pair<Labels::iterator, bool> ins =
5709     this->labels_.insert(std::make_pair(label_name, lnull));
5710   Label* label;
5711   if (!ins.second)
5712     {
5713       // The label was already in the hash table.
5714       label = ins.first->second;
5715     }
5716   else
5717     {
5718       go_assert(ins.first->second == NULL);
5719       label = new Label(label_name);
5720       ins.first->second = label;
5721     }
5722 
5723   label->set_is_used();
5724 
5725   if (issue_goto_errors)
5726     {
5727       Bindings_snapshot* snapshot = label->snapshot();
5728       if (snapshot != NULL)
5729 	snapshot->check_goto_from(gogo->current_block(), location);
5730       else
5731 	label->add_snapshot_ref(gogo->bindings_snapshot(location));
5732     }
5733 
5734   return label;
5735 }
5736 
5737 // Warn about labels that are defined but not used.
5738 
5739 void
check_labels() const5740 Function::check_labels() const
5741 {
5742   for (Labels::const_iterator p = this->labels_.begin();
5743        p != this->labels_.end();
5744        p++)
5745     {
5746       Label* label = p->second;
5747       if (!label->is_used())
5748 	go_error_at(label->location(), "label %qs defined and not used",
5749 		    Gogo::message_name(label->name()).c_str());
5750     }
5751 }
5752 
5753 // Swap one function with another.  This is used when building the
5754 // thunk we use to call a function which calls recover.  It may not
5755 // work for any other case.
5756 
5757 void
swap_for_recover(Function * x)5758 Function::swap_for_recover(Function *x)
5759 {
5760   go_assert(this->enclosing_ == x->enclosing_);
5761   std::swap(this->results_, x->results_);
5762   std::swap(this->closure_var_, x->closure_var_);
5763   std::swap(this->block_, x->block_);
5764   go_assert(this->location_ == x->location_);
5765   go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5766   go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5767 }
5768 
5769 // Traverse the tree.
5770 
5771 int
traverse(Traverse * traverse)5772 Function::traverse(Traverse* traverse)
5773 {
5774   unsigned int traverse_mask = traverse->traverse_mask();
5775 
5776   if ((traverse_mask
5777        & (Traverse::traverse_types | Traverse::traverse_expressions))
5778       != 0)
5779     {
5780       if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5781 	return TRAVERSE_EXIT;
5782     }
5783 
5784   // FIXME: We should check traverse_functions here if nested
5785   // functions are stored in block bindings.
5786   if (this->block_ != NULL
5787       && (traverse_mask
5788 	  & (Traverse::traverse_variables
5789 	     | Traverse::traverse_constants
5790 	     | Traverse::traverse_blocks
5791 	     | Traverse::traverse_statements
5792 	     | Traverse::traverse_expressions
5793 	     | Traverse::traverse_types)) != 0)
5794     {
5795       if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5796 	return TRAVERSE_EXIT;
5797     }
5798 
5799   return TRAVERSE_CONTINUE;
5800 }
5801 
5802 // Work out types for unspecified variables and constants.
5803 
5804 void
determine_types()5805 Function::determine_types()
5806 {
5807   if (this->block_ != NULL)
5808     this->block_->determine_types();
5809 }
5810 
5811 // Return the function descriptor, the value you get when you refer to
5812 // the function in Go code without calling it.
5813 
5814 Expression*
descriptor(Gogo *,Named_object * no)5815 Function::descriptor(Gogo*, Named_object* no)
5816 {
5817   go_assert(!this->is_method());
5818   go_assert(this->closure_var_ == NULL);
5819   if (this->descriptor_ == NULL)
5820     this->descriptor_ = Expression::make_func_descriptor(no);
5821   return this->descriptor_;
5822 }
5823 
5824 // Get a pointer to the variable representing the defer stack for this
5825 // function, making it if necessary.  The value of the variable is set
5826 // by the runtime routines to true if the function is returning,
5827 // rather than panicing through.  A pointer to this variable is used
5828 // as a marker for the functions on the defer stack associated with
5829 // this function.  A function-specific variable permits inlining a
5830 // function which uses defer.
5831 
5832 Expression*
defer_stack(Location location)5833 Function::defer_stack(Location location)
5834 {
5835   if (this->defer_stack_ == NULL)
5836     {
5837       Type* t = Type::lookup_bool_type();
5838       Expression* n = Expression::make_boolean(false, location);
5839       this->defer_stack_ = Statement::make_temporary(t, n, location);
5840       this->defer_stack_->set_is_address_taken();
5841     }
5842   Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5843 							 location);
5844   return Expression::make_unary(OPERATOR_AND, ref, location);
5845 }
5846 
5847 // Export the function.
5848 
5849 void
export_func(Export * exp,const Named_object * no) const5850 Function::export_func(Export* exp, const Named_object* no) const
5851 {
5852   Block* block = NULL;
5853   if (this->export_for_inlining())
5854     block = this->block_;
5855   Function::export_func_with_type(exp, no, this->type_, this->results_,
5856 				  this->is_method() && this->nointerface(),
5857 				  this->asm_name(), block, this->location_);
5858 }
5859 
5860 // Export a function with a type.
5861 
5862 void
export_func_with_type(Export * exp,const Named_object * no,const Function_type * fntype,Function::Results * result_vars,bool nointerface,const std::string & asm_name,Block * block,Location loc)5863 Function::export_func_with_type(Export* exp, const Named_object* no,
5864 				const Function_type* fntype,
5865 				Function::Results* result_vars,
5866 				bool nointerface, const std::string& asm_name,
5867 				Block* block, Location loc)
5868 {
5869   exp->write_c_string("func ");
5870 
5871   if (nointerface)
5872     {
5873       go_assert(fntype->is_method());
5874       exp->write_c_string("/*nointerface*/ ");
5875     }
5876 
5877   if (!asm_name.empty())
5878     {
5879       exp->write_c_string("/*asm ");
5880       exp->write_string(asm_name);
5881       exp->write_c_string(" */ ");
5882     }
5883 
5884   if (fntype->is_method())
5885     {
5886       exp->write_c_string("(");
5887       const Typed_identifier* receiver = fntype->receiver();
5888       exp->write_name(receiver->name());
5889       exp->write_escape(receiver->note());
5890       exp->write_c_string(" ");
5891       exp->write_type(receiver->type());
5892       exp->write_c_string(") ");
5893     }
5894 
5895   if (no->package() != NULL && !fntype->is_method())
5896     {
5897       char buf[50];
5898       snprintf(buf, sizeof buf, "<p%d>", exp->package_index(no->package()));
5899       exp->write_c_string(buf);
5900     }
5901 
5902   const std::string& name(no->name());
5903   if (!Gogo::is_hidden_name(name))
5904     exp->write_string(name);
5905   else
5906     {
5907       exp->write_c_string(".");
5908       exp->write_string(Gogo::unpack_hidden_name(name));
5909     }
5910 
5911   exp->write_c_string(" (");
5912   const Typed_identifier_list* parameters = fntype->parameters();
5913   if (parameters != NULL)
5914     {
5915       size_t i = 0;
5916       bool is_varargs = fntype->is_varargs();
5917       bool first = true;
5918       for (Typed_identifier_list::const_iterator p = parameters->begin();
5919 	   p != parameters->end();
5920 	   ++p, ++i)
5921 	{
5922 	  if (first)
5923 	    first = false;
5924 	  else
5925 	    exp->write_c_string(", ");
5926 	  exp->write_name(p->name());
5927 	  exp->write_escape(p->note());
5928 	  exp->write_c_string(" ");
5929 	  if (!is_varargs || p + 1 != parameters->end())
5930 	    exp->write_type(p->type());
5931 	  else
5932 	    {
5933 	      exp->write_c_string("...");
5934 	      exp->write_type(p->type()->array_type()->element_type());
5935 	    }
5936 	}
5937     }
5938   exp->write_c_string(")");
5939 
5940   const Typed_identifier_list* result_decls = fntype->results();
5941   if (result_decls != NULL)
5942     {
5943       if (result_decls->size() == 1
5944 	  && result_decls->begin()->name().empty()
5945 	  && block == NULL)
5946 	{
5947 	  exp->write_c_string(" ");
5948 	  exp->write_type(result_decls->begin()->type());
5949 	}
5950       else
5951 	{
5952 	  exp->write_c_string(" (");
5953 	  bool first = true;
5954 	  Results::const_iterator pr;
5955 	  if (result_vars != NULL)
5956 	    pr = result_vars->begin();
5957 	  for (Typed_identifier_list::const_iterator pd = result_decls->begin();
5958 	       pd != result_decls->end();
5959 	       ++pd)
5960 	    {
5961 	      if (first)
5962 		first = false;
5963 	      else
5964 		exp->write_c_string(", ");
5965 	      // We only use pr->name, which may be artificial, if
5966 	      // need it for inlining.
5967 	      if (block == NULL || result_vars == NULL)
5968 		exp->write_name(pd->name());
5969 	      else
5970 		exp->write_name((*pr)->name());
5971 	      exp->write_escape(pd->note());
5972 	      exp->write_c_string(" ");
5973 	      exp->write_type(pd->type());
5974 	      if (result_vars != NULL)
5975 		++pr;
5976 	    }
5977 	  if (result_vars != NULL)
5978 	    go_assert(pr == result_vars->end());
5979 	  exp->write_c_string(")");
5980 	}
5981     }
5982 
5983   if (block == NULL)
5984     exp->write_c_string("\n");
5985   else
5986     {
5987       int indent = 1;
5988       if (fntype->is_method())
5989 	indent++;
5990 
5991       Export_function_body efb(exp, indent);
5992 
5993       efb.indent();
5994       efb.write_c_string("// ");
5995       efb.write_string(Linemap::location_to_file(block->start_location()));
5996       efb.write_char(':');
5997       char buf[100];
5998       snprintf(buf, sizeof buf, "%d", Linemap::location_to_line(loc));
5999       efb.write_c_string(buf);
6000       efb.write_char('\n');
6001       block->export_block(&efb);
6002 
6003       const std::string& body(efb.body());
6004 
6005       snprintf(buf, sizeof buf, " <inl:%lu>\n",
6006 	       static_cast<unsigned long>(body.length()));
6007       exp->write_c_string(buf);
6008 
6009       exp->write_string(body);
6010     }
6011 }
6012 
6013 // Import a function.
6014 
6015 bool
import_func(Import * imp,std::string * pname,Package ** ppkg,bool * pis_exported,Typed_identifier ** preceiver,Typed_identifier_list ** pparameters,Typed_identifier_list ** presults,bool * is_varargs,bool * nointerface,std::string * asm_name,std::string * body)6016 Function::import_func(Import* imp, std::string* pname,
6017 		      Package** ppkg, bool* pis_exported,
6018 		      Typed_identifier** preceiver,
6019 		      Typed_identifier_list** pparameters,
6020 		      Typed_identifier_list** presults,
6021 		      bool* is_varargs,
6022 		      bool* nointerface,
6023 		      std::string* asm_name,
6024 		      std::string* body)
6025 {
6026   imp->require_c_string("func ");
6027 
6028   *nointerface = false;
6029   while (imp->match_c_string("/*"))
6030     {
6031       imp->advance(2);
6032       if (imp->match_c_string("nointerface"))
6033 	{
6034 	  imp->require_c_string("nointerface*/ ");
6035 	  *nointerface = true;
6036 	}
6037       else if (imp->match_c_string("asm"))
6038 	{
6039 	  imp->require_c_string("asm ");
6040 	  *asm_name = imp->read_identifier();
6041 	  imp->require_c_string(" */ ");
6042 	}
6043       else
6044 	{
6045 	  go_error_at(imp->location(),
6046 		      "import error at %d: unrecognized function comment",
6047 		      imp->pos());
6048 	  return false;
6049 	}
6050     }
6051 
6052   if (*nointerface)
6053     {
6054       // Only a method can be nointerface.
6055       go_assert(imp->peek_char() == '(');
6056     }
6057 
6058   *preceiver = NULL;
6059   if (imp->peek_char() == '(')
6060     {
6061       imp->require_c_string("(");
6062       std::string name = imp->read_name();
6063       std::string escape_note = imp->read_escape();
6064       imp->require_c_string(" ");
6065       Type* rtype = imp->read_type();
6066       *preceiver = new Typed_identifier(name, rtype, imp->location());
6067       (*preceiver)->set_note(escape_note);
6068       imp->require_c_string(") ");
6069     }
6070 
6071   if (!Import::read_qualified_identifier(imp, pname, ppkg, pis_exported))
6072     {
6073       go_error_at(imp->location(),
6074 		  "import error at %d: bad function name in export data",
6075 		  imp->pos());
6076       return false;
6077     }
6078 
6079   Typed_identifier_list* parameters;
6080   *is_varargs = false;
6081   imp->require_c_string(" (");
6082   if (imp->peek_char() == ')')
6083     parameters = NULL;
6084   else
6085     {
6086       parameters = new Typed_identifier_list();
6087       while (true)
6088 	{
6089 	  std::string name = imp->read_name();
6090 	  std::string escape_note = imp->read_escape();
6091 	  imp->require_c_string(" ");
6092 
6093 	  if (imp->match_c_string("..."))
6094 	    {
6095 	      imp->advance(3);
6096 	      *is_varargs = true;
6097 	    }
6098 
6099 	  Type* ptype = imp->read_type();
6100 	  if (*is_varargs)
6101 	    ptype = Type::make_array_type(ptype, NULL);
6102 	  Typed_identifier t = Typed_identifier(name, ptype, imp->location());
6103 	  t.set_note(escape_note);
6104 	  parameters->push_back(t);
6105 	  if (imp->peek_char() != ',')
6106 	    break;
6107 	  go_assert(!*is_varargs);
6108 	  imp->require_c_string(", ");
6109 	}
6110     }
6111   imp->require_c_string(")");
6112   *pparameters = parameters;
6113 
6114   Typed_identifier_list* results;
6115   if (imp->peek_char() != ' ' || imp->match_c_string(" <inl"))
6116     results = NULL;
6117   else
6118     {
6119       results = new Typed_identifier_list();
6120       imp->require_c_string(" ");
6121       if (imp->peek_char() != '(')
6122 	{
6123 	  Type* rtype = imp->read_type();
6124 	  results->push_back(Typed_identifier("", rtype, imp->location()));
6125 	}
6126       else
6127 	{
6128 	  imp->require_c_string("(");
6129 	  while (true)
6130 	    {
6131 	      std::string name = imp->read_name();
6132 	      std::string note = imp->read_escape();
6133 	      imp->require_c_string(" ");
6134 	      Type* rtype = imp->read_type();
6135 	      Typed_identifier t = Typed_identifier(name, rtype,
6136 						    imp->location());
6137 	      t.set_note(note);
6138 	      results->push_back(t);
6139 	      if (imp->peek_char() != ',')
6140 		break;
6141 	      imp->require_c_string(", ");
6142 	    }
6143 	  imp->require_c_string(")");
6144 	}
6145     }
6146   *presults = results;
6147 
6148   if (!imp->match_c_string(" <inl:"))
6149     {
6150       imp->require_semicolon_if_old_version();
6151       imp->require_c_string("\n");
6152       body->clear();
6153     }
6154   else
6155     {
6156       imp->require_c_string(" <inl:");
6157       std::string lenstr;
6158       int c;
6159       while (true)
6160 	{
6161 	  c = imp->peek_char();
6162 	  if (c < '0' || c > '9')
6163 	    break;
6164 	  lenstr += c;
6165 	  imp->get_char();
6166 	}
6167       imp->require_c_string(">\n");
6168 
6169       errno = 0;
6170       char* end;
6171       long llen = strtol(lenstr.c_str(), &end, 10);
6172       if (*end != '\0'
6173 	  || llen < 0
6174 	  || (llen == LONG_MAX && errno == ERANGE))
6175 	{
6176 	  go_error_at(imp->location(), "invalid inline function length %s",
6177 		      lenstr.c_str());
6178 	  return false;
6179 	}
6180 
6181       *body = imp->read(static_cast<size_t>(llen));
6182     }
6183 
6184   return true;
6185 }
6186 
6187 // Get the backend representation.
6188 
6189 Bfunction*
get_or_make_decl(Gogo * gogo,Named_object * no)6190 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
6191 {
6192   if (this->fndecl_ == NULL)
6193     {
6194       unsigned int flags = 0;
6195       bool is_init_fn = false;
6196       if (no->package() != NULL)
6197 	{
6198 	  // Functions defined in other packages must be visible.
6199 	  flags |= Backend::function_is_visible;
6200 	}
6201       else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
6202         ;
6203       else if (Gogo::unpack_hidden_name(no->name()) == "init"
6204                && !this->type_->is_method())
6205 	;
6206       else if (no->name() == gogo->get_init_fn_name())
6207 	{
6208 	  flags |= Backend::function_is_visible;
6209 	  is_init_fn = true;
6210 	}
6211       else if (Gogo::unpack_hidden_name(no->name()) == "main"
6212                && gogo->is_main_package())
6213 	flags |= Backend::function_is_visible;
6214       // Methods have to be public even if they are hidden because
6215       // they can be pulled into type descriptors when using
6216       // anonymous fields.
6217       else if (!Gogo::is_hidden_name(no->name())
6218                || this->type_->is_method())
6219         {
6220 	  if (!this->is_unnamed_type_stub_method_)
6221 	    flags |= Backend::function_is_visible;
6222         }
6223 
6224       Type* rtype = NULL;
6225       if (this->type_->is_method())
6226 	rtype = this->type_->receiver()->type();
6227 
6228       std::string asm_name;
6229       if (!this->asm_name_.empty())
6230 	{
6231 	  asm_name = this->asm_name_;
6232 
6233 	  // If an assembler name is explicitly specified, there must
6234 	  // be some reason to refer to the symbol from a different
6235 	  // object file.
6236 	  flags |= Backend::function_is_visible;
6237 	}
6238       else if (is_init_fn)
6239 	{
6240 	  // These names appear in the export data and are used
6241 	  // directly in the assembler code.  If we change this here
6242 	  // we need to change Gogo::init_imports.
6243 	  asm_name = no->name();
6244 	}
6245       else
6246 	asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
6247 
6248       // If an inline body refers to this function, then it
6249       // needs to be visible in the symbol table.
6250       if (this->is_referenced_by_inline_)
6251 	flags |= Backend::function_is_visible;
6252 
6253       // A go:linkname directive can be used to force a function to be
6254       // visible.
6255       if (this->is_exported_by_linkname_)
6256 	flags |= Backend::function_is_visible;
6257 
6258       // If a function calls the predeclared recover function, we
6259       // can't inline it, because recover behaves differently in a
6260       // function passed directly to defer.  If this is a recover
6261       // thunk that we built to test whether a function can be
6262       // recovered, we can't inline it, because that will mess up
6263       // our return address comparison.
6264       bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
6265 
6266       // If a function calls __go_set_defer_retaddr, then mark it as
6267       // uninlinable.  This prevents the GCC backend from splitting
6268       // the function; splitting the function is a bad idea because we
6269       // want the return address label to be in the same function as
6270       // the call.
6271       if (this->calls_defer_retaddr_)
6272 	is_inlinable = false;
6273 
6274       // Check the //go:noinline compiler directive.
6275       if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
6276 	is_inlinable = false;
6277 
6278       if (is_inlinable)
6279 	flags |= Backend::function_is_inlinable;
6280 
6281       // If this is a thunk created to call a function which calls
6282       // the predeclared recover function, we need to disable
6283       // stack splitting for the thunk.
6284       bool disable_split_stack = this->is_recover_thunk_;
6285 
6286       // Check the //go:nosplit compiler directive.
6287       if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
6288 	disable_split_stack = true;
6289 
6290       if (disable_split_stack)
6291 	flags |= Backend::function_no_split_stack;
6292 
6293       // This should go into a unique section if that has been
6294       // requested elsewhere, or if this is a nointerface function.
6295       // We want to put a nointerface function into a unique section
6296       // because there is a good chance that the linker garbage
6297       // collection can discard it.
6298       if (this->in_unique_section_
6299 	  || (this->is_method() && this->nointerface()))
6300 	flags |= Backend::function_in_unique_section;
6301 
6302       if (this->is_inline_only_)
6303 	flags |= Backend::function_only_inline;
6304 
6305       Btype* functype = this->type_->get_backend_fntype(gogo);
6306       this->fndecl_ =
6307           gogo->backend()->function(functype, no->get_id(gogo), asm_name,
6308 				    flags, this->location());
6309     }
6310   return this->fndecl_;
6311 }
6312 
6313 // Get the backend representation.
6314 
6315 Bfunction*
get_or_make_decl(Gogo * gogo,Named_object * no)6316 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
6317 {
6318   if (this->fndecl_ == NULL)
6319     {
6320       unsigned int flags =
6321 	(Backend::function_is_visible
6322 	 | Backend::function_is_declaration
6323 	 | Backend::function_is_inlinable);
6324 
6325       // Let Go code use an asm declaration to pick up a builtin
6326       // function.
6327       if (!this->asm_name_.empty())
6328 	{
6329 	  Bfunction* builtin_decl =
6330 	    gogo->backend()->lookup_builtin(this->asm_name_);
6331 	  if (builtin_decl != NULL)
6332 	    {
6333 	      this->fndecl_ = builtin_decl;
6334 	      return this->fndecl_;
6335 	    }
6336 
6337 	  if (this->asm_name_ == "runtime.gopanic"
6338 	      || this->asm_name_.compare(0, 13, "runtime.panic") == 0
6339 	      || this->asm_name_.compare(0, 15, "runtime.goPanic") == 0
6340               || this->asm_name_ == "runtime.block")
6341 	    flags |= Backend::function_does_not_return;
6342 	}
6343 
6344       std::string asm_name;
6345       if (this->asm_name_.empty())
6346 	{
6347 	  Type* rtype = NULL;
6348 	  if (this->fntype_->is_method())
6349 	    rtype = this->fntype_->receiver()->type();
6350 	  asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
6351 	}
6352       else if (go_id_needs_encoding(no->get_id(gogo)))
6353         asm_name = go_encode_id(no->get_id(gogo));
6354 
6355       Btype* functype = this->fntype_->get_backend_fntype(gogo);
6356       this->fndecl_ =
6357           gogo->backend()->function(functype, no->get_id(gogo), asm_name,
6358 				    flags, this->location());
6359     }
6360 
6361   return this->fndecl_;
6362 }
6363 
6364 // Build the descriptor for a function declaration.  This won't
6365 // necessarily happen if the package has just a declaration for the
6366 // function and no other reference to it, but we may still need the
6367 // descriptor for references from other packages.
6368 void
build_backend_descriptor(Gogo * gogo)6369 Function_declaration::build_backend_descriptor(Gogo* gogo)
6370 {
6371   if (this->descriptor_ != NULL)
6372     {
6373       Translate_context context(gogo, NULL, NULL, NULL);
6374       this->descriptor_->get_backend(&context);
6375     }
6376 }
6377 
6378 // Check that the types used in this declaration's signature are defined.
6379 // Reports errors for any undefined type.
6380 
6381 void
check_types() const6382 Function_declaration::check_types() const
6383 {
6384   // Calling Type::base will give errors for any undefined types.
6385   Function_type* fntype = this->type();
6386   if (fntype->receiver() != NULL)
6387     fntype->receiver()->type()->base();
6388   if (fntype->parameters() != NULL)
6389     {
6390       const Typed_identifier_list* params = fntype->parameters();
6391       for (Typed_identifier_list::const_iterator p = params->begin();
6392            p != params->end();
6393            ++p)
6394         p->type()->base();
6395     }
6396 }
6397 
6398 // Return the function's decl after it has been built.
6399 
6400 Bfunction*
get_decl() const6401 Function::get_decl() const
6402 {
6403   go_assert(this->fndecl_ != NULL);
6404   return this->fndecl_;
6405 }
6406 
6407 // Build the backend representation for the function code.
6408 
6409 void
build(Gogo * gogo,Named_object * named_function)6410 Function::build(Gogo* gogo, Named_object* named_function)
6411 {
6412   Translate_context context(gogo, named_function, NULL, NULL);
6413 
6414   // A list of parameter variables for this function.
6415   std::vector<Bvariable*> param_vars;
6416 
6417   // Variables that need to be declared for this function and their
6418   // initial values.
6419   std::vector<Bvariable*> vars;
6420   std::vector<Expression*> var_inits;
6421   std::vector<Statement*> var_decls_stmts;
6422   for (Bindings::const_definitions_iterator p =
6423 	 this->block_->bindings()->begin_definitions();
6424        p != this->block_->bindings()->end_definitions();
6425        ++p)
6426     {
6427       Location loc = (*p)->location();
6428       if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
6429 	{
6430 	  Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6431           Bvariable* parm_bvar = bvar;
6432 
6433 	  // We always pass the receiver to a method as a pointer.  If
6434 	  // the receiver is declared as a non-pointer type, then we
6435 	  // copy the value into a local variable.  For direct interface
6436           // type we pack the pointer into the type.
6437 	  if ((*p)->var_value()->is_receiver()
6438               && (*p)->var_value()->type()->points_to() == NULL)
6439 	    {
6440 	      std::string name = (*p)->name() + ".pointer";
6441 	      Type* var_type = (*p)->var_value()->type();
6442 	      Variable* parm_var =
6443 		  new Variable(Type::make_pointer_type(var_type), NULL, false,
6444 			       true, false, loc);
6445 	      Named_object* parm_no =
6446                   Named_object::make_variable(name, NULL, parm_var);
6447               parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6448 
6449               vars.push_back(bvar);
6450 
6451               Expression* parm_ref =
6452                   Expression::make_var_reference(parm_no, loc);
6453               Type* recv_type = (*p)->var_value()->type();
6454               if (recv_type->is_direct_iface_type())
6455                 parm_ref = Expression::pack_direct_iface(recv_type, parm_ref, loc);
6456               else
6457                 parm_ref =
6458                     Expression::make_dereference(parm_ref,
6459                                                  Expression::NIL_CHECK_NEEDED,
6460                                                  loc);
6461               if ((*p)->var_value()->is_in_heap())
6462                 parm_ref = Expression::make_heap_expression(parm_ref, loc);
6463               var_inits.push_back(parm_ref);
6464 	    }
6465 	  else if ((*p)->var_value()->is_in_heap())
6466 	    {
6467 	      // If we take the address of a parameter, then we need
6468 	      // to copy it into the heap.
6469 	      std::string parm_name = (*p)->name() + ".param";
6470 	      Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
6471 						false, true, false, loc);
6472 	      Named_object* parm_no =
6473 		  Named_object::make_variable(parm_name, NULL, parm_var);
6474 	      parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6475 
6476               vars.push_back(bvar);
6477 	      Expression* var_ref =
6478 		  Expression::make_var_reference(parm_no, loc);
6479 	      var_ref = Expression::make_heap_expression(var_ref, loc);
6480               var_inits.push_back(var_ref);
6481 	    }
6482           param_vars.push_back(parm_bvar);
6483 	}
6484       else if ((*p)->is_result_variable())
6485 	{
6486 	  Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6487 
6488 	  Type* type = (*p)->result_var_value()->type();
6489 	  Expression* init;
6490 	  if (!(*p)->result_var_value()->is_in_heap())
6491 	    {
6492 	      Btype* btype = type->get_backend(gogo);
6493 	      Bexpression* binit = gogo->backend()->zero_expression(btype);
6494               init = Expression::make_backend(binit, type, loc);
6495 	    }
6496 	  else
6497 	    init = Expression::make_allocation(type, loc);
6498 
6499           vars.push_back(bvar);
6500           var_inits.push_back(init);
6501 	}
6502       else if (this->defer_stack_ != NULL
6503                && (*p)->is_variable()
6504                && (*p)->var_value()->is_non_escaping_address_taken()
6505                && !(*p)->var_value()->is_in_heap())
6506         {
6507           // Local variable captured by deferred closure needs to be live
6508           // until the end of the function. We create a top-level
6509           // declaration for it.
6510           // TODO: we don't need to do this if the variable is not captured
6511           // by the defer closure. There is no easy way to check it here,
6512           // so we do this for all address-taken variables for now.
6513           Variable* var = (*p)->var_value();
6514           Temporary_statement* ts =
6515             Statement::make_temporary(var->type(), NULL, var->location());
6516           ts->set_is_address_taken();
6517           var->set_toplevel_decl(ts);
6518           var_decls_stmts.push_back(ts);
6519         }
6520     }
6521   if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
6522     {
6523       go_assert(saw_errors());
6524       return;
6525     }
6526 
6527   // If we need a closure variable, make sure to create it.
6528   // It gets installed in the function as a side effect of creation.
6529   if (this->closure_var_ != NULL)
6530     {
6531       go_assert(this->closure_var_->var_value()->is_closure());
6532       this->closure_var_->get_backend_variable(gogo, named_function);
6533     }
6534 
6535   if (this->block_ != NULL)
6536     {
6537       // Declare variables if necessary.
6538       Bblock* var_decls = NULL;
6539       std::vector<Bstatement*> var_decls_bstmt_list;
6540       Bstatement* defer_init = NULL;
6541       if (!vars.empty() || this->defer_stack_ != NULL)
6542 	{
6543           var_decls =
6544               gogo->backend()->block(this->fndecl_, NULL, vars,
6545                                      this->block_->start_location(),
6546                                      this->block_->end_location());
6547 
6548 	  if (this->defer_stack_ != NULL)
6549 	    {
6550 	      Translate_context dcontext(gogo, named_function, this->block_,
6551                                          var_decls);
6552               defer_init = this->defer_stack_->get_backend(&dcontext);
6553               var_decls_bstmt_list.push_back(defer_init);
6554               for (std::vector<Statement*>::iterator p = var_decls_stmts.begin();
6555                    p != var_decls_stmts.end();
6556                    ++p)
6557                 {
6558                   Bstatement* bstmt = (*p)->get_backend(&dcontext);
6559                   var_decls_bstmt_list.push_back(bstmt);
6560                 }
6561 	    }
6562 	}
6563 
6564       // Build the backend representation for all the statements in the
6565       // function.
6566       Translate_context bcontext(gogo, named_function, NULL, NULL);
6567       Bblock* code_block = this->block_->get_backend(&bcontext);
6568 
6569       // Initialize variables if necessary.
6570       Translate_context icontext(gogo, named_function, this->block_,
6571                                  var_decls);
6572       std::vector<Bstatement*> init;
6573       go_assert(vars.size() == var_inits.size());
6574       for (size_t i = 0; i < vars.size(); ++i)
6575 	{
6576           Bexpression* binit = var_inits[i]->get_backend(&icontext);
6577           Bstatement* init_stmt =
6578               gogo->backend()->init_statement(this->fndecl_, vars[i],
6579                                               binit);
6580           init.push_back(init_stmt);
6581 	}
6582       Bstatement* var_init = gogo->backend()->statement_list(init);
6583 
6584       // Initialize all variables before executing this code block.
6585       Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
6586       code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
6587 
6588       // If we have a defer stack, initialize it at the start of a
6589       // function.
6590       Bstatement* except = NULL;
6591       Bstatement* fini = NULL;
6592       if (defer_init != NULL)
6593 	{
6594 	  // Clean up the defer stack when we leave the function.
6595 	  this->build_defer_wrapper(gogo, named_function, &except, &fini);
6596 
6597           // Wrap the code for this function in an exception handler to handle
6598           // defer calls.
6599           code_stmt =
6600               gogo->backend()->exception_handler_statement(code_stmt,
6601                                                            except, fini,
6602                                                            this->location_);
6603 	}
6604 
6605       // Stick the code into the block we built for the receiver, if
6606       // we built one.
6607       if (var_decls != NULL)
6608         {
6609           var_decls_bstmt_list.push_back(code_stmt);
6610           gogo->backend()->block_add_statements(var_decls, var_decls_bstmt_list);
6611           code_stmt = gogo->backend()->block_statement(var_decls);
6612         }
6613 
6614       if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
6615         {
6616           go_assert(saw_errors());
6617           return;
6618         }
6619     }
6620 
6621   // If we created a descriptor for the function, make sure we emit it.
6622   if (this->descriptor_ != NULL)
6623     {
6624       Translate_context dcontext(gogo, NULL, NULL, NULL);
6625       this->descriptor_->get_backend(&dcontext);
6626     }
6627 }
6628 
6629 // Build the wrappers around function code needed if the function has
6630 // any defer statements.  This sets *EXCEPT to an exception handler
6631 // and *FINI to a finally handler.
6632 
6633 void
build_defer_wrapper(Gogo * gogo,Named_object * named_function,Bstatement ** except,Bstatement ** fini)6634 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
6635 			      Bstatement** except, Bstatement** fini)
6636 {
6637   Location end_loc = this->block_->end_location();
6638 
6639   // Add an exception handler.  This is used if a panic occurs.  Its
6640   // purpose is to stop the stack unwinding if a deferred function
6641   // calls recover.  There are more details in
6642   // libgo/runtime/go-unwind.c.
6643 
6644   std::vector<Bstatement*> stmts;
6645   Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6646 					this->defer_stack(end_loc));
6647   Translate_context context(gogo, named_function, NULL, NULL);
6648   Bexpression* defer = call->get_backend(&context);
6649   stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
6650 
6651   Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
6652   if (ret_bstmt != NULL)
6653     stmts.push_back(ret_bstmt);
6654 
6655   go_assert(*except == NULL);
6656   *except = gogo->backend()->statement_list(stmts);
6657 
6658   call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6659                             this->defer_stack(end_loc));
6660   defer = call->get_backend(&context);
6661 
6662   call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
6663         		    this->defer_stack(end_loc));
6664   Bexpression* undefer = call->get_backend(&context);
6665   Bstatement* function_defer =
6666       gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
6667                                                 end_loc);
6668   stmts = std::vector<Bstatement*>(1, function_defer);
6669   if (this->type_->results() != NULL
6670       && !this->type_->results()->empty()
6671       && !this->type_->results()->front().name().empty())
6672     {
6673       // If the result variables are named, and we are returning from
6674       // this function rather than panicing through it, we need to
6675       // return them again, because they might have been changed by a
6676       // defer function.  The runtime routines set the defer_stack
6677       // variable to true if we are returning from this function.
6678 
6679       ret_bstmt = this->return_value(gogo, named_function, end_loc);
6680       Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
6681       Bexpression* ret =
6682           gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
6683       Expression* ref =
6684 	Expression::make_temporary_reference(this->defer_stack_, end_loc);
6685       Bexpression* bref = ref->get_backend(&context);
6686       ret = gogo->backend()->conditional_expression(this->fndecl_,
6687                                                     NULL, bref, ret, NULL,
6688                                                     end_loc);
6689       stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
6690     }
6691 
6692   go_assert(*fini == NULL);
6693   *fini = gogo->backend()->statement_list(stmts);
6694 }
6695 
6696 // Return the statement that assigns values to this function's result struct.
6697 
6698 Bstatement*
return_value(Gogo * gogo,Named_object * named_function,Location location) const6699 Function::return_value(Gogo* gogo, Named_object* named_function,
6700 		       Location location) const
6701 {
6702   const Typed_identifier_list* results = this->type_->results();
6703   if (results == NULL || results->empty())
6704     return NULL;
6705 
6706   go_assert(this->results_ != NULL);
6707   if (this->results_->size() != results->size())
6708     {
6709       go_assert(saw_errors());
6710       return gogo->backend()->error_statement();
6711     }
6712 
6713   std::vector<Bexpression*> vals(results->size());
6714   for (size_t i = 0; i < vals.size(); ++i)
6715     {
6716       Named_object* no = (*this->results_)[i];
6717       Bvariable* bvar = no->get_backend_variable(gogo, named_function);
6718       Bexpression* val = gogo->backend()->var_expression(bvar, location);
6719       if (no->result_var_value()->is_in_heap())
6720 	{
6721 	  Btype* bt = no->result_var_value()->type()->get_backend(gogo);
6722 	  val = gogo->backend()->indirect_expression(bt, val, true, location);
6723 	}
6724       vals[i] = val;
6725     }
6726   return gogo->backend()->return_statement(this->fndecl_, vals, location);
6727 }
6728 
6729 // Class Block.
6730 
Block(Block * enclosing,Location location)6731 Block::Block(Block* enclosing, Location location)
6732   : enclosing_(enclosing), statements_(),
6733     bindings_(new Bindings(enclosing == NULL
6734 			   ? NULL
6735 			   : enclosing->bindings())),
6736     start_location_(location),
6737     end_location_(Linemap::unknown_location())
6738 {
6739 }
6740 
6741 // Add a statement to a block.
6742 
6743 void
add_statement(Statement * statement)6744 Block::add_statement(Statement* statement)
6745 {
6746   this->statements_.push_back(statement);
6747 }
6748 
6749 // Add a statement to the front of a block.  This is slow but is only
6750 // used for reference counts of parameters.
6751 
6752 void
add_statement_at_front(Statement * statement)6753 Block::add_statement_at_front(Statement* statement)
6754 {
6755   this->statements_.insert(this->statements_.begin(), statement);
6756 }
6757 
6758 // Replace a statement in a block.
6759 
6760 void
replace_statement(size_t index,Statement * s)6761 Block::replace_statement(size_t index, Statement* s)
6762 {
6763   go_assert(index < this->statements_.size());
6764   this->statements_[index] = s;
6765 }
6766 
6767 // Add a statement before another statement.
6768 
6769 void
insert_statement_before(size_t index,Statement * s)6770 Block::insert_statement_before(size_t index, Statement* s)
6771 {
6772   go_assert(index < this->statements_.size());
6773   this->statements_.insert(this->statements_.begin() + index, s);
6774 }
6775 
6776 // Add a statement after another statement.
6777 
6778 void
insert_statement_after(size_t index,Statement * s)6779 Block::insert_statement_after(size_t index, Statement* s)
6780 {
6781   go_assert(index < this->statements_.size());
6782   this->statements_.insert(this->statements_.begin() + index + 1, s);
6783 }
6784 
6785 // Traverse the tree.
6786 
6787 int
traverse(Traverse * traverse)6788 Block::traverse(Traverse* traverse)
6789 {
6790   unsigned int traverse_mask = traverse->traverse_mask();
6791 
6792   if ((traverse_mask & Traverse::traverse_blocks) != 0)
6793     {
6794       int t = traverse->block(this);
6795       if (t == TRAVERSE_EXIT)
6796 	return TRAVERSE_EXIT;
6797       else if (t == TRAVERSE_SKIP_COMPONENTS)
6798 	return TRAVERSE_CONTINUE;
6799     }
6800 
6801   if ((traverse_mask
6802        & (Traverse::traverse_variables
6803 	  | Traverse::traverse_constants
6804 	  | Traverse::traverse_expressions
6805 	  | Traverse::traverse_types)) != 0)
6806     {
6807       const unsigned int e_or_t = (Traverse::traverse_expressions
6808 				   | Traverse::traverse_types);
6809       const unsigned int e_or_t_or_s = (e_or_t
6810 					| Traverse::traverse_statements);
6811       for (Bindings::const_definitions_iterator pb =
6812 	     this->bindings_->begin_definitions();
6813 	   pb != this->bindings_->end_definitions();
6814 	   ++pb)
6815 	{
6816 	  int t = TRAVERSE_CONTINUE;
6817 	  switch ((*pb)->classification())
6818 	    {
6819 	    case Named_object::NAMED_OBJECT_CONST:
6820 	      if ((traverse_mask & Traverse::traverse_constants) != 0)
6821 		t = traverse->constant(*pb, false);
6822 	      if (t == TRAVERSE_CONTINUE
6823 		  && (traverse_mask & e_or_t) != 0)
6824 		{
6825 		  Type* tc = (*pb)->const_value()->type();
6826 		  if (tc != NULL
6827 		      && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
6828 		    return TRAVERSE_EXIT;
6829 		  t = (*pb)->const_value()->traverse_expression(traverse);
6830 		}
6831 	      break;
6832 
6833 	    case Named_object::NAMED_OBJECT_VAR:
6834 	    case Named_object::NAMED_OBJECT_RESULT_VAR:
6835 	      if ((traverse_mask & Traverse::traverse_variables) != 0)
6836 		t = traverse->variable(*pb);
6837 	      if (t == TRAVERSE_CONTINUE
6838 		  && (traverse_mask & e_or_t) != 0)
6839 		{
6840 		  if ((*pb)->is_result_variable()
6841 		      || (*pb)->var_value()->has_type())
6842 		    {
6843 		      Type* tv = ((*pb)->is_variable()
6844 				  ? (*pb)->var_value()->type()
6845 				  : (*pb)->result_var_value()->type());
6846 		      if (tv != NULL
6847 			  && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
6848 			return TRAVERSE_EXIT;
6849 		    }
6850 		}
6851 	      if (t == TRAVERSE_CONTINUE
6852 		  && (traverse_mask & e_or_t_or_s) != 0
6853 		  && (*pb)->is_variable())
6854 		t = (*pb)->var_value()->traverse_expression(traverse,
6855 							    traverse_mask);
6856 	      break;
6857 
6858 	    case Named_object::NAMED_OBJECT_FUNC:
6859 	    case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
6860 	      go_unreachable();
6861 
6862 	    case Named_object::NAMED_OBJECT_TYPE:
6863 	      if ((traverse_mask & e_or_t) != 0)
6864 		t = Type::traverse((*pb)->type_value(), traverse);
6865 	      break;
6866 
6867 	    case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
6868 	    case Named_object::NAMED_OBJECT_UNKNOWN:
6869 	    case Named_object::NAMED_OBJECT_ERRONEOUS:
6870 	      break;
6871 
6872 	    case Named_object::NAMED_OBJECT_PACKAGE:
6873 	    case Named_object::NAMED_OBJECT_SINK:
6874 	      go_unreachable();
6875 
6876 	    default:
6877 	      go_unreachable();
6878 	    }
6879 
6880 	  if (t == TRAVERSE_EXIT)
6881 	    return TRAVERSE_EXIT;
6882 	}
6883     }
6884 
6885   // No point in checking traverse_mask here--if we got here we always
6886   // want to walk the statements.  The traversal can insert new
6887   // statements before or after the current statement.  Inserting
6888   // statements before the current statement requires updating I via
6889   // the pointer; those statements will not be traversed.  Any new
6890   // statements inserted after the current statement will be traversed
6891   // in their turn.
6892   for (size_t i = 0; i < this->statements_.size(); ++i)
6893     {
6894       if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
6895 	return TRAVERSE_EXIT;
6896     }
6897 
6898   return TRAVERSE_CONTINUE;
6899 }
6900 
6901 // Work out types for unspecified variables and constants.
6902 
6903 void
determine_types()6904 Block::determine_types()
6905 {
6906   for (Bindings::const_definitions_iterator pb =
6907 	 this->bindings_->begin_definitions();
6908        pb != this->bindings_->end_definitions();
6909        ++pb)
6910     {
6911       if ((*pb)->is_variable())
6912 	(*pb)->var_value()->determine_type();
6913       else if ((*pb)->is_const())
6914 	(*pb)->const_value()->determine_type();
6915     }
6916 
6917   for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6918        ps != this->statements_.end();
6919        ++ps)
6920     (*ps)->determine_types();
6921 }
6922 
6923 // Return true if the statements in this block may fall through.
6924 
6925 bool
may_fall_through() const6926 Block::may_fall_through() const
6927 {
6928   if (this->statements_.empty())
6929     return true;
6930   return this->statements_.back()->may_fall_through();
6931 }
6932 
6933 // Write export data for a block.
6934 
6935 void
export_block(Export_function_body * efb)6936 Block::export_block(Export_function_body* efb)
6937 {
6938   for (Block::iterator p = this->begin();
6939        p != this->end();
6940        ++p)
6941     {
6942       efb->indent();
6943 
6944       efb->increment_indent();
6945       (*p)->export_statement(efb);
6946       efb->decrement_indent();
6947 
6948       Location loc = (*p)->location();
6949       if ((*p)->is_block_statement())
6950 	{
6951 	  // For a block we put the start location on the first brace
6952 	  // in Block_statement::do_export_statement.  Here we put the
6953 	  // end location on the final brace.
6954 	  loc = (*p)->block_statement()->block()->end_location();
6955 	}
6956       char buf[50];
6957       snprintf(buf, sizeof buf, " //%d\n", Linemap::location_to_line(loc));
6958       efb->write_c_string(buf);
6959     }
6960 }
6961 
6962 // Add exported block data to SET, reading from BODY starting at OFF.
6963 // Returns whether the import succeeded.
6964 
6965 bool
import_block(Block * set,Import_function_body * ifb,Location loc)6966 Block::import_block(Block* set, Import_function_body *ifb, Location loc)
6967 {
6968   Location eloc = ifb->location();
6969   Location sloc = loc;
6970   const std::string& body(ifb->body());
6971   size_t off = ifb->off();
6972   while (off < body.length())
6973     {
6974       int indent = ifb->indent();
6975       if (off + indent >= body.length())
6976 	{
6977 	  go_error_at(eloc,
6978 		      "invalid export data for %qs: insufficient indentation",
6979 		      ifb->name().c_str());
6980 	  return false;
6981 	}
6982       for (int i = 0; i < indent - 1; i++)
6983 	{
6984 	  if (body[off + i] != ' ')
6985 	    {
6986 	      go_error_at(eloc,
6987 			  "invalid export data for %qs: bad indentation",
6988 			  ifb->name().c_str());
6989 	      return false;
6990 	    }
6991 	}
6992 
6993       bool at_end = false;
6994       if (body[off + indent - 1] == '}')
6995 	at_end = true;
6996       else if (body[off + indent - 1] != ' ')
6997 	{
6998 	  go_error_at(eloc,
6999 		      "invalid export data for %qs: bad indentation",
7000 		      ifb->name().c_str());
7001 	  return false;
7002 	}
7003 
7004       off += indent;
7005 
7006       size_t nl = body.find('\n', off);
7007       if (nl == std::string::npos)
7008 	{
7009 	  go_error_at(eloc, "invalid export data for %qs: missing newline",
7010 		      ifb->name().c_str());
7011 	  return false;
7012 	}
7013 
7014       size_t lineno_pos = body.find(" //", off);
7015       if (lineno_pos == std::string::npos || lineno_pos >= nl)
7016 	{
7017 	  go_error_at(eloc, "invalid export data for %qs: missing line number",
7018 		      ifb->name().c_str());
7019 	  return false;
7020 	}
7021 
7022       unsigned int lineno = 0;
7023       for (size_t i = lineno_pos + 3; i < nl; ++i)
7024 	{
7025 	  char c = body[i];
7026 	  if (c < '0' || c > '9')
7027 	    {
7028 	      go_error_at(loc,
7029 			  "invalid export data for %qs: invalid line number",
7030 			  ifb->name().c_str());
7031 	      return false;
7032 	    }
7033 	  lineno = lineno * 10 + c - '0';
7034 	}
7035 
7036       ifb->gogo()->linemap()->start_line(lineno, 1);
7037       sloc = ifb->gogo()->linemap()->get_location(0);
7038 
7039       if (at_end)
7040 	{
7041 	  // An if statement can have an "else" following the "}", in
7042 	  // which case we want to leave the offset where it is, just
7043 	  // after the "}".  We don't get the block ending location
7044 	  // quite right for if statements.
7045 	  if (body.compare(off, 6, " else ") != 0)
7046 	    off = nl + 1;
7047 	  break;
7048 	}
7049 
7050       ifb->set_off(off);
7051       Statement* s = Statement::import_statement(ifb, sloc);
7052       if (s == NULL)
7053 	return false;
7054 
7055       set->add_statement(s);
7056 
7057       size_t at = ifb->off();
7058       if (at < nl + 1)
7059 	off = nl + 1;
7060       else
7061 	off = at;
7062     }
7063 
7064   ifb->set_off(off);
7065   set->set_end_location(sloc);
7066   return true;
7067 }
7068 
7069 // Convert a block to the backend representation.
7070 
7071 Bblock*
get_backend(Translate_context * context)7072 Block::get_backend(Translate_context* context)
7073 {
7074   Gogo* gogo = context->gogo();
7075   Named_object* function = context->function();
7076   std::vector<Bvariable*> vars;
7077   vars.reserve(this->bindings_->size_definitions());
7078   for (Bindings::const_definitions_iterator pv =
7079 	 this->bindings_->begin_definitions();
7080        pv != this->bindings_->end_definitions();
7081        ++pv)
7082     {
7083       if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
7084 	vars.push_back((*pv)->get_backend_variable(gogo, function));
7085     }
7086 
7087   go_assert(function != NULL);
7088   Bfunction* bfunction =
7089     function->func_value()->get_or_make_decl(gogo, function);
7090   Bblock* ret = context->backend()->block(bfunction, context->bblock(),
7091 					  vars, this->start_location_,
7092 					  this->end_location_);
7093 
7094   Translate_context subcontext(gogo, function, this, ret);
7095   std::vector<Bstatement*> bstatements;
7096   bstatements.reserve(this->statements_.size());
7097   for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
7098        p != this->statements_.end();
7099        ++p)
7100     bstatements.push_back((*p)->get_backend(&subcontext));
7101 
7102   context->backend()->block_add_statements(ret, bstatements);
7103 
7104   return ret;
7105 }
7106 
7107 // Class Bindings_snapshot.
7108 
Bindings_snapshot(const Block * b,Location location)7109 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
7110   : block_(b), counts_(), location_(location)
7111 {
7112   while (b != NULL)
7113     {
7114       this->counts_.push_back(b->bindings()->size_definitions());
7115       b = b->enclosing();
7116     }
7117 }
7118 
7119 // Report errors appropriate for a goto from B to this.
7120 
7121 void
check_goto_from(const Block * b,Location loc)7122 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
7123 {
7124   size_t dummy;
7125   if (!this->check_goto_block(loc, b, this->block_, &dummy))
7126     return;
7127   this->check_goto_defs(loc, this->block_,
7128 			this->block_->bindings()->size_definitions(),
7129 			this->counts_[0]);
7130 }
7131 
7132 // Report errors appropriate for a goto from this to B.
7133 
7134 void
check_goto_to(const Block * b)7135 Bindings_snapshot::check_goto_to(const Block* b)
7136 {
7137   size_t index;
7138   if (!this->check_goto_block(this->location_, this->block_, b, &index))
7139     return;
7140   this->check_goto_defs(this->location_, b, this->counts_[index],
7141 			b->bindings()->size_definitions());
7142 }
7143 
7144 // Report errors appropriate for a goto at LOC from BFROM to BTO.
7145 // Return true if all is well, false if we reported an error.  If this
7146 // returns true, it sets *PINDEX to the number of blocks BTO is above
7147 // BFROM.
7148 
7149 bool
check_goto_block(Location loc,const Block * bfrom,const Block * bto,size_t * pindex)7150 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
7151 				    const Block* bto, size_t* pindex)
7152 {
7153   // It is an error if BTO is not either BFROM or above BFROM.
7154   size_t index = 0;
7155   for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
7156     {
7157       if (pb == NULL)
7158 	{
7159 	  go_error_at(loc, "goto jumps into block");
7160 	  go_inform(bto->start_location(), "goto target block starts here");
7161 	  return false;
7162 	}
7163     }
7164   *pindex = index;
7165   return true;
7166 }
7167 
7168 // Report errors appropriate for a goto at LOC ending at BLOCK, where
7169 // CFROM is the number of names defined at the point of the goto and
7170 // CTO is the number of names defined at the point of the label.
7171 
7172 void
check_goto_defs(Location loc,const Block * block,size_t cfrom,size_t cto)7173 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
7174 				   size_t cfrom, size_t cto)
7175 {
7176   if (cfrom < cto)
7177     {
7178       Bindings::const_definitions_iterator p =
7179 	block->bindings()->begin_definitions();
7180       for (size_t i = 0; i < cfrom; ++i)
7181 	{
7182 	  go_assert(p != block->bindings()->end_definitions());
7183 	  ++p;
7184 	}
7185       go_assert(p != block->bindings()->end_definitions());
7186 
7187       for (; p != block->bindings()->end_definitions(); ++p)
7188 	{
7189 	  if ((*p)->is_variable())
7190 	    {
7191 	      std::string n = (*p)->message_name();
7192 	      go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
7193 	      go_inform((*p)->location(), "%qs defined here", n.c_str());
7194 	    }
7195 	}
7196     }
7197 }
7198 
7199 // Class Function_declaration.
7200 
7201 // Whether this declares a method.
7202 
7203 bool
is_method() const7204 Function_declaration::is_method() const
7205 {
7206   return this->fntype_->is_method();
7207 }
7208 
7209 // Whether this method should not be included in the type descriptor.
7210 
7211 bool
nointerface() const7212 Function_declaration::nointerface() const
7213 {
7214   go_assert(this->is_method());
7215   return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
7216 }
7217 
7218 // Record that this method should not be included in the type
7219 // descriptor.
7220 
7221 void
set_nointerface()7222 Function_declaration::set_nointerface()
7223 {
7224   this->pragmas_ |= GOPRAGMA_NOINTERFACE;
7225 }
7226 
7227 // Import an inlinable function.  This is used for an inlinable
7228 // function whose body is recorded in the export data.  Parse the
7229 // export data into a Block and create a regular function using that
7230 // Block as its body.  Redeclare this function declaration as the
7231 // function.
7232 
7233 void
import_function_body(Gogo * gogo,Named_object * no)7234 Function_declaration::import_function_body(Gogo* gogo, Named_object* no)
7235 {
7236   go_assert(no->func_declaration_value() == this);
7237   go_assert(no->package() != NULL);
7238   const std::string& body(this->imported_body_);
7239   go_assert(!body.empty());
7240 
7241   // Read the "//FILE:LINE" comment starts the export data.
7242 
7243   size_t indent = 1;
7244   if (this->is_method())
7245     indent = 2;
7246   size_t i = 0;
7247   for (; i < indent; i++)
7248     {
7249       if (body.at(i) != ' ')
7250 	{
7251 	  go_error_at(this->location_,
7252 		      "invalid export body for %qs: bad initial indentation",
7253 		      no->message_name().c_str());
7254 	  return;
7255 	}
7256     }
7257 
7258   if (body.substr(i, 2) != "//")
7259     {
7260       go_error_at(this->location_,
7261 		  "invalid export body for %qs: missing file comment",
7262 		  no->message_name().c_str());
7263       return;
7264     }
7265 
7266   size_t colon = body.find(':', i + 2);
7267   size_t nl = body.find('\n', i + 2);
7268   if (nl == std::string::npos)
7269     {
7270       go_error_at(this->location_,
7271 		  "invalid export body for %qs: missing file name",
7272 		  no->message_name().c_str());
7273       return;
7274     }
7275   if (colon == std::string::npos || nl < colon)
7276     {
7277       go_error_at(this->location_,
7278 		  "invalid export body for %qs: missing initial line number",
7279 		  no->message_name().c_str());
7280       return;
7281     }
7282 
7283   std::string file = body.substr(i + 2, colon - (i + 2));
7284   std::string linestr = body.substr(colon + 1, nl - (colon + 1));
7285   char* end;
7286   long linenol = strtol(linestr.c_str(), &end, 10);
7287   if (*end != '\0')
7288     {
7289       go_error_at(this->location_,
7290 		  "invalid export body for %qs: invalid initial line number",
7291 		  no->message_name().c_str());
7292       return;
7293     }
7294   unsigned int lineno = static_cast<unsigned int>(linenol);
7295 
7296   // Turn the file/line into a location.
7297 
7298   char* alc = new char[file.length() + 1];
7299   memcpy(alc, file.data(), file.length());
7300   alc[file.length()] = '\0';
7301   gogo->linemap()->start_file(alc, lineno);
7302   gogo->linemap()->start_line(lineno, 1);
7303   Location start_loc = gogo->linemap()->get_location(0);
7304 
7305   // Define the function with an outer block that declares the
7306   // parameters.
7307 
7308   Function_type* fntype = this->fntype_;
7309 
7310   Block* outer = new Block(NULL, start_loc);
7311 
7312   Function* fn = new Function(fntype, NULL, outer, start_loc);
7313   fn->set_is_inline_only();
7314 
7315   if (fntype->is_method())
7316     {
7317       if (this->nointerface())
7318         fn->set_nointerface();
7319       const Typed_identifier* receiver = fntype->receiver();
7320       Variable* recv_param = new Variable(receiver->type(), NULL, false,
7321 					  true, true, start_loc);
7322 
7323       std::string rname = receiver->name();
7324       unsigned rcounter = 0;
7325 
7326       // We need to give a nameless receiver a name to avoid having it
7327       // clash with some other nameless param. FIXME.
7328       Gogo::rename_if_empty(&rname, "r", &rcounter);
7329 
7330       outer->bindings()->add_variable(rname, NULL, recv_param);
7331     }
7332 
7333   const Typed_identifier_list* params = fntype->parameters();
7334   bool is_varargs = fntype->is_varargs();
7335   unsigned pcounter = 0;
7336   if (params != NULL)
7337     {
7338       for (Typed_identifier_list::const_iterator p = params->begin();
7339 	   p != params->end();
7340 	   ++p)
7341 	{
7342 	  Variable* param = new Variable(p->type(), NULL, false, true, false,
7343 					 start_loc);
7344 	  if (is_varargs && p + 1 == params->end())
7345 	    param->set_is_varargs_parameter();
7346 
7347 	  std::string pname = p->name();
7348 
7349           // We need to give each nameless parameter a non-empty name to avoid
7350           // having it clash with some other nameless param. FIXME.
7351           Gogo::rename_if_empty(&pname, "p", &pcounter);
7352 
7353 	  outer->bindings()->add_variable(pname, NULL, param);
7354 	}
7355     }
7356 
7357   fn->create_result_variables(gogo);
7358 
7359   if (!fntype->is_method())
7360     {
7361       const Package* package = no->package();
7362       no = package->bindings()->add_function(no->name(), package, fn);
7363     }
7364   else
7365     {
7366       Named_type* rtype = fntype->receiver()->type()->deref()->named_type();
7367       go_assert(rtype != NULL);
7368       no = rtype->add_method(no->name(), fn);
7369       const Package* package = rtype->named_object()->package();
7370       package->bindings()->add_method(no);
7371     }
7372 
7373   Import_function_body ifb(gogo, this->imp_, no, body, nl + 1, outer, indent);
7374 
7375   if (!Block::import_block(outer, &ifb, start_loc))
7376     return;
7377 
7378   gogo->lower_block(no, outer);
7379   outer->determine_types();
7380 
7381   gogo->add_imported_inline_function(no);
7382 }
7383 
7384 // Return the function descriptor.
7385 
7386 Expression*
descriptor(Gogo *,Named_object * no)7387 Function_declaration::descriptor(Gogo*, Named_object* no)
7388 {
7389   go_assert(!this->fntype_->is_method());
7390   if (this->descriptor_ == NULL)
7391     this->descriptor_ = Expression::make_func_descriptor(no);
7392   return this->descriptor_;
7393 }
7394 
7395 // Class Variable.
7396 
Variable(Type * type,Expression * init,bool is_global,bool is_parameter,bool is_receiver,Location location)7397 Variable::Variable(Type* type, Expression* init, bool is_global,
7398 		   bool is_parameter, bool is_receiver,
7399 		   Location location)
7400   : type_(type), init_(init), preinit_(NULL), location_(location),
7401     backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
7402     is_closure_(false), is_receiver_(is_receiver),
7403     is_varargs_parameter_(false), is_used_(false),
7404     is_address_taken_(false), is_non_escaping_address_taken_(false),
7405     seen_(false), init_is_lowered_(false), init_is_flattened_(false),
7406     type_from_init_tuple_(false), type_from_range_index_(false),
7407     type_from_range_value_(false), type_from_chan_element_(false),
7408     is_type_switch_var_(false), determined_type_(false),
7409     in_unique_section_(false), is_referenced_by_inline_(false),
7410     toplevel_decl_(NULL)
7411 {
7412   go_assert(type != NULL || init != NULL);
7413   go_assert(!is_parameter || init == NULL);
7414 }
7415 
7416 // Traverse the initializer expression.
7417 
7418 int
traverse_expression(Traverse * traverse,unsigned int traverse_mask)7419 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
7420 {
7421   if (this->preinit_ != NULL)
7422     {
7423       if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
7424 	return TRAVERSE_EXIT;
7425     }
7426   if (this->init_ != NULL
7427       && ((traverse_mask
7428 	   & (Traverse::traverse_expressions | Traverse::traverse_types))
7429 	  != 0))
7430     {
7431       if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
7432 	return TRAVERSE_EXIT;
7433     }
7434   return TRAVERSE_CONTINUE;
7435 }
7436 
7437 // Lower the initialization expression after parsing is complete.
7438 
7439 void
lower_init_expression(Gogo * gogo,Named_object * function,Statement_inserter * inserter)7440 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
7441 				Statement_inserter* inserter)
7442 {
7443   Named_object* dep = gogo->var_depends_on(this);
7444   if (dep != NULL && dep->is_variable())
7445     dep->var_value()->lower_init_expression(gogo, function, inserter);
7446 
7447   if (this->init_ != NULL && !this->init_is_lowered_)
7448     {
7449       if (this->seen_)
7450 	{
7451 	  // We will give an error elsewhere, this is just to prevent
7452 	  // an infinite loop.
7453 	  return;
7454 	}
7455       this->seen_ = true;
7456 
7457       Statement_inserter global_inserter;
7458       if (this->is_global_)
7459 	{
7460 	  global_inserter = Statement_inserter(gogo, this);
7461 	  inserter = &global_inserter;
7462 	}
7463 
7464       gogo->lower_expression(function, inserter, &this->init_);
7465 
7466       this->seen_ = false;
7467 
7468       this->init_is_lowered_ = true;
7469     }
7470 }
7471 
7472 // Flatten the initialization expression after ordering evaluations.
7473 
7474 void
flatten_init_expression(Gogo * gogo,Named_object * function,Statement_inserter * inserter)7475 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
7476                                   Statement_inserter* inserter)
7477 {
7478   Named_object* dep = gogo->var_depends_on(this);
7479   if (dep != NULL && dep->is_variable())
7480     dep->var_value()->flatten_init_expression(gogo, function, inserter);
7481 
7482   if (this->init_ != NULL && !this->init_is_flattened_)
7483     {
7484       if (this->seen_)
7485 	{
7486 	  // We will give an error elsewhere, this is just to prevent
7487 	  // an infinite loop.
7488 	  return;
7489 	}
7490       this->seen_ = true;
7491 
7492       Statement_inserter global_inserter;
7493       if (this->is_global_)
7494 	{
7495 	  global_inserter = Statement_inserter(gogo, this);
7496 	  inserter = &global_inserter;
7497 	}
7498 
7499       gogo->flatten_expression(function, inserter, &this->init_);
7500 
7501       // If an interface conversion is needed, we need a temporary
7502       // variable.
7503       if (this->type_ != NULL
7504 	  && !Type::are_identical(this->type_, this->init_->type(),
7505 				  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
7506 				  NULL)
7507 	  && this->init_->type()->interface_type() != NULL
7508 	  && !this->init_->is_variable())
7509 	{
7510 	  Temporary_statement* temp =
7511 	    Statement::make_temporary(NULL, this->init_, this->location_);
7512 	  inserter->insert(temp);
7513 	  this->init_ = Expression::make_temporary_reference(temp,
7514 							     this->location_);
7515 	}
7516 
7517       this->seen_ = false;
7518       this->init_is_flattened_ = true;
7519     }
7520 }
7521 
7522 // Get the preinit block.
7523 
7524 Block*
preinit_block(Gogo * gogo)7525 Variable::preinit_block(Gogo* gogo)
7526 {
7527   go_assert(this->is_global_);
7528   if (this->preinit_ == NULL)
7529     this->preinit_ = new Block(NULL, this->location());
7530 
7531   // If a global variable has a preinitialization statement, then we
7532   // need to have an initialization function.
7533   gogo->set_need_init_fn();
7534 
7535   return this->preinit_;
7536 }
7537 
7538 // Add a statement to be run before the initialization expression.
7539 
7540 void
add_preinit_statement(Gogo * gogo,Statement * s)7541 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
7542 {
7543   Block* b = this->preinit_block(gogo);
7544   b->add_statement(s);
7545   b->set_end_location(s->location());
7546 }
7547 
7548 // Whether this variable has a type.
7549 
7550 bool
has_type() const7551 Variable::has_type() const
7552 {
7553   if (this->type_ == NULL)
7554     return false;
7555 
7556   // A variable created in a type switch case nil does not actually
7557   // have a type yet.  It will be changed to use the initializer's
7558   // type in determine_type.
7559   if (this->is_type_switch_var_
7560       && this->type_->is_nil_constant_as_type())
7561     return false;
7562 
7563   return true;
7564 }
7565 
7566 // In an assignment which sets a variable to a tuple of EXPR, return
7567 // the type of the first element of the tuple.
7568 
7569 Type*
type_from_tuple(Expression * expr,bool report_error) const7570 Variable::type_from_tuple(Expression* expr, bool report_error) const
7571 {
7572   if (expr->map_index_expression() != NULL)
7573     {
7574       Map_type* mt = expr->map_index_expression()->get_map_type();
7575       if (mt == NULL)
7576 	return Type::make_error_type();
7577       return mt->val_type();
7578     }
7579   else if (expr->receive_expression() != NULL)
7580     {
7581       Expression* channel = expr->receive_expression()->channel();
7582       Type* channel_type = channel->type();
7583       if (channel_type->channel_type() == NULL)
7584 	return Type::make_error_type();
7585       return channel_type->channel_type()->element_type();
7586     }
7587   else
7588     {
7589       if (report_error)
7590 	go_error_at(this->location(), "invalid tuple definition");
7591       return Type::make_error_type();
7592     }
7593 }
7594 
7595 // Given EXPR used in a range clause, return either the index type or
7596 // the value type of the range, depending upon GET_INDEX_TYPE.
7597 
7598 Type*
type_from_range(Expression * expr,bool get_index_type,bool report_error) const7599 Variable::type_from_range(Expression* expr, bool get_index_type,
7600 			  bool report_error) const
7601 {
7602   Type* t = expr->type();
7603   if (t->array_type() != NULL
7604       || (t->points_to() != NULL
7605 	  && t->points_to()->array_type() != NULL
7606 	  && !t->points_to()->is_slice_type()))
7607     {
7608       if (get_index_type)
7609 	return Type::lookup_integer_type("int");
7610       else
7611 	return t->deref()->array_type()->element_type();
7612     }
7613   else if (t->is_string_type())
7614     {
7615       if (get_index_type)
7616 	return Type::lookup_integer_type("int");
7617       else
7618 	return Type::lookup_integer_type("int32");
7619     }
7620   else if (t->map_type() != NULL)
7621     {
7622       if (get_index_type)
7623 	return t->map_type()->key_type();
7624       else
7625 	return t->map_type()->val_type();
7626     }
7627   else if (t->channel_type() != NULL)
7628     {
7629       if (get_index_type)
7630 	return t->channel_type()->element_type();
7631       else
7632 	{
7633 	  if (report_error)
7634 	    go_error_at(this->location(),
7635 			("invalid definition of value variable "
7636 			 "for channel range"));
7637 	  return Type::make_error_type();
7638 	}
7639     }
7640   else
7641     {
7642       if (report_error)
7643 	go_error_at(this->location(), "invalid type for range clause");
7644       return Type::make_error_type();
7645     }
7646 }
7647 
7648 // EXPR should be a channel.  Return the channel's element type.
7649 
7650 Type*
type_from_chan_element(Expression * expr,bool report_error) const7651 Variable::type_from_chan_element(Expression* expr, bool report_error) const
7652 {
7653   Type* t = expr->type();
7654   if (t->channel_type() != NULL)
7655     return t->channel_type()->element_type();
7656   else
7657     {
7658       if (report_error)
7659 	go_error_at(this->location(), "expected channel");
7660       return Type::make_error_type();
7661     }
7662 }
7663 
7664 // Return the type of the Variable.  This may be called before
7665 // Variable::determine_type is called, which means that we may need to
7666 // get the type from the initializer.  FIXME: If we combine lowering
7667 // with type determination, then this should be unnecessary.
7668 
7669 Type*
type()7670 Variable::type()
7671 {
7672   // A variable in a type switch with a nil case will have the wrong
7673   // type here.  This gets fixed up in determine_type, below.
7674   Type* type = this->type_;
7675   Expression* init = this->init_;
7676   if (this->is_type_switch_var_
7677       && type != NULL
7678       && this->type_->is_nil_constant_as_type())
7679     {
7680       Type_guard_expression* tge = this->init_->type_guard_expression();
7681       go_assert(tge != NULL);
7682       init = tge->expr();
7683       type = NULL;
7684     }
7685 
7686   if (this->seen_)
7687     {
7688       if (this->type_ == NULL || !this->type_->is_error_type())
7689 	{
7690 	  go_error_at(this->location_, "variable initializer refers to itself");
7691 	  this->type_ = Type::make_error_type();
7692 	}
7693       return this->type_;
7694     }
7695 
7696   this->seen_ = true;
7697 
7698   if (type != NULL)
7699     ;
7700   else if (this->type_from_init_tuple_)
7701     type = this->type_from_tuple(init, false);
7702   else if (this->type_from_range_index_ || this->type_from_range_value_)
7703     type = this->type_from_range(init, this->type_from_range_index_, false);
7704   else if (this->type_from_chan_element_)
7705     type = this->type_from_chan_element(init, false);
7706   else
7707     {
7708       go_assert(init != NULL);
7709       type = init->type();
7710       go_assert(type != NULL);
7711 
7712       // Variables should not have abstract types.
7713       if (type->is_abstract())
7714 	type = type->make_non_abstract_type();
7715 
7716       if (type->is_void_type())
7717 	type = Type::make_error_type();
7718     }
7719 
7720   this->seen_ = false;
7721 
7722   return type;
7723 }
7724 
7725 // Fetch the type from a const pointer, in which case it should have
7726 // been set already.
7727 
7728 Type*
type() const7729 Variable::type() const
7730 {
7731   go_assert(this->type_ != NULL);
7732   return this->type_;
7733 }
7734 
7735 // Set the type if necessary.
7736 
7737 void
determine_type()7738 Variable::determine_type()
7739 {
7740   if (this->determined_type_)
7741     return;
7742   this->determined_type_ = true;
7743 
7744   if (this->preinit_ != NULL)
7745     this->preinit_->determine_types();
7746 
7747   // A variable in a type switch with a nil case will have the wrong
7748   // type here.  It will have an initializer which is a type guard.
7749   // We want to initialize it to the value without the type guard, and
7750   // use the type of that value as well.
7751   if (this->is_type_switch_var_
7752       && this->type_ != NULL
7753       && this->type_->is_nil_constant_as_type())
7754     {
7755       Type_guard_expression* tge = this->init_->type_guard_expression();
7756       go_assert(tge != NULL);
7757       this->type_ = NULL;
7758       this->init_ = tge->expr();
7759     }
7760 
7761   if (this->init_ == NULL)
7762     go_assert(this->type_ != NULL && !this->type_->is_abstract());
7763   else if (this->type_from_init_tuple_)
7764     {
7765       Expression *init = this->init_;
7766       init->determine_type_no_context();
7767       this->type_ = this->type_from_tuple(init, true);
7768       this->init_ = NULL;
7769     }
7770   else if (this->type_from_range_index_ || this->type_from_range_value_)
7771     {
7772       Expression* init = this->init_;
7773       init->determine_type_no_context();
7774       this->type_ = this->type_from_range(init, this->type_from_range_index_,
7775 					  true);
7776       this->init_ = NULL;
7777     }
7778   else if (this->type_from_chan_element_)
7779     {
7780       Expression* init = this->init_;
7781       init->determine_type_no_context();
7782       this->type_ = this->type_from_chan_element(init, true);
7783       this->init_ = NULL;
7784     }
7785   else
7786     {
7787       Type_context context(this->type_, false);
7788       this->init_->determine_type(&context);
7789       if (this->type_ == NULL)
7790 	{
7791 	  Type* type = this->init_->type();
7792 	  go_assert(type != NULL);
7793 	  if (type->is_abstract())
7794 	    type = type->make_non_abstract_type();
7795 
7796 	  if (type->is_void_type())
7797 	    {
7798 	      go_error_at(this->location_, "variable has no type");
7799 	      type = Type::make_error_type();
7800 	    }
7801 	  else if (type->is_nil_type())
7802 	    {
7803 	      go_error_at(this->location_, "variable defined to nil type");
7804 	      type = Type::make_error_type();
7805 	    }
7806 	  else if (type->is_call_multiple_result_type())
7807 	    {
7808 	      go_error_at(this->location_,
7809 		       "single variable set to multiple-value function call");
7810 	      type = Type::make_error_type();
7811 	    }
7812 
7813 	  this->type_ = type;
7814 	}
7815     }
7816 }
7817 
7818 // Get the initial value of a variable.  This does not
7819 // consider whether the variable is in the heap--it returns the
7820 // initial value as though it were always stored in the stack.
7821 
7822 Bexpression*
get_init(Gogo * gogo,Named_object * function)7823 Variable::get_init(Gogo* gogo, Named_object* function)
7824 {
7825   go_assert(this->preinit_ == NULL);
7826   Location loc = this->location();
7827   if (this->init_ == NULL)
7828     {
7829       go_assert(!this->is_parameter_);
7830       if (this->is_global_ || this->is_in_heap())
7831 	return NULL;
7832       Btype* btype = this->type()->get_backend(gogo);
7833       return gogo->backend()->zero_expression(btype);
7834     }
7835   else
7836     {
7837       Translate_context context(gogo, function, NULL, NULL);
7838       Expression* init = Expression::make_cast(this->type(), this->init_, loc);
7839       return init->get_backend(&context);
7840     }
7841 }
7842 
7843 // Get the initial value of a variable when a block is required.
7844 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7845 
7846 Bstatement*
get_init_block(Gogo * gogo,Named_object * function,Bvariable * var_decl)7847 Variable::get_init_block(Gogo* gogo, Named_object* function,
7848                          Bvariable* var_decl)
7849 {
7850   go_assert(this->preinit_ != NULL);
7851 
7852   // We want to add the variable assignment to the end of the preinit
7853   // block.
7854 
7855   Translate_context context(gogo, function, NULL, NULL);
7856   Bblock* bblock = this->preinit_->get_backend(&context);
7857   Bfunction* bfunction =
7858       function->func_value()->get_or_make_decl(gogo, function);
7859 
7860   // It's possible to have pre-init statements without an initializer
7861   // if the pre-init statements set the variable.
7862   Bstatement* decl_init = NULL;
7863   if (this->init_ != NULL)
7864     {
7865       if (var_decl == NULL)
7866         {
7867           Bexpression* init_bexpr = this->init_->get_backend(&context);
7868           decl_init = gogo->backend()->expression_statement(bfunction,
7869                                                             init_bexpr);
7870         }
7871       else
7872 	{
7873           Location loc = this->location();
7874           Expression* val_expr =
7875               Expression::make_cast(this->type(), this->init_, loc);
7876           Bexpression* val = val_expr->get_backend(&context);
7877           Bexpression* var_ref =
7878               gogo->backend()->var_expression(var_decl, loc);
7879           decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
7880                                                             val, loc);
7881 	}
7882     }
7883   Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
7884   if (decl_init != NULL)
7885     block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
7886   return block_stmt;
7887 }
7888 
7889 // Export the variable
7890 
7891 void
export_var(Export * exp,const Named_object * no) const7892 Variable::export_var(Export* exp, const Named_object* no) const
7893 {
7894   go_assert(this->is_global_);
7895   exp->write_c_string("var ");
7896   if (no->package() != NULL)
7897     {
7898       char buf[50];
7899       snprintf(buf, sizeof buf, "<p%d>", exp->package_index(no->package()));
7900       exp->write_c_string(buf);
7901     }
7902 
7903   if (!Gogo::is_hidden_name(no->name()))
7904     exp->write_string(no->name());
7905   else
7906     {
7907       exp->write_c_string(".");
7908       exp->write_string(Gogo::unpack_hidden_name(no->name()));
7909     }
7910 
7911   exp->write_c_string(" ");
7912   exp->write_type(this->type());
7913   exp->write_c_string("\n");
7914 }
7915 
7916 // Import a variable.
7917 
7918 bool
import_var(Import * imp,std::string * pname,Package ** ppkg,bool * pis_exported,Type ** ptype)7919 Variable::import_var(Import* imp, std::string* pname, Package** ppkg,
7920 		     bool* pis_exported, Type** ptype)
7921 {
7922   imp->require_c_string("var ");
7923   if (!Import::read_qualified_identifier(imp, pname, ppkg, pis_exported))
7924     {
7925       go_error_at(imp->location(),
7926 		  "import error at %d: bad variable name in export data",
7927 		  imp->pos());
7928       return false;
7929     }
7930   imp->require_c_string(" ");
7931   *ptype = imp->read_type();
7932   imp->require_semicolon_if_old_version();
7933   imp->require_c_string("\n");
7934   return true;
7935 }
7936 
7937 // Convert a variable to the backend representation.
7938 
7939 Bvariable*
get_backend_variable(Gogo * gogo,Named_object * function,const Package * package,const std::string & name)7940 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
7941 			       const Package* package, const std::string& name)
7942 {
7943   if (this->backend_ == NULL)
7944     {
7945       Backend* backend = gogo->backend();
7946       Type* type = this->type_;
7947       if (type->is_error_type()
7948 	  || (type->is_undefined()
7949 	      && (!this->is_global_ || package == NULL)))
7950 	this->backend_ = backend->error_variable();
7951       else
7952 	{
7953 	  bool is_parameter = this->is_parameter_;
7954 	  if (this->is_receiver_ && type->points_to() == NULL)
7955 	    is_parameter = false;
7956 	  if (this->is_in_heap())
7957 	    {
7958 	      is_parameter = false;
7959 	      type = Type::make_pointer_type(type);
7960 	    }
7961 
7962 	  const std::string n = Gogo::unpack_hidden_name(name);
7963 	  Btype* btype = type->get_backend(gogo);
7964 
7965 	  Bvariable* bvar;
7966 	  if (Map_type::is_zero_value(this))
7967 	    bvar = Map_type::backend_zero_value(gogo);
7968 	  else if (this->is_global_)
7969 	    {
7970 	      std::string var_name(package != NULL
7971 				   ? package->package_name()
7972 				   : gogo->package_name());
7973 	      var_name.push_back('.');
7974 	      var_name.append(n);
7975 
7976               std::string asm_name(gogo->global_var_asm_name(name, package));
7977 
7978 	      bool is_hidden = Gogo::is_hidden_name(name);
7979 	      // Hack to export runtime.writeBarrier.  FIXME.
7980 	      // This is because go:linkname doesn't work on variables.
7981 	      if (gogo->compiling_runtime()
7982 		  && var_name == "runtime.writeBarrier")
7983 		is_hidden = false;
7984 
7985 	      // If an inline body refers to this variable, then it
7986 	      // needs to be visible in the symbol table.
7987 	      if (this->is_referenced_by_inline_)
7988 		is_hidden = false;
7989 
7990 	      // If this variable is in a different package, then it
7991 	      // can't be treated as a hidden symbol.  This case can
7992 	      // arise when an inlined function refers to a
7993 	      // package-scope unexported variable.
7994 	      if (package != NULL)
7995 		is_hidden = false;
7996 
7997 	      bvar = backend->global_variable(var_name,
7998 					      asm_name,
7999 					      btype,
8000 					      package != NULL,
8001 					      is_hidden,
8002 					      this->in_unique_section_,
8003 					      this->location_);
8004 	    }
8005 	  else if (function == NULL)
8006 	    {
8007 	      go_assert(saw_errors());
8008 	      bvar = backend->error_variable();
8009 	    }
8010 	  else
8011 	    {
8012 	      Bfunction* bfunction = function->func_value()->get_decl();
8013 	      bool is_address_taken = (this->is_non_escaping_address_taken_
8014 				       && !this->is_in_heap());
8015 	      if (this->is_closure())
8016 		bvar = backend->static_chain_variable(bfunction, n, btype,
8017 						      this->location_);
8018 	      else if (is_parameter)
8019 		bvar = backend->parameter_variable(bfunction, n, btype,
8020 						   is_address_taken,
8021 						   this->location_);
8022 	      else
8023                 {
8024                   Bvariable* bvar_decl = NULL;
8025                   if (this->toplevel_decl_ != NULL)
8026                     {
8027                       Translate_context context(gogo, NULL, NULL, NULL);
8028                       bvar_decl = this->toplevel_decl_->temporary_statement()
8029                         ->get_backend_variable(&context);
8030                     }
8031                   bvar = backend->local_variable(bfunction, n, btype,
8032                                                  bvar_decl,
8033                                                  is_address_taken,
8034                                                  this->location_);
8035                 }
8036 	    }
8037 	  this->backend_ = bvar;
8038 	}
8039     }
8040   return this->backend_;
8041 }
8042 
8043 // Class Result_variable.
8044 
8045 // Convert a result variable to the backend representation.
8046 
8047 Bvariable*
get_backend_variable(Gogo * gogo,Named_object * function,const std::string & name)8048 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
8049 				      const std::string& name)
8050 {
8051   if (this->backend_ == NULL)
8052     {
8053       Backend* backend = gogo->backend();
8054       Type* type = this->type_;
8055       if (type->is_error())
8056 	this->backend_ = backend->error_variable();
8057       else
8058 	{
8059 	  if (this->is_in_heap())
8060 	    type = Type::make_pointer_type(type);
8061 	  Btype* btype = type->get_backend(gogo);
8062 	  Bfunction* bfunction = function->func_value()->get_decl();
8063 	  std::string n = Gogo::unpack_hidden_name(name);
8064 	  bool is_address_taken = (this->is_non_escaping_address_taken_
8065 				   && !this->is_in_heap());
8066 	  this->backend_ = backend->local_variable(bfunction, n, btype,
8067 						   NULL, is_address_taken,
8068 						   this->location_);
8069 	}
8070     }
8071   return this->backend_;
8072 }
8073 
8074 // Class Named_constant.
8075 
8076 // Set the type of a named constant.  This is only used to set the
8077 // type to an error type.
8078 
8079 void
set_type(Type * t)8080 Named_constant::set_type(Type* t)
8081 {
8082   go_assert(this->type_ == NULL || t->is_error_type());
8083   this->type_ = t;
8084 }
8085 
8086 // Traverse the initializer expression.
8087 
8088 int
traverse_expression(Traverse * traverse)8089 Named_constant::traverse_expression(Traverse* traverse)
8090 {
8091   return Expression::traverse(&this->expr_, traverse);
8092 }
8093 
8094 // Determine the type of the constant.
8095 
8096 void
determine_type()8097 Named_constant::determine_type()
8098 {
8099   if (this->type_ != NULL)
8100     {
8101       Type_context context(this->type_, false);
8102       this->expr_->determine_type(&context);
8103     }
8104   else
8105     {
8106       // A constant may have an abstract type.
8107       Type_context context(NULL, true);
8108       this->expr_->determine_type(&context);
8109       this->type_ = this->expr_->type();
8110       go_assert(this->type_ != NULL);
8111     }
8112 }
8113 
8114 // Indicate that we found and reported an error for this constant.
8115 
8116 void
set_error()8117 Named_constant::set_error()
8118 {
8119   this->type_ = Type::make_error_type();
8120   this->expr_ = Expression::make_error(this->location_);
8121 }
8122 
8123 // Export a constant.
8124 
8125 void
export_const(Export * exp,const std::string & name) const8126 Named_constant::export_const(Export* exp, const std::string& name) const
8127 {
8128   exp->write_c_string("const ");
8129   exp->write_string(name);
8130   exp->write_c_string(" ");
8131   if (!this->type_->is_abstract())
8132     {
8133       exp->write_type(this->type_);
8134       exp->write_c_string(" ");
8135     }
8136   exp->write_c_string("= ");
8137 
8138   Export_function_body efb(exp, 0);
8139   if (!this->type_->is_abstract())
8140     efb.set_type_context(this->type_);
8141   this->expr()->export_expression(&efb);
8142   exp->write_string(efb.body());
8143 
8144   exp->write_c_string("\n");
8145 }
8146 
8147 // Import a constant.
8148 
8149 void
import_const(Import * imp,std::string * pname,Type ** ptype,Expression ** pexpr)8150 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
8151 			     Expression** pexpr)
8152 {
8153   imp->require_c_string("const ");
8154   *pname = imp->read_identifier();
8155   imp->require_c_string(" ");
8156   if (imp->peek_char() == '=')
8157     *ptype = NULL;
8158   else
8159     {
8160       *ptype = imp->read_type();
8161       imp->require_c_string(" ");
8162     }
8163   imp->require_c_string("= ");
8164   *pexpr = Expression::import_expression(imp, imp->location());
8165   imp->require_semicolon_if_old_version();
8166   imp->require_c_string("\n");
8167 }
8168 
8169 // Get the backend representation.
8170 
8171 Bexpression*
get_backend(Gogo * gogo,Named_object * const_no)8172 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
8173 {
8174   if (this->bconst_ == NULL)
8175     {
8176       Translate_context subcontext(gogo, NULL, NULL, NULL);
8177       Type* type = this->type();
8178       Location loc = this->location();
8179 
8180       Expression* const_ref = Expression::make_const_reference(const_no, loc);
8181       Bexpression* const_decl = const_ref->get_backend(&subcontext);
8182       if (type != NULL && type->is_numeric_type())
8183 	{
8184 	  Btype* btype = type->get_backend(gogo);
8185 	  std::string name = const_no->get_id(gogo);
8186 	  const_decl =
8187 	    gogo->backend()->named_constant_expression(btype, name,
8188 						       const_decl, loc);
8189 	}
8190       this->bconst_ = const_decl;
8191     }
8192   return this->bconst_;
8193 }
8194 
8195 // Add a method.
8196 
8197 Named_object*
add_method(const std::string & name,Function * function)8198 Type_declaration::add_method(const std::string& name, Function* function)
8199 {
8200   Named_object* ret = Named_object::make_function(name, NULL, function);
8201   this->methods_.push_back(ret);
8202   return ret;
8203 }
8204 
8205 // Add a method declaration.
8206 
8207 Named_object*
add_method_declaration(const std::string & name,Package * package,Function_type * type,Location location)8208 Type_declaration::add_method_declaration(const std::string&  name,
8209 					 Package* package,
8210 					 Function_type* type,
8211 					 Location location)
8212 {
8213   Named_object* ret = Named_object::make_function_declaration(name, package,
8214 							      type, location);
8215   this->methods_.push_back(ret);
8216   return ret;
8217 }
8218 
8219 // Return whether any methods are defined.
8220 
8221 bool
has_methods() const8222 Type_declaration::has_methods() const
8223 {
8224   return !this->methods_.empty();
8225 }
8226 
8227 // Define methods for the real type.
8228 
8229 void
define_methods(Named_type * nt)8230 Type_declaration::define_methods(Named_type* nt)
8231 {
8232   if (this->methods_.empty())
8233     return;
8234 
8235   while (nt->is_alias())
8236     {
8237       Type *t = nt->real_type()->forwarded();
8238       if (t->named_type() != NULL)
8239 	nt = t->named_type();
8240       else if (t->forward_declaration_type() != NULL)
8241 	{
8242 	  Named_object* no = t->forward_declaration_type()->named_object();
8243 	  Type_declaration* td = no->type_declaration_value();
8244 	  td->methods_.insert(td->methods_.end(), this->methods_.begin(),
8245 			      this->methods_.end());
8246 	  this->methods_.clear();
8247 	  return;
8248 	}
8249       else
8250 	{
8251 	  for (std::vector<Named_object*>::const_iterator p =
8252 		 this->methods_.begin();
8253 	       p != this->methods_.end();
8254 	       ++p)
8255 	    go_error_at((*p)->location(),
8256 			("invalid receiver type "
8257 			 "(receiver must be a named type)"));
8258 	  return;
8259 	}
8260     }
8261 
8262   for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
8263        p != this->methods_.end();
8264        ++p)
8265     {
8266       if ((*p)->is_function_declaration()
8267 	  || !(*p)->func_value()->is_sink())
8268 	nt->add_existing_method(*p);
8269     }
8270 }
8271 
8272 // We are using the type.  Return true if we should issue a warning.
8273 
8274 bool
using_type()8275 Type_declaration::using_type()
8276 {
8277   bool ret = !this->issued_warning_;
8278   this->issued_warning_ = true;
8279   return ret;
8280 }
8281 
8282 // Class Unknown_name.
8283 
8284 // Set the real named object.
8285 
8286 void
set_real_named_object(Named_object * no)8287 Unknown_name::set_real_named_object(Named_object* no)
8288 {
8289   go_assert(this->real_named_object_ == NULL);
8290   go_assert(!no->is_unknown());
8291   this->real_named_object_ = no;
8292 }
8293 
8294 // Class Named_object.
8295 
Named_object(const std::string & name,const Package * package,Classification classification)8296 Named_object::Named_object(const std::string& name,
8297 			   const Package* package,
8298 			   Classification classification)
8299   : name_(name), package_(package), classification_(classification),
8300     is_redefinition_(false)
8301 {
8302   if (Gogo::is_sink_name(name))
8303     go_assert(classification == NAMED_OBJECT_SINK);
8304 }
8305 
8306 // Make an unknown name.  This is used by the parser.  The name must
8307 // be resolved later.  Unknown names are only added in the current
8308 // package.
8309 
8310 Named_object*
make_unknown_name(const std::string & name,Location location)8311 Named_object::make_unknown_name(const std::string& name,
8312 				Location location)
8313 {
8314   Named_object* named_object = new Named_object(name, NULL,
8315 						NAMED_OBJECT_UNKNOWN);
8316   Unknown_name* value = new Unknown_name(location);
8317   named_object->u_.unknown_value = value;
8318   return named_object;
8319 }
8320 
8321 // Make a constant.
8322 
8323 Named_object*
make_constant(const Typed_identifier & tid,const Package * package,Expression * expr,int iota_value)8324 Named_object::make_constant(const Typed_identifier& tid,
8325 			    const Package* package, Expression* expr,
8326 			    int iota_value)
8327 {
8328   Named_object* named_object = new Named_object(tid.name(), package,
8329 						NAMED_OBJECT_CONST);
8330   Named_constant* named_constant = new Named_constant(tid.type(), expr,
8331 						      iota_value,
8332 						      tid.location());
8333   named_object->u_.const_value = named_constant;
8334   return named_object;
8335 }
8336 
8337 // Make a named type.
8338 
8339 Named_object*
make_type(const std::string & name,const Package * package,Type * type,Location location)8340 Named_object::make_type(const std::string& name, const Package* package,
8341 			Type* type, Location location)
8342 {
8343   Named_object* named_object = new Named_object(name, package,
8344 						NAMED_OBJECT_TYPE);
8345   Named_type* named_type = Type::make_named_type(named_object, type, location);
8346   named_object->u_.type_value = named_type;
8347   return named_object;
8348 }
8349 
8350 // Make a type declaration.
8351 
8352 Named_object*
make_type_declaration(const std::string & name,const Package * package,Location location)8353 Named_object::make_type_declaration(const std::string& name,
8354 				    const Package* package,
8355 				    Location location)
8356 {
8357   Named_object* named_object = new Named_object(name, package,
8358 						NAMED_OBJECT_TYPE_DECLARATION);
8359   Type_declaration* type_declaration = new Type_declaration(location);
8360   named_object->u_.type_declaration = type_declaration;
8361   return named_object;
8362 }
8363 
8364 // Make a variable.
8365 
8366 Named_object*
make_variable(const std::string & name,const Package * package,Variable * variable)8367 Named_object::make_variable(const std::string& name, const Package* package,
8368 			    Variable* variable)
8369 {
8370   Named_object* named_object = new Named_object(name, package,
8371 						NAMED_OBJECT_VAR);
8372   named_object->u_.var_value = variable;
8373   return named_object;
8374 }
8375 
8376 // Make a result variable.
8377 
8378 Named_object*
make_result_variable(const std::string & name,Result_variable * result)8379 Named_object::make_result_variable(const std::string& name,
8380 				   Result_variable* result)
8381 {
8382   Named_object* named_object = new Named_object(name, NULL,
8383 						NAMED_OBJECT_RESULT_VAR);
8384   named_object->u_.result_var_value = result;
8385   return named_object;
8386 }
8387 
8388 // Make a sink.  This is used for the special blank identifier _.
8389 
8390 Named_object*
make_sink()8391 Named_object::make_sink()
8392 {
8393   return new Named_object("_", NULL, NAMED_OBJECT_SINK);
8394 }
8395 
8396 // Make a named function.
8397 
8398 Named_object*
make_function(const std::string & name,const Package * package,Function * function)8399 Named_object::make_function(const std::string& name, const Package* package,
8400 			    Function* function)
8401 {
8402   Named_object* named_object = new Named_object(name, package,
8403 						NAMED_OBJECT_FUNC);
8404   named_object->u_.func_value = function;
8405   return named_object;
8406 }
8407 
8408 // Make a function declaration.
8409 
8410 Named_object*
make_function_declaration(const std::string & name,const Package * package,Function_type * fntype,Location location)8411 Named_object::make_function_declaration(const std::string& name,
8412 					const Package* package,
8413 					Function_type* fntype,
8414 					Location location)
8415 {
8416   Named_object* named_object = new Named_object(name, package,
8417 						NAMED_OBJECT_FUNC_DECLARATION);
8418   Function_declaration *func_decl = new Function_declaration(fntype, location);
8419   named_object->u_.func_declaration_value = func_decl;
8420   return named_object;
8421 }
8422 
8423 // Make a package.
8424 
8425 Named_object*
make_package(const std::string & alias,Package * package)8426 Named_object::make_package(const std::string& alias, Package* package)
8427 {
8428   Named_object* named_object = new Named_object(alias, NULL,
8429 						NAMED_OBJECT_PACKAGE);
8430   named_object->u_.package_value = package;
8431   return named_object;
8432 }
8433 
8434 // Return the name to use in an error message.
8435 
8436 std::string
message_name() const8437 Named_object::message_name() const
8438 {
8439   if (this->package_ == NULL)
8440     return Gogo::message_name(this->name_);
8441   std::string ret;
8442   if (this->package_->has_package_name())
8443     ret = this->package_->package_name();
8444   else
8445     ret = this->package_->pkgpath();
8446   ret = Gogo::message_name(ret);
8447   ret += '.';
8448   ret += Gogo::message_name(this->name_);
8449   return ret;
8450 }
8451 
8452 // Set the type when a declaration is defined.
8453 
8454 void
set_type_value(Named_type * named_type)8455 Named_object::set_type_value(Named_type* named_type)
8456 {
8457   go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
8458   Type_declaration* td = this->u_.type_declaration;
8459   td->define_methods(named_type);
8460   unsigned int index;
8461   Named_object* in_function = td->in_function(&index);
8462   if (in_function != NULL)
8463     named_type->set_in_function(in_function, index);
8464   delete td;
8465   this->classification_ = NAMED_OBJECT_TYPE;
8466   this->u_.type_value = named_type;
8467 }
8468 
8469 // Define a function which was previously declared.
8470 
8471 void
set_function_value(Function * function)8472 Named_object::set_function_value(Function* function)
8473 {
8474   go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
8475   if (this->func_declaration_value()->has_descriptor())
8476     {
8477       Expression* descriptor =
8478 	this->func_declaration_value()->descriptor(NULL, NULL);
8479       function->set_descriptor(descriptor);
8480     }
8481   this->classification_ = NAMED_OBJECT_FUNC;
8482   // FIXME: We should free the old value.
8483   this->u_.func_value = function;
8484 }
8485 
8486 // Declare an unknown object as a type declaration.
8487 
8488 void
declare_as_type()8489 Named_object::declare_as_type()
8490 {
8491   go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
8492   Unknown_name* unk = this->u_.unknown_value;
8493   this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
8494   this->u_.type_declaration = new Type_declaration(unk->location());
8495   delete unk;
8496 }
8497 
8498 // Return the location of a named object.
8499 
8500 Location
location() const8501 Named_object::location() const
8502 {
8503   switch (this->classification_)
8504     {
8505     default:
8506     case NAMED_OBJECT_UNINITIALIZED:
8507       go_unreachable();
8508 
8509     case NAMED_OBJECT_ERRONEOUS:
8510       return Linemap::unknown_location();
8511 
8512     case NAMED_OBJECT_UNKNOWN:
8513       return this->unknown_value()->location();
8514 
8515     case NAMED_OBJECT_CONST:
8516       return this->const_value()->location();
8517 
8518     case NAMED_OBJECT_TYPE:
8519       return this->type_value()->location();
8520 
8521     case NAMED_OBJECT_TYPE_DECLARATION:
8522       return this->type_declaration_value()->location();
8523 
8524     case NAMED_OBJECT_VAR:
8525       return this->var_value()->location();
8526 
8527     case NAMED_OBJECT_RESULT_VAR:
8528       return this->result_var_value()->location();
8529 
8530     case NAMED_OBJECT_SINK:
8531       go_unreachable();
8532 
8533     case NAMED_OBJECT_FUNC:
8534       return this->func_value()->location();
8535 
8536     case NAMED_OBJECT_FUNC_DECLARATION:
8537       return this->func_declaration_value()->location();
8538 
8539     case NAMED_OBJECT_PACKAGE:
8540       return this->package_value()->location();
8541     }
8542 }
8543 
8544 // Export a named object.
8545 
8546 void
export_named_object(Export * exp) const8547 Named_object::export_named_object(Export* exp) const
8548 {
8549   switch (this->classification_)
8550     {
8551     default:
8552     case NAMED_OBJECT_UNINITIALIZED:
8553     case NAMED_OBJECT_UNKNOWN:
8554       go_unreachable();
8555 
8556     case NAMED_OBJECT_ERRONEOUS:
8557       break;
8558 
8559     case NAMED_OBJECT_CONST:
8560       this->const_value()->export_const(exp, this->name_);
8561       break;
8562 
8563     case NAMED_OBJECT_TYPE:
8564       // Types are handled by export::write_types.
8565       go_unreachable();
8566 
8567     case NAMED_OBJECT_TYPE_DECLARATION:
8568       go_error_at(this->type_declaration_value()->location(),
8569 		  "attempt to export %<%s%> which was declared but not defined",
8570 		  this->message_name().c_str());
8571       break;
8572 
8573     case NAMED_OBJECT_FUNC_DECLARATION:
8574       this->func_declaration_value()->export_func(exp, this);
8575       break;
8576 
8577     case NAMED_OBJECT_VAR:
8578       this->var_value()->export_var(exp, this);
8579       break;
8580 
8581     case NAMED_OBJECT_RESULT_VAR:
8582     case NAMED_OBJECT_SINK:
8583       go_unreachable();
8584 
8585     case NAMED_OBJECT_FUNC:
8586       this->func_value()->export_func(exp, this);
8587       break;
8588     }
8589 }
8590 
8591 // Convert a variable to the backend representation.
8592 
8593 Bvariable*
get_backend_variable(Gogo * gogo,Named_object * function)8594 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
8595 {
8596   if (this->classification_ == NAMED_OBJECT_VAR)
8597     return this->var_value()->get_backend_variable(gogo, function,
8598 						   this->package_, this->name_);
8599   else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
8600     return this->result_var_value()->get_backend_variable(gogo, function,
8601 							  this->name_);
8602   else
8603     go_unreachable();
8604 }
8605 
8606 // Return the external identifier for this object.
8607 
8608 std::string
get_id(Gogo * gogo)8609 Named_object::get_id(Gogo* gogo)
8610 {
8611   go_assert(!this->is_variable()
8612 	    && !this->is_result_variable()
8613 	    && !this->is_type());
8614   std::string decl_name;
8615   if (this->is_function_declaration()
8616       && !this->func_declaration_value()->asm_name().empty())
8617     decl_name = this->func_declaration_value()->asm_name();
8618   else
8619     {
8620       std::string package_name;
8621       if (this->package_ == NULL)
8622 	package_name = gogo->package_name();
8623       else
8624 	package_name = this->package_->package_name();
8625 
8626       // Note that this will be misleading if this is an unexported
8627       // method generated for an embedded imported type.  In that case
8628       // the unexported method should have the package name of the
8629       // package from which it is imported, but we are going to give
8630       // it our package name.  Fixing this would require knowing the
8631       // package name, but we only know the package path.  It might be
8632       // better to use package paths here anyhow.  This doesn't affect
8633       // the assembler code, because we always set that name in
8634       // Function::get_or_make_decl anyhow.  FIXME.
8635 
8636       decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
8637 
8638       Function_type* fntype;
8639       if (this->is_function())
8640 	fntype = this->func_value()->type();
8641       else if (this->is_function_declaration())
8642 	fntype = this->func_declaration_value()->type();
8643       else
8644 	fntype = NULL;
8645       if (fntype != NULL && fntype->is_method())
8646 	{
8647 	  decl_name.push_back('.');
8648 	  decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
8649 	}
8650     }
8651   return decl_name;
8652 }
8653 
8654 void
debug_go_named_object(Named_object * no)8655 debug_go_named_object(Named_object* no)
8656 {
8657   if (no == NULL)
8658     {
8659       std::cerr << "<null>";
8660       return;
8661     }
8662   std::cerr << "'" << no->name() << "': ";
8663   const char *tag;
8664   switch (no->classification())
8665     {
8666       case Named_object::NAMED_OBJECT_UNINITIALIZED:
8667         tag = "uninitialized";
8668         break;
8669       case Named_object::NAMED_OBJECT_ERRONEOUS:
8670         tag = "<error>";
8671         break;
8672       case Named_object::NAMED_OBJECT_UNKNOWN:
8673         tag = "<unknown>";
8674         break;
8675       case Named_object::NAMED_OBJECT_CONST:
8676         tag = "constant";
8677         break;
8678       case Named_object::NAMED_OBJECT_TYPE:
8679         tag = "type";
8680         break;
8681       case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8682         tag = "type_decl";
8683         break;
8684       case Named_object::NAMED_OBJECT_VAR:
8685         tag = "var";
8686         break;
8687       case Named_object::NAMED_OBJECT_RESULT_VAR:
8688         tag = "result_var";
8689         break;
8690       case Named_object::NAMED_OBJECT_SINK:
8691         tag = "<sink>";
8692         break;
8693       case Named_object::NAMED_OBJECT_FUNC:
8694         tag = "func";
8695         break;
8696       case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8697         tag = "func_decl";
8698         break;
8699       case Named_object::NAMED_OBJECT_PACKAGE:
8700         tag = "package";
8701         break;
8702       default:
8703         tag = "<unknown named object classification>";
8704         break;
8705   };
8706   std::cerr << tag << "\n";
8707 }
8708 
8709 // Get the backend representation for this named object.
8710 
8711 void
get_backend(Gogo * gogo,std::vector<Bexpression * > & const_decls,std::vector<Btype * > & type_decls,std::vector<Bfunction * > & func_decls)8712 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
8713                           std::vector<Btype*>& type_decls,
8714                           std::vector<Bfunction*>& func_decls)
8715 {
8716   // If this is a definition, avoid trying to get the backend
8717   // representation, as that can crash.
8718   if (this->is_redefinition_)
8719     {
8720       go_assert(saw_errors());
8721       return;
8722     }
8723 
8724   switch (this->classification_)
8725     {
8726     case NAMED_OBJECT_CONST:
8727       if (!Gogo::is_erroneous_name(this->name_))
8728 	const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
8729       break;
8730 
8731     case NAMED_OBJECT_TYPE:
8732       {
8733         Named_type* named_type = this->u_.type_value;
8734 
8735         // No need to do anything for aliases-- whatever has to be done
8736         // can be done for the alias target.
8737         if (named_type->is_alias())
8738           break;
8739 
8740 	if (!Gogo::is_erroneous_name(this->name_))
8741 	  type_decls.push_back(named_type->get_backend(gogo));
8742 
8743         // We need to produce a type descriptor for every named
8744         // type, and for a pointer to every named type, since
8745         // other files or packages might refer to them.  We need
8746         // to do this even for hidden types, because they might
8747         // still be returned by some function.  Simply calling the
8748         // type_descriptor method is enough to create the type
8749         // descriptor, even though we don't do anything with it.
8750         if (this->package_ == NULL && !saw_errors())
8751           {
8752             named_type->
8753                 type_descriptor_pointer(gogo, Linemap::predeclared_location());
8754 	    named_type->gc_symbol_pointer(gogo);
8755             Type* pn = Type::make_pointer_type(named_type);
8756             pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
8757 	    pn->gc_symbol_pointer(gogo);
8758           }
8759       }
8760       break;
8761 
8762     case NAMED_OBJECT_TYPE_DECLARATION:
8763       go_error_at(Linemap::unknown_location(),
8764 		  "reference to undefined type %qs",
8765 		  this->message_name().c_str());
8766       return;
8767 
8768     case NAMED_OBJECT_VAR:
8769     case NAMED_OBJECT_RESULT_VAR:
8770     case NAMED_OBJECT_SINK:
8771       go_unreachable();
8772 
8773     case NAMED_OBJECT_FUNC:
8774       {
8775 	Function* func = this->u_.func_value;
8776 	if (!Gogo::is_erroneous_name(this->name_))
8777 	  func_decls.push_back(func->get_or_make_decl(gogo, this));
8778 
8779 	if (func->block() != NULL)
8780 	  func->build(gogo, this);
8781       }
8782       break;
8783 
8784     case NAMED_OBJECT_ERRONEOUS:
8785       break;
8786 
8787     default:
8788       go_unreachable();
8789     }
8790 }
8791 
8792 // Class Bindings.
8793 
Bindings(Bindings * enclosing)8794 Bindings::Bindings(Bindings* enclosing)
8795   : enclosing_(enclosing), named_objects_(), bindings_()
8796 {
8797 }
8798 
8799 // Clear imports.
8800 
8801 void
clear_file_scope(Gogo * gogo)8802 Bindings::clear_file_scope(Gogo* gogo)
8803 {
8804   Contour::iterator p = this->bindings_.begin();
8805   while (p != this->bindings_.end())
8806     {
8807       bool keep;
8808       if (p->second->package() != NULL)
8809 	keep = false;
8810       else if (p->second->is_package())
8811 	keep = false;
8812       else if (p->second->is_function()
8813 	       && !p->second->func_value()->type()->is_method()
8814 	       && Gogo::unpack_hidden_name(p->second->name()) == "init")
8815 	keep = false;
8816       else
8817 	keep = true;
8818 
8819       if (keep)
8820 	++p;
8821       else
8822 	{
8823 	  gogo->add_file_block_name(p->second->name(), p->second->location());
8824 	  p = this->bindings_.erase(p);
8825 	}
8826     }
8827 }
8828 
8829 // Look up a symbol.
8830 
8831 Named_object*
lookup(const std::string & name) const8832 Bindings::lookup(const std::string& name) const
8833 {
8834   Contour::const_iterator p = this->bindings_.find(name);
8835   if (p != this->bindings_.end())
8836     return p->second->resolve();
8837   else if (this->enclosing_ != NULL)
8838     return this->enclosing_->lookup(name);
8839   else
8840     return NULL;
8841 }
8842 
8843 // Look up a symbol locally.
8844 
8845 Named_object*
lookup_local(const std::string & name) const8846 Bindings::lookup_local(const std::string& name) const
8847 {
8848   Contour::const_iterator p = this->bindings_.find(name);
8849   if (p == this->bindings_.end())
8850     return NULL;
8851   return p->second;
8852 }
8853 
8854 // Remove an object from a set of bindings.  This is used for a
8855 // special case in thunks for functions which call recover.
8856 
8857 void
remove_binding(Named_object * no)8858 Bindings::remove_binding(Named_object* no)
8859 {
8860   Contour::iterator pb = this->bindings_.find(no->name());
8861   go_assert(pb != this->bindings_.end());
8862   this->bindings_.erase(pb);
8863   for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
8864        pn != this->named_objects_.end();
8865        ++pn)
8866     {
8867       if (*pn == no)
8868 	{
8869 	  this->named_objects_.erase(pn);
8870 	  return;
8871 	}
8872     }
8873   go_unreachable();
8874 }
8875 
8876 // Add a method to the list of objects.  This is not added to the
8877 // lookup table.  This is so that we have a single list of objects
8878 // declared at the top level, which we walk through when it's time to
8879 // convert to trees.
8880 
8881 void
add_method(Named_object * method)8882 Bindings::add_method(Named_object* method)
8883 {
8884   this->named_objects_.push_back(method);
8885 }
8886 
8887 // Add a generic Named_object to a Contour.
8888 
8889 Named_object*
add_named_object_to_contour(Contour * contour,Named_object * named_object)8890 Bindings::add_named_object_to_contour(Contour* contour,
8891 				      Named_object* named_object)
8892 {
8893   go_assert(named_object == named_object->resolve());
8894   const std::string& name(named_object->name());
8895   go_assert(!Gogo::is_sink_name(name));
8896 
8897   std::pair<Contour::iterator, bool> ins =
8898     contour->insert(std::make_pair(name, named_object));
8899   if (!ins.second)
8900     {
8901       // The name was already there.
8902       if (named_object->package() != NULL
8903 	  && ins.first->second->package() == named_object->package()
8904 	  && (ins.first->second->classification()
8905 	      == named_object->classification()))
8906 	{
8907 	  // This is a second import of the same object.
8908 	  return ins.first->second;
8909 	}
8910       ins.first->second = this->new_definition(ins.first->second,
8911 					       named_object);
8912       return ins.first->second;
8913     }
8914   else
8915     {
8916       // Don't push declarations on the list.  We push them on when
8917       // and if we find the definitions.  That way we genericize the
8918       // functions in order.
8919       if (!named_object->is_type_declaration()
8920 	  && !named_object->is_function_declaration()
8921 	  && !named_object->is_unknown())
8922 	this->named_objects_.push_back(named_object);
8923       return named_object;
8924     }
8925 }
8926 
8927 // We had an existing named object OLD_OBJECT, and we've seen a new
8928 // one NEW_OBJECT with the same name.  FIXME: This does not free the
8929 // new object when we don't need it.
8930 
8931 Named_object*
new_definition(Named_object * old_object,Named_object * new_object)8932 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
8933 {
8934   if (new_object->is_erroneous() && !old_object->is_erroneous())
8935     return new_object;
8936 
8937   std::string reason;
8938   switch (old_object->classification())
8939     {
8940     default:
8941     case Named_object::NAMED_OBJECT_UNINITIALIZED:
8942       go_unreachable();
8943 
8944     case Named_object::NAMED_OBJECT_ERRONEOUS:
8945       return old_object;
8946 
8947     case Named_object::NAMED_OBJECT_UNKNOWN:
8948       {
8949 	Named_object* real = old_object->unknown_value()->real_named_object();
8950 	if (real != NULL)
8951 	  return this->new_definition(real, new_object);
8952 	go_assert(!new_object->is_unknown());
8953 	old_object->unknown_value()->set_real_named_object(new_object);
8954 	if (!new_object->is_type_declaration()
8955 	    && !new_object->is_function_declaration())
8956 	  this->named_objects_.push_back(new_object);
8957 	return new_object;
8958       }
8959 
8960     case Named_object::NAMED_OBJECT_CONST:
8961       break;
8962 
8963     case Named_object::NAMED_OBJECT_TYPE:
8964       if (new_object->is_type_declaration())
8965 	return old_object;
8966       break;
8967 
8968     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8969       if (new_object->is_type_declaration())
8970 	return old_object;
8971       if (new_object->is_type())
8972 	{
8973 	  old_object->set_type_value(new_object->type_value());
8974 	  new_object->type_value()->set_named_object(old_object);
8975 	  this->named_objects_.push_back(old_object);
8976 	  return old_object;
8977 	}
8978       break;
8979 
8980     case Named_object::NAMED_OBJECT_VAR:
8981     case Named_object::NAMED_OBJECT_RESULT_VAR:
8982       // We have already given an error in the parser for cases where
8983       // one parameter or result variable redeclares another one.
8984       if ((new_object->is_variable()
8985 	   && new_object->var_value()->is_parameter())
8986 	  || new_object->is_result_variable())
8987 	return old_object;
8988       break;
8989 
8990     case Named_object::NAMED_OBJECT_SINK:
8991       go_unreachable();
8992 
8993     case Named_object::NAMED_OBJECT_FUNC:
8994       break;
8995 
8996     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8997       {
8998 	// We declare the hash and equality functions before defining
8999 	// them, because we sometimes see that we need the declaration
9000 	// while we are in the middle of a different function.
9001 	//
9002 	// We declare the main function before the user defines it, to
9003 	// give better error messages.
9004 	//
9005 	// We declare inline functions before we define them, as we
9006 	// only define them if we need them.
9007 	if (new_object->is_function()
9008 	    && ((Linemap::is_predeclared_location(old_object->location())
9009 		 && Linemap::is_predeclared_location(new_object->location()))
9010 		|| (Gogo::unpack_hidden_name(old_object->name()) == "main"
9011 		    && Linemap::is_unknown_location(old_object->location()))
9012 		|| (new_object->package() != NULL
9013 		    && old_object->func_declaration_value()->has_imported_body()
9014 		    && new_object->func_value()->is_inline_only())))
9015 	  {
9016             Function_type* old_type =
9017                 old_object->func_declaration_value()->type();
9018 	    Function_type* new_type = new_object->func_value()->type();
9019 	    if (old_type->is_valid_redeclaration(new_type, &reason))
9020 	      {
9021 		Function_declaration* fd =
9022 		  old_object->func_declaration_value();
9023 		go_assert(fd->asm_name().empty());
9024 		old_object->set_function_value(new_object->func_value());
9025 		this->named_objects_.push_back(old_object);
9026 		return old_object;
9027 	      }
9028 	  }
9029       }
9030       break;
9031 
9032     case Named_object::NAMED_OBJECT_PACKAGE:
9033       break;
9034     }
9035 
9036   std::string n = old_object->message_name();
9037   if (reason.empty())
9038     go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
9039   else
9040     go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
9041 		reason.c_str());
9042   old_object->set_is_redefinition();
9043   new_object->set_is_redefinition();
9044 
9045   if (!Linemap::is_unknown_location(old_object->location())
9046       && !Linemap::is_predeclared_location(old_object->location()))
9047     go_inform(old_object->location(), "previous definition of %qs was here",
9048 	      n.c_str());
9049 
9050   return old_object;
9051 }
9052 
9053 // Add a named type.
9054 
9055 Named_object*
add_named_type(Named_type * named_type)9056 Bindings::add_named_type(Named_type* named_type)
9057 {
9058   return this->add_named_object(named_type->named_object());
9059 }
9060 
9061 // Add a function.
9062 
9063 Named_object*
add_function(const std::string & name,const Package * package,Function * function)9064 Bindings::add_function(const std::string& name, const Package* package,
9065 		       Function* function)
9066 {
9067   return this->add_named_object(Named_object::make_function(name, package,
9068 							    function));
9069 }
9070 
9071 // Add a function declaration.
9072 
9073 Named_object*
add_function_declaration(const std::string & name,const Package * package,Function_type * type,Location location)9074 Bindings::add_function_declaration(const std::string& name,
9075 				   const Package* package,
9076 				   Function_type* type,
9077 				   Location location)
9078 {
9079   Named_object* no = Named_object::make_function_declaration(name, package,
9080 							     type, location);
9081   return this->add_named_object(no);
9082 }
9083 
9084 // Define a type which was previously declared.
9085 
9086 void
define_type(Named_object * no,Named_type * type)9087 Bindings::define_type(Named_object* no, Named_type* type)
9088 {
9089   no->set_type_value(type);
9090   this->named_objects_.push_back(no);
9091 }
9092 
9093 // Mark all local variables as used.  This is used for some types of
9094 // parse error.
9095 
9096 void
mark_locals_used()9097 Bindings::mark_locals_used()
9098 {
9099   for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
9100        p != this->named_objects_.end();
9101        ++p)
9102     if ((*p)->is_variable())
9103       (*p)->var_value()->set_is_used();
9104 }
9105 
9106 // Traverse bindings.
9107 
9108 int
traverse(Traverse * traverse,bool is_global)9109 Bindings::traverse(Traverse* traverse, bool is_global)
9110 {
9111   unsigned int traverse_mask = traverse->traverse_mask();
9112 
9113   // We don't use an iterator because we permit the traversal to add
9114   // new global objects.
9115   const unsigned int e_or_t = (Traverse::traverse_expressions
9116 			       | Traverse::traverse_types);
9117   const unsigned int e_or_t_or_s = (e_or_t
9118 				    | Traverse::traverse_statements);
9119   for (size_t i = 0; i < this->named_objects_.size(); ++i)
9120     {
9121       Named_object* p = this->named_objects_[i];
9122       int t = TRAVERSE_CONTINUE;
9123       switch (p->classification())
9124 	{
9125 	case Named_object::NAMED_OBJECT_CONST:
9126 	  if ((traverse_mask & Traverse::traverse_constants) != 0)
9127 	    t = traverse->constant(p, is_global);
9128 	  if (t == TRAVERSE_CONTINUE
9129 	      && (traverse_mask & e_or_t) != 0)
9130 	    {
9131 	      Type* tc = p->const_value()->type();
9132 	      if (tc != NULL
9133 		  && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
9134 		return TRAVERSE_EXIT;
9135 	      t = p->const_value()->traverse_expression(traverse);
9136 	    }
9137 	  break;
9138 
9139 	case Named_object::NAMED_OBJECT_VAR:
9140 	case Named_object::NAMED_OBJECT_RESULT_VAR:
9141 	  if ((traverse_mask & Traverse::traverse_variables) != 0)
9142 	    t = traverse->variable(p);
9143 	  if (t == TRAVERSE_CONTINUE
9144 	      && (traverse_mask & e_or_t) != 0)
9145 	    {
9146 	      if (p->is_result_variable()
9147 		  || p->var_value()->has_type())
9148 		{
9149 		  Type* tv = (p->is_variable()
9150 			      ? p->var_value()->type()
9151 			      : p->result_var_value()->type());
9152 		  if (tv != NULL
9153 		      && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
9154 		    return TRAVERSE_EXIT;
9155 		}
9156 	    }
9157 	  if (t == TRAVERSE_CONTINUE
9158 	      && (traverse_mask & e_or_t_or_s) != 0
9159 	      && p->is_variable())
9160 	    t = p->var_value()->traverse_expression(traverse, traverse_mask);
9161 	  break;
9162 
9163 	case Named_object::NAMED_OBJECT_FUNC:
9164 	  if ((traverse_mask & Traverse::traverse_functions) != 0)
9165 	    t = traverse->function(p);
9166 
9167 	  if (t == TRAVERSE_CONTINUE
9168 	      && (traverse_mask
9169 		  & (Traverse::traverse_variables
9170 		     | Traverse::traverse_constants
9171 		     | Traverse::traverse_functions
9172 		     | Traverse::traverse_blocks
9173 		     | Traverse::traverse_statements
9174 		     | Traverse::traverse_expressions
9175 		     | Traverse::traverse_types)) != 0)
9176 	    t = p->func_value()->traverse(traverse);
9177 	  break;
9178 
9179 	case Named_object::NAMED_OBJECT_PACKAGE:
9180 	  // These are traversed in Gogo::traverse.
9181 	  go_assert(is_global);
9182 	  break;
9183 
9184 	case Named_object::NAMED_OBJECT_TYPE:
9185 	  if ((traverse_mask & e_or_t) != 0)
9186 	    t = Type::traverse(p->type_value(), traverse);
9187 	  break;
9188 
9189 	case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
9190 	case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
9191 	case Named_object::NAMED_OBJECT_UNKNOWN:
9192 	case Named_object::NAMED_OBJECT_ERRONEOUS:
9193 	  break;
9194 
9195 	case Named_object::NAMED_OBJECT_SINK:
9196 	default:
9197 	  go_unreachable();
9198 	}
9199 
9200       if (t == TRAVERSE_EXIT)
9201 	return TRAVERSE_EXIT;
9202     }
9203 
9204   // If we need to traverse types, check the function declarations,
9205   // which have types.  Also check any methods of a type declaration.
9206   if ((traverse_mask & e_or_t) != 0)
9207     {
9208       for (Bindings::const_declarations_iterator p =
9209 	     this->begin_declarations();
9210 	   p != this->end_declarations();
9211 	   ++p)
9212 	{
9213 	  if (p->second->is_function_declaration())
9214 	    {
9215 	      if (Type::traverse(p->second->func_declaration_value()->type(),
9216 				 traverse)
9217 		  == TRAVERSE_EXIT)
9218 		return TRAVERSE_EXIT;
9219 	    }
9220 	  else if (p->second->is_type_declaration())
9221 	    {
9222 	      const std::vector<Named_object*>* methods =
9223 		p->second->type_declaration_value()->methods();
9224 	      for (std::vector<Named_object*>::const_iterator pm =
9225 		     methods->begin();
9226 		   pm != methods->end();
9227 		   pm++)
9228 		{
9229 		  Named_object* no = *pm;
9230 		  Type *t;
9231 		  if (no->is_function())
9232 		    t = no->func_value()->type();
9233 		  else if (no->is_function_declaration())
9234 		    t = no->func_declaration_value()->type();
9235 		  else
9236 		    continue;
9237 		  if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
9238 		    return TRAVERSE_EXIT;
9239 		}
9240 	    }
9241 	}
9242     }
9243 
9244   // Traverse function declarations when needed.
9245   if ((traverse_mask & Traverse::traverse_func_declarations) != 0)
9246     {
9247       for (Bindings::const_declarations_iterator p = this->begin_declarations();
9248            p != this->end_declarations();
9249            ++p)
9250         {
9251           if (p->second->is_function_declaration())
9252             {
9253               if (traverse->function_declaration(p->second) == TRAVERSE_EXIT)
9254                 return TRAVERSE_EXIT;
9255             }
9256         }
9257     }
9258 
9259   return TRAVERSE_CONTINUE;
9260 }
9261 
9262 void
debug_dump()9263 Bindings::debug_dump()
9264 {
9265   std::set<Named_object*> defs;
9266   for (size_t i = 0; i < this->named_objects_.size(); ++i)
9267     defs.insert(this->named_objects_[i]);
9268   for (Contour::iterator p = this->bindings_.begin();
9269        p != this->bindings_.end();
9270        ++p)
9271     {
9272       const char* tag = "  ";
9273       if (defs.find(p->second) != defs.end())
9274         tag = "* ";
9275       std::cerr << tag;
9276       debug_go_named_object(p->second);
9277     }
9278 }
9279 
9280 void
debug_go_bindings(Bindings * bindings)9281 debug_go_bindings(Bindings* bindings)
9282 {
9283   if (bindings != NULL)
9284     bindings->debug_dump();
9285 }
9286 
9287 // Class Label.
9288 
9289 // Clear any references to this label.
9290 
9291 void
clear_refs()9292 Label::clear_refs()
9293 {
9294   for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
9295        p != this->refs_.end();
9296        ++p)
9297     delete *p;
9298   this->refs_.clear();
9299 }
9300 
9301 // Get the backend representation for a label.
9302 
9303 Blabel*
get_backend_label(Translate_context * context)9304 Label::get_backend_label(Translate_context* context)
9305 {
9306   if (this->blabel_ == NULL)
9307     {
9308       Function* function = context->function()->func_value();
9309       Bfunction* bfunction = function->get_decl();
9310       this->blabel_ = context->backend()->label(bfunction, this->name_,
9311 						this->location_);
9312     }
9313   return this->blabel_;
9314 }
9315 
9316 // Return an expression for the address of this label.
9317 
9318 Bexpression*
get_addr(Translate_context * context,Location location)9319 Label::get_addr(Translate_context* context, Location location)
9320 {
9321   Blabel* label = this->get_backend_label(context);
9322   return context->backend()->label_address(label, location);
9323 }
9324 
9325 // Return the dummy label that represents any instance of the blank label.
9326 
9327 Label*
create_dummy_label()9328 Label::create_dummy_label()
9329 {
9330   static Label* dummy_label;
9331   if (dummy_label == NULL)
9332     {
9333       dummy_label = new Label("_");
9334       dummy_label->set_is_used();
9335     }
9336   return dummy_label;
9337 }
9338 
9339 // Class Unnamed_label.
9340 
9341 // Get the backend representation for an unnamed label.
9342 
9343 Blabel*
get_blabel(Translate_context * context)9344 Unnamed_label::get_blabel(Translate_context* context)
9345 {
9346   if (this->blabel_ == NULL)
9347     {
9348       Function* function = context->function()->func_value();
9349       Bfunction* bfunction = function->get_decl();
9350       this->blabel_ = context->backend()->label(bfunction, "",
9351 						this->location_);
9352     }
9353   return this->blabel_;
9354 }
9355 
9356 // Return a statement which defines this unnamed label.
9357 
9358 Bstatement*
get_definition(Translate_context * context)9359 Unnamed_label::get_definition(Translate_context* context)
9360 {
9361   Blabel* blabel = this->get_blabel(context);
9362   return context->backend()->label_definition_statement(blabel);
9363 }
9364 
9365 // Return a goto statement to this unnamed label.
9366 
9367 Bstatement*
get_goto(Translate_context * context,Location location)9368 Unnamed_label::get_goto(Translate_context* context, Location location)
9369 {
9370   Blabel* blabel = this->get_blabel(context);
9371   return context->backend()->goto_statement(blabel, location);
9372 }
9373 
9374 // Class Package.
9375 
Package(const std::string & pkgpath,const std::string & pkgpath_symbol,Location location)9376 Package::Package(const std::string& pkgpath,
9377 		 const std::string& pkgpath_symbol, Location location)
9378   : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
9379     package_name_(), bindings_(new Bindings(NULL)),
9380     location_(location)
9381 {
9382   go_assert(!pkgpath.empty());
9383 }
9384 
9385 // Set the package name.
9386 
9387 void
set_package_name(const std::string & package_name,Location location)9388 Package::set_package_name(const std::string& package_name, Location location)
9389 {
9390   go_assert(!package_name.empty());
9391   if (this->package_name_.empty())
9392     this->package_name_ = package_name;
9393   else if (this->package_name_ != package_name)
9394     go_error_at(location,
9395 		("saw two different packages with "
9396 		 "the same package path %s: %s, %s"),
9397 		this->pkgpath_.c_str(), this->package_name_.c_str(),
9398 		package_name.c_str());
9399 }
9400 
9401 // Return the pkgpath symbol, which is a prefix for symbols defined in
9402 // this package.
9403 
9404 std::string
pkgpath_symbol() const9405 Package::pkgpath_symbol() const
9406 {
9407   if (this->pkgpath_symbol_.empty())
9408     return Gogo::pkgpath_for_symbol(this->pkgpath_);
9409   return this->pkgpath_symbol_;
9410 }
9411 
9412 // Set the package path symbol.
9413 
9414 void
set_pkgpath_symbol(const std::string & pkgpath_symbol)9415 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
9416 {
9417   go_assert(!pkgpath_symbol.empty());
9418   if (this->pkgpath_symbol_.empty())
9419     this->pkgpath_symbol_ = pkgpath_symbol;
9420   else
9421     go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
9422 }
9423 
9424 // Note that symbol from this package was and qualified by ALIAS.
9425 
9426 void
note_usage(const std::string & alias) const9427 Package::note_usage(const std::string& alias) const
9428 {
9429   Aliases::const_iterator p = this->aliases_.find(alias);
9430   go_assert(p != this->aliases_.end());
9431   p->second->note_usage();
9432 }
9433 
9434 // Forget a given usage.  If forgetting this usage means this package becomes
9435 // unused, report that error.
9436 
9437 void
forget_usage(Expression * usage) const9438 Package::forget_usage(Expression* usage) const
9439 {
9440   if (this->fake_uses_.empty())
9441     return;
9442 
9443   std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
9444   go_assert(p != this->fake_uses_.end());
9445   this->fake_uses_.erase(p);
9446 
9447   if (this->fake_uses_.empty())
9448     go_error_at(this->location(), "imported and not used: %s",
9449 		Gogo::message_name(this->package_name()).c_str());
9450 }
9451 
9452 // Clear the used field for the next file.  If the only usages of this package
9453 // are possibly fake, keep the fake usages for lowering.
9454 
9455 void
clear_used()9456 Package::clear_used()
9457 {
9458   std::string dot_alias = "." + this->package_name();
9459   Aliases::const_iterator p = this->aliases_.find(dot_alias);
9460   if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
9461     this->fake_uses_.clear();
9462 
9463   this->aliases_.clear();
9464 }
9465 
9466 Package_alias*
add_alias(const std::string & alias,Location location)9467 Package::add_alias(const std::string& alias, Location location)
9468 {
9469   Aliases::const_iterator p = this->aliases_.find(alias);
9470   if (p == this->aliases_.end())
9471     {
9472       std::pair<Aliases::iterator, bool> ret;
9473       ret = this->aliases_.insert(std::make_pair(alias,
9474                                                  new Package_alias(location)));
9475       p = ret.first;
9476     }
9477   return p->second;
9478 }
9479 
9480 // Determine types of constants.  Everything else in a package
9481 // (variables, function declarations) should already have a fixed
9482 // type.  Constants may have abstract types.
9483 
9484 void
determine_types()9485 Package::determine_types()
9486 {
9487   Bindings* bindings = this->bindings_;
9488   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
9489        p != bindings->end_definitions();
9490        ++p)
9491     {
9492       if ((*p)->is_const())
9493 	(*p)->const_value()->determine_type();
9494     }
9495 }
9496 
9497 // Class Traverse.
9498 
9499 // Destructor.
9500 
~Traverse()9501 Traverse::~Traverse()
9502 {
9503   if (this->types_seen_ != NULL)
9504     delete this->types_seen_;
9505   if (this->expressions_seen_ != NULL)
9506     delete this->expressions_seen_;
9507 }
9508 
9509 // Record that we are looking at a type, and return true if we have
9510 // already seen it.
9511 
9512 bool
remember_type(const Type * type)9513 Traverse::remember_type(const Type* type)
9514 {
9515   if (type->is_error_type())
9516     return true;
9517   go_assert((this->traverse_mask() & traverse_types) != 0
9518 	     || (this->traverse_mask() & traverse_expressions) != 0);
9519   // We mostly only have to remember named types.  But it turns out
9520   // that an interface type can refer to itself without using a name
9521   // by relying on interface inheritance, as in
9522   //
9523   //         type I interface { F() interface{I} }
9524   //
9525   // Similarly it is possible for array types to refer to themselves
9526   // without a name, e.g.
9527   //
9528   //         var x [uintptr(unsafe.Sizeof(&x))]byte
9529   //
9530   if (type->classification() != Type::TYPE_NAMED
9531       && type->classification() != Type::TYPE_ARRAY
9532       && type->classification() != Type::TYPE_INTERFACE)
9533     return false;
9534   if (this->types_seen_ == NULL)
9535     this->types_seen_ = new Types_seen();
9536   std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
9537   return !ins.second;
9538 }
9539 
9540 // Record that we are looking at an expression, and return true if we
9541 // have already seen it. NB: this routine used to assert if the traverse
9542 // mask did not include expressions/types -- this is no longer the case,
9543 // since it can be useful to remember specific expressions during
9544 // walks that only cover statements.
9545 
9546 bool
remember_expression(const Expression * expression)9547 Traverse::remember_expression(const Expression* expression)
9548 {
9549   if (this->expressions_seen_ == NULL)
9550     this->expressions_seen_ = new Expressions_seen();
9551   std::pair<Expressions_seen::iterator, bool> ins =
9552     this->expressions_seen_->insert(expression);
9553   return !ins.second;
9554 }
9555 
9556 // The default versions of these functions should never be called: the
9557 // traversal mask indicates which functions may be called.
9558 
9559 int
variable(Named_object *)9560 Traverse::variable(Named_object*)
9561 {
9562   go_unreachable();
9563 }
9564 
9565 int
constant(Named_object *,bool)9566 Traverse::constant(Named_object*, bool)
9567 {
9568   go_unreachable();
9569 }
9570 
9571 int
function(Named_object *)9572 Traverse::function(Named_object*)
9573 {
9574   go_unreachable();
9575 }
9576 
9577 int
block(Block *)9578 Traverse::block(Block*)
9579 {
9580   go_unreachable();
9581 }
9582 
9583 int
statement(Block *,size_t *,Statement *)9584 Traverse::statement(Block*, size_t*, Statement*)
9585 {
9586   go_unreachable();
9587 }
9588 
9589 int
expression(Expression **)9590 Traverse::expression(Expression**)
9591 {
9592   go_unreachable();
9593 }
9594 
9595 int
type(Type *)9596 Traverse::type(Type*)
9597 {
9598   go_unreachable();
9599 }
9600 
9601 int
function_declaration(Named_object *)9602 Traverse::function_declaration(Named_object*)
9603 {
9604   go_unreachable();
9605 }
9606 
9607 // Class Statement_inserter.
9608 
9609 void
insert(Statement * s)9610 Statement_inserter::insert(Statement* s)
9611 {
9612   if (this->statements_added_ != NULL)
9613     this->statements_added_->insert(s);
9614 
9615   if (this->block_ != NULL)
9616     {
9617       go_assert(this->pindex_ != NULL);
9618       this->block_->insert_statement_before(*this->pindex_, s);
9619       ++*this->pindex_;
9620     }
9621   else if (this->var_ != NULL)
9622     this->var_->add_preinit_statement(this->gogo_, s);
9623   else
9624     go_assert(saw_errors());
9625 }
9626