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