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