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