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 and every
3346 // function referenced by an inline function.
3347 
3348 int
function(Named_object * no)3349 Create_function_descriptors::function(Named_object* no)
3350 {
3351   if (no->is_function()
3352       && no->func_value()->enclosing() == NULL
3353       && !no->func_value()->is_method()
3354       && ((!Gogo::is_hidden_name(no->name())
3355 	   && !Gogo::is_thunk(no))
3356 	  || no->func_value()->is_referenced_by_inline()))
3357     no->func_value()->descriptor(this->gogo_, no);
3358 
3359   return TRAVERSE_CONTINUE;
3360 }
3361 
3362 // If we see a function referenced in any way other than calling it,
3363 // create a descriptor for it.
3364 
3365 int
expression(Expression ** pexpr)3366 Create_function_descriptors::expression(Expression** pexpr)
3367 {
3368   Expression* expr = *pexpr;
3369 
3370   Func_expression* fe = expr->func_expression();
3371   if (fe != NULL)
3372     {
3373       // We would not get here for a call to this function, so this is
3374       // a reference to a function other than calling it.  We need a
3375       // descriptor.
3376       if (fe->closure() != NULL)
3377 	return TRAVERSE_CONTINUE;
3378       Named_object* no = fe->named_object();
3379       if (no->is_function() && !no->func_value()->is_method())
3380 	no->func_value()->descriptor(this->gogo_, no);
3381       else if (no->is_function_declaration()
3382 	       && !no->func_declaration_value()->type()->is_method()
3383 	       && !Linemap::is_predeclared_location(no->location()))
3384 	no->func_declaration_value()->descriptor(this->gogo_, no);
3385       return TRAVERSE_CONTINUE;
3386     }
3387 
3388   Bound_method_expression* bme = expr->bound_method_expression();
3389   if (bme != NULL)
3390     {
3391       // We would not get here for a call to this method, so this is a
3392       // method value.  We need to create a thunk.
3393       Bound_method_expression::create_thunk(this->gogo_, bme->method(),
3394 					    bme->function());
3395       return TRAVERSE_CONTINUE;
3396     }
3397 
3398   Interface_field_reference_expression* ifre =
3399     expr->interface_field_reference_expression();
3400   if (ifre != NULL)
3401     {
3402       // We would not get here for a call to this interface method, so
3403       // this is a method value.  We need to create a thunk.
3404       Interface_type* type = ifre->expr()->type()->interface_type();
3405       if (type != NULL)
3406 	Interface_field_reference_expression::create_thunk(this->gogo_, type,
3407 							   ifre->name());
3408       return TRAVERSE_CONTINUE;
3409     }
3410 
3411   Call_expression* ce = expr->call_expression();
3412   if (ce != NULL)
3413     {
3414       Expression* fn = ce->fn();
3415       if (fn->func_expression() != NULL
3416 	  || fn->bound_method_expression() != NULL
3417 	  || fn->interface_field_reference_expression() != NULL)
3418 	{
3419 	  // Traverse the arguments but not the function.
3420 	  Expression_list* args = ce->args();
3421 	  if (args != NULL)
3422 	    {
3423 	      if (args->traverse(this) == TRAVERSE_EXIT)
3424 		return TRAVERSE_EXIT;
3425 	    }
3426 	  return TRAVERSE_SKIP_COMPONENTS;
3427 	}
3428     }
3429 
3430   return TRAVERSE_CONTINUE;
3431 }
3432 
3433 // Create function descriptors as needed.  We need a function
3434 // descriptor for all exported functions and for all functions that
3435 // are referenced without being called.
3436 
3437 void
create_function_descriptors()3438 Gogo::create_function_descriptors()
3439 {
3440   // Create a function descriptor for any exported function that is
3441   // declared in this package.  This is so that we have a descriptor
3442   // for functions written in assembly.  Gather the descriptors first
3443   // so that we don't add declarations while looping over them.
3444   std::vector<Named_object*> fndecls;
3445   Bindings* b = this->package_->bindings();
3446   for (Bindings::const_declarations_iterator p = b->begin_declarations();
3447        p != b->end_declarations();
3448        ++p)
3449     {
3450       Named_object* no = p->second;
3451       if (no->is_function_declaration()
3452 	  && !no->func_declaration_value()->type()->is_method()
3453 	  && !Linemap::is_predeclared_location(no->location())
3454 	  && !Gogo::is_hidden_name(no->name()))
3455 	fndecls.push_back(no);
3456     }
3457   for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
3458        p != fndecls.end();
3459        ++p)
3460     (*p)->func_declaration_value()->descriptor(this, *p);
3461   fndecls.clear();
3462 
3463   Create_function_descriptors cfd(this);
3464   this->traverse(&cfd);
3465 }
3466 
3467 // Finalize the methods of an interface type.
3468 
3469 int
type(Type * t)3470 Finalize_methods::type(Type* t)
3471 {
3472   // Check the classification so that we don't finalize the methods
3473   // twice for a named interface type.
3474   switch (t->classification())
3475     {
3476     case Type::TYPE_INTERFACE:
3477       t->interface_type()->finalize_methods();
3478       break;
3479 
3480     case Type::TYPE_NAMED:
3481       {
3482 	Named_type* nt = t->named_type();
3483 	Type* rt = nt->real_type();
3484 	if (rt->classification() != Type::TYPE_STRUCT)
3485 	  {
3486 	    // Finalize the methods of the real type first.
3487 	    if (Type::traverse(rt, this) == TRAVERSE_EXIT)
3488 	      return TRAVERSE_EXIT;
3489 
3490 	    // Finalize the methods of this type.
3491 	    nt->finalize_methods(this->gogo_);
3492 	  }
3493 	else
3494 	  {
3495 	    // We don't want to finalize the methods of a named struct
3496 	    // type, as the methods should be attached to the named
3497 	    // type, not the struct type.  We just want to finalize
3498 	    // the field types.
3499 	    //
3500 	    // It is possible that a field type refers indirectly to
3501 	    // this type, such as via a field with function type with
3502 	    // an argument or result whose type is this type.  To
3503 	    // avoid the cycle, first finalize the methods of any
3504 	    // embedded types, which are the only types we need to
3505 	    // know to finalize the methods of this type.
3506 	    const Struct_field_list* fields = rt->struct_type()->fields();
3507 	    if (fields != NULL)
3508 	      {
3509 		for (Struct_field_list::const_iterator pf = fields->begin();
3510 		     pf != fields->end();
3511 		     ++pf)
3512 		  {
3513 		    if (pf->is_anonymous())
3514 		      {
3515 			if (Type::traverse(pf->type(), this) == TRAVERSE_EXIT)
3516 			  return TRAVERSE_EXIT;
3517 		      }
3518 		  }
3519 	      }
3520 
3521 	    // Finalize the methods of this type.
3522 	    nt->finalize_methods(this->gogo_);
3523 
3524 	    // Finalize all the struct fields.
3525 	    if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3526 	      return TRAVERSE_EXIT;
3527 	  }
3528 
3529 	// If this type is defined in a different package, then finalize the
3530 	// types of all the methods, since we won't see them otherwise.
3531 	if (nt->named_object()->package() != NULL && nt->has_any_methods())
3532 	  {
3533 	    const Methods* methods = nt->methods();
3534 	    for (Methods::const_iterator p = methods->begin();
3535 		 p != methods->end();
3536 		 ++p)
3537 	      {
3538 		if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3539 		  return TRAVERSE_EXIT;
3540 	      }
3541 	  }
3542 
3543 	// Finalize the types of all methods that are declared but not
3544 	// defined, since we won't see the declarations otherwise.
3545 	if (nt->named_object()->package() == NULL
3546 	    && nt->local_methods() != NULL)
3547 	  {
3548 	    const Bindings* methods = nt->local_methods();
3549 	    for (Bindings::const_declarations_iterator p =
3550 		   methods->begin_declarations();
3551 		 p != methods->end_declarations();
3552 		 p++)
3553 	      {
3554 		if (p->second->is_function_declaration())
3555 		  {
3556 		    Type* mt = p->second->func_declaration_value()->type();
3557 		    if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3558 		      return TRAVERSE_EXIT;
3559 		  }
3560 	      }
3561 	  }
3562 
3563 	return TRAVERSE_SKIP_COMPONENTS;
3564       }
3565 
3566     case Type::TYPE_STRUCT:
3567       // Traverse the field types first in case there is an embedded
3568       // field with methods that the struct should inherit.
3569       if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3570           return TRAVERSE_EXIT;
3571       t->struct_type()->finalize_methods(this->gogo_);
3572       return TRAVERSE_SKIP_COMPONENTS;
3573 
3574     default:
3575       break;
3576     }
3577 
3578   return TRAVERSE_CONTINUE;
3579 }
3580 
3581 // Finalize method lists and build stub methods for types.
3582 
3583 void
finalize_methods()3584 Gogo::finalize_methods()
3585 {
3586   Finalize_methods finalize(this);
3587   this->traverse(&finalize);
3588 }
3589 
3590 // Finalize the method list for a type.  This is called when a type is
3591 // parsed for an inlined function body, which happens after the
3592 // finalize_methods pass.
3593 
3594 void
finalize_methods_for_type(Type * type)3595 Gogo::finalize_methods_for_type(Type* type)
3596 {
3597   Finalize_methods finalize(this);
3598   Type::traverse(type, &finalize);
3599 }
3600 
3601 // Set types for unspecified variables and constants.
3602 
3603 void
determine_types()3604 Gogo::determine_types()
3605 {
3606   Bindings* bindings = this->current_bindings();
3607   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3608        p != bindings->end_definitions();
3609        ++p)
3610     {
3611       if ((*p)->is_function())
3612 	(*p)->func_value()->determine_types();
3613       else if ((*p)->is_variable())
3614 	(*p)->var_value()->determine_type();
3615       else if ((*p)->is_const())
3616 	(*p)->const_value()->determine_type();
3617 
3618       // See if a variable requires us to build an initialization
3619       // function.  We know that we will see all global variables
3620       // here.
3621       if (!this->need_init_fn_ && (*p)->is_variable())
3622 	{
3623 	  Variable* variable = (*p)->var_value();
3624 
3625 	  // If this is a global variable which requires runtime
3626 	  // initialization, we need an initialization function.
3627 	  if (!variable->is_global())
3628 	    ;
3629 	  else if (variable->init() == NULL)
3630 	    ;
3631 	  else if (variable->type()->interface_type() != NULL)
3632 	    this->need_init_fn_ = true;
3633 	  else if (variable->init()->is_constant())
3634 	    ;
3635 	  else if (!variable->init()->is_composite_literal())
3636 	    this->need_init_fn_ = true;
3637 	  else if (variable->init()->is_nonconstant_composite_literal())
3638 	    this->need_init_fn_ = true;
3639 
3640 	  // If this is a global variable which holds a pointer value,
3641 	  // then we need an initialization function to register it as a
3642 	  // GC root.
3643 	  if (variable->is_global() && variable->type()->has_pointer())
3644 	    this->need_init_fn_ = true;
3645 	}
3646     }
3647 
3648   // Determine the types of constants in packages.
3649   for (Packages::const_iterator p = this->packages_.begin();
3650        p != this->packages_.end();
3651        ++p)
3652     p->second->determine_types();
3653 }
3654 
3655 // Traversal class used for type checking.
3656 
3657 class Check_types_traverse : public Traverse
3658 {
3659  public:
Check_types_traverse(Gogo * gogo)3660   Check_types_traverse(Gogo* gogo)
3661     : Traverse(traverse_variables
3662 	       | traverse_constants
3663 	       | traverse_functions
3664 	       | traverse_statements
3665 	       | traverse_expressions),
3666       gogo_(gogo)
3667   { }
3668 
3669   int
3670   variable(Named_object*);
3671 
3672   int
3673   constant(Named_object*, bool);
3674 
3675   int
3676   function(Named_object*);
3677 
3678   int
3679   statement(Block*, size_t* pindex, Statement*);
3680 
3681   int
3682   expression(Expression**);
3683 
3684  private:
3685   // General IR.
3686   Gogo* gogo_;
3687 };
3688 
3689 // Check that a variable initializer has the right type.
3690 
3691 int
variable(Named_object * named_object)3692 Check_types_traverse::variable(Named_object* named_object)
3693 {
3694   if (named_object->is_variable())
3695     {
3696       Variable* var = named_object->var_value();
3697 
3698       // Give error if variable type is not defined.
3699       var->type()->base();
3700 
3701       Expression* init = var->init();
3702       std::string reason;
3703       if (init != NULL
3704 	  && !Type::are_assignable(var->type(), init->type(), &reason))
3705 	{
3706 	  if (reason.empty())
3707 	    go_error_at(var->location(), "incompatible type in initialization");
3708 	  else
3709 	    go_error_at(var->location(),
3710 			"incompatible type in initialization (%s)",
3711 			reason.c_str());
3712           init = Expression::make_error(named_object->location());
3713 	  var->clear_init();
3714 	}
3715       else if (init != NULL
3716                && init->func_expression() != NULL)
3717         {
3718           Named_object* no = init->func_expression()->named_object();
3719           Function_type* fntype;
3720           if (no->is_function())
3721             fntype = no->func_value()->type();
3722           else if (no->is_function_declaration())
3723             fntype = no->func_declaration_value()->type();
3724           else
3725             go_unreachable();
3726 
3727           // Builtin functions cannot be used as function values for variable
3728           // initialization.
3729           if (fntype->is_builtin())
3730             {
3731 	      go_error_at(init->location(),
3732 			  "invalid use of special built-in function %qs; "
3733 			  "must be called",
3734 			  no->message_name().c_str());
3735             }
3736         }
3737       if (!var->is_used()
3738           && !var->is_global()
3739           && !var->is_parameter()
3740           && !var->is_receiver()
3741           && !var->type()->is_error()
3742           && (init == NULL || !init->is_error_expression())
3743           && !Lex::is_invalid_identifier(named_object->name()))
3744 	go_error_at(var->location(), "%qs declared and not used",
3745 		    named_object->message_name().c_str());
3746     }
3747   return TRAVERSE_CONTINUE;
3748 }
3749 
3750 // Check that a constant initializer has the right type.
3751 
3752 int
constant(Named_object * named_object,bool)3753 Check_types_traverse::constant(Named_object* named_object, bool)
3754 {
3755   Named_constant* constant = named_object->const_value();
3756   Type* ctype = constant->type();
3757   if (ctype->integer_type() == NULL
3758       && ctype->float_type() == NULL
3759       && ctype->complex_type() == NULL
3760       && !ctype->is_boolean_type()
3761       && !ctype->is_string_type())
3762     {
3763       if (ctype->is_nil_type())
3764 	go_error_at(constant->location(), "const initializer cannot be nil");
3765       else if (!ctype->is_error())
3766 	go_error_at(constant->location(), "invalid constant type");
3767       constant->set_error();
3768     }
3769   else if (!constant->expr()->is_constant())
3770     {
3771       go_error_at(constant->expr()->location(), "expression is not constant");
3772       constant->set_error();
3773     }
3774   else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3775 				 NULL))
3776     {
3777       go_error_at(constant->location(),
3778                   "initialization expression has wrong type");
3779       constant->set_error();
3780     }
3781   return TRAVERSE_CONTINUE;
3782 }
3783 
3784 // There are no types to check in a function, but this is where we
3785 // issue warnings about labels which are defined but not referenced.
3786 
3787 int
function(Named_object * no)3788 Check_types_traverse::function(Named_object* no)
3789 {
3790   no->func_value()->check_labels();
3791   return TRAVERSE_CONTINUE;
3792 }
3793 
3794 // Check that types are valid in a statement.
3795 
3796 int
statement(Block *,size_t *,Statement * s)3797 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3798 {
3799   s->check_types(this->gogo_);
3800   return TRAVERSE_CONTINUE;
3801 }
3802 
3803 // Check that types are valid in an expression.
3804 
3805 int
expression(Expression ** expr)3806 Check_types_traverse::expression(Expression** expr)
3807 {
3808   (*expr)->check_types(this->gogo_);
3809   return TRAVERSE_CONTINUE;
3810 }
3811 
3812 // Check that types are valid.
3813 
3814 void
check_types()3815 Gogo::check_types()
3816 {
3817   Check_types_traverse traverse(this);
3818   this->traverse(&traverse);
3819 
3820   Bindings* bindings = this->current_bindings();
3821   for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3822        p != bindings->end_declarations();
3823        ++p)
3824     {
3825       // Also check the types in a function declaration's signature.
3826       Named_object* no = p->second;
3827       if (no->is_function_declaration())
3828         no->func_declaration_value()->check_types();
3829     }
3830 }
3831 
3832 // Check the types in a single block.
3833 
3834 void
check_types_in_block(Block * block)3835 Gogo::check_types_in_block(Block* block)
3836 {
3837   Check_types_traverse traverse(this);
3838   block->traverse(&traverse);
3839 }
3840 
3841 // A traversal class which finds all the expressions which must be
3842 // evaluated in order within a statement or larger expression.  This
3843 // is used to implement the rules about order of evaluation.
3844 
3845 class Find_eval_ordering : public Traverse
3846 {
3847  private:
3848   typedef std::vector<Expression**> Expression_pointers;
3849 
3850  public:
Find_eval_ordering()3851   Find_eval_ordering()
3852     : Traverse(traverse_blocks
3853 	       | traverse_statements
3854 	       | traverse_expressions),
3855       exprs_()
3856   { }
3857 
3858   size_t
size() const3859   size() const
3860   { return this->exprs_.size(); }
3861 
3862   typedef Expression_pointers::const_iterator const_iterator;
3863 
3864   const_iterator
begin() const3865   begin() const
3866   { return this->exprs_.begin(); }
3867 
3868   const_iterator
end() const3869   end() const
3870   { return this->exprs_.end(); }
3871 
3872  protected:
3873   int
block(Block *)3874   block(Block*)
3875   { return TRAVERSE_SKIP_COMPONENTS; }
3876 
3877   int
statement(Block *,size_t *,Statement *)3878   statement(Block*, size_t*, Statement*)
3879   { return TRAVERSE_SKIP_COMPONENTS; }
3880 
3881   int
3882   expression(Expression**);
3883 
3884  private:
3885   // A list of pointers to expressions with side-effects.
3886   Expression_pointers exprs_;
3887 };
3888 
3889 // If an expression must be evaluated in order, put it on the list.
3890 
3891 int
expression(Expression ** expression_pointer)3892 Find_eval_ordering::expression(Expression** expression_pointer)
3893 {
3894   Binary_expression* binexp = (*expression_pointer)->binary_expression();
3895   if (binexp != NULL
3896       && (binexp->op() == OPERATOR_ANDAND || binexp->op() == OPERATOR_OROR))
3897     {
3898       // Shortcut expressions may potentially have side effects which need
3899       // to be ordered, so add them to the list.
3900       // We don't order its subexpressions here since they may be evaluated
3901       // conditionally. This is handled in remove_shortcuts.
3902       this->exprs_.push_back(expression_pointer);
3903       return TRAVERSE_SKIP_COMPONENTS;
3904     }
3905 
3906   // We have to look at subexpressions before this one.
3907   if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3908     return TRAVERSE_EXIT;
3909   if ((*expression_pointer)->must_eval_in_order())
3910     this->exprs_.push_back(expression_pointer);
3911   return TRAVERSE_SKIP_COMPONENTS;
3912 }
3913 
3914 // A traversal class for ordering evaluations.
3915 
3916 class Order_eval : public Traverse
3917 {
3918  public:
Order_eval(Gogo * gogo)3919   Order_eval(Gogo* gogo)
3920     : Traverse(traverse_variables
3921 	       | traverse_statements),
3922       gogo_(gogo)
3923   { }
3924 
3925   int
3926   variable(Named_object*);
3927 
3928   int
3929   statement(Block*, size_t*, Statement*);
3930 
3931  private:
3932   // The IR.
3933   Gogo* gogo_;
3934 };
3935 
3936 // Implement the order of evaluation rules for a statement.
3937 
3938 int
statement(Block * block,size_t * pindex,Statement * stmt)3939 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3940 {
3941   // FIXME: This approach doesn't work for switch statements, because
3942   // we add the new statements before the whole switch when we need to
3943   // instead add them just before the switch expression.  The right
3944   // fix is probably to lower switch statements with nonconstant cases
3945   // to a series of conditionals.
3946   if (stmt->switch_statement() != NULL)
3947     return TRAVERSE_CONTINUE;
3948 
3949   Find_eval_ordering find_eval_ordering;
3950 
3951   // If S is a variable declaration, then ordinary traversal won't do
3952   // anything.  We want to explicitly traverse the initialization
3953   // expression if there is one.
3954   Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3955   Expression* init = NULL;
3956   Expression* orig_init = NULL;
3957   if (vds == NULL)
3958     stmt->traverse_contents(&find_eval_ordering);
3959   else
3960     {
3961       init = vds->var()->var_value()->init();
3962       if (init == NULL)
3963 	return TRAVERSE_CONTINUE;
3964       orig_init = init;
3965 
3966       // It might seem that this could be
3967       // init->traverse_subexpressions.  Unfortunately that can fail
3968       // in a case like
3969       //   var err os.Error
3970       //   newvar, err := call(arg())
3971       // Here newvar will have an init of call result 0 of
3972       // call(arg()).  If we only traverse subexpressions, we will
3973       // only find arg(), and we won't bother to move anything out.
3974       // Then we get to the assignment to err, we will traverse the
3975       // whole statement, and this time we will find both call() and
3976       // arg(), and so we will move them out.  This will cause them to
3977       // be put into temporary variables before the assignment to err
3978       // but after the declaration of newvar.  To avoid that problem,
3979       // we traverse the entire expression here.
3980       Expression::traverse(&init, &find_eval_ordering);
3981     }
3982 
3983   size_t c = find_eval_ordering.size();
3984   if (c == 0)
3985     return TRAVERSE_CONTINUE;
3986 
3987   // If there is only one expression with a side-effect, we can
3988   // usually leave it in place.
3989   if (c == 1)
3990     {
3991       switch (stmt->classification())
3992 	{
3993 	case Statement::STATEMENT_ASSIGNMENT:
3994 	  // For an assignment statement, we need to evaluate an
3995 	  // expression on the right hand side before we evaluate any
3996 	  // index expression on the left hand side, so for that case
3997 	  // we always move the expression.  Otherwise we mishandle
3998 	  // m[0] = len(m) where m is a map.
3999 	  break;
4000 
4001 	case Statement::STATEMENT_EXPRESSION:
4002 	  {
4003 	    // If this is a call statement that doesn't return any
4004 	    // values, it will not have been counted as a value to
4005 	    // move.  We need to move any subexpressions in case they
4006 	    // are themselves call statements that require passing a
4007 	    // closure.
4008 	    Expression* expr = stmt->expression_statement()->expr();
4009 	    if (expr->call_expression() != NULL
4010 		&& expr->call_expression()->result_count() == 0)
4011 	      break;
4012 	    return TRAVERSE_CONTINUE;
4013 	  }
4014 
4015 	default:
4016 	  // We can leave the expression in place.
4017 	  return TRAVERSE_CONTINUE;
4018 	}
4019     }
4020 
4021   bool is_thunk = stmt->thunk_statement() != NULL;
4022   Expression_statement* es = stmt->expression_statement();
4023   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
4024        p != find_eval_ordering.end();
4025        ++p)
4026     {
4027       Expression** pexpr = *p;
4028 
4029       // The last expression in a thunk will be the call passed to go
4030       // or defer, which we must not evaluate early.
4031       if (is_thunk && p + 1 == find_eval_ordering.end())
4032 	break;
4033 
4034       Location loc = (*pexpr)->location();
4035       Statement* s;
4036       if ((*pexpr)->call_expression() == NULL
4037 	  || (*pexpr)->call_expression()->result_count() < 2)
4038 	{
4039 	  Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
4040 							      loc);
4041 	  s = ts;
4042 	  *pexpr = Expression::make_temporary_reference(ts, loc);
4043 	}
4044       else
4045 	{
4046 	  // A call expression which returns multiple results needs to
4047 	  // be handled specially.  We can't create a temporary
4048 	  // because there is no type to give it.  Any actual uses of
4049 	  // the values will be done via Call_result_expressions.
4050           //
4051           // Since a given call expression can be shared by multiple
4052           // Call_result_expressions, avoid hoisting the call the
4053           // second time we see it here. In addition, don't try to
4054           // hoist the top-level multi-return call in the statement,
4055           // since doing this would result a tree with more than one copy
4056           // of the call.
4057           if (this->remember_expression(*pexpr))
4058             s = NULL;
4059           else if (es != NULL && *pexpr == es->expr())
4060             s = NULL;
4061           else
4062             s = Statement::make_statement(*pexpr, true);
4063         }
4064 
4065       if (s != NULL)
4066         {
4067           block->insert_statement_before(*pindex, s);
4068           ++*pindex;
4069         }
4070     }
4071 
4072   if (init != orig_init)
4073     vds->var()->var_value()->set_init(init);
4074 
4075   return TRAVERSE_CONTINUE;
4076 }
4077 
4078 // Implement the order of evaluation rules for the initializer of a
4079 // global variable.
4080 
4081 int
variable(Named_object * no)4082 Order_eval::variable(Named_object* no)
4083 {
4084   if (no->is_result_variable())
4085     return TRAVERSE_CONTINUE;
4086   Variable* var = no->var_value();
4087   Expression* init = var->init();
4088   if (!var->is_global() || init == NULL)
4089     return TRAVERSE_CONTINUE;
4090 
4091   Find_eval_ordering find_eval_ordering;
4092   Expression::traverse(&init, &find_eval_ordering);
4093 
4094   if (find_eval_ordering.size() <= 1)
4095     {
4096       // If there is only one expression with a side-effect, we can
4097       // leave it in place.
4098       return TRAVERSE_SKIP_COMPONENTS;
4099     }
4100 
4101   Expression* orig_init = init;
4102 
4103   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
4104        p != find_eval_ordering.end();
4105        ++p)
4106     {
4107       Expression** pexpr = *p;
4108       Location loc = (*pexpr)->location();
4109       Statement* s;
4110       if ((*pexpr)->call_expression() == NULL
4111 	  || (*pexpr)->call_expression()->result_count() < 2)
4112 	{
4113 	  Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
4114 							      loc);
4115 	  s = ts;
4116 	  *pexpr = Expression::make_temporary_reference(ts, loc);
4117 	}
4118       else
4119 	{
4120 	  // A call expression which returns multiple results needs to
4121 	  // be handled specially.
4122 	  s = Statement::make_statement(*pexpr, true);
4123 	}
4124       var->add_preinit_statement(this->gogo_, s);
4125     }
4126 
4127   if (init != orig_init)
4128     var->set_init(init);
4129 
4130   return TRAVERSE_SKIP_COMPONENTS;
4131 }
4132 
4133 // Use temporary variables to implement the order of evaluation rules.
4134 
4135 void
order_evaluations()4136 Gogo::order_evaluations()
4137 {
4138   Order_eval order_eval(this);
4139   this->traverse(&order_eval);
4140 }
4141 
4142 // Order evaluations in a block.
4143 
4144 void
order_block(Block * block)4145 Gogo::order_block(Block* block)
4146 {
4147   Order_eval order_eval(this);
4148   block->traverse(&order_eval);
4149 }
4150 
4151 // A traversal class used to find a single shortcut operator within an
4152 // expression.
4153 
4154 class Find_shortcut : public Traverse
4155 {
4156  public:
Find_shortcut()4157   Find_shortcut()
4158     : Traverse(traverse_blocks
4159 	       | traverse_statements
4160 	       | traverse_expressions),
4161       found_(NULL)
4162   { }
4163 
4164   // A pointer to the expression which was found, or NULL if none was
4165   // found.
4166   Expression**
found() const4167   found() const
4168   { return this->found_; }
4169 
4170  protected:
4171   int
block(Block *)4172   block(Block*)
4173   { return TRAVERSE_SKIP_COMPONENTS; }
4174 
4175   int
statement(Block *,size_t *,Statement *)4176   statement(Block*, size_t*, Statement*)
4177   { return TRAVERSE_SKIP_COMPONENTS; }
4178 
4179   int
4180   expression(Expression**);
4181 
4182  private:
4183   Expression** found_;
4184 };
4185 
4186 // Find a shortcut expression.
4187 
4188 int
expression(Expression ** pexpr)4189 Find_shortcut::expression(Expression** pexpr)
4190 {
4191   Expression* expr = *pexpr;
4192   Binary_expression* be = expr->binary_expression();
4193   if (be == NULL)
4194     return TRAVERSE_CONTINUE;
4195   Operator op = be->op();
4196   if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
4197     return TRAVERSE_CONTINUE;
4198   go_assert(this->found_ == NULL);
4199   this->found_ = pexpr;
4200   return TRAVERSE_EXIT;
4201 }
4202 
4203 // A traversal class used to turn shortcut operators into explicit if
4204 // statements.
4205 
4206 class Shortcuts : public Traverse
4207 {
4208  public:
Shortcuts(Gogo * gogo)4209   Shortcuts(Gogo* gogo)
4210     : Traverse(traverse_variables
4211 	       | traverse_statements),
4212       gogo_(gogo)
4213   { }
4214 
4215  protected:
4216   int
4217   variable(Named_object*);
4218 
4219   int
4220   statement(Block*, size_t*, Statement*);
4221 
4222  private:
4223   // Convert a shortcut operator.
4224   Statement*
4225   convert_shortcut(Block* enclosing, Expression** pshortcut);
4226 
4227   // The IR.
4228   Gogo* gogo_;
4229 };
4230 
4231 // Remove shortcut operators in a single statement.
4232 
4233 int
statement(Block * block,size_t * pindex,Statement * s)4234 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
4235 {
4236   // FIXME: This approach doesn't work for switch statements, because
4237   // we add the new statements before the whole switch when we need to
4238   // instead add them just before the switch expression.  The right
4239   // fix is probably to lower switch statements with nonconstant cases
4240   // to a series of conditionals.
4241   if (s->switch_statement() != NULL)
4242     return TRAVERSE_CONTINUE;
4243 
4244   while (true)
4245     {
4246       Find_shortcut find_shortcut;
4247 
4248       // If S is a variable declaration, then ordinary traversal won't
4249       // do anything.  We want to explicitly traverse the
4250       // initialization expression if there is one.
4251       Variable_declaration_statement* vds = s->variable_declaration_statement();
4252       Expression* init = NULL;
4253       if (vds == NULL)
4254 	s->traverse_contents(&find_shortcut);
4255       else
4256 	{
4257 	  init = vds->var()->var_value()->init();
4258 	  if (init == NULL)
4259 	    return TRAVERSE_CONTINUE;
4260 	  init->traverse(&init, &find_shortcut);
4261 	}
4262       Expression** pshortcut = find_shortcut.found();
4263       if (pshortcut == NULL)
4264 	return TRAVERSE_CONTINUE;
4265 
4266       Statement* snew = this->convert_shortcut(block, pshortcut);
4267       block->insert_statement_before(*pindex, snew);
4268       ++*pindex;
4269 
4270       if (pshortcut == &init)
4271 	vds->var()->var_value()->set_init(init);
4272     }
4273 }
4274 
4275 // Remove shortcut operators in the initializer of a global variable.
4276 
4277 int
variable(Named_object * no)4278 Shortcuts::variable(Named_object* no)
4279 {
4280   if (no->is_result_variable())
4281     return TRAVERSE_CONTINUE;
4282   Variable* var = no->var_value();
4283   Expression* init = var->init();
4284   if (!var->is_global() || init == NULL)
4285     return TRAVERSE_CONTINUE;
4286 
4287   while (true)
4288     {
4289       Find_shortcut find_shortcut;
4290       init->traverse(&init, &find_shortcut);
4291       Expression** pshortcut = find_shortcut.found();
4292       if (pshortcut == NULL)
4293 	return TRAVERSE_CONTINUE;
4294 
4295       Statement* snew = this->convert_shortcut(NULL, pshortcut);
4296       var->add_preinit_statement(this->gogo_, snew);
4297       if (pshortcut == &init)
4298 	var->set_init(init);
4299     }
4300 }
4301 
4302 // Given an expression which uses a shortcut operator, return a
4303 // statement which implements it, and update *PSHORTCUT accordingly.
4304 
4305 Statement*
convert_shortcut(Block * enclosing,Expression ** pshortcut)4306 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
4307 {
4308   Binary_expression* shortcut = (*pshortcut)->binary_expression();
4309   Expression* left = shortcut->left();
4310   Expression* right = shortcut->right();
4311   Location loc = shortcut->location();
4312 
4313   Block* retblock = new Block(enclosing, loc);
4314   retblock->set_end_location(loc);
4315 
4316   Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
4317 						      left, loc);
4318   retblock->add_statement(ts);
4319 
4320   Block* block = new Block(retblock, loc);
4321   block->set_end_location(loc);
4322   Expression* tmpref = Expression::make_temporary_reference(ts, loc);
4323   Statement* assign = Statement::make_assignment(tmpref, right, loc);
4324   block->add_statement(assign);
4325 
4326   Expression* cond = Expression::make_temporary_reference(ts, loc);
4327   if (shortcut->binary_expression()->op() == OPERATOR_OROR)
4328     cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
4329 
4330   Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
4331 							 loc);
4332   retblock->add_statement(if_statement);
4333 
4334   *pshortcut = Expression::make_temporary_reference(ts, loc);
4335 
4336   delete shortcut;
4337 
4338   // Now convert any shortcut operators in LEFT and RIGHT.
4339   // LEFT and RIGHT were skipped in the top level
4340   // Gogo::order_evaluations. We need to order their
4341   // components first.
4342   Order_eval order_eval(this->gogo_);
4343   retblock->traverse(&order_eval);
4344   Shortcuts shortcuts(this->gogo_);
4345   retblock->traverse(&shortcuts);
4346 
4347   return Statement::make_block_statement(retblock, loc);
4348 }
4349 
4350 // Turn shortcut operators into explicit if statements.  Doing this
4351 // considerably simplifies the order of evaluation rules.
4352 
4353 void
remove_shortcuts()4354 Gogo::remove_shortcuts()
4355 {
4356   Shortcuts shortcuts(this);
4357   this->traverse(&shortcuts);
4358 }
4359 
4360 // Turn shortcut operators into explicit if statements in a block.
4361 
4362 void
remove_shortcuts_in_block(Block * block)4363 Gogo::remove_shortcuts_in_block(Block* block)
4364 {
4365   Shortcuts shortcuts(this);
4366   block->traverse(&shortcuts);
4367 }
4368 
4369 // Traversal to flatten parse tree after order of evaluation rules are applied.
4370 
4371 class Flatten : public Traverse
4372 {
4373  public:
Flatten(Gogo * gogo,Named_object * function)4374   Flatten(Gogo* gogo, Named_object* function)
4375     : Traverse(traverse_variables
4376 	       | traverse_functions
4377 	       | traverse_statements
4378 	       | traverse_expressions),
4379       gogo_(gogo), function_(function), inserter_()
4380   { }
4381 
4382   void
set_inserter(const Statement_inserter * inserter)4383   set_inserter(const Statement_inserter* inserter)
4384   { this->inserter_ = *inserter; }
4385 
4386   int
4387   variable(Named_object*);
4388 
4389   int
4390   function(Named_object*);
4391 
4392   int
4393   statement(Block*, size_t* pindex, Statement*);
4394 
4395   int
4396   expression(Expression**);
4397 
4398  private:
4399   // General IR.
4400   Gogo* gogo_;
4401   // The function we are traversing.
4402   Named_object* function_;
4403   // Current statement inserter for use by expressions.
4404   Statement_inserter inserter_;
4405 };
4406 
4407 // Flatten variables.
4408 
4409 int
variable(Named_object * no)4410 Flatten::variable(Named_object* no)
4411 {
4412   if (!no->is_variable())
4413     return TRAVERSE_CONTINUE;
4414 
4415   if (no->is_variable() && no->var_value()->is_global())
4416     {
4417       // Global variables can have loops in their initialization
4418       // expressions.  This is handled in flatten_init_expression.
4419       no->var_value()->flatten_init_expression(this->gogo_, this->function_,
4420                                                &this->inserter_);
4421       return TRAVERSE_CONTINUE;
4422     }
4423 
4424   if (!no->var_value()->is_parameter()
4425       && !no->var_value()->is_receiver()
4426       && !no->var_value()->is_closure()
4427       && no->var_value()->is_non_escaping_address_taken()
4428       && !no->var_value()->is_in_heap()
4429       && no->var_value()->toplevel_decl() == NULL)
4430     {
4431       // Local variable that has address taken but not escape.
4432       // It needs to be live beyond its lexical scope. So we
4433       // create a top-level declaration for it.
4434       // No need to do it if it is already in the top level.
4435       Block* top_block = function_->func_value()->block();
4436       if (top_block->bindings()->lookup_local(no->name()) != no)
4437         {
4438           Variable* var = no->var_value();
4439           Temporary_statement* ts =
4440             Statement::make_temporary(var->type(), NULL, var->location());
4441           ts->set_is_address_taken();
4442           top_block->add_statement_at_front(ts);
4443           var->set_toplevel_decl(ts);
4444         }
4445     }
4446 
4447   go_assert(!no->var_value()->has_pre_init());
4448 
4449   return TRAVERSE_SKIP_COMPONENTS;
4450 }
4451 
4452 // Flatten the body of a function.  Record the function while flattening it,
4453 // so that we can pass it down when flattening an expression.
4454 
4455 int
function(Named_object * no)4456 Flatten::function(Named_object* no)
4457 {
4458   go_assert(this->function_ == NULL);
4459   this->function_ = no;
4460   int t = no->func_value()->traverse(this);
4461   this->function_ = NULL;
4462 
4463   if (t == TRAVERSE_EXIT)
4464     return t;
4465   return TRAVERSE_SKIP_COMPONENTS;
4466 }
4467 
4468 // Flatten statement parse trees.
4469 
4470 int
statement(Block * block,size_t * pindex,Statement * sorig)4471 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
4472 {
4473   // Because we explicitly traverse the statement's contents
4474   // ourselves, we want to skip block statements here.  There is
4475   // nothing to flatten in a block statement.
4476   if (sorig->is_block_statement())
4477     return TRAVERSE_CONTINUE;
4478 
4479   Statement_inserter hold_inserter(this->inserter_);
4480   this->inserter_ = Statement_inserter(block, pindex);
4481 
4482   // Flatten the expressions first.
4483   int t = sorig->traverse_contents(this);
4484   if (t == TRAVERSE_EXIT)
4485     {
4486       this->inserter_ = hold_inserter;
4487       return t;
4488     }
4489 
4490   // Keep flattening until nothing changes.
4491   Statement* s = sorig;
4492   while (true)
4493     {
4494       Statement* snew = s->flatten(this->gogo_, this->function_, block,
4495                                    &this->inserter_);
4496       if (snew == s)
4497 	break;
4498       s = snew;
4499       t = s->traverse_contents(this);
4500       if (t == TRAVERSE_EXIT)
4501 	{
4502 	  this->inserter_ = hold_inserter;
4503 	  return t;
4504 	}
4505     }
4506 
4507   if (s != sorig)
4508     block->replace_statement(*pindex, s);
4509 
4510   this->inserter_ = hold_inserter;
4511   return TRAVERSE_SKIP_COMPONENTS;
4512 }
4513 
4514 // Flatten expression parse trees.
4515 
4516 int
expression(Expression ** pexpr)4517 Flatten::expression(Expression** pexpr)
4518 {
4519   // Keep flattening until nothing changes.
4520   while (true)
4521     {
4522       Expression* e = *pexpr;
4523       if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
4524         return TRAVERSE_EXIT;
4525 
4526       Expression* enew = e->flatten(this->gogo_, this->function_,
4527                                     &this->inserter_);
4528       if (enew == e)
4529 	break;
4530       *pexpr = enew;
4531     }
4532   return TRAVERSE_SKIP_COMPONENTS;
4533 }
4534 
4535 // Flatten a block.
4536 
4537 void
flatten_block(Named_object * function,Block * block)4538 Gogo::flatten_block(Named_object* function, Block* block)
4539 {
4540   Flatten flatten(this, function);
4541   block->traverse(&flatten);
4542 }
4543 
4544 // Flatten an expression.  INSERTER may be NULL, in which case the
4545 // expression had better not need to create any temporaries.
4546 
4547 void
flatten_expression(Named_object * function,Statement_inserter * inserter,Expression ** pexpr)4548 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
4549                          Expression** pexpr)
4550 {
4551   Flatten flatten(this, function);
4552   if (inserter != NULL)
4553     flatten.set_inserter(inserter);
4554   flatten.expression(pexpr);
4555 }
4556 
4557 void
flatten()4558 Gogo::flatten()
4559 {
4560   Flatten flatten(this, NULL);
4561   this->traverse(&flatten);
4562 }
4563 
4564 // Traversal to convert calls to the predeclared recover function to
4565 // pass in an argument indicating whether it can recover from a panic
4566 // or not.
4567 
4568 class Convert_recover : public Traverse
4569 {
4570  public:
Convert_recover(Named_object * arg)4571   Convert_recover(Named_object* arg)
4572     : Traverse(traverse_expressions),
4573       arg_(arg)
4574   { }
4575 
4576  protected:
4577   int
4578   expression(Expression**);
4579 
4580  private:
4581   // The argument to pass to the function.
4582   Named_object* arg_;
4583 };
4584 
4585 // Convert calls to recover.
4586 
4587 int
expression(Expression ** pp)4588 Convert_recover::expression(Expression** pp)
4589 {
4590   Call_expression* ce = (*pp)->call_expression();
4591   if (ce != NULL && ce->is_recover_call())
4592     ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4593 						       ce->location()));
4594   return TRAVERSE_CONTINUE;
4595 }
4596 
4597 // Traversal for build_recover_thunks.
4598 
4599 class Build_recover_thunks : public Traverse
4600 {
4601  public:
Build_recover_thunks(Gogo * gogo)4602   Build_recover_thunks(Gogo* gogo)
4603     : Traverse(traverse_functions),
4604       gogo_(gogo)
4605   { }
4606 
4607   int
4608   function(Named_object*);
4609 
4610  private:
4611   Expression*
4612   can_recover_arg(Location);
4613 
4614   // General IR.
4615   Gogo* gogo_;
4616 };
4617 
4618 // If this function calls recover, turn it into a thunk.
4619 
4620 int
function(Named_object * orig_no)4621 Build_recover_thunks::function(Named_object* orig_no)
4622 {
4623   Function* orig_func = orig_no->func_value();
4624   if (!orig_func->calls_recover()
4625       || orig_func->is_recover_thunk()
4626       || orig_func->has_recover_thunk())
4627     return TRAVERSE_CONTINUE;
4628 
4629   Gogo* gogo = this->gogo_;
4630   Location location = orig_func->location();
4631 
4632   static int count;
4633   char buf[50];
4634 
4635   Function_type* orig_fntype = orig_func->type();
4636   Typed_identifier_list* new_params = new Typed_identifier_list();
4637   std::string receiver_name;
4638   if (orig_fntype->is_method())
4639     {
4640       const Typed_identifier* receiver = orig_fntype->receiver();
4641       snprintf(buf, sizeof buf, "rt.%u", count);
4642       ++count;
4643       receiver_name = buf;
4644       new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4645 					     receiver->location()));
4646     }
4647   const Typed_identifier_list* orig_params = orig_fntype->parameters();
4648   if (orig_params != NULL && !orig_params->empty())
4649     {
4650       for (Typed_identifier_list::const_iterator p = orig_params->begin();
4651 	   p != orig_params->end();
4652 	   ++p)
4653 	{
4654 	  snprintf(buf, sizeof buf, "pt.%u", count);
4655 	  ++count;
4656 	  new_params->push_back(Typed_identifier(buf, p->type(),
4657 						 p->location()));
4658 	}
4659     }
4660   snprintf(buf, sizeof buf, "pr.%u", count);
4661   ++count;
4662   std::string can_recover_name = buf;
4663   new_params->push_back(Typed_identifier(can_recover_name,
4664 					 Type::lookup_bool_type(),
4665 					 orig_fntype->location()));
4666 
4667   const Typed_identifier_list* orig_results = orig_fntype->results();
4668   Typed_identifier_list* new_results;
4669   if (orig_results == NULL || orig_results->empty())
4670     new_results = NULL;
4671   else
4672     {
4673       new_results = new Typed_identifier_list();
4674       for (Typed_identifier_list::const_iterator p = orig_results->begin();
4675 	   p != orig_results->end();
4676 	   ++p)
4677 	new_results->push_back(Typed_identifier("", p->type(), p->location()));
4678     }
4679 
4680   Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4681 						       new_results,
4682 						       orig_fntype->location());
4683   if (orig_fntype->is_varargs())
4684     new_fntype->set_is_varargs();
4685 
4686   Type* rtype = NULL;
4687   if (orig_fntype->is_method())
4688     rtype = orig_fntype->receiver()->type();
4689   std::string name(gogo->recover_thunk_name(orig_no->name(), rtype));
4690   Named_object *new_no = gogo->start_function(name, new_fntype, false,
4691 					      location);
4692   Function *new_func = new_no->func_value();
4693   if (orig_func->enclosing() != NULL)
4694     new_func->set_enclosing(orig_func->enclosing());
4695 
4696   // We build the code for the original function attached to the new
4697   // function, and then swap the original and new function bodies.
4698   // This means that existing references to the original function will
4699   // then refer to the new function.  That makes this code a little
4700   // confusing, in that the reference to NEW_NO really refers to the
4701   // other function, not the one we are building.
4702 
4703   Expression* closure = NULL;
4704   if (orig_func->needs_closure())
4705     {
4706       // For the new function we are creating, declare a new parameter
4707       // variable NEW_CLOSURE_NO and set it to be the closure variable
4708       // of the function.  This will be set to the closure value
4709       // passed in by the caller.  Then pass a reference to this
4710       // variable as the closure value when calling the original
4711       // function.  In other words, simply pass the closure value
4712       // through the thunk we are creating.
4713       Named_object* orig_closure_no = orig_func->closure_var();
4714       Variable* orig_closure_var = orig_closure_no->var_value();
4715       Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4716 				       false, false, location);
4717       new_var->set_is_closure();
4718       snprintf(buf, sizeof buf, "closure.%u", count);
4719       ++count;
4720       Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4721 								 new_var);
4722       new_func->set_closure_var(new_closure_no);
4723       closure = Expression::make_var_reference(new_closure_no, location);
4724     }
4725 
4726   Expression* fn = Expression::make_func_reference(new_no, closure, location);
4727 
4728   Expression_list* args = new Expression_list();
4729   if (new_params != NULL)
4730     {
4731       // Note that we skip the last parameter, which is the boolean
4732       // indicating whether recover can succed.
4733       for (Typed_identifier_list::const_iterator p = new_params->begin();
4734 	   p + 1 != new_params->end();
4735 	   ++p)
4736 	{
4737 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
4738 	  go_assert(p_no != NULL
4739 		     && p_no->is_variable()
4740 		     && p_no->var_value()->is_parameter());
4741 	  args->push_back(Expression::make_var_reference(p_no, location));
4742 	}
4743     }
4744   args->push_back(this->can_recover_arg(location));
4745 
4746   gogo->start_block(location);
4747 
4748   Call_expression* call = Expression::make_call(fn, args, false, location);
4749 
4750   // Any varargs call has already been lowered.
4751   call->set_varargs_are_lowered();
4752 
4753   Statement* s = Statement::make_return_from_call(call, location);
4754   s->determine_types();
4755   gogo->add_statement(s);
4756 
4757   Block* b = gogo->finish_block(location);
4758 
4759   gogo->add_block(b, location);
4760 
4761   // Lower the call in case it returns multiple results.
4762   gogo->lower_block(new_no, b);
4763 
4764   gogo->finish_function(location);
4765 
4766   // Swap the function bodies and types.
4767   new_func->swap_for_recover(orig_func);
4768   orig_func->set_is_recover_thunk();
4769   new_func->set_calls_recover();
4770   new_func->set_has_recover_thunk();
4771 
4772   Bindings* orig_bindings = orig_func->block()->bindings();
4773   Bindings* new_bindings = new_func->block()->bindings();
4774   if (orig_fntype->is_method())
4775     {
4776       // We changed the receiver to be a regular parameter.  We have
4777       // to update the binding accordingly in both functions.
4778       Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4779       go_assert(orig_rec_no != NULL
4780 		 && orig_rec_no->is_variable()
4781 		 && !orig_rec_no->var_value()->is_receiver());
4782       orig_rec_no->var_value()->set_is_receiver();
4783 
4784       std::string new_receiver_name(orig_fntype->receiver()->name());
4785       if (new_receiver_name.empty())
4786 	{
4787 	  // Find the receiver.  It was named "r.NNN" in
4788 	  // Gogo::start_function.
4789 	  for (Bindings::const_definitions_iterator p =
4790 		 new_bindings->begin_definitions();
4791 	       p != new_bindings->end_definitions();
4792 	       ++p)
4793 	    {
4794 	      const std::string& pname((*p)->name());
4795 	      if (pname[0] == 'r' && pname[1] == '.')
4796 		{
4797 		  new_receiver_name = pname;
4798 		  break;
4799 		}
4800 	    }
4801 	  go_assert(!new_receiver_name.empty());
4802 	}
4803       Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4804       if (new_rec_no == NULL)
4805 	go_assert(saw_errors());
4806       else
4807 	{
4808 	  go_assert(new_rec_no->is_variable()
4809 		     && new_rec_no->var_value()->is_receiver());
4810 	  new_rec_no->var_value()->set_is_not_receiver();
4811 	}
4812     }
4813 
4814   // Because we flipped blocks but not types, the can_recover
4815   // parameter appears in the (now) old bindings as a parameter.
4816   // Change it to a local variable, whereupon it will be discarded.
4817   Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4818   go_assert(can_recover_no != NULL
4819 	     && can_recover_no->is_variable()
4820 	     && can_recover_no->var_value()->is_parameter());
4821   orig_bindings->remove_binding(can_recover_no);
4822 
4823   // Add the can_recover argument to the (now) new bindings, and
4824   // attach it to any recover statements.
4825   Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4826 					   false, true, false, location);
4827   can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4828 					      can_recover_var);
4829   Convert_recover convert_recover(can_recover_no);
4830   new_func->traverse(&convert_recover);
4831 
4832   // Update the function pointers in any named results.
4833   new_func->update_result_variables();
4834   orig_func->update_result_variables();
4835 
4836   return TRAVERSE_CONTINUE;
4837 }
4838 
4839 // Return the expression to pass for the .can_recover parameter to the
4840 // new function.  This indicates whether a call to recover may return
4841 // non-nil.  The expression is runtime.canrecover(__builtin_return_address()).
4842 
4843 Expression*
can_recover_arg(Location location)4844 Build_recover_thunks::can_recover_arg(Location location)
4845 {
4846   Type* uintptr_type = Type::lookup_integer_type("uintptr");
4847   static Named_object* can_recover;
4848   if (can_recover == NULL)
4849     {
4850       const Location bloc = Linemap::predeclared_location();
4851       Typed_identifier_list* param_types = new Typed_identifier_list();
4852       param_types->push_back(Typed_identifier("a", uintptr_type, bloc));
4853       Type* boolean_type = Type::lookup_bool_type();
4854       Typed_identifier_list* results = new Typed_identifier_list();
4855       results->push_back(Typed_identifier("", boolean_type, bloc));
4856       Function_type* fntype = Type::make_function_type(NULL, param_types,
4857 						       results, bloc);
4858       can_recover =
4859 	Named_object::make_function_declaration("runtime_canrecover",
4860 						NULL, fntype, bloc);
4861       can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4862     }
4863 
4864   Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4865   Expression* call = Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS,
4866                                         location, 1, zexpr);
4867   call = Expression::make_unsafe_cast(uintptr_type, call, location);
4868 
4869   Expression_list* args = new Expression_list();
4870   args->push_back(call);
4871 
4872   Expression* fn = Expression::make_func_reference(can_recover, NULL, location);
4873   return Expression::make_call(fn, args, false, location);
4874 }
4875 
4876 // Build thunks for functions which call recover.  We build a new
4877 // function with an extra parameter, which is whether a call to
4878 // recover can succeed.  We then move the body of this function to
4879 // that one.  We then turn this function into a thunk which calls the
4880 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4881 // The function will be marked as not splitting the stack.  This will
4882 // cooperate with the implementation of defer to make recover do the
4883 // right thing.
4884 
4885 void
build_recover_thunks()4886 Gogo::build_recover_thunks()
4887 {
4888   Build_recover_thunks build_recover_thunks(this);
4889   this->traverse(&build_recover_thunks);
4890 }
4891 
4892 // Look for named types to see whether we need to create an interface
4893 // method table.
4894 
4895 class Build_method_tables : public Traverse
4896 {
4897  public:
Build_method_tables(Gogo * gogo,const std::vector<Interface_type * > & interfaces)4898   Build_method_tables(Gogo* gogo,
4899 		      const std::vector<Interface_type*>& interfaces)
4900     : Traverse(traverse_types),
4901       gogo_(gogo), interfaces_(interfaces)
4902   { }
4903 
4904   int
4905   type(Type*);
4906 
4907  private:
4908   // The IR.
4909   Gogo* gogo_;
4910   // A list of locally defined interfaces which have hidden methods.
4911   const std::vector<Interface_type*>& interfaces_;
4912 };
4913 
4914 // Build all required interface method tables for types.  We need to
4915 // ensure that we have an interface method table for every interface
4916 // which has a hidden method, for every named type which implements
4917 // that interface.  Normally we can just build interface method tables
4918 // as we need them.  However, in some cases we can require an
4919 // interface method table for an interface defined in a different
4920 // package for a type defined in that package.  If that interface and
4921 // type both use a hidden method, that is OK.  However, we will not be
4922 // able to build that interface method table when we need it, because
4923 // the type's hidden method will be static.  So we have to build it
4924 // here, and just refer it from other packages as needed.
4925 
4926 void
build_interface_method_tables()4927 Gogo::build_interface_method_tables()
4928 {
4929   if (saw_errors())
4930     return;
4931 
4932   std::vector<Interface_type*> hidden_interfaces;
4933   hidden_interfaces.reserve(this->interface_types_.size());
4934   for (std::vector<Interface_type*>::const_iterator pi =
4935 	 this->interface_types_.begin();
4936        pi != this->interface_types_.end();
4937        ++pi)
4938     {
4939       const Typed_identifier_list* methods = (*pi)->methods();
4940       if (methods == NULL)
4941 	continue;
4942       for (Typed_identifier_list::const_iterator pm = methods->begin();
4943 	   pm != methods->end();
4944 	   ++pm)
4945 	{
4946 	  if (Gogo::is_hidden_name(pm->name()))
4947 	    {
4948 	      hidden_interfaces.push_back(*pi);
4949 	      break;
4950 	    }
4951 	}
4952     }
4953 
4954   if (!hidden_interfaces.empty())
4955     {
4956       // Now traverse the tree looking for all named types.
4957       Build_method_tables bmt(this, hidden_interfaces);
4958       this->traverse(&bmt);
4959     }
4960 
4961   // We no longer need the list of interfaces.
4962 
4963   this->interface_types_.clear();
4964 }
4965 
4966 // This is called for each type.  For a named type, for each of the
4967 // interfaces with hidden methods that it implements, create the
4968 // method table.
4969 
4970 int
type(Type * type)4971 Build_method_tables::type(Type* type)
4972 {
4973   Named_type* nt = type->named_type();
4974   Struct_type* st = type->struct_type();
4975   if (nt != NULL || st != NULL)
4976     {
4977       Translate_context context(this->gogo_, NULL, NULL, NULL);
4978       for (std::vector<Interface_type*>::const_iterator p =
4979 	     this->interfaces_.begin();
4980 	   p != this->interfaces_.end();
4981 	   ++p)
4982 	{
4983 	  // We ask whether a pointer to the named type implements the
4984 	  // interface, because a pointer can implement more methods
4985 	  // than a value.
4986 	  if (nt != NULL)
4987 	    {
4988 	      if ((*p)->implements_interface(Type::make_pointer_type(nt),
4989 					     NULL))
4990 		{
4991 		  nt->interface_method_table(*p, false)->get_backend(&context);
4992                   nt->interface_method_table(*p, true)->get_backend(&context);
4993 		}
4994 	    }
4995 	  else
4996 	    {
4997 	      if ((*p)->implements_interface(Type::make_pointer_type(st),
4998 					     NULL))
4999 		{
5000 		  st->interface_method_table(*p, false)->get_backend(&context);
5001 		  st->interface_method_table(*p, true)->get_backend(&context);
5002 		}
5003 	    }
5004 	}
5005     }
5006   return TRAVERSE_CONTINUE;
5007 }
5008 
5009 // Return an expression which allocates memory to hold values of type TYPE.
5010 
5011 Expression*
allocate_memory(Type * type,Location location)5012 Gogo::allocate_memory(Type* type, Location location)
5013 {
5014   Expression* td = Expression::make_type_descriptor(type, location);
5015   return Runtime::make_call(Runtime::NEW, location, 1, td);
5016 }
5017 
5018 // Traversal class used to check for return statements.
5019 
5020 class Check_return_statements_traverse : public Traverse
5021 {
5022  public:
Check_return_statements_traverse()5023   Check_return_statements_traverse()
5024     : Traverse(traverse_functions)
5025   { }
5026 
5027   int
5028   function(Named_object*);
5029 };
5030 
5031 // Check that a function has a return statement if it needs one.
5032 
5033 int
function(Named_object * no)5034 Check_return_statements_traverse::function(Named_object* no)
5035 {
5036   Function* func = no->func_value();
5037   const Function_type* fntype = func->type();
5038   const Typed_identifier_list* results = fntype->results();
5039 
5040   // We only need a return statement if there is a return value.
5041   if (results == NULL || results->empty())
5042     return TRAVERSE_CONTINUE;
5043 
5044   if (func->block()->may_fall_through())
5045     go_error_at(func->block()->end_location(),
5046 		"missing return at end of function");
5047 
5048   return TRAVERSE_CONTINUE;
5049 }
5050 
5051 // Check return statements.
5052 
5053 void
check_return_statements()5054 Gogo::check_return_statements()
5055 {
5056   Check_return_statements_traverse traverse;
5057   this->traverse(&traverse);
5058 }
5059 
5060 // Traversal class to decide whether a function body is less than the
5061 // inlining budget.  This adjusts *available as it goes, and stops the
5062 // traversal if it goes negative.
5063 
5064 class Inline_within_budget : public Traverse
5065 {
5066  public:
Inline_within_budget(int * available)5067   Inline_within_budget(int* available)
5068     : Traverse(traverse_statements
5069 	       | traverse_expressions),
5070       available_(available)
5071   { }
5072 
5073   int
5074   statement(Block*, size_t*, Statement*);
5075 
5076   int
5077   expression(Expression**);
5078 
5079  private:
5080   // Pointer to remaining budget.
5081   int* available_;
5082 };
5083 
5084 // Adjust the budget for the inlining cost of a statement.
5085 
5086 int
statement(Block *,size_t *,Statement * s)5087 Inline_within_budget::statement(Block*, size_t*, Statement* s)
5088 {
5089   if (*this->available_ < 0)
5090     return TRAVERSE_EXIT;
5091   *this->available_ -= s->inlining_cost();
5092   return TRAVERSE_CONTINUE;
5093 }
5094 
5095 // Adjust the budget for the inlining cost of an expression.
5096 
5097 int
expression(Expression ** pexpr)5098 Inline_within_budget::expression(Expression** pexpr)
5099 {
5100   if (*this->available_ < 0)
5101     return TRAVERSE_EXIT;
5102   *this->available_ -= (*pexpr)->inlining_cost();
5103   return TRAVERSE_CONTINUE;
5104 }
5105 
5106 // Traversal class to find functions whose body should be exported for
5107 // inlining by other packages.
5108 
5109 class Mark_inline_candidates : public Traverse
5110 {
5111  public:
Mark_inline_candidates(Unordered_set (Named_object *)* marked)5112   Mark_inline_candidates(Unordered_set(Named_object*)* marked)
5113     : Traverse(traverse_functions
5114 	       | traverse_types),
5115       marked_functions_(marked)
5116   { }
5117 
5118   int
5119   function(Named_object*);
5120 
5121   int
5122   type(Type*);
5123 
5124  private:
5125   // We traverse the function body trying to determine how expensive
5126   // it is for inlining.  We start with a budget, and decrease that
5127   // budget for each statement and expression.  If the budget goes
5128   // negative, we do not export the function body.  The value of this
5129   // budget is a heuristic.  In the usual GCC spirit, we could
5130   // consider setting this via a command line option.
5131   const int budget_heuristic = 80;
5132 
5133   // Set of named objects that are marked as inline candidates.
5134   Unordered_set(Named_object*)* marked_functions_;
5135 };
5136 
5137 // Mark a function if it is an inline candidate.
5138 
5139 int
function(Named_object * no)5140 Mark_inline_candidates::function(Named_object* no)
5141 {
5142   Function* func = no->func_value();
5143   if ((func->pragmas() & GOPRAGMA_NOINLINE) != 0)
5144     return TRAVERSE_CONTINUE;
5145   int budget = budget_heuristic;
5146   Inline_within_budget iwb(&budget);
5147   func->block()->traverse(&iwb);
5148   if (budget >= 0)
5149     {
5150       func->set_export_for_inlining();
5151       this->marked_functions_->insert(no);
5152     }
5153   return TRAVERSE_CONTINUE;
5154 }
5155 
5156 // Mark methods if they are inline candidates.
5157 
5158 int
type(Type * t)5159 Mark_inline_candidates::type(Type* t)
5160 {
5161   Named_type* nt = t->named_type();
5162   if (nt == NULL || nt->is_alias())
5163     return TRAVERSE_CONTINUE;
5164   const Bindings* methods = nt->local_methods();
5165   if (methods == NULL)
5166     return TRAVERSE_CONTINUE;
5167   for (Bindings::const_definitions_iterator p = methods->begin_definitions();
5168        p != methods->end_definitions();
5169        ++p)
5170     {
5171       Named_object* no = *p;
5172       go_assert(no->is_function());
5173       Function *func = no->func_value();
5174       if ((func->pragmas() & GOPRAGMA_NOINLINE) != 0)
5175         continue;
5176       int budget = budget_heuristic;
5177       Inline_within_budget iwb(&budget);
5178       func->block()->traverse(&iwb);
5179       if (budget >= 0)
5180         {
5181           func->set_export_for_inlining();
5182           this->marked_functions_->insert(no);
5183         }
5184     }
5185   return TRAVERSE_CONTINUE;
5186 }
5187 
5188 // Export identifiers as requested.
5189 
5190 void
do_exports()5191 Gogo::do_exports()
5192 {
5193   if (saw_errors())
5194     return;
5195 
5196   // Mark any functions whose body should be exported for inlining by
5197   // other packages.
5198   Unordered_set(Named_object*) marked_functions;
5199   Mark_inline_candidates mic(&marked_functions);
5200   this->traverse(&mic);
5201 
5202   // For now we always stream to a section.  Later we may want to
5203   // support streaming to a separate file.
5204   Stream_to_section stream(this->backend());
5205 
5206   // Write out either the prefix or pkgpath depending on how we were
5207   // invoked.
5208   std::string prefix;
5209   std::string pkgpath;
5210   if (this->pkgpath_from_option_)
5211     pkgpath = this->pkgpath_;
5212   else if (this->prefix_from_option_)
5213     prefix = this->prefix_;
5214   else if (this->is_main_package())
5215     pkgpath = "main";
5216   else
5217     prefix = "go";
5218 
5219   std::string init_fn_name;
5220   if (this->is_main_package())
5221     init_fn_name = "";
5222   else if (this->need_init_fn_)
5223     init_fn_name = this->get_init_fn_name();
5224   else
5225     init_fn_name = this->dummy_init_fn_name();
5226 
5227   Export exp(&stream);
5228   exp.register_builtin_types(this);
5229   exp.export_globals(this->package_name(),
5230 		     prefix,
5231 		     pkgpath,
5232 		     this->packages_,
5233 		     this->imports_,
5234 		     init_fn_name,
5235 		     this->imported_init_fns_,
5236 		     this->package_->bindings(),
5237                      &marked_functions);
5238 
5239   if (!this->c_header_.empty() && !saw_errors())
5240     this->write_c_header();
5241 }
5242 
5243 // Write the top level named struct types in C format to a C header
5244 // file.  This is used when building the runtime package, to share
5245 // struct definitions between C and Go.
5246 
5247 void
write_c_header()5248 Gogo::write_c_header()
5249 {
5250   std::ofstream out;
5251   out.open(this->c_header_.c_str());
5252   if (out.fail())
5253     {
5254       go_error_at(Linemap::unknown_location(),
5255 		  "cannot open %s: %m", this->c_header_.c_str());
5256       return;
5257     }
5258 
5259   std::list<Named_object*> types;
5260   Bindings* top = this->package_->bindings();
5261   for (Bindings::const_definitions_iterator p = top->begin_definitions();
5262        p != top->end_definitions();
5263        ++p)
5264     {
5265       Named_object* no = *p;
5266 
5267       // Skip names that start with underscore followed by something
5268       // other than an uppercase letter, as when compiling the runtime
5269       // package they are mostly types defined by mkrsysinfo.sh based
5270       // on the C system header files.  We don't need to translate
5271       // types to C and back to Go.  But do accept the special cases
5272       // _defer, _panic, and _type.
5273       std::string name = Gogo::unpack_hidden_name(no->name());
5274       if (name[0] == '_'
5275 	  && (name[1] < 'A' || name[1] > 'Z')
5276 	  && (name != "_defer" && name != "_panic" && name != "_type"))
5277 	continue;
5278 
5279       if (no->is_type() && no->type_value()->struct_type() != NULL)
5280 	types.push_back(no);
5281       if (no->is_const()
5282 	  && no->const_value()->type()->integer_type() != NULL
5283 	  && !no->const_value()->is_sink())
5284 	{
5285 	  Numeric_constant nc;
5286 	  unsigned long val;
5287 	  if (no->const_value()->expr()->numeric_constant_value(&nc)
5288 	      && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
5289 	    {
5290 	      out << "#define " << no->message_name() << ' ' << val
5291 		  << std::endl;
5292 	    }
5293 	}
5294     }
5295 
5296   std::vector<const Named_object*> written;
5297   int loop = 0;
5298   while (!types.empty())
5299     {
5300       Named_object* no = types.front();
5301       types.pop_front();
5302 
5303       std::vector<const Named_object*> requires;
5304       std::vector<const Named_object*> declare;
5305       if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
5306 								  &declare))
5307 	continue;
5308 
5309       bool ok = true;
5310       for (std::vector<const Named_object*>::const_iterator pr
5311 	     = requires.begin();
5312 	   pr != requires.end() && ok;
5313 	   ++pr)
5314 	{
5315 	  for (std::list<Named_object*>::const_iterator pt = types.begin();
5316 	       pt != types.end() && ok;
5317 	       ++pt)
5318 	    if (*pr == *pt)
5319 	      ok = false;
5320 	}
5321       if (!ok)
5322 	{
5323 	  ++loop;
5324 	  if (loop > 10000)
5325 	    {
5326 	      // This should be impossible since the code parsed and
5327 	      // type checked.
5328 	      go_unreachable();
5329 	    }
5330 
5331 	  types.push_back(no);
5332 	  continue;
5333 	}
5334 
5335       for (std::vector<const Named_object*>::const_iterator pd
5336 	     = declare.begin();
5337 	   pd != declare.end();
5338 	   ++pd)
5339 	{
5340 	  if (*pd == no)
5341 	    continue;
5342 
5343 	  std::vector<const Named_object*> drequires;
5344 	  std::vector<const Named_object*> ddeclare;
5345 	  if (!(*pd)->type_value()->struct_type()->
5346 	      can_write_to_c_header(&drequires, &ddeclare))
5347 	    continue;
5348 
5349 	  bool done = false;
5350 	  for (std::vector<const Named_object*>::const_iterator pw
5351 		 = written.begin();
5352 	       pw != written.end();
5353 	       ++pw)
5354 	    {
5355 	      if (*pw == *pd)
5356 		{
5357 		  done = true;
5358 		  break;
5359 		}
5360 	    }
5361 	  if (!done)
5362 	    {
5363 	      out << std::endl;
5364 	      out << "struct " << (*pd)->message_name() << ";" << std::endl;
5365 	      written.push_back(*pd);
5366 	    }
5367 	}
5368 
5369       out << std::endl;
5370       out << "struct " << no->message_name() << " {" << std::endl;
5371       no->type_value()->struct_type()->write_to_c_header(out);
5372       out << "};" << std::endl;
5373       written.push_back(no);
5374     }
5375 
5376   out.close();
5377   if (out.fail())
5378     go_error_at(Linemap::unknown_location(),
5379 		"error writing to %s: %m", this->c_header_.c_str());
5380 }
5381 
5382 // Find the blocks in order to convert named types defined in blocks.
5383 
5384 class Convert_named_types : public Traverse
5385 {
5386  public:
Convert_named_types(Gogo * gogo)5387   Convert_named_types(Gogo* gogo)
5388     : Traverse(traverse_blocks),
5389       gogo_(gogo)
5390   { }
5391 
5392  protected:
5393   int
5394   block(Block* block);
5395 
5396  private:
5397   Gogo* gogo_;
5398 };
5399 
5400 int
block(Block * block)5401 Convert_named_types::block(Block* block)
5402 {
5403   this->gogo_->convert_named_types_in_bindings(block->bindings());
5404   return TRAVERSE_CONTINUE;
5405 }
5406 
5407 // Convert all named types to the backend representation.  Since named
5408 // types can refer to other types, this needs to be done in the right
5409 // sequence, which is handled by Named_type::convert.  Here we arrange
5410 // to call that for each named type.
5411 
5412 void
convert_named_types()5413 Gogo::convert_named_types()
5414 {
5415   this->convert_named_types_in_bindings(this->globals_);
5416   for (Packages::iterator p = this->packages_.begin();
5417        p != this->packages_.end();
5418        ++p)
5419     {
5420       Package* package = p->second;
5421       this->convert_named_types_in_bindings(package->bindings());
5422     }
5423 
5424   Convert_named_types cnt(this);
5425   this->traverse(&cnt);
5426 
5427   // Make all the builtin named types used for type descriptors, and
5428   // then convert them.  They will only be written out if they are
5429   // needed.
5430   Type::make_type_descriptor_type();
5431   Type::make_type_descriptor_ptr_type();
5432   Function_type::make_function_type_descriptor_type();
5433   Pointer_type::make_pointer_type_descriptor_type();
5434   Struct_type::make_struct_type_descriptor_type();
5435   Array_type::make_array_type_descriptor_type();
5436   Array_type::make_slice_type_descriptor_type();
5437   Map_type::make_map_type_descriptor_type();
5438   Channel_type::make_chan_type_descriptor_type();
5439   Interface_type::make_interface_type_descriptor_type();
5440   Expression::make_func_descriptor_type();
5441   Type::convert_builtin_named_types(this);
5442 
5443   Runtime::convert_types(this);
5444 
5445   this->named_types_are_converted_ = true;
5446 
5447   Type::finish_pointer_types(this);
5448 }
5449 
5450 // Convert all names types in a set of bindings.
5451 
5452 void
convert_named_types_in_bindings(Bindings * bindings)5453 Gogo::convert_named_types_in_bindings(Bindings* bindings)
5454 {
5455   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5456        p != bindings->end_definitions();
5457        ++p)
5458     {
5459       if ((*p)->is_type())
5460 	(*p)->type_value()->convert(this);
5461     }
5462 }
5463 
5464 void
debug_go_gogo(Gogo * gogo)5465 debug_go_gogo(Gogo* gogo)
5466 {
5467   if (gogo != NULL)
5468     gogo->debug_dump();
5469 }
5470 
5471 void
debug_dump()5472 Gogo::debug_dump()
5473 {
5474   std::cerr << "Packages:\n";
5475   for (Packages::const_iterator p = this->packages_.begin();
5476        p != this->packages_.end();
5477        ++p)
5478     {
5479       const char *tag = "  ";
5480       if (p->second == this->package_)
5481         tag = "* ";
5482       std::cerr << tag << "'" << p->first << "' "
5483                 << p->second->pkgpath() << " " << ((void*)p->second) << "\n";
5484     }
5485 }
5486 
5487 // Class Function.
5488 
Function(Function_type * type,Named_object * enclosing,Block * block,Location location)5489 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
5490 		   Location location)
5491   : type_(type), enclosing_(enclosing), results_(NULL),
5492     closure_var_(NULL), block_(block), location_(location), labels_(),
5493     local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
5494     pragmas_(0), nested_functions_(0), is_sink_(false),
5495     results_are_named_(false), is_unnamed_type_stub_method_(false),
5496     calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5497     calls_defer_retaddr_(false), is_type_specific_function_(false),
5498     in_unique_section_(false), export_for_inlining_(false),
5499     is_inline_only_(false), is_referenced_by_inline_(false),
5500     is_exported_by_linkname_(false)
5501 {
5502 }
5503 
5504 // Create the named result variables.
5505 
5506 void
create_result_variables(Gogo * gogo)5507 Function::create_result_variables(Gogo* gogo)
5508 {
5509   const Typed_identifier_list* results = this->type_->results();
5510   if (results == NULL || results->empty())
5511     return;
5512 
5513   if (!results->front().name().empty())
5514     this->results_are_named_ = true;
5515 
5516   this->results_ = new Results();
5517   this->results_->reserve(results->size());
5518 
5519   Block* block = this->block_;
5520   int index = 0;
5521   for (Typed_identifier_list::const_iterator p = results->begin();
5522        p != results->end();
5523        ++p, ++index)
5524     {
5525       std::string name = p->name();
5526       if (name.empty() || Gogo::is_sink_name(name))
5527 	{
5528 	  static int result_counter;
5529 	  char buf[100];
5530 	  snprintf(buf, sizeof buf, "$ret%d", result_counter);
5531 	  ++result_counter;
5532 	  name = gogo->pack_hidden_name(buf, false);
5533 	}
5534       Result_variable* result = new Result_variable(p->type(), this, index,
5535 						    p->location());
5536       Named_object* no = block->bindings()->add_result_variable(name, result);
5537       if (no->is_result_variable())
5538 	this->results_->push_back(no);
5539       else
5540 	{
5541 	  static int dummy_result_count;
5542 	  char buf[100];
5543 	  snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
5544 	  ++dummy_result_count;
5545 	  name = gogo->pack_hidden_name(buf, false);
5546 	  no = block->bindings()->add_result_variable(name, result);
5547 	  go_assert(no->is_result_variable());
5548 	  this->results_->push_back(no);
5549 	}
5550     }
5551 }
5552 
5553 // Update the named result variables when cloning a function which
5554 // calls recover.
5555 
5556 void
update_result_variables()5557 Function::update_result_variables()
5558 {
5559   if (this->results_ == NULL)
5560     return;
5561 
5562   for (Results::iterator p = this->results_->begin();
5563        p != this->results_->end();
5564        ++p)
5565     (*p)->result_var_value()->set_function(this);
5566 }
5567 
5568 // Whether this method should not be included in the type descriptor.
5569 
5570 bool
nointerface() const5571 Function::nointerface() const
5572 {
5573   go_assert(this->is_method());
5574   return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
5575 }
5576 
5577 // Record that this method should not be included in the type
5578 // descriptor.
5579 
5580 void
set_nointerface()5581 Function::set_nointerface()
5582 {
5583   this->pragmas_ |= GOPRAGMA_NOINTERFACE;
5584 }
5585 
5586 // Return the closure variable, creating it if necessary.
5587 
5588 Named_object*
closure_var()5589 Function::closure_var()
5590 {
5591   if (this->closure_var_ == NULL)
5592     {
5593       go_assert(this->descriptor_ == NULL);
5594       // We don't know the type of the variable yet.  We add fields as
5595       // we find them.
5596       Location loc = this->type_->location();
5597       Struct_field_list* sfl = new Struct_field_list;
5598       Struct_type* struct_type = Type::make_struct_type(sfl, loc);
5599       struct_type->set_is_struct_incomparable();
5600       Variable* var = new Variable(Type::make_pointer_type(struct_type),
5601 				   NULL, false, false, false, loc);
5602       var->set_is_used();
5603       var->set_is_closure();
5604       this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
5605       // Note that the new variable is not in any binding contour.
5606     }
5607   return this->closure_var_;
5608 }
5609 
5610 // Set the type of the closure variable.
5611 
5612 void
set_closure_type()5613 Function::set_closure_type()
5614 {
5615   if (this->closure_var_ == NULL)
5616     return;
5617   Named_object* closure = this->closure_var_;
5618   Struct_type* st = closure->var_value()->type()->deref()->struct_type();
5619 
5620   // The first field of a closure is always a pointer to the function
5621   // code.
5622   Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
5623   st->push_field(Struct_field(Typed_identifier(".f", voidptr_type,
5624 					       this->location_)));
5625 
5626   unsigned int index = 1;
5627   for (Closure_fields::const_iterator p = this->closure_fields_.begin();
5628        p != this->closure_fields_.end();
5629        ++p, ++index)
5630     {
5631       Named_object* no = p->first;
5632       char buf[20];
5633       snprintf(buf, sizeof buf, "%u", index);
5634       std::string n = no->name() + buf;
5635       Type* var_type;
5636       if (no->is_variable())
5637 	var_type = no->var_value()->type();
5638       else
5639 	var_type = no->result_var_value()->type();
5640       Type* field_type = Type::make_pointer_type(var_type);
5641       st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
5642     }
5643 }
5644 
5645 // Return whether this function is a method.
5646 
5647 bool
is_method() const5648 Function::is_method() const
5649 {
5650   return this->type_->is_method();
5651 }
5652 
5653 // Add a label definition.
5654 
5655 Label*
add_label_definition(Gogo * gogo,const std::string & label_name,Location location)5656 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
5657 			       Location location)
5658 {
5659   Label* lnull = NULL;
5660   std::pair<Labels::iterator, bool> ins =
5661     this->labels_.insert(std::make_pair(label_name, lnull));
5662   Label* label;
5663   if (label_name == "_")
5664     {
5665       label = Label::create_dummy_label();
5666       if (ins.second)
5667 	ins.first->second = label;
5668     }
5669   else if (ins.second)
5670     {
5671       // This is a new label.
5672       label = new Label(label_name);
5673       ins.first->second = label;
5674     }
5675   else
5676     {
5677       // The label was already in the hash table.
5678       label = ins.first->second;
5679       if (label->is_defined())
5680 	{
5681 	  go_error_at(location, "label %qs already defined",
5682 		      Gogo::message_name(label_name).c_str());
5683 	  go_inform(label->location(), "previous definition of %qs was here",
5684 		    Gogo::message_name(label_name).c_str());
5685 	  return new Label(label_name);
5686 	}
5687     }
5688 
5689   label->define(location, gogo->bindings_snapshot(location));
5690 
5691   // Issue any errors appropriate for any previous goto's to this
5692   // label.
5693   const std::vector<Bindings_snapshot*>& refs(label->refs());
5694   for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
5695        p != refs.end();
5696        ++p)
5697     (*p)->check_goto_to(gogo->current_block());
5698   label->clear_refs();
5699 
5700   return label;
5701 }
5702 
5703 // Add a reference to a label.
5704 
5705 Label*
add_label_reference(Gogo * gogo,const std::string & label_name,Location location,bool issue_goto_errors)5706 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5707 			      Location location, bool issue_goto_errors)
5708 {
5709   Label* lnull = NULL;
5710   std::pair<Labels::iterator, bool> ins =
5711     this->labels_.insert(std::make_pair(label_name, lnull));
5712   Label* label;
5713   if (!ins.second)
5714     {
5715       // The label was already in the hash table.
5716       label = ins.first->second;
5717     }
5718   else
5719     {
5720       go_assert(ins.first->second == NULL);
5721       label = new Label(label_name);
5722       ins.first->second = label;
5723     }
5724 
5725   label->set_is_used();
5726 
5727   if (issue_goto_errors)
5728     {
5729       Bindings_snapshot* snapshot = label->snapshot();
5730       if (snapshot != NULL)
5731 	snapshot->check_goto_from(gogo->current_block(), location);
5732       else
5733 	label->add_snapshot_ref(gogo->bindings_snapshot(location));
5734     }
5735 
5736   return label;
5737 }
5738 
5739 // Warn about labels that are defined but not used.
5740 
5741 void
check_labels() const5742 Function::check_labels() const
5743 {
5744   for (Labels::const_iterator p = this->labels_.begin();
5745        p != this->labels_.end();
5746        p++)
5747     {
5748       Label* label = p->second;
5749       if (!label->is_used())
5750 	go_error_at(label->location(), "label %qs defined and not used",
5751 		    Gogo::message_name(label->name()).c_str());
5752     }
5753 }
5754 
5755 // Swap one function with another.  This is used when building the
5756 // thunk we use to call a function which calls recover.  It may not
5757 // work for any other case.
5758 
5759 void
swap_for_recover(Function * x)5760 Function::swap_for_recover(Function *x)
5761 {
5762   go_assert(this->enclosing_ == x->enclosing_);
5763   std::swap(this->results_, x->results_);
5764   std::swap(this->closure_var_, x->closure_var_);
5765   std::swap(this->block_, x->block_);
5766   go_assert(this->location_ == x->location_);
5767   go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5768   go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5769 }
5770 
5771 // Traverse the tree.
5772 
5773 int
traverse(Traverse * traverse)5774 Function::traverse(Traverse* traverse)
5775 {
5776   unsigned int traverse_mask = traverse->traverse_mask();
5777 
5778   if ((traverse_mask
5779        & (Traverse::traverse_types | Traverse::traverse_expressions))
5780       != 0)
5781     {
5782       if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5783 	return TRAVERSE_EXIT;
5784     }
5785 
5786   // FIXME: We should check traverse_functions here if nested
5787   // functions are stored in block bindings.
5788   if (this->block_ != NULL
5789       && (traverse_mask
5790 	  & (Traverse::traverse_variables
5791 	     | Traverse::traverse_constants
5792 	     | Traverse::traverse_blocks
5793 	     | Traverse::traverse_statements
5794 	     | Traverse::traverse_expressions
5795 	     | Traverse::traverse_types)) != 0)
5796     {
5797       if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5798 	return TRAVERSE_EXIT;
5799     }
5800 
5801   return TRAVERSE_CONTINUE;
5802 }
5803 
5804 // Work out types for unspecified variables and constants.
5805 
5806 void
determine_types()5807 Function::determine_types()
5808 {
5809   if (this->block_ != NULL)
5810     this->block_->determine_types();
5811 }
5812 
5813 // Return the function descriptor, the value you get when you refer to
5814 // the function in Go code without calling it.
5815 
5816 Expression*
descriptor(Gogo *,Named_object * no)5817 Function::descriptor(Gogo*, Named_object* no)
5818 {
5819   go_assert(!this->is_method());
5820   go_assert(this->closure_var_ == NULL);
5821   if (this->descriptor_ == NULL)
5822     this->descriptor_ = Expression::make_func_descriptor(no);
5823   return this->descriptor_;
5824 }
5825 
5826 // Get a pointer to the variable representing the defer stack for this
5827 // function, making it if necessary.  The value of the variable is set
5828 // by the runtime routines to true if the function is returning,
5829 // rather than panicing through.  A pointer to this variable is used
5830 // as a marker for the functions on the defer stack associated with
5831 // this function.  A function-specific variable permits inlining a
5832 // function which uses defer.
5833 
5834 Expression*
defer_stack(Location location)5835 Function::defer_stack(Location location)
5836 {
5837   if (this->defer_stack_ == NULL)
5838     {
5839       Type* t = Type::lookup_bool_type();
5840       Expression* n = Expression::make_boolean(false, location);
5841       this->defer_stack_ = Statement::make_temporary(t, n, location);
5842       this->defer_stack_->set_is_address_taken();
5843     }
5844   Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5845 							 location);
5846   return Expression::make_unary(OPERATOR_AND, ref, location);
5847 }
5848 
5849 // Export the function.
5850 
5851 void
export_func(Export * exp,const Named_object * no) const5852 Function::export_func(Export* exp, const Named_object* no) const
5853 {
5854   Block* block = NULL;
5855   if (this->export_for_inlining())
5856     block = this->block_;
5857   Function::export_func_with_type(exp, no, this->type_, this->results_,
5858 				  this->is_method() && this->nointerface(),
5859 				  this->asm_name(), block, this->location_);
5860 }
5861 
5862 // Export a function with a type.
5863 
5864 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)5865 Function::export_func_with_type(Export* exp, const Named_object* no,
5866 				const Function_type* fntype,
5867 				Function::Results* result_vars,
5868 				bool nointerface, const std::string& asm_name,
5869 				Block* block, Location loc)
5870 {
5871   exp->write_c_string("func ");
5872 
5873   if (nointerface)
5874     {
5875       go_assert(fntype->is_method());
5876       exp->write_c_string("/*nointerface*/ ");
5877     }
5878 
5879   if (!asm_name.empty())
5880     {
5881       exp->write_c_string("/*asm ");
5882       exp->write_string(asm_name);
5883       exp->write_c_string(" */ ");
5884     }
5885 
5886   if (fntype->is_method())
5887     {
5888       exp->write_c_string("(");
5889       const Typed_identifier* receiver = fntype->receiver();
5890       exp->write_name(receiver->name());
5891       exp->write_escape(receiver->note());
5892       exp->write_c_string(" ");
5893       exp->write_type(receiver->type());
5894       exp->write_c_string(") ");
5895     }
5896 
5897   if (no->package() != NULL && !fntype->is_method())
5898     {
5899       char buf[50];
5900       snprintf(buf, sizeof buf, "<p%d>", exp->package_index(no->package()));
5901       exp->write_c_string(buf);
5902     }
5903 
5904   const std::string& name(no->name());
5905   if (!Gogo::is_hidden_name(name))
5906     exp->write_string(name);
5907   else
5908     {
5909       exp->write_c_string(".");
5910       exp->write_string(Gogo::unpack_hidden_name(name));
5911     }
5912 
5913   exp->write_c_string(" (");
5914   const Typed_identifier_list* parameters = fntype->parameters();
5915   if (parameters != NULL)
5916     {
5917       size_t i = 0;
5918       bool is_varargs = fntype->is_varargs();
5919       bool first = true;
5920       for (Typed_identifier_list::const_iterator p = parameters->begin();
5921 	   p != parameters->end();
5922 	   ++p, ++i)
5923 	{
5924 	  if (first)
5925 	    first = false;
5926 	  else
5927 	    exp->write_c_string(", ");
5928 	  exp->write_name(p->name());
5929 	  exp->write_escape(p->note());
5930 	  exp->write_c_string(" ");
5931 	  if (!is_varargs || p + 1 != parameters->end())
5932 	    exp->write_type(p->type());
5933 	  else
5934 	    {
5935 	      exp->write_c_string("...");
5936 	      exp->write_type(p->type()->array_type()->element_type());
5937 	    }
5938 	}
5939     }
5940   exp->write_c_string(")");
5941 
5942   const Typed_identifier_list* result_decls = fntype->results();
5943   if (result_decls != NULL)
5944     {
5945       if (result_decls->size() == 1
5946 	  && result_decls->begin()->name().empty()
5947 	  && block == NULL)
5948 	{
5949 	  exp->write_c_string(" ");
5950 	  exp->write_type(result_decls->begin()->type());
5951 	}
5952       else
5953 	{
5954 	  exp->write_c_string(" (");
5955 	  bool first = true;
5956 	  Results::const_iterator pr;
5957 	  if (result_vars != NULL)
5958 	    pr = result_vars->begin();
5959 	  for (Typed_identifier_list::const_iterator pd = result_decls->begin();
5960 	       pd != result_decls->end();
5961 	       ++pd)
5962 	    {
5963 	      if (first)
5964 		first = false;
5965 	      else
5966 		exp->write_c_string(", ");
5967 	      // We only use pr->name, which may be artificial, if
5968 	      // need it for inlining.
5969 	      if (block == NULL || result_vars == NULL)
5970 		exp->write_name(pd->name());
5971 	      else
5972 		exp->write_name((*pr)->name());
5973 	      exp->write_escape(pd->note());
5974 	      exp->write_c_string(" ");
5975 	      exp->write_type(pd->type());
5976 	      if (result_vars != NULL)
5977 		++pr;
5978 	    }
5979 	  if (result_vars != NULL)
5980 	    go_assert(pr == result_vars->end());
5981 	  exp->write_c_string(")");
5982 	}
5983     }
5984 
5985   if (block == NULL)
5986     exp->write_c_string("\n");
5987   else
5988     {
5989       int indent = 1;
5990       if (fntype->is_method())
5991 	indent++;
5992 
5993       Export_function_body efb(exp, indent);
5994 
5995       efb.indent();
5996       efb.write_c_string("// ");
5997       efb.write_string(Linemap::location_to_file(block->start_location()));
5998       efb.write_char(':');
5999       char buf[100];
6000       snprintf(buf, sizeof buf, "%d", Linemap::location_to_line(loc));
6001       efb.write_c_string(buf);
6002       efb.write_char('\n');
6003       block->export_block(&efb);
6004 
6005       const std::string& body(efb.body());
6006 
6007       snprintf(buf, sizeof buf, " <inl:%lu>\n",
6008 	       static_cast<unsigned long>(body.length()));
6009       exp->write_c_string(buf);
6010 
6011       exp->write_string(body);
6012     }
6013 }
6014 
6015 // Import a function.
6016 
6017 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)6018 Function::import_func(Import* imp, std::string* pname,
6019 		      Package** ppkg, bool* pis_exported,
6020 		      Typed_identifier** preceiver,
6021 		      Typed_identifier_list** pparameters,
6022 		      Typed_identifier_list** presults,
6023 		      bool* is_varargs,
6024 		      bool* nointerface,
6025 		      std::string* asm_name,
6026 		      std::string* body)
6027 {
6028   imp->require_c_string("func ");
6029 
6030   *nointerface = false;
6031   while (imp->match_c_string("/*"))
6032     {
6033       imp->advance(2);
6034       if (imp->match_c_string("nointerface"))
6035 	{
6036 	  imp->require_c_string("nointerface*/ ");
6037 	  *nointerface = true;
6038 	}
6039       else if (imp->match_c_string("asm"))
6040 	{
6041 	  imp->require_c_string("asm ");
6042 	  *asm_name = imp->read_identifier();
6043 	  imp->require_c_string(" */ ");
6044 	}
6045       else
6046 	{
6047 	  go_error_at(imp->location(),
6048 		      "import error at %d: unrecognized function comment",
6049 		      imp->pos());
6050 	  return false;
6051 	}
6052     }
6053 
6054   if (*nointerface)
6055     {
6056       // Only a method can be nointerface.
6057       go_assert(imp->peek_char() == '(');
6058     }
6059 
6060   *preceiver = NULL;
6061   if (imp->peek_char() == '(')
6062     {
6063       imp->require_c_string("(");
6064       std::string name = imp->read_name();
6065       std::string escape_note = imp->read_escape();
6066       imp->require_c_string(" ");
6067       Type* rtype = imp->read_type();
6068       *preceiver = new Typed_identifier(name, rtype, imp->location());
6069       (*preceiver)->set_note(escape_note);
6070       imp->require_c_string(") ");
6071     }
6072 
6073   if (!Import::read_qualified_identifier(imp, pname, ppkg, pis_exported))
6074     {
6075       go_error_at(imp->location(),
6076 		  "import error at %d: bad function name in export data",
6077 		  imp->pos());
6078       return false;
6079     }
6080 
6081   Typed_identifier_list* parameters;
6082   *is_varargs = false;
6083   imp->require_c_string(" (");
6084   if (imp->peek_char() == ')')
6085     parameters = NULL;
6086   else
6087     {
6088       parameters = new Typed_identifier_list();
6089       while (true)
6090 	{
6091 	  std::string name = imp->read_name();
6092 	  std::string escape_note = imp->read_escape();
6093 	  imp->require_c_string(" ");
6094 
6095 	  if (imp->match_c_string("..."))
6096 	    {
6097 	      imp->advance(3);
6098 	      *is_varargs = true;
6099 	    }
6100 
6101 	  Type* ptype = imp->read_type();
6102 	  if (*is_varargs)
6103 	    ptype = Type::make_array_type(ptype, NULL);
6104 	  Typed_identifier t = Typed_identifier(name, ptype, imp->location());
6105 	  t.set_note(escape_note);
6106 	  parameters->push_back(t);
6107 	  if (imp->peek_char() != ',')
6108 	    break;
6109 	  go_assert(!*is_varargs);
6110 	  imp->require_c_string(", ");
6111 	}
6112     }
6113   imp->require_c_string(")");
6114   *pparameters = parameters;
6115 
6116   Typed_identifier_list* results;
6117   if (imp->peek_char() != ' ' || imp->match_c_string(" <inl"))
6118     results = NULL;
6119   else
6120     {
6121       results = new Typed_identifier_list();
6122       imp->require_c_string(" ");
6123       if (imp->peek_char() != '(')
6124 	{
6125 	  Type* rtype = imp->read_type();
6126 	  results->push_back(Typed_identifier("", rtype, imp->location()));
6127 	}
6128       else
6129 	{
6130 	  imp->require_c_string("(");
6131 	  while (true)
6132 	    {
6133 	      std::string name = imp->read_name();
6134 	      std::string note = imp->read_escape();
6135 	      imp->require_c_string(" ");
6136 	      Type* rtype = imp->read_type();
6137 	      Typed_identifier t = Typed_identifier(name, rtype,
6138 						    imp->location());
6139 	      t.set_note(note);
6140 	      results->push_back(t);
6141 	      if (imp->peek_char() != ',')
6142 		break;
6143 	      imp->require_c_string(", ");
6144 	    }
6145 	  imp->require_c_string(")");
6146 	}
6147     }
6148   *presults = results;
6149 
6150   if (!imp->match_c_string(" <inl:"))
6151     {
6152       imp->require_semicolon_if_old_version();
6153       imp->require_c_string("\n");
6154       body->clear();
6155     }
6156   else
6157     {
6158       imp->require_c_string(" <inl:");
6159       std::string lenstr;
6160       int c;
6161       while (true)
6162 	{
6163 	  c = imp->peek_char();
6164 	  if (c < '0' || c > '9')
6165 	    break;
6166 	  lenstr += c;
6167 	  imp->get_char();
6168 	}
6169       imp->require_c_string(">\n");
6170 
6171       errno = 0;
6172       char* end;
6173       long llen = strtol(lenstr.c_str(), &end, 10);
6174       if (*end != '\0'
6175 	  || llen < 0
6176 	  || (llen == LONG_MAX && errno == ERANGE))
6177 	{
6178 	  go_error_at(imp->location(), "invalid inline function length %s",
6179 		      lenstr.c_str());
6180 	  return false;
6181 	}
6182 
6183       *body = imp->read(static_cast<size_t>(llen));
6184     }
6185 
6186   return true;
6187 }
6188 
6189 // Get the backend representation.
6190 
6191 Bfunction*
get_or_make_decl(Gogo * gogo,Named_object * no)6192 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
6193 {
6194   if (this->fndecl_ == NULL)
6195     {
6196       unsigned int flags = 0;
6197       bool is_init_fn = false;
6198       if (no->package() != NULL)
6199 	{
6200 	  // Functions defined in other packages must be visible.
6201 	  flags |= Backend::function_is_visible;
6202 	}
6203       else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
6204         ;
6205       else if (Gogo::unpack_hidden_name(no->name()) == "init"
6206                && !this->type_->is_method())
6207 	;
6208       else if (no->name() == gogo->get_init_fn_name())
6209 	{
6210 	  flags |= Backend::function_is_visible;
6211 	  is_init_fn = true;
6212 	}
6213       else if (Gogo::unpack_hidden_name(no->name()) == "main"
6214                && gogo->is_main_package())
6215 	flags |= Backend::function_is_visible;
6216       // Methods have to be public even if they are hidden because
6217       // they can be pulled into type descriptors when using
6218       // anonymous fields.
6219       else if (!Gogo::is_hidden_name(no->name())
6220                || this->type_->is_method())
6221         {
6222 	  if (!this->is_unnamed_type_stub_method_)
6223 	    flags |= Backend::function_is_visible;
6224         }
6225 
6226       Type* rtype = NULL;
6227       if (this->type_->is_method())
6228 	rtype = this->type_->receiver()->type();
6229 
6230       std::string asm_name;
6231       if (!this->asm_name_.empty())
6232 	{
6233 	  asm_name = this->asm_name_;
6234 
6235 	  // If an assembler name is explicitly specified, there must
6236 	  // be some reason to refer to the symbol from a different
6237 	  // object file.
6238 	  flags |= Backend::function_is_visible;
6239 	}
6240       else if (is_init_fn)
6241 	{
6242 	  // These names appear in the export data and are used
6243 	  // directly in the assembler code.  If we change this here
6244 	  // we need to change Gogo::init_imports.
6245 	  asm_name = no->name();
6246 	}
6247       else
6248 	asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
6249 
6250       // If an inline body refers to this function, then it
6251       // needs to be visible in the symbol table.
6252       if (this->is_referenced_by_inline_)
6253 	flags |= Backend::function_is_visible;
6254 
6255       // A go:linkname directive can be used to force a function to be
6256       // visible.
6257       if (this->is_exported_by_linkname_)
6258 	flags |= Backend::function_is_visible;
6259 
6260       // If a function calls the predeclared recover function, we
6261       // can't inline it, because recover behaves differently in a
6262       // function passed directly to defer.  If this is a recover
6263       // thunk that we built to test whether a function can be
6264       // recovered, we can't inline it, because that will mess up
6265       // our return address comparison.
6266       bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
6267 
6268       // If a function calls __go_set_defer_retaddr, then mark it as
6269       // uninlinable.  This prevents the GCC backend from splitting
6270       // the function; splitting the function is a bad idea because we
6271       // want the return address label to be in the same function as
6272       // the call.
6273       if (this->calls_defer_retaddr_)
6274 	is_inlinable = false;
6275 
6276       // Check the //go:noinline compiler directive.
6277       if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
6278 	is_inlinable = false;
6279 
6280       if (is_inlinable)
6281 	flags |= Backend::function_is_inlinable;
6282 
6283       // If this is a thunk created to call a function which calls
6284       // the predeclared recover function, we need to disable
6285       // stack splitting for the thunk.
6286       bool disable_split_stack = this->is_recover_thunk_;
6287 
6288       // Check the //go:nosplit compiler directive.
6289       if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
6290 	disable_split_stack = true;
6291 
6292       if (disable_split_stack)
6293 	flags |= Backend::function_no_split_stack;
6294 
6295       // This should go into a unique section if that has been
6296       // requested elsewhere, or if this is a nointerface function.
6297       // We want to put a nointerface function into a unique section
6298       // because there is a good chance that the linker garbage
6299       // collection can discard it.
6300       if (this->in_unique_section_
6301 	  || (this->is_method() && this->nointerface()))
6302 	flags |= Backend::function_in_unique_section;
6303 
6304       if (this->is_inline_only_)
6305 	flags |= Backend::function_only_inline;
6306 
6307       Btype* functype = this->type_->get_backend_fntype(gogo);
6308       this->fndecl_ =
6309           gogo->backend()->function(functype, no->get_id(gogo), asm_name,
6310 				    flags, this->location());
6311     }
6312   return this->fndecl_;
6313 }
6314 
6315 // Get the backend representation.
6316 
6317 Bfunction*
get_or_make_decl(Gogo * gogo,Named_object * no)6318 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
6319 {
6320   if (this->fndecl_ == NULL)
6321     {
6322       unsigned int flags =
6323 	(Backend::function_is_visible
6324 	 | Backend::function_is_declaration
6325 	 | Backend::function_is_inlinable);
6326 
6327       // Let Go code use an asm declaration to pick up a builtin
6328       // function.
6329       if (!this->asm_name_.empty())
6330 	{
6331 	  Bfunction* builtin_decl =
6332 	    gogo->backend()->lookup_builtin(this->asm_name_);
6333 	  if (builtin_decl != NULL)
6334 	    {
6335 	      this->fndecl_ = builtin_decl;
6336 	      return this->fndecl_;
6337 	    }
6338 
6339 	  if (this->asm_name_ == "runtime.gopanic"
6340 	      || this->asm_name_.compare(0, 13, "runtime.panic") == 0
6341 	      || this->asm_name_.compare(0, 15, "runtime.goPanic") == 0
6342               || this->asm_name_ == "runtime.block")
6343 	    flags |= Backend::function_does_not_return;
6344 	}
6345 
6346       std::string asm_name;
6347       if (this->asm_name_.empty())
6348 	{
6349 	  Type* rtype = NULL;
6350 	  if (this->fntype_->is_method())
6351 	    rtype = this->fntype_->receiver()->type();
6352 	  asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
6353 	}
6354       else if (go_id_needs_encoding(no->get_id(gogo)))
6355         asm_name = go_encode_id(no->get_id(gogo));
6356 
6357       Btype* functype = this->fntype_->get_backend_fntype(gogo);
6358       this->fndecl_ =
6359           gogo->backend()->function(functype, no->get_id(gogo), asm_name,
6360 				    flags, this->location());
6361     }
6362 
6363   return this->fndecl_;
6364 }
6365 
6366 // Build the descriptor for a function declaration.  This won't
6367 // necessarily happen if the package has just a declaration for the
6368 // function and no other reference to it, but we may still need the
6369 // descriptor for references from other packages.
6370 void
build_backend_descriptor(Gogo * gogo)6371 Function_declaration::build_backend_descriptor(Gogo* gogo)
6372 {
6373   if (this->descriptor_ != NULL)
6374     {
6375       Translate_context context(gogo, NULL, NULL, NULL);
6376       this->descriptor_->get_backend(&context);
6377     }
6378 }
6379 
6380 // Check that the types used in this declaration's signature are defined.
6381 // Reports errors for any undefined type.
6382 
6383 void
check_types() const6384 Function_declaration::check_types() const
6385 {
6386   // Calling Type::base will give errors for any undefined types.
6387   Function_type* fntype = this->type();
6388   if (fntype->receiver() != NULL)
6389     fntype->receiver()->type()->base();
6390   if (fntype->parameters() != NULL)
6391     {
6392       const Typed_identifier_list* params = fntype->parameters();
6393       for (Typed_identifier_list::const_iterator p = params->begin();
6394            p != params->end();
6395            ++p)
6396         p->type()->base();
6397     }
6398 }
6399 
6400 // Return the function's decl after it has been built.
6401 
6402 Bfunction*
get_decl() const6403 Function::get_decl() const
6404 {
6405   go_assert(this->fndecl_ != NULL);
6406   return this->fndecl_;
6407 }
6408 
6409 // Build the backend representation for the function code.
6410 
6411 void
build(Gogo * gogo,Named_object * named_function)6412 Function::build(Gogo* gogo, Named_object* named_function)
6413 {
6414   Translate_context context(gogo, named_function, NULL, NULL);
6415 
6416   // A list of parameter variables for this function.
6417   std::vector<Bvariable*> param_vars;
6418 
6419   // Variables that need to be declared for this function and their
6420   // initial values.
6421   std::vector<Bvariable*> vars;
6422   std::vector<Expression*> var_inits;
6423   std::vector<Statement*> var_decls_stmts;
6424   for (Bindings::const_definitions_iterator p =
6425 	 this->block_->bindings()->begin_definitions();
6426        p != this->block_->bindings()->end_definitions();
6427        ++p)
6428     {
6429       Location loc = (*p)->location();
6430       if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
6431 	{
6432 	  Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6433           Bvariable* parm_bvar = bvar;
6434 
6435 	  // We always pass the receiver to a method as a pointer.  If
6436 	  // the receiver is declared as a non-pointer type, then we
6437 	  // copy the value into a local variable.  For direct interface
6438           // type we pack the pointer into the type.
6439 	  if ((*p)->var_value()->is_receiver()
6440               && (*p)->var_value()->type()->points_to() == NULL)
6441 	    {
6442 	      std::string name = (*p)->name() + ".pointer";
6443 	      Type* var_type = (*p)->var_value()->type();
6444 	      Variable* parm_var =
6445 		  new Variable(Type::make_pointer_type(var_type), NULL, false,
6446 			       true, false, loc);
6447 	      Named_object* parm_no =
6448                   Named_object::make_variable(name, NULL, parm_var);
6449               parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6450 
6451               vars.push_back(bvar);
6452 
6453               Expression* parm_ref =
6454                   Expression::make_var_reference(parm_no, loc);
6455               Type* recv_type = (*p)->var_value()->type();
6456               if (recv_type->is_direct_iface_type())
6457                 parm_ref = Expression::pack_direct_iface(recv_type, parm_ref, loc);
6458               else
6459                 parm_ref =
6460                     Expression::make_dereference(parm_ref,
6461                                                  Expression::NIL_CHECK_NEEDED,
6462                                                  loc);
6463               if ((*p)->var_value()->is_in_heap())
6464                 parm_ref = Expression::make_heap_expression(parm_ref, loc);
6465               var_inits.push_back(parm_ref);
6466 	    }
6467 	  else if ((*p)->var_value()->is_in_heap())
6468 	    {
6469 	      // If we take the address of a parameter, then we need
6470 	      // to copy it into the heap.
6471 	      std::string parm_name = (*p)->name() + ".param";
6472 	      Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
6473 						false, true, false, loc);
6474 	      Named_object* parm_no =
6475 		  Named_object::make_variable(parm_name, NULL, parm_var);
6476 	      parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6477 
6478               vars.push_back(bvar);
6479 	      Expression* var_ref =
6480 		  Expression::make_var_reference(parm_no, loc);
6481 	      var_ref = Expression::make_heap_expression(var_ref, loc);
6482               var_inits.push_back(var_ref);
6483 	    }
6484           param_vars.push_back(parm_bvar);
6485 	}
6486       else if ((*p)->is_result_variable())
6487 	{
6488 	  Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6489 
6490 	  Type* type = (*p)->result_var_value()->type();
6491 	  Expression* init;
6492 	  if (!(*p)->result_var_value()->is_in_heap())
6493 	    {
6494 	      Btype* btype = type->get_backend(gogo);
6495 	      Bexpression* binit = gogo->backend()->zero_expression(btype);
6496               init = Expression::make_backend(binit, type, loc);
6497 	    }
6498 	  else
6499 	    init = Expression::make_allocation(type, loc);
6500 
6501           vars.push_back(bvar);
6502           var_inits.push_back(init);
6503 	}
6504       else if (this->defer_stack_ != NULL
6505                && (*p)->is_variable()
6506                && (*p)->var_value()->is_non_escaping_address_taken()
6507                && !(*p)->var_value()->is_in_heap())
6508         {
6509           // Local variable captured by deferred closure needs to be live
6510           // until the end of the function. We create a top-level
6511           // declaration for it.
6512           // TODO: we don't need to do this if the variable is not captured
6513           // by the defer closure. There is no easy way to check it here,
6514           // so we do this for all address-taken variables for now.
6515           Variable* var = (*p)->var_value();
6516           Temporary_statement* ts =
6517             Statement::make_temporary(var->type(), NULL, var->location());
6518           ts->set_is_address_taken();
6519           var->set_toplevel_decl(ts);
6520           var_decls_stmts.push_back(ts);
6521         }
6522     }
6523   if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
6524     {
6525       go_assert(saw_errors());
6526       return;
6527     }
6528 
6529   // If we need a closure variable, make sure to create it.
6530   // It gets installed in the function as a side effect of creation.
6531   if (this->closure_var_ != NULL)
6532     {
6533       go_assert(this->closure_var_->var_value()->is_closure());
6534       this->closure_var_->get_backend_variable(gogo, named_function);
6535     }
6536 
6537   if (this->block_ != NULL)
6538     {
6539       // Declare variables if necessary.
6540       Bblock* var_decls = NULL;
6541       std::vector<Bstatement*> var_decls_bstmt_list;
6542       Bstatement* defer_init = NULL;
6543       if (!vars.empty() || this->defer_stack_ != NULL)
6544 	{
6545           var_decls =
6546               gogo->backend()->block(this->fndecl_, NULL, vars,
6547                                      this->block_->start_location(),
6548                                      this->block_->end_location());
6549 
6550 	  if (this->defer_stack_ != NULL)
6551 	    {
6552 	      Translate_context dcontext(gogo, named_function, this->block_,
6553                                          var_decls);
6554               defer_init = this->defer_stack_->get_backend(&dcontext);
6555               var_decls_bstmt_list.push_back(defer_init);
6556               for (std::vector<Statement*>::iterator p = var_decls_stmts.begin();
6557                    p != var_decls_stmts.end();
6558                    ++p)
6559                 {
6560                   Bstatement* bstmt = (*p)->get_backend(&dcontext);
6561                   var_decls_bstmt_list.push_back(bstmt);
6562                 }
6563 	    }
6564 	}
6565 
6566       // Build the backend representation for all the statements in the
6567       // function.
6568       Translate_context bcontext(gogo, named_function, NULL, NULL);
6569       Bblock* code_block = this->block_->get_backend(&bcontext);
6570 
6571       // Initialize variables if necessary.
6572       Translate_context icontext(gogo, named_function, this->block_,
6573                                  var_decls);
6574       std::vector<Bstatement*> init;
6575       go_assert(vars.size() == var_inits.size());
6576       for (size_t i = 0; i < vars.size(); ++i)
6577 	{
6578           Bexpression* binit = var_inits[i]->get_backend(&icontext);
6579           Bstatement* init_stmt =
6580               gogo->backend()->init_statement(this->fndecl_, vars[i],
6581                                               binit);
6582           init.push_back(init_stmt);
6583 	}
6584       Bstatement* var_init = gogo->backend()->statement_list(init);
6585 
6586       // Initialize all variables before executing this code block.
6587       Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
6588       code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
6589 
6590       // If we have a defer stack, initialize it at the start of a
6591       // function.
6592       Bstatement* except = NULL;
6593       Bstatement* fini = NULL;
6594       if (defer_init != NULL)
6595 	{
6596 	  // Clean up the defer stack when we leave the function.
6597 	  this->build_defer_wrapper(gogo, named_function, &except, &fini);
6598 
6599           // Wrap the code for this function in an exception handler to handle
6600           // defer calls.
6601           code_stmt =
6602               gogo->backend()->exception_handler_statement(code_stmt,
6603                                                            except, fini,
6604                                                            this->location_);
6605 	}
6606 
6607       // Stick the code into the block we built for the receiver, if
6608       // we built one.
6609       if (var_decls != NULL)
6610         {
6611           var_decls_bstmt_list.push_back(code_stmt);
6612           gogo->backend()->block_add_statements(var_decls, var_decls_bstmt_list);
6613           code_stmt = gogo->backend()->block_statement(var_decls);
6614         }
6615 
6616       if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
6617         {
6618           go_assert(saw_errors());
6619           return;
6620         }
6621     }
6622 
6623   // If we created a descriptor for the function, make sure we emit it.
6624   if (this->descriptor_ != NULL)
6625     {
6626       Translate_context dcontext(gogo, NULL, NULL, NULL);
6627       this->descriptor_->get_backend(&dcontext);
6628     }
6629 }
6630 
6631 // Build the wrappers around function code needed if the function has
6632 // any defer statements.  This sets *EXCEPT to an exception handler
6633 // and *FINI to a finally handler.
6634 
6635 void
build_defer_wrapper(Gogo * gogo,Named_object * named_function,Bstatement ** except,Bstatement ** fini)6636 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
6637 			      Bstatement** except, Bstatement** fini)
6638 {
6639   Location end_loc = this->block_->end_location();
6640 
6641   // Add an exception handler.  This is used if a panic occurs.  Its
6642   // purpose is to stop the stack unwinding if a deferred function
6643   // calls recover.  There are more details in
6644   // libgo/runtime/go-unwind.c.
6645 
6646   std::vector<Bstatement*> stmts;
6647   Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6648 					this->defer_stack(end_loc));
6649   Translate_context context(gogo, named_function, NULL, NULL);
6650   Bexpression* defer = call->get_backend(&context);
6651   stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
6652 
6653   Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
6654   if (ret_bstmt != NULL)
6655     stmts.push_back(ret_bstmt);
6656 
6657   go_assert(*except == NULL);
6658   *except = gogo->backend()->statement_list(stmts);
6659 
6660   call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6661                             this->defer_stack(end_loc));
6662   defer = call->get_backend(&context);
6663 
6664   call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
6665         		    this->defer_stack(end_loc));
6666   Bexpression* undefer = call->get_backend(&context);
6667   Bstatement* function_defer =
6668       gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
6669                                                 end_loc);
6670   stmts = std::vector<Bstatement*>(1, function_defer);
6671   if (this->type_->results() != NULL
6672       && !this->type_->results()->empty()
6673       && !this->type_->results()->front().name().empty())
6674     {
6675       // If the result variables are named, and we are returning from
6676       // this function rather than panicing through it, we need to
6677       // return them again, because they might have been changed by a
6678       // defer function.  The runtime routines set the defer_stack
6679       // variable to true if we are returning from this function.
6680 
6681       ret_bstmt = this->return_value(gogo, named_function, end_loc);
6682       Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
6683       Bexpression* ret =
6684           gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
6685       Expression* ref =
6686 	Expression::make_temporary_reference(this->defer_stack_, end_loc);
6687       Bexpression* bref = ref->get_backend(&context);
6688       ret = gogo->backend()->conditional_expression(this->fndecl_,
6689                                                     NULL, bref, ret, NULL,
6690                                                     end_loc);
6691       stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
6692     }
6693 
6694   go_assert(*fini == NULL);
6695   *fini = gogo->backend()->statement_list(stmts);
6696 }
6697 
6698 // Return the statement that assigns values to this function's result struct.
6699 
6700 Bstatement*
return_value(Gogo * gogo,Named_object * named_function,Location location) const6701 Function::return_value(Gogo* gogo, Named_object* named_function,
6702 		       Location location) const
6703 {
6704   const Typed_identifier_list* results = this->type_->results();
6705   if (results == NULL || results->empty())
6706     return NULL;
6707 
6708   go_assert(this->results_ != NULL);
6709   if (this->results_->size() != results->size())
6710     {
6711       go_assert(saw_errors());
6712       return gogo->backend()->error_statement();
6713     }
6714 
6715   std::vector<Bexpression*> vals(results->size());
6716   for (size_t i = 0; i < vals.size(); ++i)
6717     {
6718       Named_object* no = (*this->results_)[i];
6719       Bvariable* bvar = no->get_backend_variable(gogo, named_function);
6720       Bexpression* val = gogo->backend()->var_expression(bvar, location);
6721       if (no->result_var_value()->is_in_heap())
6722 	{
6723 	  Btype* bt = no->result_var_value()->type()->get_backend(gogo);
6724 	  val = gogo->backend()->indirect_expression(bt, val, true, location);
6725 	}
6726       vals[i] = val;
6727     }
6728   return gogo->backend()->return_statement(this->fndecl_, vals, location);
6729 }
6730 
6731 // Class Block.
6732 
Block(Block * enclosing,Location location)6733 Block::Block(Block* enclosing, Location location)
6734   : enclosing_(enclosing), statements_(),
6735     bindings_(new Bindings(enclosing == NULL
6736 			   ? NULL
6737 			   : enclosing->bindings())),
6738     start_location_(location),
6739     end_location_(Linemap::unknown_location())
6740 {
6741 }
6742 
6743 // Add a statement to a block.
6744 
6745 void
add_statement(Statement * statement)6746 Block::add_statement(Statement* statement)
6747 {
6748   this->statements_.push_back(statement);
6749 }
6750 
6751 // Add a statement to the front of a block.  This is slow but is only
6752 // used for reference counts of parameters.
6753 
6754 void
add_statement_at_front(Statement * statement)6755 Block::add_statement_at_front(Statement* statement)
6756 {
6757   this->statements_.insert(this->statements_.begin(), statement);
6758 }
6759 
6760 // Replace a statement in a block.
6761 
6762 void
replace_statement(size_t index,Statement * s)6763 Block::replace_statement(size_t index, Statement* s)
6764 {
6765   go_assert(index < this->statements_.size());
6766   this->statements_[index] = s;
6767 }
6768 
6769 // Add a statement before another statement.
6770 
6771 void
insert_statement_before(size_t index,Statement * s)6772 Block::insert_statement_before(size_t index, Statement* s)
6773 {
6774   go_assert(index < this->statements_.size());
6775   this->statements_.insert(this->statements_.begin() + index, s);
6776 }
6777 
6778 // Add a statement after another statement.
6779 
6780 void
insert_statement_after(size_t index,Statement * s)6781 Block::insert_statement_after(size_t index, Statement* s)
6782 {
6783   go_assert(index < this->statements_.size());
6784   this->statements_.insert(this->statements_.begin() + index + 1, s);
6785 }
6786 
6787 // Traverse the tree.
6788 
6789 int
traverse(Traverse * traverse)6790 Block::traverse(Traverse* traverse)
6791 {
6792   unsigned int traverse_mask = traverse->traverse_mask();
6793 
6794   if ((traverse_mask & Traverse::traverse_blocks) != 0)
6795     {
6796       int t = traverse->block(this);
6797       if (t == TRAVERSE_EXIT)
6798 	return TRAVERSE_EXIT;
6799       else if (t == TRAVERSE_SKIP_COMPONENTS)
6800 	return TRAVERSE_CONTINUE;
6801     }
6802 
6803   if ((traverse_mask
6804        & (Traverse::traverse_variables
6805 	  | Traverse::traverse_constants
6806 	  | Traverse::traverse_expressions
6807 	  | Traverse::traverse_types)) != 0)
6808     {
6809       const unsigned int e_or_t = (Traverse::traverse_expressions
6810 				   | Traverse::traverse_types);
6811       const unsigned int e_or_t_or_s = (e_or_t
6812 					| Traverse::traverse_statements);
6813       for (Bindings::const_definitions_iterator pb =
6814 	     this->bindings_->begin_definitions();
6815 	   pb != this->bindings_->end_definitions();
6816 	   ++pb)
6817 	{
6818 	  int t = TRAVERSE_CONTINUE;
6819 	  switch ((*pb)->classification())
6820 	    {
6821 	    case Named_object::NAMED_OBJECT_CONST:
6822 	      if ((traverse_mask & Traverse::traverse_constants) != 0)
6823 		t = traverse->constant(*pb, false);
6824 	      if (t == TRAVERSE_CONTINUE
6825 		  && (traverse_mask & e_or_t) != 0)
6826 		{
6827 		  Type* tc = (*pb)->const_value()->type();
6828 		  if (tc != NULL
6829 		      && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
6830 		    return TRAVERSE_EXIT;
6831 		  t = (*pb)->const_value()->traverse_expression(traverse);
6832 		}
6833 	      break;
6834 
6835 	    case Named_object::NAMED_OBJECT_VAR:
6836 	    case Named_object::NAMED_OBJECT_RESULT_VAR:
6837 	      if ((traverse_mask & Traverse::traverse_variables) != 0)
6838 		t = traverse->variable(*pb);
6839 	      if (t == TRAVERSE_CONTINUE
6840 		  && (traverse_mask & e_or_t) != 0)
6841 		{
6842 		  if ((*pb)->is_result_variable()
6843 		      || (*pb)->var_value()->has_type())
6844 		    {
6845 		      Type* tv = ((*pb)->is_variable()
6846 				  ? (*pb)->var_value()->type()
6847 				  : (*pb)->result_var_value()->type());
6848 		      if (tv != NULL
6849 			  && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
6850 			return TRAVERSE_EXIT;
6851 		    }
6852 		}
6853 	      if (t == TRAVERSE_CONTINUE
6854 		  && (traverse_mask & e_or_t_or_s) != 0
6855 		  && (*pb)->is_variable())
6856 		t = (*pb)->var_value()->traverse_expression(traverse,
6857 							    traverse_mask);
6858 	      break;
6859 
6860 	    case Named_object::NAMED_OBJECT_FUNC:
6861 	    case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
6862 	      go_unreachable();
6863 
6864 	    case Named_object::NAMED_OBJECT_TYPE:
6865 	      if ((traverse_mask & e_or_t) != 0)
6866 		t = Type::traverse((*pb)->type_value(), traverse);
6867 	      break;
6868 
6869 	    case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
6870 	    case Named_object::NAMED_OBJECT_UNKNOWN:
6871 	    case Named_object::NAMED_OBJECT_ERRONEOUS:
6872 	      break;
6873 
6874 	    case Named_object::NAMED_OBJECT_PACKAGE:
6875 	    case Named_object::NAMED_OBJECT_SINK:
6876 	      go_unreachable();
6877 
6878 	    default:
6879 	      go_unreachable();
6880 	    }
6881 
6882 	  if (t == TRAVERSE_EXIT)
6883 	    return TRAVERSE_EXIT;
6884 	}
6885     }
6886 
6887   // No point in checking traverse_mask here--if we got here we always
6888   // want to walk the statements.  The traversal can insert new
6889   // statements before or after the current statement.  Inserting
6890   // statements before the current statement requires updating I via
6891   // the pointer; those statements will not be traversed.  Any new
6892   // statements inserted after the current statement will be traversed
6893   // in their turn.
6894   for (size_t i = 0; i < this->statements_.size(); ++i)
6895     {
6896       if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
6897 	return TRAVERSE_EXIT;
6898     }
6899 
6900   return TRAVERSE_CONTINUE;
6901 }
6902 
6903 // Work out types for unspecified variables and constants.
6904 
6905 void
determine_types()6906 Block::determine_types()
6907 {
6908   for (Bindings::const_definitions_iterator pb =
6909 	 this->bindings_->begin_definitions();
6910        pb != this->bindings_->end_definitions();
6911        ++pb)
6912     {
6913       if ((*pb)->is_variable())
6914 	(*pb)->var_value()->determine_type();
6915       else if ((*pb)->is_const())
6916 	(*pb)->const_value()->determine_type();
6917     }
6918 
6919   for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6920        ps != this->statements_.end();
6921        ++ps)
6922     (*ps)->determine_types();
6923 }
6924 
6925 // Return true if the statements in this block may fall through.
6926 
6927 bool
may_fall_through() const6928 Block::may_fall_through() const
6929 {
6930   if (this->statements_.empty())
6931     return true;
6932   return this->statements_.back()->may_fall_through();
6933 }
6934 
6935 // Write export data for a block.
6936 
6937 void
export_block(Export_function_body * efb)6938 Block::export_block(Export_function_body* efb)
6939 {
6940   for (Block::iterator p = this->begin();
6941        p != this->end();
6942        ++p)
6943     {
6944       efb->indent();
6945 
6946       efb->increment_indent();
6947       (*p)->export_statement(efb);
6948       efb->decrement_indent();
6949 
6950       Location loc = (*p)->location();
6951       if ((*p)->is_block_statement())
6952 	{
6953 	  // For a block we put the start location on the first brace
6954 	  // in Block_statement::do_export_statement.  Here we put the
6955 	  // end location on the final brace.
6956 	  loc = (*p)->block_statement()->block()->end_location();
6957 	}
6958       char buf[50];
6959       snprintf(buf, sizeof buf, " //%d\n", Linemap::location_to_line(loc));
6960       efb->write_c_string(buf);
6961     }
6962 }
6963 
6964 // Add exported block data to SET, reading from BODY starting at OFF.
6965 // Returns whether the import succeeded.
6966 
6967 bool
import_block(Block * set,Import_function_body * ifb,Location loc)6968 Block::import_block(Block* set, Import_function_body *ifb, Location loc)
6969 {
6970   Location eloc = ifb->location();
6971   Location sloc = loc;
6972   const std::string& body(ifb->body());
6973   size_t off = ifb->off();
6974   while (off < body.length())
6975     {
6976       int indent = ifb->indent();
6977       if (off + indent >= body.length())
6978 	{
6979 	  go_error_at(eloc,
6980 		      "invalid export data for %qs: insufficient indentation",
6981 		      ifb->name().c_str());
6982 	  return false;
6983 	}
6984       for (int i = 0; i < indent - 1; i++)
6985 	{
6986 	  if (body[off + i] != ' ')
6987 	    {
6988 	      go_error_at(eloc,
6989 			  "invalid export data for %qs: bad indentation",
6990 			  ifb->name().c_str());
6991 	      return false;
6992 	    }
6993 	}
6994 
6995       bool at_end = false;
6996       if (body[off + indent - 1] == '}')
6997 	at_end = true;
6998       else if (body[off + indent - 1] != ' ')
6999 	{
7000 	  go_error_at(eloc,
7001 		      "invalid export data for %qs: bad indentation",
7002 		      ifb->name().c_str());
7003 	  return false;
7004 	}
7005 
7006       off += indent;
7007 
7008       size_t nl = body.find('\n', off);
7009       if (nl == std::string::npos)
7010 	{
7011 	  go_error_at(eloc, "invalid export data for %qs: missing newline",
7012 		      ifb->name().c_str());
7013 	  return false;
7014 	}
7015 
7016       size_t lineno_pos = body.find(" //", off);
7017       if (lineno_pos == std::string::npos || lineno_pos >= nl)
7018 	{
7019 	  go_error_at(eloc, "invalid export data for %qs: missing line number",
7020 		      ifb->name().c_str());
7021 	  return false;
7022 	}
7023 
7024       unsigned int lineno = 0;
7025       for (size_t i = lineno_pos + 3; i < nl; ++i)
7026 	{
7027 	  char c = body[i];
7028 	  if (c < '0' || c > '9')
7029 	    {
7030 	      go_error_at(loc,
7031 			  "invalid export data for %qs: invalid line number",
7032 			  ifb->name().c_str());
7033 	      return false;
7034 	    }
7035 	  lineno = lineno * 10 + c - '0';
7036 	}
7037 
7038       ifb->gogo()->linemap()->start_line(lineno, 1);
7039       sloc = ifb->gogo()->linemap()->get_location(0);
7040 
7041       if (at_end)
7042 	{
7043 	  // An if statement can have an "else" following the "}", in
7044 	  // which case we want to leave the offset where it is, just
7045 	  // after the "}".  We don't get the block ending location
7046 	  // quite right for if statements.
7047 	  if (body.compare(off, 6, " else ") != 0)
7048 	    off = nl + 1;
7049 	  break;
7050 	}
7051 
7052       ifb->set_off(off);
7053       Statement* s = Statement::import_statement(ifb, sloc);
7054       if (s == NULL)
7055 	return false;
7056 
7057       set->add_statement(s);
7058 
7059       size_t at = ifb->off();
7060       if (at < nl + 1)
7061 	off = nl + 1;
7062       else
7063 	off = at;
7064     }
7065 
7066   ifb->set_off(off);
7067   set->set_end_location(sloc);
7068   return true;
7069 }
7070 
7071 // Convert a block to the backend representation.
7072 
7073 Bblock*
get_backend(Translate_context * context)7074 Block::get_backend(Translate_context* context)
7075 {
7076   Gogo* gogo = context->gogo();
7077   Named_object* function = context->function();
7078   std::vector<Bvariable*> vars;
7079   vars.reserve(this->bindings_->size_definitions());
7080   for (Bindings::const_definitions_iterator pv =
7081 	 this->bindings_->begin_definitions();
7082        pv != this->bindings_->end_definitions();
7083        ++pv)
7084     {
7085       if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
7086 	vars.push_back((*pv)->get_backend_variable(gogo, function));
7087     }
7088 
7089   go_assert(function != NULL);
7090   Bfunction* bfunction =
7091     function->func_value()->get_or_make_decl(gogo, function);
7092   Bblock* ret = context->backend()->block(bfunction, context->bblock(),
7093 					  vars, this->start_location_,
7094 					  this->end_location_);
7095 
7096   Translate_context subcontext(gogo, function, this, ret);
7097   std::vector<Bstatement*> bstatements;
7098   bstatements.reserve(this->statements_.size());
7099   for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
7100        p != this->statements_.end();
7101        ++p)
7102     bstatements.push_back((*p)->get_backend(&subcontext));
7103 
7104   context->backend()->block_add_statements(ret, bstatements);
7105 
7106   return ret;
7107 }
7108 
7109 // Class Bindings_snapshot.
7110 
Bindings_snapshot(const Block * b,Location location)7111 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
7112   : block_(b), counts_(), location_(location)
7113 {
7114   while (b != NULL)
7115     {
7116       this->counts_.push_back(b->bindings()->size_definitions());
7117       b = b->enclosing();
7118     }
7119 }
7120 
7121 // Report errors appropriate for a goto from B to this.
7122 
7123 void
check_goto_from(const Block * b,Location loc)7124 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
7125 {
7126   size_t dummy;
7127   if (!this->check_goto_block(loc, b, this->block_, &dummy))
7128     return;
7129   this->check_goto_defs(loc, this->block_,
7130 			this->block_->bindings()->size_definitions(),
7131 			this->counts_[0]);
7132 }
7133 
7134 // Report errors appropriate for a goto from this to B.
7135 
7136 void
check_goto_to(const Block * b)7137 Bindings_snapshot::check_goto_to(const Block* b)
7138 {
7139   size_t index;
7140   if (!this->check_goto_block(this->location_, this->block_, b, &index))
7141     return;
7142   this->check_goto_defs(this->location_, b, this->counts_[index],
7143 			b->bindings()->size_definitions());
7144 }
7145 
7146 // Report errors appropriate for a goto at LOC from BFROM to BTO.
7147 // Return true if all is well, false if we reported an error.  If this
7148 // returns true, it sets *PINDEX to the number of blocks BTO is above
7149 // BFROM.
7150 
7151 bool
check_goto_block(Location loc,const Block * bfrom,const Block * bto,size_t * pindex)7152 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
7153 				    const Block* bto, size_t* pindex)
7154 {
7155   // It is an error if BTO is not either BFROM or above BFROM.
7156   size_t index = 0;
7157   for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
7158     {
7159       if (pb == NULL)
7160 	{
7161 	  go_error_at(loc, "goto jumps into block");
7162 	  go_inform(bto->start_location(), "goto target block starts here");
7163 	  return false;
7164 	}
7165     }
7166   *pindex = index;
7167   return true;
7168 }
7169 
7170 // Report errors appropriate for a goto at LOC ending at BLOCK, where
7171 // CFROM is the number of names defined at the point of the goto and
7172 // CTO is the number of names defined at the point of the label.
7173 
7174 void
check_goto_defs(Location loc,const Block * block,size_t cfrom,size_t cto)7175 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
7176 				   size_t cfrom, size_t cto)
7177 {
7178   if (cfrom < cto)
7179     {
7180       Bindings::const_definitions_iterator p =
7181 	block->bindings()->begin_definitions();
7182       for (size_t i = 0; i < cfrom; ++i)
7183 	{
7184 	  go_assert(p != block->bindings()->end_definitions());
7185 	  ++p;
7186 	}
7187       go_assert(p != block->bindings()->end_definitions());
7188 
7189       for (; p != block->bindings()->end_definitions(); ++p)
7190 	{
7191 	  if ((*p)->is_variable())
7192 	    {
7193 	      std::string n = (*p)->message_name();
7194 	      go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
7195 	      go_inform((*p)->location(), "%qs defined here", n.c_str());
7196 	    }
7197 	}
7198     }
7199 }
7200 
7201 // Class Function_declaration.
7202 
7203 // Whether this declares a method.
7204 
7205 bool
is_method() const7206 Function_declaration::is_method() const
7207 {
7208   return this->fntype_->is_method();
7209 }
7210 
7211 // Whether this method should not be included in the type descriptor.
7212 
7213 bool
nointerface() const7214 Function_declaration::nointerface() const
7215 {
7216   go_assert(this->is_method());
7217   return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
7218 }
7219 
7220 // Record that this method should not be included in the type
7221 // descriptor.
7222 
7223 void
set_nointerface()7224 Function_declaration::set_nointerface()
7225 {
7226   this->pragmas_ |= GOPRAGMA_NOINTERFACE;
7227 }
7228 
7229 // Import an inlinable function.  This is used for an inlinable
7230 // function whose body is recorded in the export data.  Parse the
7231 // export data into a Block and create a regular function using that
7232 // Block as its body.  Redeclare this function declaration as the
7233 // function.
7234 
7235 void
import_function_body(Gogo * gogo,Named_object * no)7236 Function_declaration::import_function_body(Gogo* gogo, Named_object* no)
7237 {
7238   go_assert(no->func_declaration_value() == this);
7239   go_assert(no->package() != NULL);
7240   const std::string& body(this->imported_body_);
7241   go_assert(!body.empty());
7242 
7243   // Read the "//FILE:LINE" comment starts the export data.
7244 
7245   size_t indent = 1;
7246   if (this->is_method())
7247     indent = 2;
7248   size_t i = 0;
7249   for (; i < indent; i++)
7250     {
7251       if (body.at(i) != ' ')
7252 	{
7253 	  go_error_at(this->location_,
7254 		      "invalid export body for %qs: bad initial indentation",
7255 		      no->message_name().c_str());
7256 	  return;
7257 	}
7258     }
7259 
7260   if (body.substr(i, 2) != "//")
7261     {
7262       go_error_at(this->location_,
7263 		  "invalid export body for %qs: missing file comment",
7264 		  no->message_name().c_str());
7265       return;
7266     }
7267 
7268   size_t colon = body.find(':', i + 2);
7269   size_t nl = body.find('\n', i + 2);
7270   if (nl == std::string::npos)
7271     {
7272       go_error_at(this->location_,
7273 		  "invalid export body for %qs: missing file name",
7274 		  no->message_name().c_str());
7275       return;
7276     }
7277   if (colon == std::string::npos || nl < colon)
7278     {
7279       go_error_at(this->location_,
7280 		  "invalid export body for %qs: missing initial line number",
7281 		  no->message_name().c_str());
7282       return;
7283     }
7284 
7285   std::string file = body.substr(i + 2, colon - (i + 2));
7286   std::string linestr = body.substr(colon + 1, nl - (colon + 1));
7287   char* end;
7288   long linenol = strtol(linestr.c_str(), &end, 10);
7289   if (*end != '\0')
7290     {
7291       go_error_at(this->location_,
7292 		  "invalid export body for %qs: invalid initial line number",
7293 		  no->message_name().c_str());
7294       return;
7295     }
7296   unsigned int lineno = static_cast<unsigned int>(linenol);
7297 
7298   // Turn the file/line into a location.
7299 
7300   char* alc = new char[file.length() + 1];
7301   memcpy(alc, file.data(), file.length());
7302   alc[file.length()] = '\0';
7303   gogo->linemap()->start_file(alc, lineno);
7304   gogo->linemap()->start_line(lineno, 1);
7305   Location start_loc = gogo->linemap()->get_location(0);
7306 
7307   // Define the function with an outer block that declares the
7308   // parameters.
7309 
7310   Function_type* fntype = this->fntype_;
7311 
7312   Block* outer = new Block(NULL, start_loc);
7313 
7314   Function* fn = new Function(fntype, NULL, outer, start_loc);
7315   fn->set_is_inline_only();
7316 
7317   if (fntype->is_method())
7318     {
7319       if (this->nointerface())
7320         fn->set_nointerface();
7321       const Typed_identifier* receiver = fntype->receiver();
7322       Variable* recv_param = new Variable(receiver->type(), NULL, false,
7323 					  true, true, start_loc);
7324 
7325       std::string rname = receiver->name();
7326       unsigned rcounter = 0;
7327 
7328       // We need to give a nameless receiver a name to avoid having it
7329       // clash with some other nameless param. FIXME.
7330       Gogo::rename_if_empty(&rname, "r", &rcounter);
7331 
7332       outer->bindings()->add_variable(rname, NULL, recv_param);
7333     }
7334 
7335   const Typed_identifier_list* params = fntype->parameters();
7336   bool is_varargs = fntype->is_varargs();
7337   unsigned pcounter = 0;
7338   if (params != NULL)
7339     {
7340       for (Typed_identifier_list::const_iterator p = params->begin();
7341 	   p != params->end();
7342 	   ++p)
7343 	{
7344 	  Variable* param = new Variable(p->type(), NULL, false, true, false,
7345 					 start_loc);
7346 	  if (is_varargs && p + 1 == params->end())
7347 	    param->set_is_varargs_parameter();
7348 
7349 	  std::string pname = p->name();
7350 
7351           // We need to give each nameless parameter a non-empty name to avoid
7352           // having it clash with some other nameless param. FIXME.
7353           Gogo::rename_if_empty(&pname, "p", &pcounter);
7354 
7355 	  outer->bindings()->add_variable(pname, NULL, param);
7356 	}
7357     }
7358 
7359   fn->create_result_variables(gogo);
7360 
7361   if (!fntype->is_method())
7362     {
7363       const Package* package = no->package();
7364       no = package->bindings()->add_function(no->name(), package, fn);
7365     }
7366   else
7367     {
7368       Named_type* rtype = fntype->receiver()->type()->deref()->named_type();
7369       go_assert(rtype != NULL);
7370       no = rtype->add_method(no->name(), fn);
7371       const Package* package = rtype->named_object()->package();
7372       package->bindings()->add_method(no);
7373     }
7374 
7375   Import_function_body ifb(gogo, this->imp_, no, body, nl + 1, outer, indent);
7376 
7377   if (!Block::import_block(outer, &ifb, start_loc))
7378     return;
7379 
7380   gogo->lower_block(no, outer);
7381   outer->determine_types();
7382 
7383   gogo->add_imported_inline_function(no);
7384 }
7385 
7386 // Return the function descriptor.
7387 
7388 Expression*
descriptor(Gogo *,Named_object * no)7389 Function_declaration::descriptor(Gogo*, Named_object* no)
7390 {
7391   go_assert(!this->fntype_->is_method());
7392   if (this->descriptor_ == NULL)
7393     this->descriptor_ = Expression::make_func_descriptor(no);
7394   return this->descriptor_;
7395 }
7396 
7397 // Class Variable.
7398 
Variable(Type * type,Expression * init,bool is_global,bool is_parameter,bool is_receiver,Location location)7399 Variable::Variable(Type* type, Expression* init, bool is_global,
7400 		   bool is_parameter, bool is_receiver,
7401 		   Location location)
7402   : type_(type), init_(init), preinit_(NULL), location_(location),
7403     backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
7404     is_closure_(false), is_receiver_(is_receiver),
7405     is_varargs_parameter_(false), is_used_(false),
7406     is_address_taken_(false), is_non_escaping_address_taken_(false),
7407     seen_(false), init_is_lowered_(false), init_is_flattened_(false),
7408     type_from_init_tuple_(false), type_from_range_index_(false),
7409     type_from_range_value_(false), type_from_chan_element_(false),
7410     is_type_switch_var_(false), determined_type_(false),
7411     in_unique_section_(false), is_referenced_by_inline_(false),
7412     toplevel_decl_(NULL)
7413 {
7414   go_assert(type != NULL || init != NULL);
7415   go_assert(!is_parameter || init == NULL);
7416 }
7417 
7418 // Traverse the initializer expression.
7419 
7420 int
traverse_expression(Traverse * traverse,unsigned int traverse_mask)7421 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
7422 {
7423   if (this->preinit_ != NULL)
7424     {
7425       if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
7426 	return TRAVERSE_EXIT;
7427     }
7428   if (this->init_ != NULL
7429       && ((traverse_mask
7430 	   & (Traverse::traverse_expressions | Traverse::traverse_types))
7431 	  != 0))
7432     {
7433       if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
7434 	return TRAVERSE_EXIT;
7435     }
7436   return TRAVERSE_CONTINUE;
7437 }
7438 
7439 // Lower the initialization expression after parsing is complete.
7440 
7441 void
lower_init_expression(Gogo * gogo,Named_object * function,Statement_inserter * inserter)7442 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
7443 				Statement_inserter* inserter)
7444 {
7445   Named_object* dep = gogo->var_depends_on(this);
7446   if (dep != NULL && dep->is_variable())
7447     dep->var_value()->lower_init_expression(gogo, function, inserter);
7448 
7449   if (this->init_ != NULL && !this->init_is_lowered_)
7450     {
7451       if (this->seen_)
7452 	{
7453 	  // We will give an error elsewhere, this is just to prevent
7454 	  // an infinite loop.
7455 	  return;
7456 	}
7457       this->seen_ = true;
7458 
7459       Statement_inserter global_inserter;
7460       if (this->is_global_)
7461 	{
7462 	  global_inserter = Statement_inserter(gogo, this);
7463 	  inserter = &global_inserter;
7464 	}
7465 
7466       gogo->lower_expression(function, inserter, &this->init_);
7467 
7468       this->seen_ = false;
7469 
7470       this->init_is_lowered_ = true;
7471     }
7472 }
7473 
7474 // Flatten the initialization expression after ordering evaluations.
7475 
7476 void
flatten_init_expression(Gogo * gogo,Named_object * function,Statement_inserter * inserter)7477 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
7478                                   Statement_inserter* inserter)
7479 {
7480   Named_object* dep = gogo->var_depends_on(this);
7481   if (dep != NULL && dep->is_variable())
7482     dep->var_value()->flatten_init_expression(gogo, function, inserter);
7483 
7484   if (this->init_ != NULL && !this->init_is_flattened_)
7485     {
7486       if (this->seen_)
7487 	{
7488 	  // We will give an error elsewhere, this is just to prevent
7489 	  // an infinite loop.
7490 	  return;
7491 	}
7492       this->seen_ = true;
7493 
7494       Statement_inserter global_inserter;
7495       if (this->is_global_)
7496 	{
7497 	  global_inserter = Statement_inserter(gogo, this);
7498 	  inserter = &global_inserter;
7499 	}
7500 
7501       gogo->flatten_expression(function, inserter, &this->init_);
7502 
7503       // If an interface conversion is needed, we need a temporary
7504       // variable.
7505       if (this->type_ != NULL
7506 	  && !Type::are_identical(this->type_, this->init_->type(),
7507 				  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
7508 				  NULL)
7509 	  && this->init_->type()->interface_type() != NULL
7510 	  && !this->init_->is_variable())
7511 	{
7512 	  Temporary_statement* temp =
7513 	    Statement::make_temporary(NULL, this->init_, this->location_);
7514 	  inserter->insert(temp);
7515 	  this->init_ = Expression::make_temporary_reference(temp,
7516 							     this->location_);
7517 	}
7518 
7519       this->seen_ = false;
7520       this->init_is_flattened_ = true;
7521     }
7522 }
7523 
7524 // Get the preinit block.
7525 
7526 Block*
preinit_block(Gogo * gogo)7527 Variable::preinit_block(Gogo* gogo)
7528 {
7529   go_assert(this->is_global_);
7530   if (this->preinit_ == NULL)
7531     this->preinit_ = new Block(NULL, this->location());
7532 
7533   // If a global variable has a preinitialization statement, then we
7534   // need to have an initialization function.
7535   gogo->set_need_init_fn();
7536 
7537   return this->preinit_;
7538 }
7539 
7540 // Add a statement to be run before the initialization expression.
7541 
7542 void
add_preinit_statement(Gogo * gogo,Statement * s)7543 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
7544 {
7545   Block* b = this->preinit_block(gogo);
7546   b->add_statement(s);
7547   b->set_end_location(s->location());
7548 }
7549 
7550 // Whether this variable has a type.
7551 
7552 bool
has_type() const7553 Variable::has_type() const
7554 {
7555   if (this->type_ == NULL)
7556     return false;
7557 
7558   // A variable created in a type switch case nil does not actually
7559   // have a type yet.  It will be changed to use the initializer's
7560   // type in determine_type.
7561   if (this->is_type_switch_var_
7562       && this->type_->is_nil_constant_as_type())
7563     return false;
7564 
7565   return true;
7566 }
7567 
7568 // In an assignment which sets a variable to a tuple of EXPR, return
7569 // the type of the first element of the tuple.
7570 
7571 Type*
type_from_tuple(Expression * expr,bool report_error) const7572 Variable::type_from_tuple(Expression* expr, bool report_error) const
7573 {
7574   if (expr->map_index_expression() != NULL)
7575     {
7576       Map_type* mt = expr->map_index_expression()->get_map_type();
7577       if (mt == NULL)
7578 	return Type::make_error_type();
7579       return mt->val_type();
7580     }
7581   else if (expr->receive_expression() != NULL)
7582     {
7583       Expression* channel = expr->receive_expression()->channel();
7584       Type* channel_type = channel->type();
7585       if (channel_type->channel_type() == NULL)
7586 	return Type::make_error_type();
7587       return channel_type->channel_type()->element_type();
7588     }
7589   else
7590     {
7591       if (report_error)
7592 	go_error_at(this->location(), "invalid tuple definition");
7593       return Type::make_error_type();
7594     }
7595 }
7596 
7597 // Given EXPR used in a range clause, return either the index type or
7598 // the value type of the range, depending upon GET_INDEX_TYPE.
7599 
7600 Type*
type_from_range(Expression * expr,bool get_index_type,bool report_error) const7601 Variable::type_from_range(Expression* expr, bool get_index_type,
7602 			  bool report_error) const
7603 {
7604   Type* t = expr->type();
7605   if (t->array_type() != NULL
7606       || (t->points_to() != NULL
7607 	  && t->points_to()->array_type() != NULL
7608 	  && !t->points_to()->is_slice_type()))
7609     {
7610       if (get_index_type)
7611 	return Type::lookup_integer_type("int");
7612       else
7613 	return t->deref()->array_type()->element_type();
7614     }
7615   else if (t->is_string_type())
7616     {
7617       if (get_index_type)
7618 	return Type::lookup_integer_type("int");
7619       else
7620 	return Type::lookup_integer_type("int32");
7621     }
7622   else if (t->map_type() != NULL)
7623     {
7624       if (get_index_type)
7625 	return t->map_type()->key_type();
7626       else
7627 	return t->map_type()->val_type();
7628     }
7629   else if (t->channel_type() != NULL)
7630     {
7631       if (get_index_type)
7632 	return t->channel_type()->element_type();
7633       else
7634 	{
7635 	  if (report_error)
7636 	    go_error_at(this->location(),
7637 			("invalid definition of value variable "
7638 			 "for channel range"));
7639 	  return Type::make_error_type();
7640 	}
7641     }
7642   else
7643     {
7644       if (report_error)
7645 	go_error_at(this->location(), "invalid type for range clause");
7646       return Type::make_error_type();
7647     }
7648 }
7649 
7650 // EXPR should be a channel.  Return the channel's element type.
7651 
7652 Type*
type_from_chan_element(Expression * expr,bool report_error) const7653 Variable::type_from_chan_element(Expression* expr, bool report_error) const
7654 {
7655   Type* t = expr->type();
7656   if (t->channel_type() != NULL)
7657     return t->channel_type()->element_type();
7658   else
7659     {
7660       if (report_error)
7661 	go_error_at(this->location(), "expected channel");
7662       return Type::make_error_type();
7663     }
7664 }
7665 
7666 // Return the type of the Variable.  This may be called before
7667 // Variable::determine_type is called, which means that we may need to
7668 // get the type from the initializer.  FIXME: If we combine lowering
7669 // with type determination, then this should be unnecessary.
7670 
7671 Type*
type()7672 Variable::type()
7673 {
7674   // A variable in a type switch with a nil case will have the wrong
7675   // type here.  This gets fixed up in determine_type, below.
7676   Type* type = this->type_;
7677   Expression* init = this->init_;
7678   if (this->is_type_switch_var_
7679       && type != NULL
7680       && this->type_->is_nil_constant_as_type())
7681     {
7682       Type_guard_expression* tge = this->init_->type_guard_expression();
7683       go_assert(tge != NULL);
7684       init = tge->expr();
7685       type = NULL;
7686     }
7687 
7688   if (this->seen_)
7689     {
7690       if (this->type_ == NULL || !this->type_->is_error_type())
7691 	{
7692 	  go_error_at(this->location_, "variable initializer refers to itself");
7693 	  this->type_ = Type::make_error_type();
7694 	}
7695       return this->type_;
7696     }
7697 
7698   this->seen_ = true;
7699 
7700   if (type != NULL)
7701     ;
7702   else if (this->type_from_init_tuple_)
7703     type = this->type_from_tuple(init, false);
7704   else if (this->type_from_range_index_ || this->type_from_range_value_)
7705     type = this->type_from_range(init, this->type_from_range_index_, false);
7706   else if (this->type_from_chan_element_)
7707     type = this->type_from_chan_element(init, false);
7708   else
7709     {
7710       go_assert(init != NULL);
7711       type = init->type();
7712       go_assert(type != NULL);
7713 
7714       // Variables should not have abstract types.
7715       if (type->is_abstract())
7716 	type = type->make_non_abstract_type();
7717 
7718       if (type->is_void_type())
7719 	type = Type::make_error_type();
7720     }
7721 
7722   this->seen_ = false;
7723 
7724   return type;
7725 }
7726 
7727 // Fetch the type from a const pointer, in which case it should have
7728 // been set already.
7729 
7730 Type*
type() const7731 Variable::type() const
7732 {
7733   go_assert(this->type_ != NULL);
7734   return this->type_;
7735 }
7736 
7737 // Set the type if necessary.
7738 
7739 void
determine_type()7740 Variable::determine_type()
7741 {
7742   if (this->determined_type_)
7743     return;
7744   this->determined_type_ = true;
7745 
7746   if (this->preinit_ != NULL)
7747     this->preinit_->determine_types();
7748 
7749   // A variable in a type switch with a nil case will have the wrong
7750   // type here.  It will have an initializer which is a type guard.
7751   // We want to initialize it to the value without the type guard, and
7752   // use the type of that value as well.
7753   if (this->is_type_switch_var_
7754       && this->type_ != NULL
7755       && this->type_->is_nil_constant_as_type())
7756     {
7757       Type_guard_expression* tge = this->init_->type_guard_expression();
7758       go_assert(tge != NULL);
7759       this->type_ = NULL;
7760       this->init_ = tge->expr();
7761     }
7762 
7763   if (this->init_ == NULL)
7764     go_assert(this->type_ != NULL && !this->type_->is_abstract());
7765   else if (this->type_from_init_tuple_)
7766     {
7767       Expression *init = this->init_;
7768       init->determine_type_no_context();
7769       this->type_ = this->type_from_tuple(init, true);
7770       this->init_ = NULL;
7771     }
7772   else if (this->type_from_range_index_ || this->type_from_range_value_)
7773     {
7774       Expression* init = this->init_;
7775       init->determine_type_no_context();
7776       this->type_ = this->type_from_range(init, this->type_from_range_index_,
7777 					  true);
7778       this->init_ = NULL;
7779     }
7780   else if (this->type_from_chan_element_)
7781     {
7782       Expression* init = this->init_;
7783       init->determine_type_no_context();
7784       this->type_ = this->type_from_chan_element(init, true);
7785       this->init_ = NULL;
7786     }
7787   else
7788     {
7789       Type_context context(this->type_, false);
7790       this->init_->determine_type(&context);
7791       if (this->type_ == NULL)
7792 	{
7793 	  Type* type = this->init_->type();
7794 	  go_assert(type != NULL);
7795 	  if (type->is_abstract())
7796 	    type = type->make_non_abstract_type();
7797 
7798 	  if (type->is_void_type())
7799 	    {
7800 	      go_error_at(this->location_, "variable has no type");
7801 	      type = Type::make_error_type();
7802 	    }
7803 	  else if (type->is_nil_type())
7804 	    {
7805 	      go_error_at(this->location_, "variable defined to nil type");
7806 	      type = Type::make_error_type();
7807 	    }
7808 	  else if (type->is_call_multiple_result_type())
7809 	    {
7810 	      go_error_at(this->location_,
7811 		       "single variable set to multiple-value function call");
7812 	      type = Type::make_error_type();
7813 	    }
7814 
7815 	  this->type_ = type;
7816 	}
7817     }
7818 }
7819 
7820 // Get the initial value of a variable.  This does not
7821 // consider whether the variable is in the heap--it returns the
7822 // initial value as though it were always stored in the stack.
7823 
7824 Bexpression*
get_init(Gogo * gogo,Named_object * function)7825 Variable::get_init(Gogo* gogo, Named_object* function)
7826 {
7827   go_assert(this->preinit_ == NULL);
7828   Location loc = this->location();
7829   if (this->init_ == NULL)
7830     {
7831       go_assert(!this->is_parameter_);
7832       if (this->is_global_ || this->is_in_heap())
7833 	return NULL;
7834       Btype* btype = this->type()->get_backend(gogo);
7835       return gogo->backend()->zero_expression(btype);
7836     }
7837   else
7838     {
7839       Translate_context context(gogo, function, NULL, NULL);
7840       Expression* init = Expression::make_cast(this->type(), this->init_, loc);
7841       return init->get_backend(&context);
7842     }
7843 }
7844 
7845 // Get the initial value of a variable when a block is required.
7846 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7847 
7848 Bstatement*
get_init_block(Gogo * gogo,Named_object * function,Bvariable * var_decl)7849 Variable::get_init_block(Gogo* gogo, Named_object* function,
7850                          Bvariable* var_decl)
7851 {
7852   go_assert(this->preinit_ != NULL);
7853 
7854   // We want to add the variable assignment to the end of the preinit
7855   // block.
7856 
7857   Translate_context context(gogo, function, NULL, NULL);
7858   Bblock* bblock = this->preinit_->get_backend(&context);
7859   Bfunction* bfunction =
7860       function->func_value()->get_or_make_decl(gogo, function);
7861 
7862   // It's possible to have pre-init statements without an initializer
7863   // if the pre-init statements set the variable.
7864   Bstatement* decl_init = NULL;
7865   if (this->init_ != NULL)
7866     {
7867       if (var_decl == NULL)
7868         {
7869           Bexpression* init_bexpr = this->init_->get_backend(&context);
7870           decl_init = gogo->backend()->expression_statement(bfunction,
7871                                                             init_bexpr);
7872         }
7873       else
7874 	{
7875           Location loc = this->location();
7876           Expression* val_expr =
7877               Expression::make_cast(this->type(), this->init_, loc);
7878           Bexpression* val = val_expr->get_backend(&context);
7879           Bexpression* var_ref =
7880               gogo->backend()->var_expression(var_decl, loc);
7881           decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
7882                                                             val, loc);
7883 	}
7884     }
7885   Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
7886   if (decl_init != NULL)
7887     block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
7888   return block_stmt;
7889 }
7890 
7891 // Export the variable
7892 
7893 void
export_var(Export * exp,const Named_object * no) const7894 Variable::export_var(Export* exp, const Named_object* no) const
7895 {
7896   go_assert(this->is_global_);
7897   exp->write_c_string("var ");
7898   if (no->package() != NULL)
7899     {
7900       char buf[50];
7901       snprintf(buf, sizeof buf, "<p%d>", exp->package_index(no->package()));
7902       exp->write_c_string(buf);
7903     }
7904 
7905   if (!Gogo::is_hidden_name(no->name()))
7906     exp->write_string(no->name());
7907   else
7908     {
7909       exp->write_c_string(".");
7910       exp->write_string(Gogo::unpack_hidden_name(no->name()));
7911     }
7912 
7913   exp->write_c_string(" ");
7914   exp->write_type(this->type());
7915   exp->write_c_string("\n");
7916 }
7917 
7918 // Import a variable.
7919 
7920 bool
import_var(Import * imp,std::string * pname,Package ** ppkg,bool * pis_exported,Type ** ptype)7921 Variable::import_var(Import* imp, std::string* pname, Package** ppkg,
7922 		     bool* pis_exported, Type** ptype)
7923 {
7924   imp->require_c_string("var ");
7925   if (!Import::read_qualified_identifier(imp, pname, ppkg, pis_exported))
7926     {
7927       go_error_at(imp->location(),
7928 		  "import error at %d: bad variable name in export data",
7929 		  imp->pos());
7930       return false;
7931     }
7932   imp->require_c_string(" ");
7933   *ptype = imp->read_type();
7934   imp->require_semicolon_if_old_version();
7935   imp->require_c_string("\n");
7936   return true;
7937 }
7938 
7939 // Convert a variable to the backend representation.
7940 
7941 Bvariable*
get_backend_variable(Gogo * gogo,Named_object * function,const Package * package,const std::string & name)7942 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
7943 			       const Package* package, const std::string& name)
7944 {
7945   if (this->backend_ == NULL)
7946     {
7947       Backend* backend = gogo->backend();
7948       Type* type = this->type_;
7949       if (type->is_error_type()
7950 	  || (type->is_undefined()
7951 	      && (!this->is_global_ || package == NULL)))
7952 	this->backend_ = backend->error_variable();
7953       else
7954 	{
7955 	  bool is_parameter = this->is_parameter_;
7956 	  if (this->is_receiver_ && type->points_to() == NULL)
7957 	    is_parameter = false;
7958 	  if (this->is_in_heap())
7959 	    {
7960 	      is_parameter = false;
7961 	      type = Type::make_pointer_type(type);
7962 	    }
7963 
7964 	  const std::string n = Gogo::unpack_hidden_name(name);
7965 	  Btype* btype = type->get_backend(gogo);
7966 
7967 	  Bvariable* bvar;
7968 	  if (Map_type::is_zero_value(this))
7969 	    bvar = Map_type::backend_zero_value(gogo);
7970 	  else if (this->is_global_)
7971 	    {
7972 	      std::string var_name(package != NULL
7973 				   ? package->package_name()
7974 				   : gogo->package_name());
7975 	      var_name.push_back('.');
7976 	      var_name.append(n);
7977 
7978               std::string asm_name(gogo->global_var_asm_name(name, package));
7979 
7980 	      bool is_hidden = Gogo::is_hidden_name(name);
7981 	      // Hack to export runtime.writeBarrier.  FIXME.
7982 	      // This is because go:linkname doesn't work on variables.
7983 	      if (gogo->compiling_runtime()
7984 		  && var_name == "runtime.writeBarrier")
7985 		is_hidden = false;
7986 
7987 	      // If an inline body refers to this variable, then it
7988 	      // needs to be visible in the symbol table.
7989 	      if (this->is_referenced_by_inline_)
7990 		is_hidden = false;
7991 
7992 	      // If this variable is in a different package, then it
7993 	      // can't be treated as a hidden symbol.  This case can
7994 	      // arise when an inlined function refers to a
7995 	      // package-scope unexported variable.
7996 	      if (package != NULL)
7997 		is_hidden = false;
7998 
7999 	      bvar = backend->global_variable(var_name,
8000 					      asm_name,
8001 					      btype,
8002 					      package != NULL,
8003 					      is_hidden,
8004 					      this->in_unique_section_,
8005 					      this->location_);
8006 	    }
8007 	  else if (function == NULL)
8008 	    {
8009 	      go_assert(saw_errors());
8010 	      bvar = backend->error_variable();
8011 	    }
8012 	  else
8013 	    {
8014 	      Bfunction* bfunction = function->func_value()->get_decl();
8015 	      bool is_address_taken = (this->is_non_escaping_address_taken_
8016 				       && !this->is_in_heap());
8017 	      if (this->is_closure())
8018 		bvar = backend->static_chain_variable(bfunction, n, btype,
8019 						      this->location_);
8020 	      else if (is_parameter)
8021 		bvar = backend->parameter_variable(bfunction, n, btype,
8022 						   is_address_taken,
8023 						   this->location_);
8024 	      else
8025                 {
8026                   Bvariable* bvar_decl = NULL;
8027                   if (this->toplevel_decl_ != NULL)
8028                     {
8029                       Translate_context context(gogo, NULL, NULL, NULL);
8030                       bvar_decl = this->toplevel_decl_->temporary_statement()
8031                         ->get_backend_variable(&context);
8032                     }
8033                   bvar = backend->local_variable(bfunction, n, btype,
8034                                                  bvar_decl,
8035                                                  is_address_taken,
8036                                                  this->location_);
8037                 }
8038 	    }
8039 	  this->backend_ = bvar;
8040 	}
8041     }
8042   return this->backend_;
8043 }
8044 
8045 // Class Result_variable.
8046 
8047 // Convert a result variable to the backend representation.
8048 
8049 Bvariable*
get_backend_variable(Gogo * gogo,Named_object * function,const std::string & name)8050 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
8051 				      const std::string& name)
8052 {
8053   if (this->backend_ == NULL)
8054     {
8055       Backend* backend = gogo->backend();
8056       Type* type = this->type_;
8057       if (type->is_error())
8058 	this->backend_ = backend->error_variable();
8059       else
8060 	{
8061 	  if (this->is_in_heap())
8062 	    type = Type::make_pointer_type(type);
8063 	  Btype* btype = type->get_backend(gogo);
8064 	  Bfunction* bfunction = function->func_value()->get_decl();
8065 	  std::string n = Gogo::unpack_hidden_name(name);
8066 	  bool is_address_taken = (this->is_non_escaping_address_taken_
8067 				   && !this->is_in_heap());
8068 	  this->backend_ = backend->local_variable(bfunction, n, btype,
8069 						   NULL, is_address_taken,
8070 						   this->location_);
8071 	}
8072     }
8073   return this->backend_;
8074 }
8075 
8076 // Class Named_constant.
8077 
8078 // Set the type of a named constant.  This is only used to set the
8079 // type to an error type.
8080 
8081 void
set_type(Type * t)8082 Named_constant::set_type(Type* t)
8083 {
8084   go_assert(this->type_ == NULL || t->is_error_type());
8085   this->type_ = t;
8086 }
8087 
8088 // Traverse the initializer expression.
8089 
8090 int
traverse_expression(Traverse * traverse)8091 Named_constant::traverse_expression(Traverse* traverse)
8092 {
8093   return Expression::traverse(&this->expr_, traverse);
8094 }
8095 
8096 // Determine the type of the constant.
8097 
8098 void
determine_type()8099 Named_constant::determine_type()
8100 {
8101   if (this->type_ != NULL)
8102     {
8103       Type_context context(this->type_, false);
8104       this->expr_->determine_type(&context);
8105     }
8106   else
8107     {
8108       // A constant may have an abstract type.
8109       Type_context context(NULL, true);
8110       this->expr_->determine_type(&context);
8111       this->type_ = this->expr_->type();
8112       go_assert(this->type_ != NULL);
8113     }
8114 }
8115 
8116 // Indicate that we found and reported an error for this constant.
8117 
8118 void
set_error()8119 Named_constant::set_error()
8120 {
8121   this->type_ = Type::make_error_type();
8122   this->expr_ = Expression::make_error(this->location_);
8123 }
8124 
8125 // Export a constant.
8126 
8127 void
export_const(Export * exp,const std::string & name) const8128 Named_constant::export_const(Export* exp, const std::string& name) const
8129 {
8130   exp->write_c_string("const ");
8131   exp->write_string(name);
8132   exp->write_c_string(" ");
8133   if (!this->type_->is_abstract())
8134     {
8135       exp->write_type(this->type_);
8136       exp->write_c_string(" ");
8137     }
8138   exp->write_c_string("= ");
8139 
8140   Export_function_body efb(exp, 0);
8141   if (!this->type_->is_abstract())
8142     efb.set_type_context(this->type_);
8143   this->expr()->export_expression(&efb);
8144   exp->write_string(efb.body());
8145 
8146   exp->write_c_string("\n");
8147 }
8148 
8149 // Import a constant.
8150 
8151 void
import_const(Import * imp,std::string * pname,Type ** ptype,Expression ** pexpr)8152 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
8153 			     Expression** pexpr)
8154 {
8155   imp->require_c_string("const ");
8156   *pname = imp->read_identifier();
8157   imp->require_c_string(" ");
8158   if (imp->peek_char() == '=')
8159     *ptype = NULL;
8160   else
8161     {
8162       *ptype = imp->read_type();
8163       imp->require_c_string(" ");
8164     }
8165   imp->require_c_string("= ");
8166   *pexpr = Expression::import_expression(imp, imp->location());
8167   imp->require_semicolon_if_old_version();
8168   imp->require_c_string("\n");
8169 }
8170 
8171 // Get the backend representation.
8172 
8173 Bexpression*
get_backend(Gogo * gogo,Named_object * const_no)8174 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
8175 {
8176   if (this->bconst_ == NULL)
8177     {
8178       Translate_context subcontext(gogo, NULL, NULL, NULL);
8179       Type* type = this->type();
8180       Location loc = this->location();
8181 
8182       Expression* const_ref = Expression::make_const_reference(const_no, loc);
8183       Bexpression* const_decl = const_ref->get_backend(&subcontext);
8184       if (type != NULL && type->is_numeric_type())
8185 	{
8186 	  Btype* btype = type->get_backend(gogo);
8187 	  std::string name = const_no->get_id(gogo);
8188 	  const_decl =
8189 	    gogo->backend()->named_constant_expression(btype, name,
8190 						       const_decl, loc);
8191 	}
8192       this->bconst_ = const_decl;
8193     }
8194   return this->bconst_;
8195 }
8196 
8197 // Add a method.
8198 
8199 Named_object*
add_method(const std::string & name,Function * function)8200 Type_declaration::add_method(const std::string& name, Function* function)
8201 {
8202   Named_object* ret = Named_object::make_function(name, NULL, function);
8203   this->methods_.push_back(ret);
8204   return ret;
8205 }
8206 
8207 // Add a method declaration.
8208 
8209 Named_object*
add_method_declaration(const std::string & name,Package * package,Function_type * type,Location location)8210 Type_declaration::add_method_declaration(const std::string&  name,
8211 					 Package* package,
8212 					 Function_type* type,
8213 					 Location location)
8214 {
8215   Named_object* ret = Named_object::make_function_declaration(name, package,
8216 							      type, location);
8217   this->methods_.push_back(ret);
8218   return ret;
8219 }
8220 
8221 // Return whether any methods are defined.
8222 
8223 bool
has_methods() const8224 Type_declaration::has_methods() const
8225 {
8226   return !this->methods_.empty();
8227 }
8228 
8229 // Define methods for the real type.
8230 
8231 void
define_methods(Named_type * nt)8232 Type_declaration::define_methods(Named_type* nt)
8233 {
8234   if (this->methods_.empty())
8235     return;
8236 
8237   while (nt->is_alias())
8238     {
8239       Type *t = nt->real_type()->forwarded();
8240       if (t->named_type() != NULL)
8241 	nt = t->named_type();
8242       else if (t->forward_declaration_type() != NULL)
8243 	{
8244 	  Named_object* no = t->forward_declaration_type()->named_object();
8245 	  Type_declaration* td = no->type_declaration_value();
8246 	  td->methods_.insert(td->methods_.end(), this->methods_.begin(),
8247 			      this->methods_.end());
8248 	  this->methods_.clear();
8249 	  return;
8250 	}
8251       else
8252 	{
8253 	  for (std::vector<Named_object*>::const_iterator p =
8254 		 this->methods_.begin();
8255 	       p != this->methods_.end();
8256 	       ++p)
8257 	    go_error_at((*p)->location(),
8258 			("invalid receiver type "
8259 			 "(receiver must be a named type)"));
8260 	  return;
8261 	}
8262     }
8263 
8264   for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
8265        p != this->methods_.end();
8266        ++p)
8267     {
8268       if ((*p)->is_function_declaration()
8269 	  || !(*p)->func_value()->is_sink())
8270 	nt->add_existing_method(*p);
8271     }
8272 }
8273 
8274 // We are using the type.  Return true if we should issue a warning.
8275 
8276 bool
using_type()8277 Type_declaration::using_type()
8278 {
8279   bool ret = !this->issued_warning_;
8280   this->issued_warning_ = true;
8281   return ret;
8282 }
8283 
8284 // Class Unknown_name.
8285 
8286 // Set the real named object.
8287 
8288 void
set_real_named_object(Named_object * no)8289 Unknown_name::set_real_named_object(Named_object* no)
8290 {
8291   go_assert(this->real_named_object_ == NULL);
8292   go_assert(!no->is_unknown());
8293   this->real_named_object_ = no;
8294 }
8295 
8296 // Class Named_object.
8297 
Named_object(const std::string & name,const Package * package,Classification classification)8298 Named_object::Named_object(const std::string& name,
8299 			   const Package* package,
8300 			   Classification classification)
8301   : name_(name), package_(package), classification_(classification),
8302     is_redefinition_(false)
8303 {
8304   if (Gogo::is_sink_name(name))
8305     go_assert(classification == NAMED_OBJECT_SINK);
8306 }
8307 
8308 // Make an unknown name.  This is used by the parser.  The name must
8309 // be resolved later.  Unknown names are only added in the current
8310 // package.
8311 
8312 Named_object*
make_unknown_name(const std::string & name,Location location)8313 Named_object::make_unknown_name(const std::string& name,
8314 				Location location)
8315 {
8316   Named_object* named_object = new Named_object(name, NULL,
8317 						NAMED_OBJECT_UNKNOWN);
8318   Unknown_name* value = new Unknown_name(location);
8319   named_object->u_.unknown_value = value;
8320   return named_object;
8321 }
8322 
8323 // Make a constant.
8324 
8325 Named_object*
make_constant(const Typed_identifier & tid,const Package * package,Expression * expr,int iota_value)8326 Named_object::make_constant(const Typed_identifier& tid,
8327 			    const Package* package, Expression* expr,
8328 			    int iota_value)
8329 {
8330   Named_object* named_object = new Named_object(tid.name(), package,
8331 						NAMED_OBJECT_CONST);
8332   Named_constant* named_constant = new Named_constant(tid.type(), expr,
8333 						      iota_value,
8334 						      tid.location());
8335   named_object->u_.const_value = named_constant;
8336   return named_object;
8337 }
8338 
8339 // Make a named type.
8340 
8341 Named_object*
make_type(const std::string & name,const Package * package,Type * type,Location location)8342 Named_object::make_type(const std::string& name, const Package* package,
8343 			Type* type, Location location)
8344 {
8345   Named_object* named_object = new Named_object(name, package,
8346 						NAMED_OBJECT_TYPE);
8347   Named_type* named_type = Type::make_named_type(named_object, type, location);
8348   named_object->u_.type_value = named_type;
8349   return named_object;
8350 }
8351 
8352 // Make a type declaration.
8353 
8354 Named_object*
make_type_declaration(const std::string & name,const Package * package,Location location)8355 Named_object::make_type_declaration(const std::string& name,
8356 				    const Package* package,
8357 				    Location location)
8358 {
8359   Named_object* named_object = new Named_object(name, package,
8360 						NAMED_OBJECT_TYPE_DECLARATION);
8361   Type_declaration* type_declaration = new Type_declaration(location);
8362   named_object->u_.type_declaration = type_declaration;
8363   return named_object;
8364 }
8365 
8366 // Make a variable.
8367 
8368 Named_object*
make_variable(const std::string & name,const Package * package,Variable * variable)8369 Named_object::make_variable(const std::string& name, const Package* package,
8370 			    Variable* variable)
8371 {
8372   Named_object* named_object = new Named_object(name, package,
8373 						NAMED_OBJECT_VAR);
8374   named_object->u_.var_value = variable;
8375   return named_object;
8376 }
8377 
8378 // Make a result variable.
8379 
8380 Named_object*
make_result_variable(const std::string & name,Result_variable * result)8381 Named_object::make_result_variable(const std::string& name,
8382 				   Result_variable* result)
8383 {
8384   Named_object* named_object = new Named_object(name, NULL,
8385 						NAMED_OBJECT_RESULT_VAR);
8386   named_object->u_.result_var_value = result;
8387   return named_object;
8388 }
8389 
8390 // Make a sink.  This is used for the special blank identifier _.
8391 
8392 Named_object*
make_sink()8393 Named_object::make_sink()
8394 {
8395   return new Named_object("_", NULL, NAMED_OBJECT_SINK);
8396 }
8397 
8398 // Make a named function.
8399 
8400 Named_object*
make_function(const std::string & name,const Package * package,Function * function)8401 Named_object::make_function(const std::string& name, const Package* package,
8402 			    Function* function)
8403 {
8404   Named_object* named_object = new Named_object(name, package,
8405 						NAMED_OBJECT_FUNC);
8406   named_object->u_.func_value = function;
8407   return named_object;
8408 }
8409 
8410 // Make a function declaration.
8411 
8412 Named_object*
make_function_declaration(const std::string & name,const Package * package,Function_type * fntype,Location location)8413 Named_object::make_function_declaration(const std::string& name,
8414 					const Package* package,
8415 					Function_type* fntype,
8416 					Location location)
8417 {
8418   Named_object* named_object = new Named_object(name, package,
8419 						NAMED_OBJECT_FUNC_DECLARATION);
8420   Function_declaration *func_decl = new Function_declaration(fntype, location);
8421   named_object->u_.func_declaration_value = func_decl;
8422   return named_object;
8423 }
8424 
8425 // Make a package.
8426 
8427 Named_object*
make_package(const std::string & alias,Package * package)8428 Named_object::make_package(const std::string& alias, Package* package)
8429 {
8430   Named_object* named_object = new Named_object(alias, NULL,
8431 						NAMED_OBJECT_PACKAGE);
8432   named_object->u_.package_value = package;
8433   return named_object;
8434 }
8435 
8436 // Return the name to use in an error message.
8437 
8438 std::string
message_name() const8439 Named_object::message_name() const
8440 {
8441   if (this->package_ == NULL)
8442     return Gogo::message_name(this->name_);
8443   std::string ret;
8444   if (this->package_->has_package_name())
8445     ret = this->package_->package_name();
8446   else
8447     ret = this->package_->pkgpath();
8448   ret = Gogo::message_name(ret);
8449   ret += '.';
8450   ret += Gogo::message_name(this->name_);
8451   return ret;
8452 }
8453 
8454 // Set the type when a declaration is defined.
8455 
8456 void
set_type_value(Named_type * named_type)8457 Named_object::set_type_value(Named_type* named_type)
8458 {
8459   go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
8460   Type_declaration* td = this->u_.type_declaration;
8461   td->define_methods(named_type);
8462   unsigned int index;
8463   Named_object* in_function = td->in_function(&index);
8464   if (in_function != NULL)
8465     named_type->set_in_function(in_function, index);
8466   delete td;
8467   this->classification_ = NAMED_OBJECT_TYPE;
8468   this->u_.type_value = named_type;
8469 }
8470 
8471 // Define a function which was previously declared.
8472 
8473 void
set_function_value(Function * function)8474 Named_object::set_function_value(Function* function)
8475 {
8476   go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
8477   if (this->func_declaration_value()->has_descriptor())
8478     {
8479       Expression* descriptor =
8480 	this->func_declaration_value()->descriptor(NULL, NULL);
8481       function->set_descriptor(descriptor);
8482     }
8483   this->classification_ = NAMED_OBJECT_FUNC;
8484   // FIXME: We should free the old value.
8485   this->u_.func_value = function;
8486 }
8487 
8488 // Declare an unknown object as a type declaration.
8489 
8490 void
declare_as_type()8491 Named_object::declare_as_type()
8492 {
8493   go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
8494   Unknown_name* unk = this->u_.unknown_value;
8495   this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
8496   this->u_.type_declaration = new Type_declaration(unk->location());
8497   delete unk;
8498 }
8499 
8500 // Return the location of a named object.
8501 
8502 Location
location() const8503 Named_object::location() const
8504 {
8505   switch (this->classification_)
8506     {
8507     default:
8508     case NAMED_OBJECT_UNINITIALIZED:
8509       go_unreachable();
8510 
8511     case NAMED_OBJECT_ERRONEOUS:
8512       return Linemap::unknown_location();
8513 
8514     case NAMED_OBJECT_UNKNOWN:
8515       return this->unknown_value()->location();
8516 
8517     case NAMED_OBJECT_CONST:
8518       return this->const_value()->location();
8519 
8520     case NAMED_OBJECT_TYPE:
8521       return this->type_value()->location();
8522 
8523     case NAMED_OBJECT_TYPE_DECLARATION:
8524       return this->type_declaration_value()->location();
8525 
8526     case NAMED_OBJECT_VAR:
8527       return this->var_value()->location();
8528 
8529     case NAMED_OBJECT_RESULT_VAR:
8530       return this->result_var_value()->location();
8531 
8532     case NAMED_OBJECT_SINK:
8533       go_unreachable();
8534 
8535     case NAMED_OBJECT_FUNC:
8536       return this->func_value()->location();
8537 
8538     case NAMED_OBJECT_FUNC_DECLARATION:
8539       return this->func_declaration_value()->location();
8540 
8541     case NAMED_OBJECT_PACKAGE:
8542       return this->package_value()->location();
8543     }
8544 }
8545 
8546 // Export a named object.
8547 
8548 void
export_named_object(Export * exp) const8549 Named_object::export_named_object(Export* exp) const
8550 {
8551   switch (this->classification_)
8552     {
8553     default:
8554     case NAMED_OBJECT_UNINITIALIZED:
8555     case NAMED_OBJECT_UNKNOWN:
8556       go_unreachable();
8557 
8558     case NAMED_OBJECT_ERRONEOUS:
8559       break;
8560 
8561     case NAMED_OBJECT_CONST:
8562       this->const_value()->export_const(exp, this->name_);
8563       break;
8564 
8565     case NAMED_OBJECT_TYPE:
8566       // Types are handled by export::write_types.
8567       go_unreachable();
8568 
8569     case NAMED_OBJECT_TYPE_DECLARATION:
8570       go_error_at(this->type_declaration_value()->location(),
8571 		  "attempt to export %<%s%> which was declared but not defined",
8572 		  this->message_name().c_str());
8573       break;
8574 
8575     case NAMED_OBJECT_FUNC_DECLARATION:
8576       this->func_declaration_value()->export_func(exp, this);
8577       break;
8578 
8579     case NAMED_OBJECT_VAR:
8580       this->var_value()->export_var(exp, this);
8581       break;
8582 
8583     case NAMED_OBJECT_RESULT_VAR:
8584     case NAMED_OBJECT_SINK:
8585       go_unreachable();
8586 
8587     case NAMED_OBJECT_FUNC:
8588       this->func_value()->export_func(exp, this);
8589       break;
8590     }
8591 }
8592 
8593 // Convert a variable to the backend representation.
8594 
8595 Bvariable*
get_backend_variable(Gogo * gogo,Named_object * function)8596 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
8597 {
8598   if (this->classification_ == NAMED_OBJECT_VAR)
8599     return this->var_value()->get_backend_variable(gogo, function,
8600 						   this->package_, this->name_);
8601   else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
8602     return this->result_var_value()->get_backend_variable(gogo, function,
8603 							  this->name_);
8604   else
8605     go_unreachable();
8606 }
8607 
8608 // Return the external identifier for this object.
8609 
8610 std::string
get_id(Gogo * gogo)8611 Named_object::get_id(Gogo* gogo)
8612 {
8613   go_assert(!this->is_variable()
8614 	    && !this->is_result_variable()
8615 	    && !this->is_type());
8616   std::string decl_name;
8617   if (this->is_function_declaration()
8618       && !this->func_declaration_value()->asm_name().empty())
8619     decl_name = this->func_declaration_value()->asm_name();
8620   else
8621     {
8622       std::string package_name;
8623       if (this->package_ == NULL)
8624 	package_name = gogo->package_name();
8625       else
8626 	package_name = this->package_->package_name();
8627 
8628       // Note that this will be misleading if this is an unexported
8629       // method generated for an embedded imported type.  In that case
8630       // the unexported method should have the package name of the
8631       // package from which it is imported, but we are going to give
8632       // it our package name.  Fixing this would require knowing the
8633       // package name, but we only know the package path.  It might be
8634       // better to use package paths here anyhow.  This doesn't affect
8635       // the assembler code, because we always set that name in
8636       // Function::get_or_make_decl anyhow.  FIXME.
8637 
8638       decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
8639 
8640       Function_type* fntype;
8641       if (this->is_function())
8642 	fntype = this->func_value()->type();
8643       else if (this->is_function_declaration())
8644 	fntype = this->func_declaration_value()->type();
8645       else
8646 	fntype = NULL;
8647       if (fntype != NULL && fntype->is_method())
8648 	{
8649 	  decl_name.push_back('.');
8650 	  decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
8651 	}
8652     }
8653   return decl_name;
8654 }
8655 
8656 void
debug_go_named_object(Named_object * no)8657 debug_go_named_object(Named_object* no)
8658 {
8659   if (no == NULL)
8660     {
8661       std::cerr << "<null>";
8662       return;
8663     }
8664   std::cerr << "'" << no->name() << "': ";
8665   const char *tag;
8666   switch (no->classification())
8667     {
8668       case Named_object::NAMED_OBJECT_UNINITIALIZED:
8669         tag = "uninitialized";
8670         break;
8671       case Named_object::NAMED_OBJECT_ERRONEOUS:
8672         tag = "<error>";
8673         break;
8674       case Named_object::NAMED_OBJECT_UNKNOWN:
8675         tag = "<unknown>";
8676         break;
8677       case Named_object::NAMED_OBJECT_CONST:
8678         tag = "constant";
8679         break;
8680       case Named_object::NAMED_OBJECT_TYPE:
8681         tag = "type";
8682         break;
8683       case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8684         tag = "type_decl";
8685         break;
8686       case Named_object::NAMED_OBJECT_VAR:
8687         tag = "var";
8688         break;
8689       case Named_object::NAMED_OBJECT_RESULT_VAR:
8690         tag = "result_var";
8691         break;
8692       case Named_object::NAMED_OBJECT_SINK:
8693         tag = "<sink>";
8694         break;
8695       case Named_object::NAMED_OBJECT_FUNC:
8696         tag = "func";
8697         break;
8698       case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8699         tag = "func_decl";
8700         break;
8701       case Named_object::NAMED_OBJECT_PACKAGE:
8702         tag = "package";
8703         break;
8704       default:
8705         tag = "<unknown named object classification>";
8706         break;
8707   };
8708   std::cerr << tag << "\n";
8709 }
8710 
8711 // Get the backend representation for this named object.
8712 
8713 void
get_backend(Gogo * gogo,std::vector<Bexpression * > & const_decls,std::vector<Btype * > & type_decls,std::vector<Bfunction * > & func_decls)8714 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
8715                           std::vector<Btype*>& type_decls,
8716                           std::vector<Bfunction*>& func_decls)
8717 {
8718   // If this is a definition, avoid trying to get the backend
8719   // representation, as that can crash.
8720   if (this->is_redefinition_)
8721     {
8722       go_assert(saw_errors());
8723       return;
8724     }
8725 
8726   switch (this->classification_)
8727     {
8728     case NAMED_OBJECT_CONST:
8729       if (!Gogo::is_erroneous_name(this->name_))
8730 	const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
8731       break;
8732 
8733     case NAMED_OBJECT_TYPE:
8734       {
8735         Named_type* named_type = this->u_.type_value;
8736 
8737         // No need to do anything for aliases-- whatever has to be done
8738         // can be done for the alias target.
8739         if (named_type->is_alias())
8740           break;
8741 
8742 	if (!Gogo::is_erroneous_name(this->name_))
8743 	  type_decls.push_back(named_type->get_backend(gogo));
8744 
8745         // We need to produce a type descriptor for every named
8746         // type, and for a pointer to every named type, since
8747         // other files or packages might refer to them.  We need
8748         // to do this even for hidden types, because they might
8749         // still be returned by some function.  Simply calling the
8750         // type_descriptor method is enough to create the type
8751         // descriptor, even though we don't do anything with it.
8752         if (this->package_ == NULL && !saw_errors())
8753           {
8754             named_type->
8755                 type_descriptor_pointer(gogo, Linemap::predeclared_location());
8756 	    named_type->gc_symbol_pointer(gogo);
8757             Type* pn = Type::make_pointer_type(named_type);
8758             pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
8759 	    pn->gc_symbol_pointer(gogo);
8760           }
8761       }
8762       break;
8763 
8764     case NAMED_OBJECT_TYPE_DECLARATION:
8765       go_error_at(Linemap::unknown_location(),
8766 		  "reference to undefined type %qs",
8767 		  this->message_name().c_str());
8768       return;
8769 
8770     case NAMED_OBJECT_VAR:
8771     case NAMED_OBJECT_RESULT_VAR:
8772     case NAMED_OBJECT_SINK:
8773       go_unreachable();
8774 
8775     case NAMED_OBJECT_FUNC:
8776       {
8777 	Function* func = this->u_.func_value;
8778 	if (!Gogo::is_erroneous_name(this->name_))
8779 	  func_decls.push_back(func->get_or_make_decl(gogo, this));
8780 
8781 	if (func->block() != NULL)
8782 	  func->build(gogo, this);
8783       }
8784       break;
8785 
8786     case NAMED_OBJECT_ERRONEOUS:
8787       break;
8788 
8789     default:
8790       go_unreachable();
8791     }
8792 }
8793 
8794 // Class Bindings.
8795 
Bindings(Bindings * enclosing)8796 Bindings::Bindings(Bindings* enclosing)
8797   : enclosing_(enclosing), named_objects_(), bindings_()
8798 {
8799 }
8800 
8801 // Clear imports.
8802 
8803 void
clear_file_scope(Gogo * gogo)8804 Bindings::clear_file_scope(Gogo* gogo)
8805 {
8806   Contour::iterator p = this->bindings_.begin();
8807   while (p != this->bindings_.end())
8808     {
8809       bool keep;
8810       if (p->second->package() != NULL)
8811 	keep = false;
8812       else if (p->second->is_package())
8813 	keep = false;
8814       else if (p->second->is_function()
8815 	       && !p->second->func_value()->type()->is_method()
8816 	       && Gogo::unpack_hidden_name(p->second->name()) == "init")
8817 	keep = false;
8818       else
8819 	keep = true;
8820 
8821       if (keep)
8822 	++p;
8823       else
8824 	{
8825 	  gogo->add_file_block_name(p->second->name(), p->second->location());
8826 	  p = this->bindings_.erase(p);
8827 	}
8828     }
8829 }
8830 
8831 // Look up a symbol.
8832 
8833 Named_object*
lookup(const std::string & name) const8834 Bindings::lookup(const std::string& name) const
8835 {
8836   Contour::const_iterator p = this->bindings_.find(name);
8837   if (p != this->bindings_.end())
8838     return p->second->resolve();
8839   else if (this->enclosing_ != NULL)
8840     return this->enclosing_->lookup(name);
8841   else
8842     return NULL;
8843 }
8844 
8845 // Look up a symbol locally.
8846 
8847 Named_object*
lookup_local(const std::string & name) const8848 Bindings::lookup_local(const std::string& name) const
8849 {
8850   Contour::const_iterator p = this->bindings_.find(name);
8851   if (p == this->bindings_.end())
8852     return NULL;
8853   return p->second;
8854 }
8855 
8856 // Remove an object from a set of bindings.  This is used for a
8857 // special case in thunks for functions which call recover.
8858 
8859 void
remove_binding(Named_object * no)8860 Bindings::remove_binding(Named_object* no)
8861 {
8862   Contour::iterator pb = this->bindings_.find(no->name());
8863   go_assert(pb != this->bindings_.end());
8864   this->bindings_.erase(pb);
8865   for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
8866        pn != this->named_objects_.end();
8867        ++pn)
8868     {
8869       if (*pn == no)
8870 	{
8871 	  this->named_objects_.erase(pn);
8872 	  return;
8873 	}
8874     }
8875   go_unreachable();
8876 }
8877 
8878 // Add a method to the list of objects.  This is not added to the
8879 // lookup table.  This is so that we have a single list of objects
8880 // declared at the top level, which we walk through when it's time to
8881 // convert to trees.
8882 
8883 void
add_method(Named_object * method)8884 Bindings::add_method(Named_object* method)
8885 {
8886   this->named_objects_.push_back(method);
8887 }
8888 
8889 // Add a generic Named_object to a Contour.
8890 
8891 Named_object*
add_named_object_to_contour(Contour * contour,Named_object * named_object)8892 Bindings::add_named_object_to_contour(Contour* contour,
8893 				      Named_object* named_object)
8894 {
8895   go_assert(named_object == named_object->resolve());
8896   const std::string& name(named_object->name());
8897   go_assert(!Gogo::is_sink_name(name));
8898 
8899   std::pair<Contour::iterator, bool> ins =
8900     contour->insert(std::make_pair(name, named_object));
8901   if (!ins.second)
8902     {
8903       // The name was already there.
8904       if (named_object->package() != NULL
8905 	  && ins.first->second->package() == named_object->package()
8906 	  && (ins.first->second->classification()
8907 	      == named_object->classification()))
8908 	{
8909 	  // This is a second import of the same object.
8910 	  return ins.first->second;
8911 	}
8912       ins.first->second = this->new_definition(ins.first->second,
8913 					       named_object);
8914       return ins.first->second;
8915     }
8916   else
8917     {
8918       // Don't push declarations on the list.  We push them on when
8919       // and if we find the definitions.  That way we genericize the
8920       // functions in order.
8921       if (!named_object->is_type_declaration()
8922 	  && !named_object->is_function_declaration()
8923 	  && !named_object->is_unknown())
8924 	this->named_objects_.push_back(named_object);
8925       return named_object;
8926     }
8927 }
8928 
8929 // We had an existing named object OLD_OBJECT, and we've seen a new
8930 // one NEW_OBJECT with the same name.  FIXME: This does not free the
8931 // new object when we don't need it.
8932 
8933 Named_object*
new_definition(Named_object * old_object,Named_object * new_object)8934 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
8935 {
8936   if (new_object->is_erroneous() && !old_object->is_erroneous())
8937     return new_object;
8938 
8939   std::string reason;
8940   switch (old_object->classification())
8941     {
8942     default:
8943     case Named_object::NAMED_OBJECT_UNINITIALIZED:
8944       go_unreachable();
8945 
8946     case Named_object::NAMED_OBJECT_ERRONEOUS:
8947       return old_object;
8948 
8949     case Named_object::NAMED_OBJECT_UNKNOWN:
8950       {
8951 	Named_object* real = old_object->unknown_value()->real_named_object();
8952 	if (real != NULL)
8953 	  return this->new_definition(real, new_object);
8954 	go_assert(!new_object->is_unknown());
8955 	old_object->unknown_value()->set_real_named_object(new_object);
8956 	if (!new_object->is_type_declaration()
8957 	    && !new_object->is_function_declaration())
8958 	  this->named_objects_.push_back(new_object);
8959 	return new_object;
8960       }
8961 
8962     case Named_object::NAMED_OBJECT_CONST:
8963       break;
8964 
8965     case Named_object::NAMED_OBJECT_TYPE:
8966       if (new_object->is_type_declaration())
8967 	return old_object;
8968       break;
8969 
8970     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8971       if (new_object->is_type_declaration())
8972 	return old_object;
8973       if (new_object->is_type())
8974 	{
8975 	  old_object->set_type_value(new_object->type_value());
8976 	  new_object->type_value()->set_named_object(old_object);
8977 	  this->named_objects_.push_back(old_object);
8978 	  return old_object;
8979 	}
8980       break;
8981 
8982     case Named_object::NAMED_OBJECT_VAR:
8983     case Named_object::NAMED_OBJECT_RESULT_VAR:
8984       // We have already given an error in the parser for cases where
8985       // one parameter or result variable redeclares another one.
8986       if ((new_object->is_variable()
8987 	   && new_object->var_value()->is_parameter())
8988 	  || new_object->is_result_variable())
8989 	return old_object;
8990       break;
8991 
8992     case Named_object::NAMED_OBJECT_SINK:
8993       go_unreachable();
8994 
8995     case Named_object::NAMED_OBJECT_FUNC:
8996       break;
8997 
8998     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8999       {
9000 	// We declare the hash and equality functions before defining
9001 	// them, because we sometimes see that we need the declaration
9002 	// while we are in the middle of a different function.
9003 	//
9004 	// We declare the main function before the user defines it, to
9005 	// give better error messages.
9006 	//
9007 	// We declare inline functions before we define them, as we
9008 	// only define them if we need them.
9009 	if (new_object->is_function()
9010 	    && ((Linemap::is_predeclared_location(old_object->location())
9011 		 && Linemap::is_predeclared_location(new_object->location()))
9012 		|| (Gogo::unpack_hidden_name(old_object->name()) == "main"
9013 		    && Linemap::is_unknown_location(old_object->location()))
9014 		|| (new_object->package() != NULL
9015 		    && old_object->func_declaration_value()->has_imported_body()
9016 		    && new_object->func_value()->is_inline_only())))
9017 	  {
9018             Function_type* old_type =
9019                 old_object->func_declaration_value()->type();
9020 	    Function_type* new_type = new_object->func_value()->type();
9021 	    if (old_type->is_valid_redeclaration(new_type, &reason))
9022 	      {
9023 		Function_declaration* fd =
9024 		  old_object->func_declaration_value();
9025 		go_assert(fd->asm_name().empty());
9026 		old_object->set_function_value(new_object->func_value());
9027 		this->named_objects_.push_back(old_object);
9028 		return old_object;
9029 	      }
9030 	  }
9031       }
9032       break;
9033 
9034     case Named_object::NAMED_OBJECT_PACKAGE:
9035       break;
9036     }
9037 
9038   std::string n = old_object->message_name();
9039   if (reason.empty())
9040     go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
9041   else
9042     go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
9043 		reason.c_str());
9044   old_object->set_is_redefinition();
9045   new_object->set_is_redefinition();
9046 
9047   if (!Linemap::is_unknown_location(old_object->location())
9048       && !Linemap::is_predeclared_location(old_object->location()))
9049     go_inform(old_object->location(), "previous definition of %qs was here",
9050 	      n.c_str());
9051 
9052   return old_object;
9053 }
9054 
9055 // Add a named type.
9056 
9057 Named_object*
add_named_type(Named_type * named_type)9058 Bindings::add_named_type(Named_type* named_type)
9059 {
9060   return this->add_named_object(named_type->named_object());
9061 }
9062 
9063 // Add a function.
9064 
9065 Named_object*
add_function(const std::string & name,const Package * package,Function * function)9066 Bindings::add_function(const std::string& name, const Package* package,
9067 		       Function* function)
9068 {
9069   return this->add_named_object(Named_object::make_function(name, package,
9070 							    function));
9071 }
9072 
9073 // Add a function declaration.
9074 
9075 Named_object*
add_function_declaration(const std::string & name,const Package * package,Function_type * type,Location location)9076 Bindings::add_function_declaration(const std::string& name,
9077 				   const Package* package,
9078 				   Function_type* type,
9079 				   Location location)
9080 {
9081   Named_object* no = Named_object::make_function_declaration(name, package,
9082 							     type, location);
9083   return this->add_named_object(no);
9084 }
9085 
9086 // Define a type which was previously declared.
9087 
9088 void
define_type(Named_object * no,Named_type * type)9089 Bindings::define_type(Named_object* no, Named_type* type)
9090 {
9091   no->set_type_value(type);
9092   this->named_objects_.push_back(no);
9093 }
9094 
9095 // Mark all local variables as used.  This is used for some types of
9096 // parse error.
9097 
9098 void
mark_locals_used()9099 Bindings::mark_locals_used()
9100 {
9101   for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
9102        p != this->named_objects_.end();
9103        ++p)
9104     if ((*p)->is_variable())
9105       (*p)->var_value()->set_is_used();
9106 }
9107 
9108 // Traverse bindings.
9109 
9110 int
traverse(Traverse * traverse,bool is_global)9111 Bindings::traverse(Traverse* traverse, bool is_global)
9112 {
9113   unsigned int traverse_mask = traverse->traverse_mask();
9114 
9115   // We don't use an iterator because we permit the traversal to add
9116   // new global objects.
9117   const unsigned int e_or_t = (Traverse::traverse_expressions
9118 			       | Traverse::traverse_types);
9119   const unsigned int e_or_t_or_s = (e_or_t
9120 				    | Traverse::traverse_statements);
9121   for (size_t i = 0; i < this->named_objects_.size(); ++i)
9122     {
9123       Named_object* p = this->named_objects_[i];
9124       int t = TRAVERSE_CONTINUE;
9125       switch (p->classification())
9126 	{
9127 	case Named_object::NAMED_OBJECT_CONST:
9128 	  if ((traverse_mask & Traverse::traverse_constants) != 0)
9129 	    t = traverse->constant(p, is_global);
9130 	  if (t == TRAVERSE_CONTINUE
9131 	      && (traverse_mask & e_or_t) != 0)
9132 	    {
9133 	      Type* tc = p->const_value()->type();
9134 	      if (tc != NULL
9135 		  && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
9136 		return TRAVERSE_EXIT;
9137 	      t = p->const_value()->traverse_expression(traverse);
9138 	    }
9139 	  break;
9140 
9141 	case Named_object::NAMED_OBJECT_VAR:
9142 	case Named_object::NAMED_OBJECT_RESULT_VAR:
9143 	  if ((traverse_mask & Traverse::traverse_variables) != 0)
9144 	    t = traverse->variable(p);
9145 	  if (t == TRAVERSE_CONTINUE
9146 	      && (traverse_mask & e_or_t) != 0)
9147 	    {
9148 	      if (p->is_result_variable()
9149 		  || p->var_value()->has_type())
9150 		{
9151 		  Type* tv = (p->is_variable()
9152 			      ? p->var_value()->type()
9153 			      : p->result_var_value()->type());
9154 		  if (tv != NULL
9155 		      && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
9156 		    return TRAVERSE_EXIT;
9157 		}
9158 	    }
9159 	  if (t == TRAVERSE_CONTINUE
9160 	      && (traverse_mask & e_or_t_or_s) != 0
9161 	      && p->is_variable())
9162 	    t = p->var_value()->traverse_expression(traverse, traverse_mask);
9163 	  break;
9164 
9165 	case Named_object::NAMED_OBJECT_FUNC:
9166 	  if ((traverse_mask & Traverse::traverse_functions) != 0)
9167 	    t = traverse->function(p);
9168 
9169 	  if (t == TRAVERSE_CONTINUE
9170 	      && (traverse_mask
9171 		  & (Traverse::traverse_variables
9172 		     | Traverse::traverse_constants
9173 		     | Traverse::traverse_functions
9174 		     | Traverse::traverse_blocks
9175 		     | Traverse::traverse_statements
9176 		     | Traverse::traverse_expressions
9177 		     | Traverse::traverse_types)) != 0)
9178 	    t = p->func_value()->traverse(traverse);
9179 	  break;
9180 
9181 	case Named_object::NAMED_OBJECT_PACKAGE:
9182 	  // These are traversed in Gogo::traverse.
9183 	  go_assert(is_global);
9184 	  break;
9185 
9186 	case Named_object::NAMED_OBJECT_TYPE:
9187 	  if ((traverse_mask & e_or_t) != 0)
9188 	    t = Type::traverse(p->type_value(), traverse);
9189 	  break;
9190 
9191 	case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
9192 	case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
9193 	case Named_object::NAMED_OBJECT_UNKNOWN:
9194 	case Named_object::NAMED_OBJECT_ERRONEOUS:
9195 	  break;
9196 
9197 	case Named_object::NAMED_OBJECT_SINK:
9198 	default:
9199 	  go_unreachable();
9200 	}
9201 
9202       if (t == TRAVERSE_EXIT)
9203 	return TRAVERSE_EXIT;
9204     }
9205 
9206   // If we need to traverse types, check the function declarations,
9207   // which have types.  Also check any methods of a type declaration.
9208   if ((traverse_mask & e_or_t) != 0)
9209     {
9210       for (Bindings::const_declarations_iterator p =
9211 	     this->begin_declarations();
9212 	   p != this->end_declarations();
9213 	   ++p)
9214 	{
9215 	  if (p->second->is_function_declaration())
9216 	    {
9217 	      if (Type::traverse(p->second->func_declaration_value()->type(),
9218 				 traverse)
9219 		  == TRAVERSE_EXIT)
9220 		return TRAVERSE_EXIT;
9221 	    }
9222 	  else if (p->second->is_type_declaration())
9223 	    {
9224 	      const std::vector<Named_object*>* methods =
9225 		p->second->type_declaration_value()->methods();
9226 	      for (std::vector<Named_object*>::const_iterator pm =
9227 		     methods->begin();
9228 		   pm != methods->end();
9229 		   pm++)
9230 		{
9231 		  Named_object* no = *pm;
9232 		  Type *t;
9233 		  if (no->is_function())
9234 		    t = no->func_value()->type();
9235 		  else if (no->is_function_declaration())
9236 		    t = no->func_declaration_value()->type();
9237 		  else
9238 		    continue;
9239 		  if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
9240 		    return TRAVERSE_EXIT;
9241 		}
9242 	    }
9243 	}
9244     }
9245 
9246   // Traverse function declarations when needed.
9247   if ((traverse_mask & Traverse::traverse_func_declarations) != 0)
9248     {
9249       for (Bindings::const_declarations_iterator p = this->begin_declarations();
9250            p != this->end_declarations();
9251            ++p)
9252         {
9253           if (p->second->is_function_declaration())
9254             {
9255               if (traverse->function_declaration(p->second) == TRAVERSE_EXIT)
9256                 return TRAVERSE_EXIT;
9257             }
9258         }
9259     }
9260 
9261   return TRAVERSE_CONTINUE;
9262 }
9263 
9264 void
debug_dump()9265 Bindings::debug_dump()
9266 {
9267   std::set<Named_object*> defs;
9268   for (size_t i = 0; i < this->named_objects_.size(); ++i)
9269     defs.insert(this->named_objects_[i]);
9270   for (Contour::iterator p = this->bindings_.begin();
9271        p != this->bindings_.end();
9272        ++p)
9273     {
9274       const char* tag = "  ";
9275       if (defs.find(p->second) != defs.end())
9276         tag = "* ";
9277       std::cerr << tag;
9278       debug_go_named_object(p->second);
9279     }
9280 }
9281 
9282 void
debug_go_bindings(Bindings * bindings)9283 debug_go_bindings(Bindings* bindings)
9284 {
9285   if (bindings != NULL)
9286     bindings->debug_dump();
9287 }
9288 
9289 // Class Label.
9290 
9291 // Clear any references to this label.
9292 
9293 void
clear_refs()9294 Label::clear_refs()
9295 {
9296   for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
9297        p != this->refs_.end();
9298        ++p)
9299     delete *p;
9300   this->refs_.clear();
9301 }
9302 
9303 // Get the backend representation for a label.
9304 
9305 Blabel*
get_backend_label(Translate_context * context)9306 Label::get_backend_label(Translate_context* context)
9307 {
9308   if (this->blabel_ == NULL)
9309     {
9310       Function* function = context->function()->func_value();
9311       Bfunction* bfunction = function->get_decl();
9312       this->blabel_ = context->backend()->label(bfunction, this->name_,
9313 						this->location_);
9314     }
9315   return this->blabel_;
9316 }
9317 
9318 // Return an expression for the address of this label.
9319 
9320 Bexpression*
get_addr(Translate_context * context,Location location)9321 Label::get_addr(Translate_context* context, Location location)
9322 {
9323   Blabel* label = this->get_backend_label(context);
9324   return context->backend()->label_address(label, location);
9325 }
9326 
9327 // Return the dummy label that represents any instance of the blank label.
9328 
9329 Label*
create_dummy_label()9330 Label::create_dummy_label()
9331 {
9332   static Label* dummy_label;
9333   if (dummy_label == NULL)
9334     {
9335       dummy_label = new Label("_");
9336       dummy_label->set_is_used();
9337     }
9338   return dummy_label;
9339 }
9340 
9341 // Class Unnamed_label.
9342 
9343 // Get the backend representation for an unnamed label.
9344 
9345 Blabel*
get_blabel(Translate_context * context)9346 Unnamed_label::get_blabel(Translate_context* context)
9347 {
9348   if (this->blabel_ == NULL)
9349     {
9350       Function* function = context->function()->func_value();
9351       Bfunction* bfunction = function->get_decl();
9352       this->blabel_ = context->backend()->label(bfunction, "",
9353 						this->location_);
9354     }
9355   return this->blabel_;
9356 }
9357 
9358 // Return a statement which defines this unnamed label.
9359 
9360 Bstatement*
get_definition(Translate_context * context)9361 Unnamed_label::get_definition(Translate_context* context)
9362 {
9363   Blabel* blabel = this->get_blabel(context);
9364   return context->backend()->label_definition_statement(blabel);
9365 }
9366 
9367 // Return a goto statement to this unnamed label.
9368 
9369 Bstatement*
get_goto(Translate_context * context,Location location)9370 Unnamed_label::get_goto(Translate_context* context, Location location)
9371 {
9372   Blabel* blabel = this->get_blabel(context);
9373   return context->backend()->goto_statement(blabel, location);
9374 }
9375 
9376 // Class Package.
9377 
Package(const std::string & pkgpath,const std::string & pkgpath_symbol,Location location)9378 Package::Package(const std::string& pkgpath,
9379 		 const std::string& pkgpath_symbol, Location location)
9380   : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
9381     package_name_(), bindings_(new Bindings(NULL)),
9382     location_(location)
9383 {
9384   go_assert(!pkgpath.empty());
9385 }
9386 
9387 // Set the package name.
9388 
9389 void
set_package_name(const std::string & package_name,Location location)9390 Package::set_package_name(const std::string& package_name, Location location)
9391 {
9392   go_assert(!package_name.empty());
9393   if (this->package_name_.empty())
9394     this->package_name_ = package_name;
9395   else if (this->package_name_ != package_name)
9396     go_error_at(location,
9397 		("saw two different packages with "
9398 		 "the same package path %s: %s, %s"),
9399 		this->pkgpath_.c_str(), this->package_name_.c_str(),
9400 		package_name.c_str());
9401 }
9402 
9403 // Return the pkgpath symbol, which is a prefix for symbols defined in
9404 // this package.
9405 
9406 std::string
pkgpath_symbol() const9407 Package::pkgpath_symbol() const
9408 {
9409   if (this->pkgpath_symbol_.empty())
9410     return Gogo::pkgpath_for_symbol(this->pkgpath_);
9411   return this->pkgpath_symbol_;
9412 }
9413 
9414 // Set the package path symbol.
9415 
9416 void
set_pkgpath_symbol(const std::string & pkgpath_symbol)9417 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
9418 {
9419   go_assert(!pkgpath_symbol.empty());
9420   if (this->pkgpath_symbol_.empty())
9421     this->pkgpath_symbol_ = pkgpath_symbol;
9422   else
9423     go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
9424 }
9425 
9426 // Note that symbol from this package was and qualified by ALIAS.
9427 
9428 void
note_usage(const std::string & alias) const9429 Package::note_usage(const std::string& alias) const
9430 {
9431   Aliases::const_iterator p = this->aliases_.find(alias);
9432   go_assert(p != this->aliases_.end());
9433   p->second->note_usage();
9434 }
9435 
9436 // Forget a given usage.  If forgetting this usage means this package becomes
9437 // unused, report that error.
9438 
9439 void
forget_usage(Expression * usage) const9440 Package::forget_usage(Expression* usage) const
9441 {
9442   if (this->fake_uses_.empty())
9443     return;
9444 
9445   std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
9446   go_assert(p != this->fake_uses_.end());
9447   this->fake_uses_.erase(p);
9448 
9449   if (this->fake_uses_.empty())
9450     go_error_at(this->location(), "imported and not used: %s",
9451 		Gogo::message_name(this->package_name()).c_str());
9452 }
9453 
9454 // Clear the used field for the next file.  If the only usages of this package
9455 // are possibly fake, keep the fake usages for lowering.
9456 
9457 void
clear_used()9458 Package::clear_used()
9459 {
9460   std::string dot_alias = "." + this->package_name();
9461   Aliases::const_iterator p = this->aliases_.find(dot_alias);
9462   if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
9463     this->fake_uses_.clear();
9464 
9465   this->aliases_.clear();
9466 }
9467 
9468 Package_alias*
add_alias(const std::string & alias,Location location)9469 Package::add_alias(const std::string& alias, Location location)
9470 {
9471   Aliases::const_iterator p = this->aliases_.find(alias);
9472   if (p == this->aliases_.end())
9473     {
9474       std::pair<Aliases::iterator, bool> ret;
9475       ret = this->aliases_.insert(std::make_pair(alias,
9476                                                  new Package_alias(location)));
9477       p = ret.first;
9478     }
9479   return p->second;
9480 }
9481 
9482 // Determine types of constants.  Everything else in a package
9483 // (variables, function declarations) should already have a fixed
9484 // type.  Constants may have abstract types.
9485 
9486 void
determine_types()9487 Package::determine_types()
9488 {
9489   Bindings* bindings = this->bindings_;
9490   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
9491        p != bindings->end_definitions();
9492        ++p)
9493     {
9494       if ((*p)->is_const())
9495 	(*p)->const_value()->determine_type();
9496     }
9497 }
9498 
9499 // Class Traverse.
9500 
9501 // Destructor.
9502 
~Traverse()9503 Traverse::~Traverse()
9504 {
9505   if (this->types_seen_ != NULL)
9506     delete this->types_seen_;
9507   if (this->expressions_seen_ != NULL)
9508     delete this->expressions_seen_;
9509 }
9510 
9511 // Record that we are looking at a type, and return true if we have
9512 // already seen it.
9513 
9514 bool
remember_type(const Type * type)9515 Traverse::remember_type(const Type* type)
9516 {
9517   if (type->is_error_type())
9518     return true;
9519   go_assert((this->traverse_mask() & traverse_types) != 0
9520 	     || (this->traverse_mask() & traverse_expressions) != 0);
9521   // We mostly only have to remember named types.  But it turns out
9522   // that an interface type can refer to itself without using a name
9523   // by relying on interface inheritance, as in
9524   //
9525   //         type I interface { F() interface{I} }
9526   //
9527   // Similarly it is possible for array types to refer to themselves
9528   // without a name, e.g.
9529   //
9530   //         var x [uintptr(unsafe.Sizeof(&x))]byte
9531   //
9532   if (type->classification() != Type::TYPE_NAMED
9533       && type->classification() != Type::TYPE_ARRAY
9534       && type->classification() != Type::TYPE_INTERFACE)
9535     return false;
9536   if (this->types_seen_ == NULL)
9537     this->types_seen_ = new Types_seen();
9538   std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
9539   return !ins.second;
9540 }
9541 
9542 // Record that we are looking at an expression, and return true if we
9543 // have already seen it. NB: this routine used to assert if the traverse
9544 // mask did not include expressions/types -- this is no longer the case,
9545 // since it can be useful to remember specific expressions during
9546 // walks that only cover statements.
9547 
9548 bool
remember_expression(const Expression * expression)9549 Traverse::remember_expression(const Expression* expression)
9550 {
9551   if (this->expressions_seen_ == NULL)
9552     this->expressions_seen_ = new Expressions_seen();
9553   std::pair<Expressions_seen::iterator, bool> ins =
9554     this->expressions_seen_->insert(expression);
9555   return !ins.second;
9556 }
9557 
9558 // The default versions of these functions should never be called: the
9559 // traversal mask indicates which functions may be called.
9560 
9561 int
variable(Named_object *)9562 Traverse::variable(Named_object*)
9563 {
9564   go_unreachable();
9565 }
9566 
9567 int
constant(Named_object *,bool)9568 Traverse::constant(Named_object*, bool)
9569 {
9570   go_unreachable();
9571 }
9572 
9573 int
function(Named_object *)9574 Traverse::function(Named_object*)
9575 {
9576   go_unreachable();
9577 }
9578 
9579 int
block(Block *)9580 Traverse::block(Block*)
9581 {
9582   go_unreachable();
9583 }
9584 
9585 int
statement(Block *,size_t *,Statement *)9586 Traverse::statement(Block*, size_t*, Statement*)
9587 {
9588   go_unreachable();
9589 }
9590 
9591 int
expression(Expression **)9592 Traverse::expression(Expression**)
9593 {
9594   go_unreachable();
9595 }
9596 
9597 int
type(Type *)9598 Traverse::type(Type*)
9599 {
9600   go_unreachable();
9601 }
9602 
9603 int
function_declaration(Named_object *)9604 Traverse::function_declaration(Named_object*)
9605 {
9606   go_unreachable();
9607 }
9608 
9609 // Class Statement_inserter.
9610 
9611 void
insert(Statement * s)9612 Statement_inserter::insert(Statement* s)
9613 {
9614   if (this->statements_added_ != NULL)
9615     this->statements_added_->insert(s);
9616 
9617   if (this->block_ != NULL)
9618     {
9619       go_assert(this->pindex_ != NULL);
9620       this->block_->insert_statement_before(*this->pindex_, s);
9621       ++*this->pindex_;
9622     }
9623   else if (this->var_ != NULL)
9624     this->var_->add_preinit_statement(this->gogo_, s);
9625   else
9626     go_assert(saw_errors());
9627 }
9628